text
stringlengths
14
6.51M
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2015 Vincent Parrett & Contributors } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DUnitX.Banner; interface procedure ShowBanner; implementation uses DUnitX.ConsoleWriter.Base, DUnitX.IoC; procedure ShowBanner; var consoleWriter : IDUnitXConsoleWriter; procedure WriteLine(const value : string); begin if consoleWriter <> nil then consoleWriter.WriteLn(value) else System.Writeln(value); end; begin consoleWriter := TDUnitXIoC.DefaultContainer.Resolve<IDUnitXConsoleWriter>(); if consoleWriter <> nil then consoleWriter.SetColour(ccBrightWhite, ccDefault); WriteLine('**********************************************************************'); WriteLine('* DUnitX - (c) 2015-2020 Vincent Parrett & Contributors *'); WriteLine('* *'); WriteLine('* License - http://www.apache.org/licenses/LICENSE-2.0 *'); WriteLine('**********************************************************************'); WriteLine(''); if consoleWriter <> nil then consoleWriter.SetColour(ccDefault); end; end.
unit UAMC_SendPak_MercuryNetwork; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } { This is specific unit that knowns how to send the 'Appraisal Package' } { to ISGN. Each AMC is slightly different. so we have a unique } { TWorkflowBaseFrame for each AMC. } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, MSXML6_TLB, WinHTTP_TLB, uLKJSON, UContainer, UAMC_Globals, UAMC_Base, UAMC_Login, UAMC_Port, UAMC_WorkflowBaseFrame, CheckLst, UGlobals; type TAMC_SendPak_MercuryNetwork = class(TWorkflowBaseFrame) btnUpload: TButton; StaticText1: TStaticText; chkBxList: TCheckListBox; procedure btnUploadClick(Sender: TObject); private FAMCOrder: AMCOrderInfo; FOrderID: String; //this is the associated OrderID FAppraiserHash: String; //this is the appraiser Login (Base64 Encoded username + ':' + password) FUploaded: Boolean; //have the files been uploaded? FAppraisalOrderID: String; FTrackingID: String; procedure PrepFileForUploading(ADataFile: TDataFile; var fData, fDataID: String); procedure PostStatusToAW(aStatusCode:Integer); procedure ComposeDetailByStatus(var jsDetail: TlkJSONObject); function CheckForFullAccessOnMercury: Boolean; function ReadIniSettings:Boolean; function Ok2UseMercury:Boolean; public constructor CreateFrame(AOwner: TComponent; ADoc: TContainer; AData: TDataPackage); override; procedure InitPackageData; override; function ProcessedOK: Boolean; override; procedure UploadAppraisalPackage; function UploadDataFile(PDFBase64Data, XMLBase64Data: String): Boolean; property CanAccessMercury: Boolean read CheckForFullAccessOnMercury; end; implementation {$R *.dfm} uses UWebConfig, UAMC_Utils, UWindowsInfo, UStatus, UBase64, UAMC_Delivery, ZipForge, ULicUser, uUtil2, uUtil1,AWSI_Server_Clickforms, USendHelp, IniFiles,UCRMServices, UStrings; //ISGN data format identifiers const fmtPDF = 'PDF'; fmtMISMO26 = 'MISMO'; fmtMISMO26GSE = 'MISMOGSE'; fmtENV = 'ENV'; { TAMC_SendPak_ISGN } constructor TAMC_SendPak_MercuryNetwork.CreateFrame(AOwner: TComponent; ADoc: TContainer; AData: TDataPackage); begin inherited; FOrderID := ''; //no orderID yet end; function GetDataFileDescriptionText(thisType: String): String; begin if CompareText(thisType, fTypXML26) = 0 then result := XML2_6Desc else if CompareText(thisType, fTypXML26GSE) = 0 then result := XML2_6GSEDesc else if CompareText(thisType, fTypPDF) = 0 then result := PDFFileDesc else if CompareText(thisType, fTypENV) = 0 then result := ENVFileDesc else if CompareText(thisType, fTypXML241) = 0 then result := XML2_41Desc else result := 'Undefined Data File Type'; end; //Display the package contents to be uploaded procedure TAMC_SendPak_MercuryNetwork.InitPackageData; var fileType, strDesc: String; n: integer; begin FUploaded := False; btnUpload.Enabled := True; StaticText1.Caption :=' Appraisal Package files to Upload:'; //get ISGN specific data if assigned(PackageData.FAMCData) then begin FOrderID := TAMCData_ISGN(PackageData.FAMCData).FOrderID; FAppraiserHash := TAMCData_ISGN(PackageData.FAMCData).FAppraiserHash; end; //display the file types that will be uploaded chkBxList.Clear; //in case we are entering multiple times with PackageData.DataFiles do for n := 0 to count-1 do begin fileType := TDataFile(Items[n]).FType; strDesc := GetDataFileDescriptionText(fileType); if pos('xml', lowerCase(strDesc)) > 0 then //for xml, only add to the box if RequireXML True begin chkBxList.items.Add(strDesc); chkBxList.Checked[n] := FDoc.FAMCOrderInfo.RequireXML; chkBxList.ItemEnabled[n] := FDoc.FAMCOrderInfo.RequireXML; end else //Always upload pdf begin chkBxList.items.Add(strDesc); chkBxList.Checked[n] := True; end; end; end; function TAMC_SendPak_MercuryNetwork.ProcessedOK: Boolean; begin PackageData.FGoToNextOk := FUploaded; PackageData.FAlertMsg := 'The appraisal report was successfully uploaded'; //ending msg to user PackageData.FHardStop := not FUploaded; PackageData.FAlertMsg := ''; if not FUploaded then PackageData.FAlertMsg := 'Please upload the report before moving to the next step.'; result := PackageData.FGoToNextOk; end; function TAMC_SendPak_MercuryNetwork.CheckForFullAccessOnMercury: Boolean; var AWResponse: clsGetUsageAvailabilityData; VendorTokenKey:String; begin result := True; //no need to check if it's not Mercury if pos('MERCURY',UpperCase(FDoc.FAMCOrderInfo.ProviderID)) > 0 then //for Mercury, we call OK2UseAWProduct to return TRUE for full access FALSE = No Access begin result := CurrentUser.OK2UseAWProduct(pidMercuryNetwork, AWResponse, True); if not result then begin try result := GetCRM_PersmissionOnly(CRM_MercuryNetworkUID,CRM_Mercury_ServiceMethod,CurrentUser.AWUserInfo,False,VendorTokenKey); except on E:Exception do ShowAlert(atWarnAlert,msgServiceNotAvaible); end; end; end; end; function TAMC_SendPak_MercuryNetwork.ReadIniSettings:Boolean; const Session_Name = 'Operation'; var PrefFile: TMemIniFile; IniFilePath : String; InitialPref: Integer; aInt: String; aChar: String; begin result := False; IniFilePath := IncludeTrailingPathDelimiter(appPref_DirPref) + cClickFormsINI; PrefFile := TMemIniFile.Create(IniFilePath); //create the INI reader try With PrefFile do begin result := appPref_MercuryTries <= MAX_Mercury_Count; if not result and (appPref_MercuryTries > MAX_Mercury_Count) then HelpCmdHandler(cmdHelpAWShop4Service, CurrentUser.UserCustUID, CurrentUser.AWUserInfo.UserLoginEmail); //link to the AppraisalWorld store inc(appPref_MercuryTries); aChar := EncodeDigit2Char(appPref_MercuryTries); WriteString(Session_Name, MERCURY_KEY, aChar); UpdateFile; end; finally PrefFile.free; end; end; function TAMC_SendPak_MercuryNetwork.Ok2UseMercury:Boolean; const rspTryIt = 6; rspPurchase = 7; WarnTriesMsg = 'Your Mercury Network Connection trial has “%d” transfers remaining. '+ 'To add the Mercury Network Connection to your membership plan, '+ 'call your sales representative or visit the AppraisalWorld store. ' ; WarnPurchaseMsg = 'The Mercury Network Connection is not part of your current ClickFORMS Membership. '+ 'Please call your sales representative at 800-622-8727 or visit the AppraisalWorld store.'; var rsp, aCount: Integer; aCaption, aMsg: String; abool: Boolean; begin result := CanAccessMercury; if not result then //Cannot access Mercury, attract user with 10 # of tries begin if appPref_MercuryTries <= MAX_Mercury_Count then begin aCount := MAX_Mercury_Count - appPref_MercuryTries; if appPref_MercuryTries = 0 then aCaption := Format('Maximum # of Tries = %d',[MAX_Mercury_Count]) else if appPref_MercuryTries > 0 then aCaption := Format('# of Tries: %d of %d',[appPref_MercuryTries,MAX_Mercury_Count]); aMsg := Format(WarnTriesMsg,[aCount]); rsp := WhichOption123Ex2(aCaption, aBool, 'OK', 'Purchase', 'Cancel',aMsg, 85, False); if rsp = rspTryIt then begin result := ReadIniSettings; end else if rsp = rspPurchase then begin HelpCmdHandler(cmdHelpAWShop4Service, CurrentUser.AWUserInfo.AWIdentifier, CurrentUser.AWUserInfo.UserLoginEmail); end; end else if appPref_MercuryTries > MAX_Mercury_Count then //reach maximum # of tries, stop user to route user to AW store begin aCount := MAX_Mercury_Count - appPref_MercuryTries; rsp := WhichOption123Ex2(aCaption,aBool, '', 'Purchase', 'Cancel', WarnPurchaseMsg, 85, False); if rsp = rspPurchase then HelpCmdHandler(cmdHelpAWShop4Service, CurrentUser.AWUserInfo.AWIdentifier, CurrentUser.AWUserInfo.UserLoginEmail); exit; end; end; end; procedure TAMC_SendPak_MercuryNetwork.btnUploadClick(Sender: TObject); begin UploadAppraisalPackage; // if FDoc.DataModified then // ShowAlert(atWarnAlert,'There are unsaved changes to the report. Please save the report and regenerate the XML and all other required files before uploading.') // else // begin // if Ok2UseMercury then // begin // end; // end; end; function ConvertToMercuryType(fType: String): String; begin if compareText(fType, fTypXML26) = 0 then result := fmtMISMO26 else if compareText(fType, fTypXML26GSE) = 0 then result := fmtMISMO26GSE else if compareText(fType, fTypPDF) = 0 then result := fmtPDF else if compareText(fType, fTypENV) = 0 then result := fmtENV else result := 'UNKNOWN'; //this should NEVER happen end; procedure TAMC_SendPak_MercuryNetwork.PrepFileForUploading(ADataFile: TDataFile; var fData, fDataID: String); begin //extract the data fData := ADataFile.FData; //get StreetLinks format identifier fDataID := ConvertToMercuryType(ADataFile.FType); //should it be base64 encoded? if (CompareText(fDataID, fmtPDF) = 0) OR (CompareText(fDataID, fmtMISMO26GSE) = 0) or (CompareText(fDataID, fmtMISMO26) = 0) then fData := Base64Encode(fData); end; procedure TAMC_SendPak_MercuryNetwork.UploadAppraisalPackage; const sCompletedInvoiced = 19; var aData, aDataType: String; n, i: Integer; aPDFData, aXMLData:String; begin StaticText1.Caption :=' Uploading Appraisal Package files to Mercury Network'; btnUpload.Enabled := False; with PackageData do for n := 0 to DataFiles.count -1 do begin if chkBxList.Checked[n] then begin PrepFileForUploading(TDataFile(DataFiles[n]), aData, aDataType); if pos(lowerCase(fmtPDF), LowerCase(aDataType)) > 0 then aPDFData := aData else if pos(lowerCase(fmtMISMO26GSE), LowerCase(aDataType)) > 0 then aXMLData := aData; end; end; FUploaded := UploadDataFile(aPDFData, aXMLData); if not FUPloaded then exit; if FUploaded then StaticText1.Caption :=' All Appraisal Package files Uploaded to Merucury' else begin btnUpload.Enabled := True; StaticText1.Caption :=' Appraisal Package files to Upload:'; end; if FUploaded then //Tell AW order is completed begin PostStatusToAW(sCompletedInvoiced); end; end; procedure TAMC_SendPak_MercuryNetwork.ComposeDetailByStatus(var jsDetail: TlkJSONObject); var aDate: String; aNote: String; begin aDate := FormatdateTime('mm/dd/yyyy', Date); aNote := Format('Upload Completed order @%s',[aDate]); jsdetail.Add('invoiced_date', aDate); jsDetail.Add('amount_invoiced', 0.00); jsdetail.Add('notes', aNote); end; procedure TAMC_SendPak_MercuryNetwork.PostStatusToAW(aStatusCode:Integer); var jsObj, jsPostRequest, jsDetail: TlkJSONObject; errMsg: String; url: String; sl:TStringList; RequestStr: String; aInt: Integer; HTTPRequest: IWinHTTPRequest; jsResponse: String; begin aInt := httpRespOK; FAppraisalOrderID := FDoc.FAMCOrderInfo.AppraisalOrderID; FTrackingID := Format('%d',[FDoc.FAMCOrderInfo.TrackingID]); PushMouseCursor(crHourglass); try errMsg := ''; if use_Mercury_live_URL then url := live_PostStatusToAW_URL else url := test_PostStatusToAW_URL; jsPostRequest := TlkJSONObject.Create(true); jsDetail := tlkJSonObject.Create(true); // jsPostRequest.Add('appraiser_id', GetValidInteger(CurrentUser.AWUserInfo.AWIdentifier)); //this is the inspection id jsPostRequest.Add('order_id',GetValidInteger(FAppraisalOrderID)); jsPostRequest.Add('tracking_id', FTrackingID); jsPostRequest.Add('status_id', aStatusCode); //Details: based on status code to set detail json ComposeDetailByStatus(jsDetail); jsPostRequest.Add('details',jsDetail); RequestStr := TlkJSON.GenerateText(jsPostRequest); httpRequest := CoWinHTTPRequest.Create; httpRequest.SetTimeouts(60000,60000,60000,60000); //1 minute for everything httpRequest.Open('POST',url,False); httpRequest.SetRequestHeader('Content-type','application/text'); httpRequest.SetRequestHeader('Content-length', IntToStr(length(RequestStr))); try httpRequest.send(RequestStr); except on e:Exception do errMsg := e.Message; end; if httpRequest.Status <> httpRespOK then errMsg := 'The server returned error code '+ IntToStr(httpRequest.status) + ' '+ errMsg else begin jsResponse := httpRequest.ResponseText; jsObj := TlkJSON.ParseText(jsResponse) as TlkJSONobject; if jsObj <> nil then begin aInt := jsObj.Field['code'].value; if aInt <> httpRespOK then begin //showAlert(atWarnAlert, jsObj.getString('errormessage')); // end else begin //ShowNotice('Update status successfully.'); end; end; end; finally PopMousecursor; if assigned(jsObj) then jsObj.Free; end; end; function TAMC_SendPak_MercuryNetwork.UploadDataFile(PDFBase64Data, XMLBase64Data: String): Boolean; const // MercuryURL = 'https://wbsvcqa.mercuryvmp.com/api/Vendors/Status/'; sOrderCompleted = 301000; var URL: String; uploadStr: String; httpRequest: IWinHTTPRequest; jsPostRequest, jsPDF, jsXML: TlkJSONObject; jsDataList: TlkJSONList; //set up for an array CurrentDateTime: String; RequestStr: String; VendorTokenKey: String; aPDFFileName, aXMLFileName: String; aItem: String; sl:TStringList; i, iTrackingID: Integer; aFileName, expPath: String; begin result := False; expPath := IncludeTrailingPathDelimiter(appPref_DirExports); expPath := Format('%sMercury\',[expPath]); ForceDirectories(expPath); aFileName := Format('%s\%s',[appPref_DirLicenses,MercuryTokeFileName]); sl:=TStringList.Create; sl.LoadFromFile(aFileName); for i:= 0 to sl.Count -1 do begin aItem := sl[i]; if pos('Token', aItem) > 0 then begin popStr(aItem, '='); aItem := Trim(aItem); VendorTokenKey := UBase64.Base64Decode(aItem); end; end; //exit; if VendorTokenKey = '' Then begin ShowAlert(atWarnAlert, 'Vendor Token Key is EMPTY.'); exit; end; iTrackingID := FDoc.FAMCOrderInfo.TrackingID; if iTrackingID = 0 then begin ShowAlert(atWarnAlert, 'Mercury Order Tracking # is required.'); exit; end; if use_Mercury_Live_URL then url := live_Post_UploadToMercury_URL else url := test_Post_UploadToMercury_URL; VendorTokenKey := Format('Bearer %s',[VendorTokenKey]); httpRequest := CoWinHTTPRequest.Create; with httpRequest do begin Open('POST',URL, False); SetTimeouts(600000,600000,600000,600000); //10 minute for everything SetRequestHeader('Content-type','application/json'); SetRequestHeader('Cache-Control','no-cache'); // SetRequestHeader('Pragma', 'no-cache'); SetRequestHeader('Content-length', IntToStr(length(PDFBase64Data + XMLBase64Data))); SetRequestHeader('Authorization',VendorTokenKey); jsPostRequest := TlkJSONObject.Create(true); jsDataList := TlkJSonList.Create; jsPostRequest.Add('ListStatusID', sOrderCompleted); //Inspection completed jsPostRequest.Add('StatusComment','Upload completed order file.'); jsPostRequest.Add('TrackingID',iTrackingID); CurrentDateTime := FormatDateTime('yyyy-mm-dd hh:mm:ss.000',now); jsPostRequest.Add('InspectiondateTime', CurrentDateTime); //PDF file if PDFBase64Data <> '' then begin jsPDF := TlkJSONObject.Create(true); //aPDFFileName := 'AppraisalReport.pdf'; aPDFFileName := Format('%d.pdf',[iTrackingID]); jsPDF.Add('FileName',aPDFFileName); jsPDF.Add('DocumentType','Appraisal Report'); jsPDF.Add('Base64Content',PDFBase64Data); jsDataList.Add(jsPDF); end; //XML file if XMLBase64Data <> '' then begin jsXML := TlkJSONObject.Create(true); //aXMLFileName := 'AppraisalReport.xml'; aXMLFilename := Format('%d.xml',[iTrackingID]); jsXML.Add('FileName',aXMLFileName); jsXML.Add('DocumentType','MISMO 2.6 GSE'); jsXML.Add('Base64Content',XMLBase64Data); jsDataList.Add(jsXML); end; jsPostRequest.Add('StatusDocuments', jsDataList); RequestStr := TlkJSON.GenerateText(jsPostRequest); PushMouseCursor(crHourGlass); try try sl.text := RequestStr; if use_Mercury_Live_URL then aFileName := Format('%spost_Mercury_live.txt',[expPath]) else aFileName := Format('%spost_Mercury_qa.txt',[expPath]); sl.SaveToFile(aFileName); httpRequest.send(RequestStr); if status <> httpRespOK then begin showAlert(atWarnAlert, Format('Status = %d httpRequest.ResponseText = %s',[status,httpRequest.ResponseText])); result := False; exit; end else begin ShowMessage('Upload files to Mercury Network successfully'); result := True; end; except on e:Exception do begin PopMouseCursor; ShowAlert(atWarnAlert, e.Message); exit; end; end; finally PopMouseCursor; sl.free; if assigned(jsXML) then jsXML.Free; if assigned(jsPDF) then jsPDF.Free; end; end; end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2012-2013 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.Pickers.iOS; interface procedure RegisterPickersService; procedure UnregisterPickersService; implementation uses System.Classes, System.SysUtils, System.TypInfo, System.Types, System.DateUtils, System.Math, FMX.Pickers, FMX.Platform, FMX.Types, FMX.Consts, FMX.Controls, FMX.Platform.iOS, FMX.Forms, FMX.Helpers.iOS, Macapi.ObjectiveC, Macapi.ObjCRuntime, iOSapi.Foundation, iOSapi.CocoaTypes, iOSapi.UIKit, iOSapi.CoreGraphics; type IDialogActions = interface (NSObject) ['{59D129A3-8EA1-4B48-A09F-4DF2ACA7E26F}'] procedure Cancel; cdecl; procedure Done; cdecl; procedure Hidden; cdecl; procedure StartChangeDeviceOrientation(notification: Pointer); cdecl; end; TPickerState = (psHidden, psShowed); { Only for iPad } TPopoverDelegate = class; { Native animated popup with 2 buttons (Done, Close) } TPopupDialog = class (TOCLocal) strict private FOnShow: TNotifyEvent; FOnHide: TNotifyEvent; protected FParentControl: TControl; FPickerState: TPickerState; // For iPad FUIPopoverController: UIPopoverController; FUIPopoverContent: UIViewController; FUIPopoverDelegate: TPopoverDelegate; // Common controls for all devices: iPhone and iPad idioms FUIContainerView: UIView; FUIToolBar: UIToolBar; FUICloseButton: UIBarButtonItem; FUIFlexibleSepararator: UIBarButtonItem; FUIDoneButton: UIBarButtonItem; procedure DoShow; virtual; procedure DoDone; virtual; procedure DoCancel; virtual; procedure DoHide; virtual; procedure DoPopoverDismiss; function GetPopupFrame: NSRect; virtual; function GetToolbarFrame: NSRect; function GetContentFrame: NSRect; { TOCLocal } function GetObjectiveCClass: PTypeInfo; override; public constructor Create; destructor Destroy; override; procedure Show; procedure Hide; { IDialogActions } procedure Cancel; cdecl; procedure Done; cdecl; procedure Hidden; cdecl; procedure StartChangeDeviceOrientation(notification: Pointer); cdecl; property ParentControl: TControl read FParentControl write FParentControl; property PickerState: TPickerState read FPickerState; property OnShow: TNotifyEvent read FOnShow write FOnShow; property OnHide: TNotifyEvent read FOnHide write FOnHide; end; TPopoverDelegate = class (TOCLocal, UIPopoverControllerDelegate) strict private FPopupDialog: TPopupDialog; public constructor Create(const APopupDialog: TPopupDialog); { UIPopoverControllerDelegate } procedure popoverControllerDidDismissPopover(popoverController: UIPopoverController); cdecl; function popoverControllerShouldDismissPopover(popoverController: UIPopoverController): Boolean; cdecl; end; { To inherit the IDialogActions interface it is impossible Because the child interface can be not registered in Objective C at the moment of creation of a copy of a class. It registers at the moment of creation of a copy of a class. } IDateTimeDialogActions = interface (NSObject) ['{47CDC1C0-8FF6-4815-94A0-79893BDFD722}'] procedure Cancel; cdecl; procedure Done; cdecl; procedure Hidden; cdecl; procedure StartChangeDeviceOrientation(notification: Pointer); cdecl; end; { Native animated popup with 2 buttons (Done, Close) and Date picker } TDateTimePopupDialog = class (TPopupDialog) private FDateTimePicker: UIDatePicker; FOnDateChanged: TOnDateChanged; function GetDateTime: TDateTime; procedure SetDateTime(const Value: TDateTime); procedure SetShowMode(const Value: TDatePickerShowMode); procedure DoDateChanged; procedure SetDateTimeConstraints(const Index: Integer; const Value: TDate); protected procedure DoDone; override; { TOCLocal } function GetObjectiveCClass: PTypeInfo; override; public constructor Create; destructor Destroy; override; property Kind: TDatePickerShowMode write SetShowMode; property DateTime: TDateTime read GetDateTime write SetDateTime; property MinDate: TDate index 1 write SetDateTimeConstraints; property MaxDate: TDate index 2 write SetDateTimeConstraints; property OnDateChanged: TOnDateChanged read FOnDateChanged write FOnDateChanged; end; IListBoxDialogActions = interface (NSObject) ['{0BA0DD09-C216-44A6-99AA-5F139F936557}'] procedure Cancel; cdecl; procedure Done; cdecl; procedure Hidden; cdecl; procedure StartChangeDeviceOrientation(notification: Pointer); cdecl; end; TPickerDelegate = class; TPickerDataSource = class; { Native animated popup with 2 buttons (Done, Close) and Custom picker } TListBoxPopupDialog = class (TPopupDialog) private FOnValueChanged: TOnValueChanged; procedure SetValues(const AValues: TStrings); procedure DoValueChanged; procedure SetItemIndex(const Value: Integer); protected FValues: NSMutableArray; FListBoxPicker: UIPickerView; FDelegate: TPickerDelegate; FDataSource: TPickerDataSource; procedure DoDone; override; { TOCLocal } function GetObjectiveCClass: PTypeInfo; override; public constructor Create; destructor Destroy; override; property Values: TStrings write SetValues; property ItemIndex: Integer write SetItemIndex; property OnValueChanged: TOnValueChanged read FOnValueChanged write FOnValueChanged; end; {$REGION 'Helpers for event handling of native components'} { Class implement delegate and protocol interfaces for work with UIPickerView in |TPickerServiceiOS| } TPickerDataSource = class (TOCLocal, UIPickerViewDataSource) strict private FValues: NSArray; public { UIPickerViewDataSource } function numberOfComponentsInPickerView(pickerView: UIPickerView): NSInteger; cdecl; function pickerView(pickerView: UIPickerView; numberOfRowsInComponent: NSInteger): NSInteger; cdecl; constructor Create(const AValues: NSArray); destructor Destroy; override; property Values: NSArray read FValues write FValues; end; TPickerDelegate = class (TOCLocal, UIPickerViewDelegate) strict private FValues: NSArray; public constructor Create(const AValues: NSArray); destructor Destroy; override; { UIPickerViewDelegate } // procedure pickerView(pickerView: UIPickerView; didSelectRow: NSInteger; inComponent: NSInteger); cdecl; // function pickerView(pickerView: UIPickerView; rowHeightForComponent: NSInteger): Single; cdecl; overload; function pickerView(pickerView: UIPickerView; titleForRow: NSInteger; forComponent: NSInteger): NSString; cdecl; // function pickerView(pickerView: UIPickerView; viewForRow: NSInteger; forComponent: NSInteger; reusingView: UIView): UIView; cdecl; overload; // function pickerView(pickerView: UIPickerView; widthForComponent: NSInteger): Single; cdecl; overload; property Values: NSArray read FValues write FValues; end; {$ENDREGION} { TCocoaDateTimePicker } TCocoaDateTimePicker = class (TCustomDateTimePicker) strict private FPopupDateTimePicker: TDateTimePopupDialog; public constructor Create(const APickerService: TPickerFactoryService); override; destructor Destroy; override; procedure Show; override; procedure Hide; override; function IsShown: Boolean; override; end; { TCocoaListPicker } TCocoaListPicker = class (TCustomListPicker) strict private FPopupListPicker: TListBoxPopupDialog; public constructor Create(const APickerService: TPickerFactoryService); override; destructor Destroy; override; procedure Show; override; procedure Hide; override; function IsShown: Boolean; override; end; { Picker Service } TCocoaPickerService = class (TPickerFactoryService) protected function DoCreateDateTimePicker: TCustomDateTimePicker; override; function DoCreateListPicker: TCustomListPicker; override; end; var PickerService: TPickerFactoryService; procedure RegisterPickersService; begin PickerService := TCocoaPickerService.Create; TPlatformServices.Current.AddPlatformService(IFMXPickerService, PickerService); end; procedure UnregisterPickersService; begin TPlatformServices.Current.RemovePlatformService(IFMXPickerService); PickerService := nil; end; { TCocoaPickerSerivce } function TCocoaPickerService.DoCreateDateTimePicker: TCustomDateTimePicker; begin Result := TCocoaDateTimePicker.Create(Self); end; function TCocoaPickerService.DoCreateListPicker: TCustomListPicker; begin Result := TCocoaListPicker.Create(Self); end; { TCocoaDateTimePicker } constructor TCocoaDateTimePicker.Create(const APickerService: TPickerFactoryService); begin inherited Create(APickerService); FPopupDateTimePicker := TDateTimePopupDialog.Create; end; destructor TCocoaDateTimePicker.Destroy; begin FreeAndNil(FPopupDateTimePicker); inherited Destroy; end; procedure TCocoaDateTimePicker.Hide; begin if IsShown then FPopupDateTimePicker.Hide; end; function TCocoaDateTimePicker.IsShown: Boolean; begin Result := FPopupDateTimePicker.PickerState = TPickerState.psShowed; end; procedure TCocoaDateTimePicker.Show; begin FPopupDateTimePicker.ParentControl := Parent; FPopupDateTimePicker.Kind := ShowMode; FPopupDateTimePicker.MinDate := MinDate; FPopupDateTimePicker.MaxDate := MaxDate; FPopupDateTimePicker.DateTime := Date; FPopupDateTimePicker.OnDateChanged := OnDateChanged; FPopupDateTimePicker.OnHide := OnHide; FPopupDateTimePicker.OnShow := OnShow; FPopupDateTimePicker.Show; end; { TPopupDialog } procedure TPopupDialog.Cancel; begin DoCancel; Hide; end; constructor TPopupDialog.Create; var PickerFrame: NSRect; Buttons: NSMutableArray; begin inherited Create; //Subscribing to change orientation events DefaultNotificationCenter.addObserver(GetObjectID, sel_getUid('StartChangeDeviceOrientation:'), (NSSTR(FMXStartChangeDeviceOrientation) as ILocalObject).GetObjectID, nil); // Root view FUIContainerView := TUIView.Create; PickerFrame := GetPopupFrame; FUIContainerView.setFrame(PickerFrame); if IsPad then begin FUIPopoverContent := TUIViewController.Create; FUIPopoverContent.setView(FUIContainerView); FUIPopoverContent.setContentSizeForViewInPopover(PickerFrame.size); FUIPopoverController := TUIPopoverController.Alloc; FUIPopoverController.initWithContentViewController(FUIPopoverContent); FUIPopoverDelegate := TPopoverDelegate.Create(Self); FUIPopoverController.setDelegate(FUIPopoverDelegate.GetObjectID); end; // Toolbar FUIToolBar := TUIToolbar.Create; FUIToolBar.setBarStyle(UIBarStyleBlackOpaque); FUIToolBar.setFrame(GetToolbarFrame); FUIToolBar.setAlpha(0.8); FUIContainerView.addSubview(FUIToolBar); FUIToolBar.setAutoresizingMask(UIViewAutoresizingFlexibleWidth); Buttons := TNSMutableArray.Create; // Close Button FUICloseButton := TUIBarButtonItem.Create; FUICloseButton.setTitle(NSSTR(SPickerCancel)); FUICloseButton.setStyle(UIBarButtonItemStyleBordered); FUICloseButton.setTarget(Self.GetObjectID); FUICloseButton.setAction(sel_getUid('Cancel')); Buttons.addObject(ILocalObject(FUICloseButton).GetObjectID); // Flexible Separator FUIFlexibleSepararator := TUIBarButtonItem.Create; FUIFlexibleSepararator.initWithBarButtonSystemItem(UIBarButtonSystemItemFlexibleSpace, nil, nil); Buttons.addObject(ILocalObject(FUIFlexibleSepararator).GetObjectID); FUIDoneButton := TUIBarButtonItem.Create; FUIDoneButton.setTitle(NSSTR(SPickerDone)); FUIDoneButton.setStyle(UIBarButtonItemStyleDone); FUIDoneButton.setTarget(Self.GetObjectID); FUIDoneButton.setAction(sel_getUid('Done')); Buttons.addObject(ILocalObject(FUIDoneButton).GetObjectID); // Add button to Toolbar FUIToolBar.setItems(Buttons); end; function TPopupDialog.GetPopupFrame: NSRect; var ScreenRect: NSRect; begin ScreenRect := MainScreen.applicationFrame; if IsPad then begin Result.origin.x := 0; Result.origin.y := 0; Result.size.width := 320; Result.size.height := 260; end else begin case SharedApplication.statusBarOrientation of UIInterfaceOrientationPortrait, UIInterfaceOrientationPortraitUpsideDown: begin Result.origin.x := 0; Result.origin.y := ScreenRect.size.height - 260; Result.size.width := 320; Result.size.height := 260; end; UIInterfaceOrientationLandscapeLeft, UIInterfaceOrientationLandscapeRight: begin Result.origin.x := 0; Result.origin.y := ScreenRect.size.width - 260; Result.size.width := ScreenRect.size.height; Result.size.height := 260; end; end; end; end; destructor TPopupDialog.Destroy; begin DefaultNotificationCenter.removeObserver(GetObjectID); FUIDoneButton.release; FUIFlexibleSepararator.release; FUICloseButton.release; FUIToolBar.release; FUIContainerView.release; if IsPad then begin FUIPopoverContent.release; FUIPopoverController.release; FUIPopoverDelegate.Free; end; inherited Destroy; end; procedure TPopupDialog.DoCancel; begin // Nothing end; procedure TPopupDialog.DoDone; begin // Nothing end; procedure TPopupDialog.DoHide; begin FPickerState := TPickerState.psHidden; if Assigned(FOnHide) then FOnHide(FParentControl); if Assigned(Screen.ActiveForm) then Screen.ActiveForm.Focused := nil; end; procedure TPopupDialog.Done; begin DoDone; Hide; end; procedure TPopupDialog.DoPopoverDismiss; begin DoHide; end; procedure TPopupDialog.DoShow; begin FPickerState := TPickerState.psShowed; if Assigned(FOnShow) then FOnShow(FParentControl); end; function TPopupDialog.GetToolbarFrame: NSRect; begin Result := GetPopupFrame; Result.origin.x := 0; Result.origin.y := 0; Result.size.height := 44; end; function TPopupDialog.GetContentFrame: NSRect; var ToolBarFrame: NSRect; begin Result := GetPopupFrame; ToolBarFrame := GetToolbarFrame; Result.origin.x := 0; Result.origin.y := ToolBarFrame.origin.y + ToolBarFrame.size.height; Result.size.height := Result.size.height - ToolBarFrame.size.height; end; function TPopupDialog.GetObjectiveCClass: PTypeInfo; begin Result := TypeInfo(IDialogActions); end; procedure TPopupDialog.Hidden; begin if not IsPad and (FPickerState = TPickerState.psHidden) then FUIContainerView.removeFromSuperview; end; procedure TPopupDialog.Hide; var EndFrame: NSRect; begin if not Assigned(FUIContainerView.superview) then Exit; if IsPad then FUIPopoverController.dismissPopoverAnimated(True) else begin EndFrame := GetPopupFrame; EndFrame.origin.y := EndFrame.origin.y + EndFrame.size.height; // Start Slide down Animation TUIView.OCClass.beginAnimations(nil, nil); try TUIView.OCClass.setAnimationDuration(0.3); FUIContainerView.setFrame(EndFrame); TUIView.OCClass.setAnimationDelegate(Self.GetObjectID); TUIView.OCClass.setAnimationDidStopSelector(sel_getUid('Hidden')) finally TUIView.OCClass.commitAnimations; end; end; DoHide; end; procedure TPopupDialog.Show; var StartFrame: CGRect; EndFrame: NSRect; AbsolutePos: TPointF; begin if IsPad then begin AbsolutePos := FParentControl.LocalToAbsolute(PointF(0, 0)); FUIPopoverController.presentPopoverFromRect( CGRectMake(AbsolutePos.X, AbsolutePos.Y, FParentControl.Width, FParentControl.Height) , SharedApplication.keyWindow.rootViewController.view, UIPopoverArrowDirectionAny, True); end else begin SharedApplication.keyWindow.rootViewController.view.addSubview(FUIContainerView); // Setting animation StartFrame := GetPopupFrame; EndFrame := StartFrame; StartFrame.origin.y := StartFrame.origin.y + StartFrame.size.height; FUIContainerView.setFrame(StartFrame); // Start Animation TUIView.OCClass.beginAnimations(nil, nil); try TUIView.OCClass.setAnimationDuration(0.3); FUIContainerView.setFrame(EndFrame); finally TUIView.OCClass.commitAnimations; end; end; DoShow; end; procedure TPopupDialog.StartChangeDeviceOrientation(notification: Pointer); begin FUIContainerView.setFrame(GetPopupFrame); end; { TCocoaListPicker } constructor TCocoaListPicker.Create(const APickerService: TPickerFactoryService); begin inherited Create(APickerService); FPopupListPicker := TListBoxPopupDialog.Create; end; destructor TCocoaListPicker.Destroy; begin FreeAndNil(FPopupListPicker); inherited Destroy; end; procedure TCocoaListPicker.Hide; begin if IsShown then FPopupListPicker.Hide; end; function TCocoaListPicker.IsShown: Boolean; begin Result := FPopupListPicker.PickerState = TPickerState.psShowed; end; procedure TCocoaListPicker.Show; begin if Values.Count = 0 then Exit; FPopupListPicker.ParentControl := Parent; FPopupListPicker.Values := Values; FPopupListPicker.ItemIndex := ItemIndex; FPopupListPicker.OnValueChanged := OnValueChanged; FPopupListPicker.OnHide := OnHide; FPopupListPicker.OnShow := OnShow; FPopupListPicker.Show; end; { TDateTimePopupDialog } constructor TDateTimePopupDialog.Create; var PickerView: UIPickerView; begin inherited Create; // Date picker FDateTimePicker := TUIDatePicker.Alloc; FDateTimePicker.initWithFrame(GetContentFrame); FDateTimePicker.setFrame(GetContentFrame); FDateTimePicker.setTimeZone(TNSTimeZone.Wrap(TNSTimeZone.OCClass.timeZoneForSecondsFromGMT(0))); // Date picker isn't expanded on width by default like as UIPickerView. // Therefore that it was aligned it is necessary to receive UIPickerView // from child's views. if FDateTimePicker.subviews.count > 0 then begin PickerView := TUIPickerView.Wrap(FDateTimePicker.subviews.objectAtIndex(0)); PickerView.setAutoresizingMask(UIViewAutoresizingFlexibleWidth or UIViewAutoresizingFlexibleLeftMargin or UIViewAutoresizingFlexibleRightMargin); end; FDateTimePicker.setAutoresizingMask(UIViewAutoresizingFlexibleWidth or UIViewAutoresizingFlexibleLeftMargin or UIViewAutoresizingFlexibleRightMargin); FUIContainerView.addSubview(FDateTimePicker); end; destructor TDateTimePopupDialog.Destroy; begin FDateTimePicker.release; inherited Destroy; end; procedure TDateTimePopupDialog.DoDateChanged; begin if Assigned(FOnDateChanged) then FOnDateChanged(FParentControl, DateTime); end; procedure TDateTimePopupDialog.DoDone; begin DoDateChanged; end; function TDateTimePopupDialog.GetDateTime: TDateTime; function TrimSeconds(const ADateTime: TDateTime): TDateTime; var Hour: Word; Min: Word; Sec: Word; MSec: Word; begin DecodeTime(ADateTime, Hour, Min, Sec, MSec); Result := DateOf(ADateTime) + EncodeTime(Hour, Min, 0, 0); end; var DateTimeWithoutSec: TDateTime; begin // Native ios UIDatePicker doesn't allow users to set second. // We must to trim second from datetime DateTimeWithoutSec := TrimSeconds(NSDateToDateTime(FDateTimePicker.date)); Result := TrimSeconds(DateTimeWithoutSec); end; function TDateTimePopupDialog.GetObjectiveCClass: PTypeInfo; begin Result := TypeInfo(IDateTimeDialogActions); end; procedure TDateTimePopupDialog.SetDateTime(const Value: TDateTime); begin // Bug in using NSDate in UIDatePicker. When we set time 10:00:00, // UIDatePicker shows 9:59:59, but UIDatePicker.date.description shows 10:00:00 // So we need to add 0.1 sec for it FDateTimePicker.setDate(DateTimeToNSDate(Value + 0.1 / SecsPerDay)); end; procedure TDateTimePopupDialog.SetDateTimeConstraints(const Index: Integer; const Value: TDate); begin case Index of 1: begin if not SameValue(Value, 0.0) then FDateTimePicker.setMinimumDate(DateTimeToNSDate(Value)) else FDateTimePicker.setMinimumDate(nil); end; 2: begin if not SameValue(Value, 0.0) then FDateTimePicker.setMaximumDate(DateTimeToNSDate(Value)) else FDateTimePicker.setMaximumDate(nil); end; end; end; procedure TDateTimePopupDialog.SetShowMode(const Value: TDatePickerShowMode); var DatePickerMode: UIDatePickerMode; begin case Value of psmDate: DatePickerMode := UIDatePickerModeDate; psmTime: DatePickerMode := UIDatePickerModeTime; psmDateTime: DatePickerMode := UIDatePickerModeDateAndTime; else DatePickerMode := UIDatePickerModeDateAndTime; end; FDateTimePicker.setDatePickerMode(DatePickerMode); end; { TListBoxPopupDialog } constructor TListBoxPopupDialog.Create; begin inherited Create; FValues := TNSMutableArray.Create; // ListBox picker FListBoxPicker := TUIPickerView.Create; FListBoxPicker.setFrame(GetContentFrame); FListBoxPicker.setShowsSelectionIndicator(True); FListBoxPicker.setAutoresizingMask(UIViewAutoresizingFlexibleWidth); FDelegate := TPickerDelegate.Create(FValues); FDataSource := TPickerDataSource.Create(FValues); FListBoxPicker.setDataSource(FDataSource.GetObjectID); FListBoxPicker.setDelegate(FDelegate.GetObjectID); FUIContainerView.addSubview(FListBoxPicker); end; destructor TListBoxPopupDialog.Destroy; begin FValues.release; FListBoxPicker.release; inherited Destroy; end; procedure TListBoxPopupDialog.DoDone; begin DoValueChanged; end; procedure TListBoxPopupDialog.DoValueChanged; begin if Assigned(FOnValueChanged) and (FValues.count > 0) then FOnValueChanged(FParentControl, FListBoxPicker.selectedRowInComponent(0)); end; function TListBoxPopupDialog.GetObjectiveCClass: PTypeInfo; begin Result := TypeInfo(IListBoxDialogActions); end; procedure TListBoxPopupDialog.SetItemIndex(const Value: Integer); begin FListBoxPicker.selectRow(Value, 0, False); end; procedure TListBoxPopupDialog.SetValues(const AValues: TStrings); var I: Integer; OCValue: NSString; begin Assert(Assigned(AValues), 'AValue can not be nil'); FValues.removeAllObjects; for I := 0 to AValues.Count - 1 do begin if AValues[I].IsEmpty then OCValue := TNSString.Create else OCValue := NSStr(AValues[I]); FValues.addObject((OCValue as ILocalObject).GetObjectID) end; FDelegate.Values := FValues; FDataSource.Values := FValues; FListBoxPicker.reloadAllComponents; end; { TPickerDataSource } constructor TPickerDataSource.Create(const AValues: NSArray); begin inherited Create; FValues := AValues; end; destructor TPickerDataSource.Destroy; begin FValues := nil; inherited Destroy; end; function TPickerDataSource.numberOfComponentsInPickerView( pickerView: UIPickerView): NSInteger; begin Result := 1; end; function TPickerDataSource.pickerView(pickerView: UIPickerView; numberOfRowsInComponent: NSInteger): NSInteger; begin Result := FValues.count; end; { TPickerDelegate } constructor TPickerDelegate.Create(const AValues: NSArray); begin inherited Create; FValues := AValues; end; destructor TPickerDelegate.Destroy; begin FValues := nil; inherited; end; function TPickerDelegate.pickerView(pickerView: UIPickerView; titleForRow, forComponent: NSInteger): NSString; begin Result := TNSString.Wrap(FValues.objectAtIndex(titleForRow)); end; { TPopoverDelegate } constructor TPopoverDelegate.Create(const APopupDialog: TPopupDialog); begin inherited Create; FPopupDialog := APopupDialog; end; procedure TPopoverDelegate.popoverControllerDidDismissPopover( popoverController: UIPopoverController); begin FPopupDialog.DoPopoverDismiss; end; function TPopoverDelegate.popoverControllerShouldDismissPopover( popoverController: UIPopoverController): Boolean; begin Result := True; end; end.
unit AutoMapper; interface uses Spring.Collections; type TAutoMapper<T : class, constructor> = class private class procedure DoMapping(const Entity : TObject; const Target : TObject; Configuration : IDictionary<string, string>); public class function Map(const Entity : TObject; Configuration : IDictionary<string, string> = nil): T; overload; class procedure Map(const Source : TObject; const Target : T; Configuration : IDictionary<string, string> = nil); overload; end; AutoMapper4D = class helper for TObject function Adapt<T: class, constructor>: T; overload; procedure Adapt<T: class, constructor>(const DestObject: T); overload; end; implementation uses System.SysUtils, System.Rtti, Spring.Reflection, uFuzzyStringMatch; { TAutoMapper<T> } class procedure TAutoMapper<T>.DoMapping(const Entity: TObject; const Target : TObject; Configuration : IDictionary<string, string>); var TempPropName : string; begin TType.GetType<T>.Properties.ForEach( procedure(const AProp : TRttiProperty) var aType : TRttiType; MappedProp : string; begin if not AProp.PropertyType.IsInstance then begin aType := TType.FindType(Entity.ClassName); if not Assigned(Configuration) then begin if AType.HasProperty(AProp.Name) then AProp.SetValue(Target, aType.GetProperty(AProp.Name).GetValue(Entity)) else //do fuzzy match begin aType.Properties.ForEach( procedure(const Prop : TRttiProperty) begin if TFuzzyStringMatch.StringSimilarityRatio(AProp.Name, Prop.Name, True) >= 0.8 then begin AProp.SetValue(Target, aType.GetProperty(Prop.Name).GetValue(Entity)); end; end); end; end else begin if Configuration.TryGetValue(AProp.Name, MappedProp) then begin if AType.HasProperty(MappedProp) then AProp.SetValue(Target, aType.GetProperty(MappedProp).GetValue(Entity)) else raise Exception.CreateFmt('Invalid property mapping. Source: %s; Target: %s', [MappedProp, AProp.Name]); end; end; end; end); end; class function TAutoMapper<T>.Map(const Entity: TObject; Configuration: IDictionary<string, string>): T; var Obj : T; begin Obj := T.Create; DoMapping(Entity, Obj, Configuration); Result := Obj; end; class procedure TAutoMapper<T>.Map(const Source: TObject; const Target: T; Configuration: IDictionary<string, string>); begin DoMapping(Source, Target, Configuration); end; { AutoMapper4D } function AutoMapper4D.Adapt<T>: T; begin Result := T.Create; TAutoMapper<T>.Map(Self, Result); end; procedure AutoMapper4D.Adapt<T>(const DestObject: T); begin TAutoMapper<T>.Map(Self, DestObject); end; end.
unit pMpqEditor; interface uses Windows, pMpqAPI, Classes, SysUtils, Forms, dialogs; type TMpqListDone = procedure(List:TStringList) of object; TMpq = class(TObject) private procedure OpenMpq; procedure CloseMpq; public MpqName:String; MpqFile: MpqHandle; constructor Create(FileName:String); function Read(FileName:String; Strings: TStrings):Boolean; function Write(FileName:String; Strings: TStrings):Boolean; function FileExists(FileName:String;Reopen:Boolean):Boolean; function ExportFile(FileInMPQ,RealFile:String):Boolean; end; TMpqListfiles = class(TThread) private List:TStringList; public Mpq:TMpq; OnDone: TMpqListDone; protected procedure Execute; override; end; implementation procedure TMpqListfiles.Execute; var listfile:TStringList; i,max:Integer; begin List:=TStringList.Create; Mpq.OpenMpq; if Mpq.FileExists('(listfile)', false) then Mpq.Read('(listfile)', List) else begin listfile:=TStringList.Create; listfile.LoadFromFile(ExtractFilePath(Application.ExeName)+'mpqlist.txt'); Max := listfile.Count-1; for i := 0 to Max do if Mpq.FileExists(listfile[i], false) then List.Add(listfile[i]); listfile.Free; end; OnDone(List); Mpq.CloseMpq; FreeOnTerminate := True; Terminate; end; function TMpq.FileExists(FileName:String;Reopen:Boolean):Boolean; var FileHandle: MpqHandle; begin Result := False; if Reopen then OpenMpq; if SFileOpenFileEx(MpqFile,PChar(FileName),0,@FileHandle) then Result := True; SFileCloseFile(FileHandle); if Reopen then CloseMpq; end; procedure TMpq.OpenMpq; begin if not SFileOpenArchive(PChar(MpqName),0,0,@MpqFile) then begin SFileCloseArchive(MpqFile); raise Exception.Create('This is not a valid Mpq archive!'); end; end; procedure TMpq.CloseMpq; begin SFileCloseArchive(MpqFile); end; function TMpq.ExportFile(FileInMPQ,RealFile:String):Boolean; const iBufferSize = 65536; var msStream: TFileStream; pFileName: PChar; FileHandle: MpqHandle; ptBuffer: Pointer; dwBytesRead: dWord; begin Result := True; pFileName := PChar(FileInMPQ); if not SysUtils.FileExists(RealFile) then msStream := TFileStream.Create(RealFile, fmOpenWrite); GetMem(ptBuffer,iBufferSize); if not SFileOpenFileEx(MpqFile,pFileName,0,@FileHandle) then begin SFileCloseFile(FileHandle); CloseMpq; raise Exception.Create('File not found!'); Exit; end; repeat SFileReadFile(FileHandle,ptBuffer,iBufferSize,@dwBytesRead,nil); msStream.Write(ptBuffer^,dwBytesRead); until dwBytesRead < iBufferSize; SFileCloseFile(FileHandle); FreeMem(ptBuffer); CloseMpq; msStream.Free; end; function TMpq.Write(FileName:String; Strings: TStrings):Boolean; var msStream: TMemoryStream; begin Result := true; // Strings.Text ShowMessage(FileName);ShowMessage(MpqName); msStream := TMemoryStream.Create; Strings.SaveToStream(msStream); MpqFile := MPQOpenArchiveForUpdate(PChar(MpqName),MOAU_OPEN_EXISTING,0); try MPQDeleteFile(MpqFile,'(attributes)'); MPQDeleteFile(MpqFile, PChar(FileName)); MpqAddFileFromBufferEx(MpqFile, msStream.Memory, msStream.Size, PChar(FileName), MAFA_COMPRESS or MAFA_REPLACE_EXISTING, MAFA_COMPRESS_DEFLATE, Z_BEST_COMPRESSION); MpqCompactArchive(MpqFile); except on E:Exception do Result := false; end; //try MPQCloseUpdatedArchive(MpqFile,0); msStream.Free; end; function TMpq.Read(FileName:String; Strings: TStrings):Boolean; const iBufferSize = 65536; var FileHandle: MpqHandle; ptBuffer: Pointer; dwBytesRead: dWord; ssStream: TStringStream; begin try Result := False; OpenMpq; GetMem(ptBuffer,iBufferSize); if not SFileOpenFileEx(MpqFile,PChar(FileName),0,@FileHandle) then begin SFileCloseFile(FileHandle); CloseMpq; raise Exception.Create('File not found!'); Exit; end; ssStream := TStringStream.Create(''); repeat SFileReadFile(FileHandle,ptBuffer,iBufferSize,@dwBytesRead,nil); ssStream.Write(ptBuffer^,dwBytesRead); until dwBytesRead < iBufferSize; SFileCloseFile(FileHandle); FreeMem(ptBuffer); CloseMpq; Strings.Clear; Strings.Text := ssStream.DataString; ssStream.Free; except on E:Exception do begin ssStream.Free; CloseMpq; raise Exception.Create('Load Error'); end; end; end; constructor TMpq.Create(FileName:String); begin inherited Create; MpqName := FileName; if not SFileOpenArchive(PChar(MpqName),0,0,@MpqFile) then raise Exception.Create('This is not a valid Mpq archive!'); SFileCloseArchive(MpqFile); end; end.
(* Glenn Kentwell 97060941 Computer Science 1 Semester 1 1997 Tutorial 6 (Monday 5-6pm) Program to calculate the deposit required for a loan. *) program CalcDeposit; uses Crt; const MidAddOn = 1250; { $1250 is added to deposit if $25,000 < loan < $50000} HiAddOn = 5000; { $5000 is added to deposit if $50,000 < loan < $100,000} LowPercent = 0.05; { deposit is 5% of loan amount if loan < $25,000 } MidPercent = 0.10; { deposit is 10% if between $25,000 and $50,000 } HiPercent = 0.25; { deposit is 25% if between $50,000 and $100,000 } LowBracket = 25000; { loans less than $25,000 } MidBracket = 50000; { loans less than $50,000 } HiBracket = 100000; { loans less than $100,000 } InvalidLoan = -1; { variable Deposit is given this value if loan > 100,000} LoanPrompt = 'Amount of loan : '; DepositAnswer = 'The deposit required is $'; AnotherQuery = 'Calculate another deposit? [Y/n] '; LoanTooHigh = 'Sorry, I can only calculate deposits for loans $100,000 or less'; var LoanAmount, Deposit: longint; procedure CalculateDeposit; (* This procedure calculates the deposit required depending on the size of the loan requested. *) begin If LoanAmount < LowBracket then Deposit:= Round(LoanAmount * LowPercent) else If (LoanAmount >= LowBracket) and (LoanAmount < MidBracket) then Deposit:= Round((LoanAmount - LowBracket) * MidPercent) + MidAddOn else If (LoanAmount >= MidBracket) and (LoanAmount <= HiBracket) then Deposit:= Round((LoanAmount - MidBracket) * HiPercent) + HiAddOn else If LoanAmount > HiBracket then Deposit:= InvalidLoan; end; procedure GiveAnswer; (* This procedure writes the amount of the deposit to the screen if the variable Deposit is not -1, ie the loan was more than $100,000 *) begin if Deposit <> InvalidLoan then Write(DepositAnswer, Deposit) else Write(LoanTooHigh); end; function Loans: Boolean; (* This function prompts the user for a loan amount, calls the procedures CalculateDeposit and GiveAnswer, then asks the user if they want to calculate another deposit. If the user presses the 'n' key on the keyboard, this function is assigned the value False, otherwise it is given the value True. *) var Ch: char; begin Write(LoanPrompt); Readln(LoanAmount); CalculateDeposit; GiveAnswer; Writeln; Write(AnotherQuery); Ch:= ReadKey; if UpCase(Ch) <> 'N' then Loans:= True else Loans:= False; Writeln; end; (* The main program part clears the screen, then calls the function Loans. Loans is called repeatedly until it becomes False, then the program ends. *) begin ClrScr; While Loans do Loans; end.
unit uRecipeUSZipCode; interface uses Classes, RegularExpressions, uDemo, uRecipe; type TRecipeUSZipCode = class(TRecipe) public class function Description: String; override; function Pattern: String; override; function Options: TRegexOptions; override; procedure GetInputs(const Inputs: TStrings); override; end; implementation { TRecipeUSZipCode } class function TRecipeUSZipCode.Description: String; begin Result := 'Recipes\US ZIP (5 or 5+4)'; end; {$REGION} /// <B>Source</B>: http://www.regexlib.com/REDetails.aspx?regexp_id=74 /// <B>Author</B>: Blake Facey /// /// Matches standard 5 digit US Zip Codes, or the US ZIP + 4 Standard. /// /// <B>Notes</B>: /// -Replaced "beginning of string (^)" and "end of string ($)" with /// "word boundaries (\b)" /// -The "roExplicitCapture" options is used to prevent capturing the second /// 4-digit code as a capturing group. function TRecipeUSZipCode.Pattern: String; begin Result := '\b\d{5}(-\d{4})?\b'; end; function TRecipeUSZipCode.Options: TRegexOptions; begin Result := [roExplicitCapture]; end; procedure TRecipeUSZipCode.GetInputs(const Inputs: TStrings); begin Inputs.Add('55555-5555'); Inputs.Add('34564-3342'); Inputs.Add('90210'); Inputs.Add('434454444'); Inputs.Add('645-32-2345'); Inputs.Add('abc'); Inputs.Add('Lorem ipsum dolor sit 55555-5555 amet, consectetur adipisicing'); Inputs.Add('34564-3342 elit, sed do 90210 eiusmod tempor incididunt ut'); Inputs.Add('labore et dolore 434454444 magna aliqua. Ut enim ad minim'); Inputs.Add('veniam, quis 645-32-2345 nostrud exercitation ullamco laboris'); Inputs.Add('nisi ut aliquip ex ea commodo consequat.'); end; {$ENDREGION} initialization RegisterDemo(TRecipeUSZipCode); end.
unit uFrmAutoForm; interface uses SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmBaseAutoForm, FMTBcd, DB, DBClient, Provider, SqlExpr, StdCtrls, Buttons, DBCtrls, Grids, DBGrids, ExtCtrls, SimpleDS, ComCtrls, ToolWin, ImgList, ActnList, WideStrings, DBXFirebird, uDM, System.ImageList, System.Actions; const MARGIN = 10; type TDefaultValue = record FieldName: string; DefaultValue: Variant; end; TTipoFloat = (tfFloat, tfBCD, tfFMTBCD, tfCurrency, tfExtended, tfSingle); type TfrmAutoForm = class(TfrmBaseAutoForm) sdsMetaData: TSimpleDataSet; sqAutoForm: TSQLDataSet; dspAutoForm: TDataSetProvider; cdsAutoForm: TClientDataSet; procedure FormShow(Sender: TObject); procedure cdsAutoFormNewRecord(DataSet: TDataSet); procedure FormCreate(Sender: TObject); procedure Ac_ConfirmarExecute(Sender: TObject); private { Private declarations } FTableDisplayName: string; FKeyField: string; FCurHeight: Integer; FCurWidth: Integer; FMaxHeight: Integer; FDefaultValues: array of TDefaultValue; procedure AddKeyField(const KeyField: string; const ToDataSet: TDataSet); procedure SetUpWithReadMetaData(const Field: TField); procedure AddControl(const Control: TControl; const DisplayLabel: string); function InternalAddStringField(const FieldName, DisplayFieldName: string; DisplayWidth: Integer; const ToDataSet: TDataSet; Mascara: String = ''; SetFcous: Boolean = False): TControl; function InternalAddDateField(const FieldName, DisplayFieldName: string; const ToDataSet: TDataSet): TControl; function InternalAddFloatField(const FieldName, DisplayFieldName: string; DisplayWidth: Integer; const ToDataSet: TDataSet; TipoFloat: TTipoFloat; Currency: Boolean = False): TControl; function InternalAddIntegerField(const FieldName, DisplayFieldName: string; DisplayWidth: Integer; const ToDataSet: TDataSet): TControl; function InternalAddMemoField(const FieldName, DisplayFieldName: string; DisplayWidth, DisplayHeight: Integer; const ToDataSet: TDataSet; StringField: Boolean = False): TControl; function InternalAddTimeField(const FieldName, DisplayFieldName: string; const ToDataSet: TDataSet): TControl; function InternalAddLookupField(const FieldName, DisplayFieldName, KeyField, ListField, SQL: string; DisplayWidth: Integer; const ToDataSet: TDataSet): TControl;overload; function InternalAddLookupField(const FieldName, DisplayFieldName, KeyField, ListField, SQL: string; DisplayWidth: Integer; const ToDataSet: TDataSet;Dominio: Boolean): TControl;overload; function CreateStringControl(const Field: TField; SetFcous: Boolean = False): TControl; function CreateDateControl(const Field: TField): TControl; function CreateFloatControl(const Field: TField): TControl; function CreateIntegerControl(const Field: TField): TControl; function CreateMemoControl(const Field: TField; DisplayHeight: Integer): TControl; function CreateTimeControl(const Field: TField): TControl; function CreateComboControl(const Sql, DisplayFieldName: string; DisplayWidth: Integer): TControl; function CreateLookupControl(const Field: TField; const KeyField, ListField, SQL: string): TControl; public { Public declarations } constructor Create(AOwner: TComponent; const TableName, TableDisplayName, KeyField, Filter: string); reintroduce; overload; constructor Create(AOwner: TComponent; const SQL, TableDisplayName, KeyField: string); reintroduce; overload; function GetDisplayName: string;override; function GetKeyField: string;override; procedure SetDefaultValue(const FieldName: string; const Value: Variant); procedure SetLookUpValue(const KeyField: string; const KeyValue: Variant); function AddStringField(const FieldName, DisplayFieldName: string; DisplayWidth: Integer; Mascara: String = ''; SetFocus: Boolean = False): TControl; function AddIntegerField(const FieldName, DisplayFieldName: string; DisplayWidth: Integer): TControl; function AddFloatField(const FieldName, DisplayFieldName: string; DisplayWidth: Integer; TipoFloat: TTipoFloat; Currency: Boolean = False): TControl; function AddMemoField(const FieldName, DisplayFieldName: string; DisplayWidth, DisplayHeight: Integer): TControl;overload; function AddMemoField(const FieldName, DisplayFieldName: string; DisplayWidth, DisplayHeight: Integer; StringField: Boolean): TControl;overload; function AddDateField(const FieldName, DisplayFieldName: string): TControl; function AddTimeField(const FieldName, DisplayFieldName: string): TControl; function AddComboBox(const Sql, DisplayFieldName: string; DisplayWidth: Integer): TControl; function AddLookupField(const FieldName, DisplayFieldName, KeyField, ListField, SQL: string; DisplayWidth: Integer): TControl; overload; function AddLookupField(const FieldName, DisplayFieldName, KeyField, ListField, SQL: string; DisplayWidth: Integer; Dominio:Boolean) :TControl; overload; function AddSpace(DisplayWidth: Integer): TControl; end; var frmAutoForm: TfrmAutoForm; implementation {$R *.dfm} { TfrmAutoForm } constructor TfrmAutoForm.Create(AOwner: TComponent; const TableName, TableDisplayName, KeyField, Filter: string); var ASql: string; begin ASql := 'select * from ' + TableName; if Filter <> '' then ASql := ASql + ' where ' + Filter; Self.Create(AOwner, ASql, TableDisplayName, KeyField); end; constructor TfrmAutoForm.Create(AOwner: TComponent; const SQL, TableDisplayName, KeyField: string); begin inherited Create(AOwner); FKeyField := KeyField; FTableDisplayName := TableDisplayName; sqAutoForm.CommandText := SQL; sdsMetaData.DataSet.CommandText := SQL; sdsMetaData.Open; AddKeyField(KeyField, sqAutoForm); AddKeyField(KeyField, cdsAutoForm); FCurHeight := MARGIN; FCurWidth := MARGIN; FMaxHeight := MARGIN; end; function TfrmAutoForm.CreateComboControl(const Sql, DisplayFieldName: string; DisplayWidth: Integer): TControl; var AControl: TComboBox; ASql: TSimpleDataSet; begin AControl := TComboBox.Create(Self); AControl.Width := DisplayWidth * 6; AControl.BevelKind := bkFlat; AControl.Height := 24; ASql := TSimpleDataSet.Create(Self); { TODO 5 -oRodrigo -cMelhorias : Chamar Singleton Aqui } ASql.Connection := DM.DBConn; ASql.DataSet.CommandText := Sql; ASql.Open; ASql.First; AControl.Parent := pnlControls; while not ASql.Eof do begin AControl.Items.Add(ASql.Fields[0].AsString); ASql.Next; end; AddControl(AControl, DisplayFieldName); Result := AControl; end; function TfrmAutoForm.GetKeyField: string; begin Result := FKeyField; end; function TfrmAutoForm.GetDisplayName: string; begin Result := FTableDisplayName; end; procedure TfrmAutoForm.AddKeyField(const KeyField: string; const ToDataSet: TDataSet); var AddedKeyField: TField; begin AddedKeyField := TIntegerField.Create(ToDataSet); AddedKeyField.FieldName := KeyField; AddedKeyField.Visible := False; SetUpWithReadMetaData(AddedKeyField); AddedKeyField.DataSet := ToDataSet; end; function TfrmAutoForm.AddLookupField(const FieldName, DisplayFieldName, KeyField, ListField, SQL: string; DisplayWidth: Integer; Dominio: Boolean): TControl; begin InternalAddLookupField(FieldName, DisplayFieldName, KeyField, ListField, SQL, DisplayWidth, sqAutoForm, Dominio); Result := InternalAddLookupField(FieldName, DisplayFieldName, KeyField, ListField, SQL, DisplayWidth, cdsAutoForm, Dominio); end; function TfrmAutoForm.AddMemoField(const FieldName, DisplayFieldName: string; DisplayWidth, DisplayHeight: Integer; StringField: Boolean): TControl; begin InternalAddMemoField(FieldName, DisplayFieldName, DisplayWidth, DisplayHeight, sqAutoForm, StringField); Result := InternalAddMemoField(FieldName, DisplayFieldName, DisplayWidth, DisplayHeight, cdsAutoForm, StringField); end; procedure TfrmAutoForm.SetUpWithReadMetaData(const Field: TField); begin Field.Size := sdsMetadata.FieldByName(Field.FieldName).Size; Field.Required := sdsMetadata.FieldByName(Field.FieldName).Required; if Field.FieldName = FKeyField then begin Field.ProviderFlags := [pfInWhere, pfInUpdate, pfInKey]; //Field.Required := False; end else Field.ProviderFlags := [pfInUpdate]; end; function TfrmAutoForm.AddSpace(DisplayWidth: Integer): TControl; var AControl: TEdit; begin AControl := TEdit.Create(Self); AControl.Visible := False; AControl.Width := DisplayWidth * 6; AddControl(AControl, ''); Result := AControl; end; function TfrmAutoForm.AddStringField(const FieldName, DisplayFieldName: string; DisplayWidth: Integer; Mascara: String = ''; SetFocus: Boolean = False): TControl; begin InternalAddStringField(FieldName, DisplayFieldName, DisplayWidth, sqAutoForm); Result := InternalAddStringField(FieldName, DisplayFieldName, DisplayWidth, cdsAutoForm, Mascara, SetFocus); end; function TfrmAutoForm.InternalAddStringField(const FieldName, DisplayFieldName: string; DisplayWidth: Integer; const ToDataSet: TDataSet; Mascara: String = ''; SetFcous: Boolean = False): TControl; var AddedKeyField: TField; begin Result := nil; AddedKeyField := TStringField.Create(ToDataSet); AddedKeyField.FieldName := FieldName; AddedKeyField.DisplayLabel := DisplayFieldName; AddedKeyField.DisplayWidth := DisplayWidth; SetUpWithReadMetaData(AddedKeyField); AddedKeyField.DataSet := ToDataSet; if ToDataSet = cdsAutoForm then begin Result := CreateStringControl(AddedKeyField,SetFcous); AddedKeyField.EditMask := Mascara; end; end; function TfrmAutoForm.CreateStringControl(const Field: TField; SetFcous: Boolean = False): TControl; var AControl: TDBEdit; begin AControl := nil; AControl := TDBEdit.Create(Self); AControl.Width := Field.DisplayWidth * 6; AControl.DataSource := dsAutoForm; AControl.DataField := Field.FieldName; AControl.BevelKind := bkFlat; AControl.BorderStyle := bsNone; AControl.Height := 24; if SetFcous then AControl.Tag := 99; AddControl(AControl, Field.DisplayLabel); Result := AControl; end; procedure TfrmAutoForm.Ac_ConfirmarExecute(Sender: TObject); var I: Integer; begin inherited; for I := 0 to cdsAutoForm.FieldCount - 1 do begin if cdsAutoForm.Fields[I].FieldKind = fkLookup then begin cdsAutoForm.Fields[I].LookupDataSet.Refresh; end; end; end; function TfrmAutoForm.AddComboBox(const Sql, DisplayFieldName: string; DisplayWidth: Integer): TControl; begin Result := CreateComboControl(Sql,DisplayFieldName,DisplayWidth); end; procedure TfrmAutoForm.AddControl(const Control: TControl; const DisplayLabel: string); const BETWEEN_CONTROL_AND_LABEL = 3; BETWEEN_CONTROLS_Y = 8; BETWEEN_CONTROLS_X = 10; var ALabel: TLabel; ATempMax: Integer; begin ALabel := TLabel.Create(Self); ALabel.Caption := DisplayLabel; if Control.Width < ALabel.Width then Control.Width := ALabel.Width; if (FCurWidth + Control.Width + MARGIN) > pnlControls.Width then begin FCurHeight := FMaxHeight - MARGIN + BETWEEN_CONTROLS_Y; FCurWidth := MARGIN; end; ALabel.Parent := pnlControls; ALabel.Left := FCurWidth; ALabel.Top := FCurHeight; Control.Parent := pnlControls; Control.Left := FCurWidth; if DisplayLabel = '' then begin Control.Top := FCurHeight; ALabel.Height := 0; end else Control.Top := FCurHeight + ALabel.Height + BETWEEN_CONTROL_AND_LABEL; ATempMax := Control.Top + Control.Height + MARGIN; if ATempMax > FMaxHeight then FMaxHeight := ATempMax; Inc(FCurWidth, Control.Width + BETWEEN_CONTROLS_X); end; function TfrmAutoForm.AddIntegerField(const FieldName, DisplayFieldName: string; DisplayWidth: Integer): TControl; begin InternalAddIntegerField(FieldName, DisplayFieldName, DisplayWidth, sqAutoForm); Result := InternalAddIntegerField(FieldName, DisplayFieldName, DisplayWidth, cdsAutoForm); end; function TfrmAutoForm.AddFloatField(const FieldName, DisplayFieldName: string; DisplayWidth: Integer; TipoFloat: TTipoFloat; Currency: Boolean = False): TControl; begin InternalAddFloatField(FieldName, DisplayFieldName, DisplayWidth, sqAutoForm, TipoFloat); Result := InternalAddFloatField(FieldName, DisplayFieldName, DisplayWidth, cdsAutoForm, TipoFloat, Currency); end; function TfrmAutoForm.AddMemoField(const FieldName, DisplayFieldName: string; DisplayWidth, DisplayHeight: Integer): TControl; begin InternalAddMemoField(FieldName, DisplayFieldName, DisplayWidth, DisplayHeight, sqAutoForm); Result := InternalAddMemoField(FieldName, DisplayFieldName, DisplayWidth, DisplayHeight, cdsAutoForm); end; function TfrmAutoForm.AddDateField(const FieldName, DisplayFieldName: string): TControl; begin InternalAddDateField(FieldName, DisplayFieldName, sqAutoForm); Result := InternalAddDateField(FieldName, DisplayFieldName, cdsAutoForm); end; function TfrmAutoForm.AddTimeField(const FieldName, DisplayFieldName: string): TControl; begin InternalAddTimeField(FieldName, DisplayFieldName, sqAutoForm); Result := InternalAddTimeField(FieldName, DisplayFieldName, cdsAutoForm); end; function TfrmAutoForm.InternalAddIntegerField(const FieldName, DisplayFieldName: string; DisplayWidth: Integer; const ToDataSet: TDataSet): TControl; var AddedKeyField: TField; begin Result := nil; AddedKeyField := TIntegerField.Create(ToDataSet); AddedKeyField.FieldName := FieldName; AddedKeyField.DisplayLabel := DisplayFieldName; AddedKeyField.DisplayWidth := DisplayWidth; SetUpWithReadMetaData(AddedKeyField); AddedKeyField.DataSet := ToDataSet; if ToDataSet = cdsAutoForm then Result := CreateIntegerControl(AddedKeyField); end; function TfrmAutoForm.InternalAddLookupField(const FieldName, DisplayFieldName, KeyField, ListField, SQL: string; DisplayWidth: Integer; const ToDataSet: TDataSet; Dominio: Boolean): TControl; var AddedKeyField: TField; AControl: TDBLookupComboBox; begin Result := nil; AddedKeyField := TStringField.Create(ToDataSet); AddedKeyField.Visible := False; AddedKeyField.FieldName := FieldName; AddedKeyField.DisplayLabel := DisplayFieldName; AddedKeyField.DisplayWidth := DisplayWidth; SetUpWithReadMetaData(AddedKeyField); AddedKeyField.DataSet := ToDataSet; if ToDataSet = cdsAutoForm then begin AControl := (CreateLookupControl(AddedKeyField, KeyField, ListField, SQL) as TDBLookupComboBox); AddedKeyField := TStringField.Create(ToDataSet); AddedKeyField.FieldKind := fkLookup; AddedKeyField.FieldName := 'LOOKUP' + ListField+FieldName; AddedKeyField.DisplayLabel := DisplayFieldName; AddedKeyField.DisplayWidth := DisplayWidth; AddedKeyField.Size := AControl.ListSource.DataSet.FieldByName(ListField).Size; AddedKeyField.LookupDataSet := AControl.ListSource.DataSet; AddedKeyField.LookupKeyFields := KeyField; AddedKeyField.LookupResultField := ListField; AddedKeyField.KeyFields := FieldName; AddedKeyField.Lookup := True; AddedKeyField.DataSet := ToDataSet; end; Result := AControl; end; function TfrmAutoForm.CreateIntegerControl(const Field: TField): TControl; begin Result := CreateStringControl(Field); end; function TfrmAutoForm.InternalAddFloatField(const FieldName, DisplayFieldName: string; DisplayWidth: Integer; const ToDataSet: TDataSet; TipoFloat: TTipoFloat; Currency: Boolean = False): TControl; var AddedKeyField: TField; begin Result := nil; case TipoFloat of tfFloat: AddedKeyField := TFloatField.Create(ToDataSet); tfBCD: AddedKeyField := TBCDField.Create(ToDataSet); tfFMTBCD: AddedKeyField := TFMTBCDField.Create(ToDataSet); tfCurrency: AddedKeyField := TCurrencyField.Create(ToDataSet); tfExtended: AddedKeyField := TExtendedField.Create(ToDataSet); tfSingle: AddedKeyField := TSingleField.Create(ToDataSet); end; AddedKeyField.FieldName := FieldName; AddedKeyField.DisplayLabel := DisplayFieldName; AddedKeyField.DisplayWidth := DisplayWidth; SetUpWithReadMetaData(AddedKeyField); AddedKeyField.DataSet := ToDataSet; if ToDataSet = cdsAutoForm then begin Result := CreateFloatControl(AddedKeyField); TFloatField(AddedKeyField).Currency := Currency; end; end; function TfrmAutoForm.CreateFloatControl(const Field: TField): TControl; begin Result := CreateStringControl(Field); end; function TfrmAutoForm.InternalAddMemoField(const FieldName, DisplayFieldName: string; DisplayWidth, DisplayHeight: Integer; const ToDataSet: TDataSet; StringField: Boolean = False): TControl; var AddedKeyField: TField; begin Result := nil; if StringField then AddedKeyField := TStringField.Create(ToDataSet) else AddedKeyField := TMemoField.Create(ToDataSet); AddedKeyField.FieldName := FieldName; AddedKeyField.DisplayLabel := DisplayFieldName; AddedKeyField.DisplayWidth := DisplayWidth; SetUpWithReadMetaData(AddedKeyField); AddedKeyField.DataSet := ToDataSet; if ToDataSet = cdsAutoForm then Result := CreateMemoControl(AddedKeyField, DisplayHeight); end; function TfrmAutoForm.CreateMemoControl(const Field: TField; DisplayHeight: Integer): TControl; var AControl: TDBMemo; begin AControl := TDBMemo.Create(Self); AControl.Width := pnlControls.Width - (MARGIN * 2); AControl.Height := DisplayHeight; AControl.DataSource := dsAutoForm; AControl.DataField := Field.FieldName; AControl.ScrollBars := ssVertical; AControl.WantReturns := True; AControl.BevelKind := bkFlat; AControl.BorderStyle := bsNone; AddControl(AControl, Field.DisplayLabel); Result := AControl; end; function TfrmAutoForm.InternalAddDateField(const FieldName, DisplayFieldName: string; const ToDataSet: TDataSet): TControl; var AddedKeyField: TField; begin Result := nil; AddedKeyField := TDateField.Create(ToDataSet); AddedKeyField.FieldName := FieldName; AddedKeyField.DisplayLabel := DisplayFieldName; AddedKeyField.DisplayWidth := 15; SetUpWithReadMetaData(AddedKeyField); AddedKeyField.DataSet := ToDataSet; if ToDataSet = cdsAutoForm then Result := CreateDateControl(AddedKeyField); end; function TfrmAutoForm.CreateDateControl(const Field: TField): TControl; begin Field.EditMask := '!99/99/9999;1;_'; Result := CreateStringControl(Field); end; function TfrmAutoForm.InternalAddTimeField(const FieldName, DisplayFieldName: string; const ToDataSet: TDataSet): TControl; var AddedKeyField: TField; begin Result := nil; AddedKeyField := TTimeField.Create(ToDataSet); AddedKeyField.FieldName := FieldName; AddedKeyField.DisplayLabel := DisplayFieldName; SetUpWithReadMetaData(AddedKeyField); AddedKeyField.DataSet := ToDataSet; if ToDataSet = cdsAutoForm then Result := CreateTimeControl(AddedKeyField); end; function TfrmAutoForm.CreateTimeControl(const Field: TField): TControl; begin Field.EditMask := '!99:99;1;_'; Result := CreateStringControl(Field); end; function TfrmAutoForm.AddLookupField(const FieldName, DisplayFieldName, KeyField, ListField, SQL: string; DisplayWidth: Integer): TControl; begin InternalAddLookupField(FieldName, DisplayFieldName, KeyField, ListField, SQL, DisplayWidth, sqAutoForm); Result := InternalAddLookupField(FieldName, DisplayFieldName, KeyField, ListField, SQL, DisplayWidth, cdsAutoForm); end; function TfrmAutoForm.InternalAddLookupField(const FieldName, DisplayFieldName, KeyField, ListField, SQL: string; DisplayWidth: Integer; const ToDataSet: TDataSet): TControl; var AddedKeyField: TField; AControl: TDBLookupComboBox; begin Result := nil; AddedKeyField := TIntegerField.Create(ToDataSet); AddedKeyField.Visible := False; AddedKeyField.FieldName := FieldName; AddedKeyField.DisplayLabel := DisplayFieldName; AddedKeyField.DisplayWidth := DisplayWidth; SetUpWithReadMetaData(AddedKeyField); AddedKeyField.DataSet := ToDataSet; if ToDataSet = cdsAutoForm then begin AControl := (CreateLookupControl(AddedKeyField, KeyField, ListField, SQL) as TDBLookupComboBox); AddedKeyField := TStringField.Create(ToDataSet); AddedKeyField.FieldKind := fkLookup; AddedKeyField.FieldName := 'LOOKUP'+ListField+FieldName; AddedKeyField.DisplayLabel := DisplayFieldName; AddedKeyField.DisplayWidth := DisplayWidth; AddedKeyField.Size := AControl.ListSource.DataSet.FieldByName(ListField).Size; AddedKeyField.LookupDataSet := AControl.ListSource.DataSet; AddedKeyField.LookupKeyFields := KeyField; AddedKeyField.LookupResultField := ListField; AddedKeyField.KeyFields := FieldName; AddedKeyField.Lookup := True; AddedKeyField.DataSet := ToDataSet; end; Result := AControl; end; function TfrmAutoForm.CreateLookupControl(const Field: TField; const KeyField, ListField, SQL: string): TControl; var AListSource: TDataSource; ADataSet: TSimpleDataSet; AControl: TDBLookupComboBox; begin AListSource := TDataSource.Create(Self); ADataSet := TSimpleDataSet.Create(Self); { TODO 5 -oRodrigo -cMelhorias : Chamar Singleton Aqui } ADataSet.Connection := DM.DBConn; ADataSet.DataSet.CommandText := SQL; ADataSet.Open; AListSource.DataSet := ADataSet; AControl := TDBLookupComboBox.Create(Self); AControl.Parent := pnlControls; AControl.Width := Field.DisplayWidth * 6; AControl.KeyField := KeyField; AControl.ListField := ListField; AControl.ListSource := AListSource; AControl.DataSource := dsAutoForm; AControl.DataField := Field.FieldName; AControl.BevelKind := bkFlat; AControl.Height := 24; AddControl(AControl, Field.DisplayLabel); Result := AControl; end; procedure TfrmAutoForm.SetDefaultValue(const FieldName: string; const Value: Variant); begin SetLength(FDefaultValues, Length(FDefaultValues) + 1); FDefaultValues[High(FDefaultValues)].FieldName := FieldName; FDefaultValues[High(FDefaultValues)].DefaultValue := Value; end; procedure TfrmAutoForm.SetLookUpValue(const KeyField: string; const KeyValue: Variant); var sdsKeyField, cdsKeyField: TField; begin sdsKeyField := TIntegerField.Create(sqAutoForm); sdsKeyField.FieldName := KeyField; SetUpWithReadMetaData(sdsKeyField); sdsKeyField.DataSet := sqAutoForm; cdsKeyField := TIntegerField.Create(cdsAutoForm); cdsKeyField.FieldName := KeyField; SetUpWithReadMetaData(cdsKeyField); cdsKeyField.DataSet := cdsAutoForm; SetDefaultValue(KeyField,KeyValue); end; procedure TfrmAutoForm.FormCreate(Sender: TObject); begin inherited; //sdsMetaData.Connection := Conexao; { TODO 5 -oRodrigo -cMelhorias : Chamar Singleton Aqui } sdsMetaData.Connection := DM.DBConn; end; procedure TfrmAutoForm.FormShow(Sender: TObject); var i: Integer; begin inherited; pnlControls.Height := FMaxHeight; for i := 0 to pnlControls.ControlCount - 1 do begin if pnlControls.Controls[i] is TWinControl then begin //ActiveControl := (pnlControls.Controls[i] as TWinControl); Break; end; end; end; procedure TfrmAutoForm.cdsAutoFormNewRecord(DataSet: TDataSet); var I: Integer; begin inherited; for I := 0 to Length(FDefaultValues)-1 do begin cdsAutoForm.FindField(FDefaultValues[I].FieldName).Value := FDefaultValues[I].DefaultValue; end; end; end.
{$M 32192,0,0} { Leave memory for child process } program FileList; uses Crt, Dos, Buttons, Cursor; const MaxDirSize = 300; type TypeOfFiles = (DIR, PROG); TApplication = object procedure Init; procedure Run; procedure Done; end; TFile = object Name: string[8]; FileType: TypeOfFiles; procedure Clear; procedure Add(HName: string; Attributes: Byte); procedure WriteName; procedure Run; end; TList = object Files: array[1..MaxDirSize] of TFile; DirInfo: SearchRec; Directry: string[80]; Selected, Count, TotalFiles: integer; procedure Screen; procedure NewList; procedure FindList(HDirectry, HPath: string; HAttr: Byte); procedure DisplayList; procedure Select; procedure DosShell; procedure ParentDir; procedure Memory; function Dir: string; end; var I, X, Y: integer; FileViewer: TApplication; FirstDirectory: TList; procedure TFile.Clear; begin Name:= ''; FileType:= DIR; end; procedure TFile.Add; begin Clear; I:= 1; Repeat Insert(HName[I], Name, Length(Name) + 1); Inc(I); Until (HName[I] = '.') or (I = Length(HName) + 1); if (HName[I] = '.') and (HName[I - 1] = '.') and (Length(HName) = 2) then Insert(HName[I], Name, Length(Name) + 1); if Attributes = Archive then FileType:= PROG; if Attributes = Directory then FileType:= DIR; end; procedure TFile.WriteName; begin if FileType = DIR then TextColor(LightGray) else TextColor(Yellow); Write(' ', Name); For I:= Length(Name) to 9 do Write(' '); end; procedure TFile.Run; var ChangeDir: string[80]; begin if FileType = PROG then begin SwapVectors; Exec(GetEnv('COMSPEC'), '/C ' + Name); SwapVectors; if DosError <> 0 then WriteLn('Could not execute COMMAND.COM'); FirstDirectory.Screen; FirstDirectory.DisplayList; end; if FileType = DIR then begin ChangeDir:= FirstDirectory.Dir; FirstDirectory.Screen; FirstDirectory.NewList; FirstDirectory.FindList(ChangeDir + Name, '*.'#0#0#0, Directory); FirstDirectory.FindList('', '*.COM', Archive); FirstDirectory.FindList('', '*.EXE', Archive); FirstDirectory.DisplayList; end; end; procedure TList.Screen; begin Window(1, 1, 80, 25); TextColor(DarkGray); TextBackGround(Cyan); ClrScr; GoToXY(30, 1); Write('Program Finder'); GoToXY(1, 25); TextColor(LightRed); Write('KEYS:'); TextColor(Black); Write(' Arrows to scroll'); TextColor(Yellow); Write(' Enter'); TextColor(Black); Write(' - Run selection'); TextColor(Yellow); Write(' Space'); TextColor(Black); Write(' - Dos Shell'); TextColor(Yellow); Write(' ESC'); TextColor(Black); Write(' - Quit'); Window(1, 2, 80, 24); TextColor(LightGray); TextBackGround(Blue); ClrScr; NoCursor; end; procedure TList.NewList; begin Count:= 0; TotalFiles:= 0; Directry:= ''; end; procedure TList.FindList; begin Directry:= HDirectry; ChDir(Directry); FindFirst(HPath, HAttr, DirInfo); While (DosError = 0) and (Count < MaxDirSize) do begin Inc(Count); Files[TotalFiles + Count].Add(DirInfo.Name, HAttr); FindNext(DirInfo); end; TotalFiles:= TotalFiles + Count; Count:= 0; end; procedure TList.DisplayList; begin X:= 5; Y:= 2; Count:= 0; Repeat GoToXY(X, Y); Inc(Count); Files[Count].WriteName; Inc(Y); if Y > 22 then begin Y:= 2; Inc(X, 12); end; Until Count >= TotalFiles; X:= 5; Y:= 2; Count:= 1; end; procedure TList.DosShell; begin SwapVectors; Window(1, 1, 80, 25); TextBackGround(Blue); ClrScr; NormCursor; Writeln('Type EXIT to return to Program Finder.'); Exec(GetEnv('COMSPEC'), '/C ' + 'C:\COMMAND.COM'); SwapVectors; if DosError <> 0 then begin WriteLn('Could not execute COMMAND.COM'); Readln; end; NoCursor; Screen; NewList; FindList('', '*.'#0#0#0, Directory); FindList('', '*.COM' + '*.EXE', Archive); DisplayList; end; procedure TList.Select; var OldCount, Xx, Yy: integer; begin X:= 5; Y:= 2; Count:= 1; TextBackGround(Magenta); GoToXY(X, Y); Files[Count].WriteName; While Key.Key <> Esc do begin Key.GetKeys; Xx:= X; Yy:= Y; OldCount:= Count; if Key.Key = Down then begin if Count < TotalFiles then begin Inc(Count); Inc(Y); if Y > 22 then begin Inc(X, 12); Y:= 2; end; end; end; if Key.Key = Up then begin if Count > 1 then begin Dec(Count); Dec(Y); if Y < 2 then begin Y:= 22; Dec(X, 12); end; end; end; if Key.Key = Home then begin Count:= 1; X:= 5; Y:= 2; end; if Key.Key = _End then begin Repeat Inc(Count); Inc(Y); if Y > 22 then begin Y:= 2; Inc(X, 12); end; Until Count = TotalFiles; end; if Key.Key = Left then if Count - 21 > 0 then begin Dec(Count, 21); Dec(X, 12); end; if Key.Key = Right then if Count + 21 <= TotalFiles then begin Inc(Count, 21); Inc(X, 12); end; if Key.Key = F5 then Memory; if Key.Key = Enter then Files[Count].Run else if Key.Key = Space then DosShell else begin TextBackGround(Blue); GoToXY(Xx, Yy); Files[OldCount].WriteName; end; TextBackGround(Magenta); GoToXY(X, Y); Files[Count].WriteName; end; end; procedure TList.ParentDir; begin Screen; NewList; FindList('..', '*.'#0#0#0, Directory); FindList('', '*.COM', Archive); FindList('', '*.EXE', Archive); DisplayList; end; procedure TList.Memory; begin TextBackGround(Black); Window(21, 10, 62, 20); ClrScr; TextBackGround(LightGray); Window(19, 9, 60, 19); ClrScr; TextColor(Yellow); GoToXY (10, 2); Writeln ('MEMORY & DISK INFORMATION'); TextColor(Blue); GoToXY (19, 4); Writeln ('Memory:'); GoToXY(9, 5); Write(MemAvail:8,' bytes free'); TextColor(Black); GoToXY(5, 7); Write('Free Disk Space: ', DiskFree(0):12, ' bytes'); GoToXY(5, 8); Write('of Disk Size: ', DiskSize(0):15, ' bytes.'); TextColor(LightRed); GoToXY(16, 10); Write('Press a key...'); Readkey; Screen; DisplayList; end; function TList.Dir: string; begin Dir:= Directry; end; procedure TApplication.Init; begin end; procedure TApplication.Run; begin FirstDirectory.Screen; FirstDirectory.NewList; FirstDirectory.FindList('', '*.'#0#0#0, Directory); FirstDirectory.FindList('', '*.COM', Archive); FirstDirectory.FindList('', '*.EXE', Archive); FirstDirectory.DisplayList; FirstDirectory.Select; end; procedure TApplication.Done; begin TextColor(LightGray); TextBackGround(Black); Window(1, 1, 80, 25); ClrScr; NormCursor; end; begin FileViewer.Init; FileViewer.Run; FileViewer.Done; end.
unit dll; interface uses windows,Classes; type pPeerGroupInfo = ^TPeerGroupInfo; TPeerGroupInfo = class(Tlist) GroupID:integer; Creator:integer; GroupName:string[12]; GroupDes:string[30]; NeedPass:boolean; end; Puserinfo =^TUserInfo; TUserInfo = class (tobject) connecting:boolean; UserID:integer; UserName, AhthorPassword:string[12]; ISOnline:boolean; Connected:boolean; MacAddress:string[12]; Con_ConnectionType:integer; Con_IP:string[15]; Con_port:integer; Con_RetryTime:integer; Con_send:int64; Con_recv:int64; tvUserReconn:integer; peerport:integer; con_AContext:pointer; con_Lastrecv:tdatetime; clientDM:pointer; procedure TryConnect_start; virtual; abstract; procedure RefInfo_whenConnect(ip:string;port:integer;Mac:string); virtual; abstract; procedure DissconnectPeer; virtual; abstract; // procedure sendtopeer(str:string);overload; procedure sendtopeer(buffer:pchar; buflength:integer); virtual; abstract; procedure RetryTimer(Sender: TObject); virtual; abstract; end; procedure CVN_SendCmd(str:string);StdCall; external 'cvn_main.dll'; procedure CVN_ConnectUser(Userid:integer;password:string);stdcall;external 'cvn_main.dll'; procedure CVN_Login(cvnurl,username,password:pchar);stdcall;external 'cvn_main.dll'; procedure CVN_Logout;stdcall;external 'cvn_main.dll'; procedure CVN_DisConnectUser(Userid:integer);stdcall; external 'cvn_main.dll'; function CVN_ConnecttoServer(url:string):boolean;StdCall; external 'cvn_main.dll'; //Procedure synapp(App:TApplication);stdcall; external 'Dll/cvn_main.dll'; Procedure CVN_Message(Aproc:TfarProc);StdCall; external 'cvn_main.dll'; function CVN_AllUserInfo:TPeerGroupInfo;StdCall; external 'cvn_main.dll'; function CVN_GetUserList:TList;StdCall; external 'cvn_main.dll'; function CVN_getTCPc2cport:integer;stdcall; external 'cvn_main.dll'; function CVN_getUDPc2cport:integer;stdcall; external 'cvn_main.dll'; //function CVN_Getmyinnerip:string;stdcall; external '../Dll/cvn_main.dll'; function CVN_InitEther:boolean;stdcall; external 'cvn_main.dll'; procedure CVN_FreeRes;stdcall;external 'cvn_main.dll'; procedure CVN_GetEtherName(p:pchar); external 'cvn_main.dll'; procedure CVN_InitClientServer(tcpport,udpport:integer);stdcall; external 'cvn_main.dll'; function CVN_CountRecive:int64;Stdcall; external 'cvn_main.dll'; function CVN_CountSend:int64;Stdcall; external 'cvn_main.dll'; function getUserByID(userid:integer):Tuserinfo; stdcall; external 'cvn_main.dll'; function getuserByName(userName:string):Tuserinfo; stdcall; external 'cvn_main.dll'; function getUserByIDex(userid:integer):Puserinfo; stdcall; external 'cvn_main.dll'; function getUserByMAC(mac:string):Tuserinfo; stdcall; external 'cvn_main.dll'; function getGroupByID(groupid:integer):TPeerGroupInfo; stdcall; external 'cvn_main.dll'; function getuFriendByID(userid:integer):Tuserinfo; stdcall; external 'cvn_main.dll'; function diduserinlist(userid:integer):boolean; stdcall; external 'cvn_main.dll'; implementation end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit Server.Data.Main; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, Data.DB, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet , WiRL.Core.Attributes; type TDataMain = class(TDataModule) DatabaseConnection: TFDConnection; [Rest] EmployeeQuery: TFDQuery; private { Private declarations } public end; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} end.
unit lfEdClinicas; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, DbCtrls, StdCtrls, Buttons, ExtCtrls, lfDataMod; type { TfrmEdClinicas } TfrmEdClinicas = class(TForm) dbeCodigo: TDBEdit; dbeNombre: TDBEdit; dbnEdClinicas: TDBNavigator; lblCodigo: TLabel; lblNombre: TLabel; sbtValidar: TSpeedButton; sbtCancelar: TSpeedButton; procedure dbnEdClinicasBeforeAction(Sender: TObject; Button: TDBNavButtonType); procedure dbnEdClinicasClick(Sender: TObject; Button: TDBNavButtonType); procedure FormActivate(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure sbtCancelarClick(Sender: TObject); procedure sbtValidarClick(Sender: TObject); private procedure ActivaEditar; procedure DesactivaEditar; function ValiNombre: Boolean; function ValiCodigo: Boolean; procedure ValiEnFDB(Sender: TObject; sMensaje, sTitulo : String); procedure AnotarReg; procedure EditarReg; public { public declarations } end; var frmEdClinicas: TfrmEdClinicas; implementation {$R *.lfm} { TfrmEdClinicas } procedure TfrmEdClinicas.FormActivate(Sender: TObject); begin dbeCodigo.Enabled := False; dbeNombre.Enabled := False; sbtValidar.Enabled := False; sbtCancelar.Enabled := False; end; procedure TfrmEdClinicas.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin sbtCancelarClick(frmEdClinicas); CloseAction := caHide; end; procedure TfrmEdClinicas.dbnEdClinicasBeforeAction(Sender: TObject; Button: TDBNavButtonType); var sTituloQD, sMensajeQD: String; begin case Button of nbDelete: begin sTituloQD := 'B.DD. CirMax -> T. Clinicas -> Eliminar'; sMensajeQD := '¿Confirmas el borrado de esta clínica?: ' + dbeCodigo.Text + ', '+ dbeNombre.Text; if QuestionDlg (sTituloQD, sMensajeQD, mtConfirmation, [mrYes, 'Si', mrNo, 'No'],'') = mrYes then begin with dmCirmax.sqrClinicas do begin Delete; Edit; Post; ApplyUpdates; end; dmCirmax.strCirmaxFDB.CommitRetaining; dmCirmax.sqrClinicas.Refresh; end; Abort; // Abortar la acción del botón nbDelete end; end; end; procedure TfrmEdClinicas.dbnEdClinicasClick(Sender: TObject; Button: TDBNavButtonType); begin case Button of nbInsert: begin dbeCodigo.Enabled := True; ActivaEditar; dbeCodigo.SetFocus; end; nbEdit: begin ActivaEditar; dbeNombre.SetFocus; end; end; end; procedure TfrmEdClinicas.sbtValidarClick(Sender: TObject); begin if (dbeCodigo.Enabled = False) then begin if ValiNombre() then EditarReg else dbeNombre.SetFocus; end else begin if ValiCodigo() then AnotarReg else dbeCodigo.SetFocus; end; end; procedure TfrmEdClinicas.sbtCancelarClick(Sender: TObject); begin with dmCirmax.sqrClinicas do begin CancelUpdates; Refresh; end; DesactivaEditar; end; procedure TfrmEdClinicas.ActivaEditar; begin dbnEdClinicas.Enabled := False; dbeNombre.Enabled := True; sbtValidar.Enabled := True; sbtCancelar.Enabled := True; end; procedure TfrmEdClinicas.DesactivaEditar; begin dbnEdClinicas.Enabled := True; dbeCodigo.Enabled := False; dbeNombre.Enabled := False; sbtValidar.Enabled := False; sbtCancelar.Enabled := False; end; function TfrmEdClinicas.ValiNombre: Boolean; var sTituQD, sMensaQD : String; begin if (Length(Trim(dbeNombre.Text)) = 0) then begin sTituQD := 'B.DD. CirMax -> T. Clinicas -> Editar'; sMensaQD := 'Error: VALOR NULO para el campo: "NOMBRE" de la tabla: "CLINICAS"'; QuestionDlg (sTituQD, sMensaQD, mtError,[mrOK,'Aceptar'],''); Result := False; end else Result := True; end; function TfrmEdClinicas.ValiCodigo: Boolean; var sTituQD, sMensaQD : String; begin if (Length(Trim(dbeCodigo.Text)) = 0) then begin sTituQD := 'B.DD. CirMax -> T. Clinicas -> Editar'; sMensaQD := 'Error: VALOR NULO para el campo: "CODIGO" de la tabla: "CLINICAS"'; QuestionDlg (sTituQD, sMensaQD, mtError,[mrOK,'Aceptar'],''); Result := False; end else Result := True; end; procedure TfrmEdClinicas.ValiEnFDB(Sender: TObject; sMensaje, sTitulo: String); var sTituloQD, sMensajeQD: String; sMenErr, sCadBusErr1, sTipErr, sTabla, sCampo, sValor, sCadBusTab1, sCadFinTab1, sCadBusCam1, sCadFinCam1, sCadBusVal1, sCadFinVal1, sCadBusErr2, sCadBusTab2, sCadFinTab2, sCadBusCam2, sCadFinCam2 : String; iPosCB1, iPosCB2, iIniTab1, iLonTab1, iIniCam1, iLonCam1, iIniVal1, iLonVal1, iIniTab2, iLonTab2, iIniCam2, iLonCam2 : Integer; begin sCadBusErr1 := 'PRIMARY or UNIQUE KEY'; sCadBusTab1 := 'on table "'; sCadFinTab1 := '-Problematic'; sCadBusCam1 := 'key value is ("'; sCadFinCam1 := '" = '; sCadBusVal1 := sCadFinCam1; sCadFinVal1 := ')'; sCadBusErr2 := 'validation error for column'; sCadBusTab2 := 'for column "'; sCadFinTab2 := '"."'; sCadBusCam2 := sCadFinTab2; sCadFinCam2 := '", value'; sMenErr := sMensaje; sTituloQD := sTitulo; iPosCB1 := Pos(sCadBusErr1, sMenErr); if (iPosCB1>0) then begin sTipErr := 'VALOR DUPLICADO'; iIniTab1 := Pos(sCadBusTab1, sMenErr) + Length(sCadBusTab1); iLonTab1 := Pos(sCadFinTab1, sMenErr) - iIniTab1 - 4; // {" #13#10} sTabla := Copy(sMenErr, iIniTab1, iLonTab1); iIniCam1 := Pos(sCadBusCam1, sMenErr) + Length(sCadBusCam1); iLonCam1 := Pos(sCadFinCam1, sMenErr) - iIniCam1; sCampo := Copy(sMenErr, iIniCam1, iLonCam1); iIniVal1 := Pos(sCadBusVal1, sMenErr) + Length(sCadBusVal1); iLonVal1 := Pos(sCadFinVal1, sMenErr) - iIniVal1; sValor := Copy(sMenErr, iIniVal1, iLonVal1); sMensajeQD := 'Error: ' + sTipErr + ' al guardar: ' + sValor + ' en el campo: ' + sCampo + ' de la tabla: ' + sTabla; if sCampo = 'NOMBRE' then dbeNombre.SetFocus; end; iPosCB2 := Pos(sCadBusErr2, sMenErr); if (iPosCB2 > 0) then begin sTipErr := 'VALOR NULO'; iIniTab2 := Pos(sCadBusTab2, sMenErr) + Length(sCadBusTab2); iLonTab2 := Pos(sCadFinTab2, sMenErr) - iIniTab2; sTabla := Copy(sMenErr, iIniTab2, iLonTab2); iIniCam2 := Pos(sCadBusCam2, sMenErr) + Length(sCadBusCam2); iLonCam2 := Pos(sCadFinCam2, sMenErr) - iIniCam2; sCampo := Copy(sMenErr, iIniCam2, iLonCam2); sMensajeQD := 'Error: ' + sTipErr + ' para el campo: ' + sCampo + ' de la tabla: ' + sTabla; if sCampo = 'NOMBRE' then dbeNombre.SetFocus; end; QuestionDlg (sTituloQD, sMensajeQD, mtError,[mrOK,'Aceptar'],''); end; procedure TfrmEdClinicas.EditarReg; var sMenErr, sTituQD : String; begin try with dmCirmax do begin sqrClinicas.Edit; sqrClinicas.ApplyUpdates; strCirmaxFDB.CommitRetaining; DesactivaEditar; end; except on E: Exception do begin sMenErr := E.Message; sTituQD := 'B.DD. Cirmax -> T. Clínicas -> Editar'; ValiEnFDB(sbtValidar, sMenErr, sTituQD); end; end; end; procedure TfrmEdClinicas.AnotarReg; var sMenErr, sTituQD : String; begin try with dmCirmax do begin sqrClinicas.Insert; sqrClinicas.ApplyUpdates; strCirmaxFDB.CommitRetaining; DesactivaEditar; end; except on E: Exception do begin sMenErr := E.Message; sTituQD := 'B.DD. Cirmax -> T. Clínicas -> Anotar'; ValiEnFDB(sbtValidar, sMenErr, sTituQD); end; end; end; end.
{ "dfmVersion": "1.1", "taskInfo": { "name": "PSJH", "sourceEndpoint": "Oracle", "sourceEndpointType": "ORACLE", "sourceEndpointUser": "system", "replicationServer": "SPVM1.qa.int", "operation": "dataProduced" }, "fileInfo": { "name": "20191212-004656467", "extension": "csv", "location": "e:\\Giri\\YONATAN.BD7__ct", "startWriteTimestamp": "2019-12-12T00:45:54.636", "endWriteTimestamp": "2019-12-12T00:46:52.461", "firstTransactionTimestamp": "2019-12-12T00:45:52.000", "lastTransactionTimestamp": "2019-12-12T00:46:42.000", "content": "changes", "recordCount": 120, "errorCount": 0 }, "formatInfo": { "format": "delimited", "options": { "fieldDelimiter": ",", "recordDelimiter": "\n", "nullValue": "", "quoteChar": "\"", "escapeChar": "" } }, "dataInfo": { "sourceSchema": "YONATAN", "sourceTable": "BD7", "targetSchema": "YONATAN", "targetTable": "BD7__ct", "tableVersion": 1, "columns": [{ "ordinal": 1, "name": "header__change_seq", "type": "STRING", "length": 35, "precision": 0, "scale": 0, "primaryKeyPos": 0 }, { "ordinal": 2, "name": "header__change_oper", "type": "STRING", "length": 1, "precision": 0, "scale": 0, "primaryKeyPos": 0 }, { "ordinal": 3, "name": "header__change_mask", "type": "BYTES", "length": 128, "precision": 0, "scale": 0, "primaryKeyPos": 0 }, { "ordinal": 4, "name": "header__stream_position", "type": "STRING", "length": 128, "precision": 0, "scale": 0, "primaryKeyPos": 0 }, { "ordinal": 5, "name": "header__operation", "type": "STRING", "length": 12, "precision": 0, "scale": 0, "primaryKeyPos": 0 }, { "ordinal": 6, "name": "header__transaction_id", "type": "STRING", "length": 32, "precision": 0, "scale": 0, "primaryKeyPos": 0 }, { "ordinal": 7, "name": "header__timestamp", "type": "DATETIME", "length": 0, "precision": 0, "scale": 0, "primaryKeyPos": 0 }, { "ordinal": 8, "name": "LOOPNUM", "type": "NUMERIC", "length": 0, "precision": 38, "scale": 0, "primaryKeyPos": 1 }, { "ordinal": 9, "name": "TRANSACTIONNUM", "type": "NUMERIC", "length": 0, "precision": 38, "scale": 0, "primaryKeyPos": 2 }, { "ordinal": 10, "name": "B", "type": "STRING", "length": 152, "precision": 0, "scale": 0, "primaryKeyPos": 0 }, { "ordinal": 11, "name": "C", "type": "DATETIME", "length": 0, "precision": 0, "scale": 0, "primaryKeyPos": 0 }, { "ordinal": 12, "name": "D", "type": "STRING", "length": 10, "precision": 0, "scale": 0, "primaryKeyPos": 0 }] } }
unit win.diskfile; interface uses Types, Windows; type PFileUrl = ^TFileUrl; TFileUrl = record Url : AnsiString; end; PWinFile = ^TWinFile; TWinFile = record FileHandle : THandle; FileMapHandle : THandle; FileMapRootView : Pointer; FilePosition : DWORD; FileSizeLow : DWORD; end; PWinFileMap = ^TWinFileMap; TWinFileMap = record WinFile : PWinFile; MapHandle : THandle; MapSize : DWORD; SizeHigh : DWORD; SizeLow : DWORD; MapView : Pointer; end; PWinFileOpen = ^TWinFileOpen; TWinFileOpen = record FileName : PAnsiChar; DesiredAccess : DWORD; // GENERIC_READ ShareMode : DWORD; // FILE_SHARE_READ Security : PSecurityAttributes; // FILE_SHARE_READ Creation : DWORD; // OPEN_EXISTING Attribs : DWORD; // FILE_ATTRIBUTE_NORMAL TemplateFile : THandle; // 0 end; const faSymLink = $00000400 platform; // Only available on Vista and above faDirectory = $00000010; {line 2250} FILE_SHARE_READ = $00000001; FILE_SHARE_WRITE = $00000002; FILE_SHARE_DELETE = $00000004; FILE_ATTRIBUTE_READONLY = $00000001; FILE_ATTRIBUTE_HIDDEN = $00000002; FILE_ATTRIBUTE_SYSTEM = $00000004; FILE_ATTRIBUTE_DIRECTORY = $00000010; FILE_ATTRIBUTE_ARCHIVE = $00000020; FILE_ATTRIBUTE_DEVICE = $00000040; FILE_ATTRIBUTE_NORMAL = $00000080; FILE_ATTRIBUTE_TEMPORARY = $00000100; FILE_ATTRIBUTE_SPARSE_FILE = $00000200; FILE_ATTRIBUTE_REPARSE_POINT = $00000400; FILE_ATTRIBUTE_COMPRESSED = $00000800; FILE_ATTRIBUTE_OFFLINE = $00001000; FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = $00002000; FILE_ATTRIBUTE_ENCRYPTED = $00004000; FILE_ATTRIBUTE_VIRTUAL = $00010000; INVALID_FILE_ATTRIBUTES = DWORD($FFFFFFFF); function CheckOutWinFile: PWinFile; procedure CheckInWinFile(var AWinFile: PWinFile); function WinFileOpen(AWinFile: PWinFile; AFileUrl: AnsiString; AForceOpen: Boolean): Boolean; procedure WinFileClose(AWinFile: PWinFile); procedure WinFileUpdateSize(AWinFile: PWinFile; const Value: integer); function IsWinFileExists(const AFileName: AnsiString): Boolean; function IsWinFileExistsLockedOrShared(const AFilename: Ansistring): Boolean; function WinFileOpenMap(AWinFile: PWinFile): Boolean; procedure WinFileCloseMap(AWinFile: PWinFile); function CheckOutWinFileMap: PWinFileMap; procedure CheckInWinFileMap(var AWinFileMap: PWinFileMap); function WinFileMapOpen(AWinFileMap: PWinFileMap): Boolean; procedure WinFileMapClose(AWinFileMap: PWinFileMap); implementation function CheckOutWinFile: PWinFile; begin Result := System.New(PWinFile); FillChar(Result^, SizeOf(TWinFile), 0); end; procedure CheckInWinFile(var AWinFile: PWinFile); begin if nil = AWinFile then exit; WinFileClose(AWinFile); FreeMem(AWinFile); AWinFile := nil; end; function WinFileOpen(AWinFile: PWinFile; AFileUrl: AnsiString; AForceOpen: Boolean): Boolean; var tmpFlags: DWORD; tmpCreation: DWORD; begin tmpFlags := Windows.FILE_ATTRIBUTE_NORMAL; tmpCreation := Windows.OPEN_EXISTING; if AForceOpen then begin if not IsWinFileExists(AFileUrl) then begin tmpCreation := Windows.CREATE_NEW; end; end; AWinFile.FileHandle := Windows.CreateFileA(PAnsiChar(AFileUrl), Windows.GENERIC_ALL, // GENERIC_READ Windows.FILE_SHARE_READ or Windows.FILE_SHARE_WRITE or Windows.FILE_SHARE_DELETE, nil, tmpCreation, tmpFlags, 0); Result := (AWinFile.FileHandle <> 0) and (AWinFile.FileHandle <> Windows.INVALID_HANDLE_VALUE); if Result then begin AWinFile.FileSizeLow := Windows.GetFileSize(AWinFile.FileHandle, nil); end; end; procedure WinFileClose(AWinFile: PWinFile); begin if (0 <> AWinFile.FileHandle) and (INVALID_HANDLE_VALUE <> AWinFile.FileHandle) then begin WinFileCloseMap(AWinFile); if Windows.CloseHandle(AWinFile.FileHandle) then begin AWinFile.FileHandle := 0; end; end; end; function IsWinFileExistsLockedOrShared(const AFilename: Ansistring): Boolean; var tmpFindData: TWin32FindData; tmpFindHandle: THandle; begin { Either the file is locked/share_exclusive or we got an access denied } tmpFindHandle := FindFirstFileA(PAnsiChar(AFilename), tmpFindData); if tmpFindHandle <> INVALID_HANDLE_VALUE then begin Windows.FindClose(tmpFindHandle); Result := tmpFindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0; end else Result := False; end; function IsWinFileExists(const AFileName: AnsiString): Boolean; var tmpCode: Integer; tmpErrorCode: DWORD; begin tmpCode := Windows.GetFileAttributesA(PAnsiChar(AFileName)); if -1 = tmpCode then begin tmpErrorCode := Windows.GetLastError; Result := (tmpErrorCode <> ERROR_FILE_NOT_FOUND) and (tmpErrorCode <> ERROR_PATH_NOT_FOUND) and (tmpErrorCode <> ERROR_INVALID_NAME); if Result then begin Result := IsWinFileExistsLockedOrShared(AFileName); end; end else begin Result := (FILE_ATTRIBUTE_DIRECTORY and tmpCode = 0) end; end; procedure WinFileUpdateSize(AWinFile: PWinFile; const Value: integer); begin if AWinFile.FileSizeLow <> Value then begin if 0 < Value then begin Windows.SetFilePointer(AWinFile.FileHandle, Value, nil, FILE_BEGIN); Windows.SetEndOfFile(AWinFile.FileHandle); Windows.SetFilePointer(AWinFile.FileHandle, 0, nil, FILE_BEGIN); AWinFile.FileSizeLow := Value; end; end; end; function WinFileOpenMap(AWinFile: PWinFile): Boolean; begin AWinFile.FileMapHandle := Windows.CreateFileMappingA(AWinFile.FileHandle, nil, Windows.PAGE_READWRITE, 0, 0, nil); if AWinFile.FileMapHandle <> 0 then begin // OpenFileMapping AWinFile.FileMapRootView := Windows.MapViewOfFile(AWinFile.FileMapHandle, Windows.FILE_MAP_ALL_ACCESS, 0, 0, 0); // fWinFileData.FileMapRootView := MapViewOfFileEx( // fWinFileData.FileMapHandle, //hFileMappingObject: THandle; // Windows.FILE_MAP_ALL_ACCESS, //dwDesiredAccess, // 0, //dwFileOffsetHigh, // 0, //dwFileOffsetLow, // 0, //dwNumberOfBytesToMap: DWORD; // nil //lpBaseAddress: Pointer // ); end; Result := nil <> AWinFile.FileMapRootView; end; procedure WinFileCloseMap(AWinFile: PWinFile); begin if nil <> AWinFile.FileMapRootView then begin UnMapViewOfFile(AWinFile.FileMapRootView); AWinFile.FileMapRootView := nil; end; if 0 <> AWinFile.FileMapHandle then begin Windows.CloseHandle(AWinFile.FileMapHandle); AWinFile.FileMapHandle := 0; end; end; function CheckOutWinFileMap: PWinFileMap; begin Result := System.New(PWinFileMap); FillChar(Result^, SizeOf(TWinFileMap), 0); end; procedure CheckInWinFileMap(var AWinFileMap: PWinFileMap); begin if nil <> AWinFileMap then begin WinFileMapClose(AWinFileMap); FreeMem(AWinFileMap); AWinFileMap := nil; end; end; function WinFileMapOpen(AWinFileMap: PWinFileMap): Boolean; begin if nil = AWinFileMap.MapView then begin if 0 = AWinFileMap.MapHandle then begin AWinFileMap.MapHandle := Windows.CreateFileMappingA(AWinFileMap.WinFile.FileHandle, nil, //lpFileMappingAttributes: PSecurityAttributes; 0, //flProtect: DWORD AWinFileMap.SizeHigh, //dwMaximumSizeHigh: DWORD AWinFileMap.SizeLow, //dwMaximumSizeLow: DWORD nil //lpName: PAnsiChar ); end; if (0 <> AWinFileMap.MapHandle) and (INVALID_HANDLE_VALUE <> AWinFileMap.MapHandle) then begin AWinFileMap.MapView := Windows.MapViewOfFile(AWinFileMap.MapHandle, 0, 0, 0, AWinFileMap.MapSize); end; end; Result := nil <> AWinFileMap.MapView; end; procedure WinFileMapClose(AWinFileMap: PWinFileMap); begin if nil <> AWinFileMap then begin if nil <> AWinFileMap.MapView then begin if UnmapViewOfFile(AWinFileMap.MapView) then begin AWinFileMap.MapView := nil; end; end; if 0 <> AWinFileMap.MapHandle then begin if CloseHandle(AWinFileMap.MapHandle) then begin AWinFileMap.MapHandle := 0; end; end; end; end; end.
(* Standard audio This file is a part of Audio Components Suite. All rights reserved. See the license file for more details. Copyright (c) 2002-2009, Andrei Borovsky, anb@symmetrica.net Copyright (c) 2005-2006 Christian Ulrich, mail@z0m3ie.de Copyright (c) 2014-2015 Sergey Bodrov, serbod@gmail.com *) { Status: TStdAudioOut Win: AcsBuffer, prefetching, tested OK Lin: not updated TStdAudioIn Win: not updated Lin: not updated } unit acs_stdaudio; interface uses Classes, SysUtils, syncobjs, ACS_Types, ACS_Classes, ACS_Audio, ACS_Strings {$IFDEF MSWINDOWS} , MMSystem {$ELSE} , baseunix, Soundcard {$ENDIF} ; const LATENCY = 110; type {$IFDEF MSWINDOWS} {$IFDEF FPC} TWaveInCapsA = WAVEINCAPSA; TWaveInCaps = TWaveInCapsA; TWaveHdr = WAVEHDR; {$ENDIF} PPWaveHdr = ^PWaveHdr; {$ENDIF} { TStdAudioOut } { Windows Wavemapper consume audio data as chain of prepared buffers - blocks. Each block points to sample data and to next block. When block played, it set flag WHDR_DONE } TStdAudioOut = class(TAcsAudioOutDriver) private _audio_fd: Integer; FTimeElapsed: Real; {$IFDEF MSWINDOWS} { first block in chain } FirstBlock: PWaveHdr; { last block in chain } LastBlock: PWaveHdr; { number of blocks in use } FBlockCount: Integer; { size of single block, aligned to sample size } FBlockSize: Integer; //EOC: PPWaveHdr; { how many buffer blocks we use } FReadChunks: Integer; procedure WriteBlock(P: Pointer; Len: Integer); { remove played block from chain, return remaining blocks size } function ClearUsedBlocks(): Integer; {$ENDIF} protected function GetTE(): Real; override; function GetDeviceCount(): Integer; override; procedure SetDevice(Ch: Integer); override; function GetDeviceName(ADeviceNumber: Integer): string; override; function GetDeviceInfo(ADeviceNumber: Integer): TAcsDeviceInfo; override; public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; procedure Init(); override; function DoOutput(Abort: Boolean): Boolean; override; procedure Done(); override; { increase played time by number of played bytes, used in player callback } procedure PlayedBytes(AValue: Integer); end; { TStdAudioIn } TStdAudioIn = class(TAcsAudioInDriver) private {$IFDEF MSWINDOWS} BlockChain: PWaveHdr; FBlocksCount: Integer; aBlock: Integer; EOC: PPWaveHdr; {$ENDIF} _audio_fd: Integer; FOpened: Integer; FRecBytes: Integer; procedure OpenAudio; procedure CloseAudio; {$IFDEF MSWINDOWS} procedure NewBlock; procedure AddBlockToChain(WH: PWaveHdr); {$ENDIF} protected function GetBPS(): Integer; override; function GetCh(): Integer; override; function GetSR(): Integer; override; function GetDeviceCount(): Integer; override; procedure SetDevice(Ch: Integer); override; function GetDeviceName(ADeviceNumber: Integer): string; override; function GetDeviceInfo(ADeviceNumber: Integer): TAcsDeviceInfo; override; public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; function GetData(ABuffer: Pointer; ABufferSize: Integer): Integer; override; procedure Init(); override; procedure Done(); override; end; var InputChannelsCount: Integer; OutputChannelsCount: Integer; function GetAudioDeviceInfo(DevID: Integer; OutputDev: Boolean): TAcsDeviceInfo; implementation var CrSecI, CrSecO: TCriticalSection; {$IFDEF MSWINDOWS} {$I win32\acs_audio.inc} {$ELSE} {$I linux\acs_audio.inc} {$ENDIF} function TStdAudioOut.GetTE(): Real; begin //Result:=inherited GetTE; Result:=FTimeElapsed; end; function TStdAudioOut.GetDeviceName(ADeviceNumber: Integer): string; begin Result:=GetDeviceInfo(ADeviceNumber).DeviceName; end; function TStdAudioOut.GetDeviceInfo(ADeviceNumber: Integer): TAcsDeviceInfo; begin //Result:=GetAudioDeviceInfo(FBaseChannel, True); Result:=GetAudioDeviceInfo(ADeviceNumber, True); end; function TStdAudioOut.GetDeviceCount(): Integer; begin Result:=OutputChannelsCount; end; procedure TStdAudioOut.PlayedBytes(AValue: Integer); begin FTimeElapsed:=FTimeElapsed + ((AValue div FSampleSize) / FInput.SampleRate); end; { TStdAudioIn } function TStdAudioIn.GetDeviceName(ADeviceNumber: Integer): string; begin Result:=GetDeviceInfo(ADeviceNumber).DeviceName; end; function TStdAudioIn.GetDeviceInfo(ADeviceNumber: Integer): TAcsDeviceInfo; begin //Result:=GetAudioDeviceInfo(FBaseChannel, False); Result:=GetAudioDeviceInfo(ADeviceNumber, False); end; function TStdAudioIn.GetDeviceCount(): Integer; begin Result:=InputChannelsCount; end; constructor TStdAudioIn.Create(AOwner: TComponent); begin inherited Create(AOwner); FBPS:=8; FChan:=1; FSampleRate:=8000; //FSize:=-1; FRecTime:=600; BufferSize:=$1000; {$IFDEF MSWINDOWS} FBlocksCount:=4; {$ENDIF} end; initialization {$IFDEF MSWINDOWS} CrSecI := TCriticalSection.Create(); CrSecO := TCriticalSection.Create(); {$ENDIF} CountChannels(); if OutputChannelsCount > 0 then RegisterAudioOut('Wavemapper', TStdAudioOut, LATENCY); if InputChannelsCount > 0 then RegisterAudioIn('Wavemapper', TStdAudioIn, LATENCY); finalization {$IFDEF MSWINDOWS} FreeAndNil(CrSecO); FreeAndNil(CrSecI); {$ENDIF} end.
unit PessoaDAO; interface uses FireDAC.Comp.Client, Firedac.Stan.Param, Pessoa; type TPessoaDAO = class (TObject) private FConnection: TFDConnection; public Constructor Create_TPessoaDAO(pConnection: TFDConnection); procedure GravarPessoa(pPessoa : TPessoa); procedure EditarPessoa(pPessoa : TPessoa); procedure DeletarPessoa(idPessoa : int64); function RetornarPessoa(idPessoa : int64; var pPessoa : TPessoa): Boolean; end; implementation { TPessoaDAO } constructor TPessoaDAO.Create_TPessoaDAO(pConnection: TFDConnection); begin FConnection := pConnection; end; procedure TPessoaDAO.GravarPessoa(pPessoa: TPessoa); var lQuery : TFDQuery; begin lQuery := TFDQuery.Create(nil); try lQuery.Connection := FConnection; lQuery.SQL.Add('INSERT INTO PESSOA (id, nome) VALUES (:id , :nome )'); lQuery.ParamByName('id').AsInteger := pPessoa.FId; lQuery.ParamByName('nome').AsString := pPessoa.FNome; lQuery.ExecSQL; finally lQuery.Free; end; end; procedure TPessoaDAO.EditarPessoa(pPessoa: TPessoa); var lQuery : TFDQuery; begin lQuery := TFDQuery.Create(nil); try lQuery.Connection := FConnection; lQuery.SQL.Add('UPDATE PESSOA SET nome = :nome WHERE id = :pIdPessoa'); lQuery.ParamByName('nome').AsString := pPessoa.FNome; lQuery.ParamByName('pIdPessoa').AsInteger := pPessoa.FId; lQuery.ExecSQL; finally lQuery.Free; end; end; procedure TPessoaDAO.DeletarPessoa(idPessoa: int64); var lQuery : TFDQuery; begin lQuery := TFDQuery.Create(nil); try lQuery.Connection := FConnection; lQuery.SQL.Add('DELETE FROM PESSOA WHERE id = :idPessoa '); lQuery.ParamByName('idPessoa').AsInteger := idPessoa; lQuery.ExecSQL; finally lQuery.Free; end; end; function TPessoaDAO.RetornarPessoa(idPessoa: int64; var pPessoa: TPessoa): Boolean; var lQuery: TFDQuery; begin lQuery := TFDQuery.Create(nil); try lQuery.Connection := FConnection; lQuery.SQL.Add('SELECT * FROM PESSOA WHERE id = :pIdPessoa'); lQuery.ParamByName('pIdPessoa').AsInteger := idPessoa; lQuery.Open; Result := lQuery.RecordCount > 0; if Result then begin pPessoa.FId := idPessoa; pPessoa.FNome := lQuery.FieldByName('nome').AsString; end; finally lQuery.Free; end; end; end.
unit MainWinUnit; {$mode objfpc}{$H+} interface uses SysUtils, StrUtils, fgl, Classes, Typinfo, MUI, muihelper, MUIClass.Base, MUIClass.Window, MUIClass.Area, MUIClass.List, MUIClass.Group, NodeTreeUnit, MUICompUnit, MUIClass.Gadget, MUIClass.Dialog, MUIClass.Image, MUIClass.Menu, IDETypes, menueditorunit; type TMainWindow = class(TMUIWindow) private FProjName: string; procedure SetProjName(AValue: string); public Tree: TItemTree; ItemList, PropList, EventList: TMUIListView; CurItem: TItemNode; CurProp,CurEvent: TItemProp; ItemProps, EventProps: TItemProps; TestApp: TMUIApplication; ChooseComp: TMUICycle; EditPages: TMUIGroup; BoolLabel, IntLabel, StringLabel, StrArrayLabel, ItemName, EventLabel: TMUIText; IntSet, StrSet, EventName: TMUIString; BoolSet: TMUICycle; AddBtn, RemBtn, AutoEvent, EditEvent: TMUIButton; IncludeProp: TMUICheckMark; PropPages: TMUIRegister; BlockEvents: Boolean; MenuLabel: TMUIText; // event handler procedure AddClick(Sender: TObject); procedure RemoveClick(Sender: TObject); procedure ShowEvent(Sender: TObject); procedure ItemListSelect(Sender: TObject); procedure PropListSelect(Sender: TObject); procedure PropDisplay(Sender: TObject; ToPrint: PPChar; Entry: PChar); procedure EventListSelect(Sender: TObject); procedure EventListDblClick(Sender: TObject); procedure EventDisplay(Sender: TObject; ToPrint: PPChar; Entry: PChar); procedure OpenStrArrayWin(Sender: TObject); procedure CreateMenuStrip(Sender: TObject); procedure RemoveMenuStrip(Sender: TObject); procedure MenuChangedEvent(Sender: TObject); procedure MenuSelectEvent(Sender: TObject); procedure IncludeChange(Sender: TObject); procedure AutoEventClick(Sender: TObject); procedure EditEventClick(Sender: TObject); // Menu events procedure NewClick(Sender: TObject); procedure LoadClick(Sender: TObject); procedure SaveClick(Sender: TObject); procedure ExportClick(Sender: TObject); procedure QuitClick(Sender: TObject); procedure AboutMenuClick(Sender: TObject); procedure ConfigMUIMenuClick(Sender: TObject); // Update Properties of CurItem procedure UpdateProperties; procedure UpdateItemList; procedure CreateSource(FileName: string); function FindEventHandler(Obj: TItemNode; Event: string): TEventHandler; public // TestWin stuff procedure CreateTestWin; procedure DestroyTestWin; // procedure SetIntProp(Sender: TObject); procedure SetBoolProp(Sender: TObject); procedure SetStringProp(Sender: TObject); procedure SetEvent(Sender: TObject); procedure ClickEvent(Sender: TObject); public constructor Create; override; destructor Destroy; override; property ProjName: string read FProjName write SetProjName; end; var MainWindow: TMainWindow; DefaultProjectPath: string; DefaultExportPath: string; implementation uses StrArraySetUnit, math, prefsunit; // Create Main Window constructor TMainWindow.Create; var Grp, Grp2: TMUIGroup; StrCycle: TStringArray; ME: TMUIMenu; ItemWin: TItemNode; TestWin: TMUIWindow; i: Integer; begin inherited; ProjName := ''; DefaultProjectPath := ExtractFilePath(ParamStr(0)); if FileExists(IncludeTrailingPathDelimiter(DefaultProjectPath) + 'projects') then DefaultProjectPath := IncludeTrailingPathDelimiter(DefaultProjectPath) + 'projects'; DefaultExportPath := ExtractFilePath(ParamStr(0)); ItemProps := TItemProps.Create(True); EventProps := TItemProps.Create(True); // Window props LeftEdge := 0; Height := MUIV_Window_Height_Visible(80); Width := MUIV_Window_Width_Visible(30); OnShow := @ShowEvent; // Top Panel Grp := TMUIGroup.Create; with Grp do begin Horiz := True; Parent := Self; end; // Choose Component // Create the ComboBox Entries from the List SetLength(StrCycle, MUIComps.Count); for i := 0 to MUIComps.Count - 1 do StrCycle[i] := ' ' + MUIComps[i].Name + ' '; ChooseComp := TMUICycle.Create; with ChooseComp do begin Entries := StrCycle; Parent := Grp; end; // Add a component AddBtn := TMUIButton.Create('Add'); with AddBtn do begin OnClick := @AddClick; Parent := Grp; end; // Remove Component RemBtn := TMUIButton.Create('Remove'); with RemBtn do begin OnClick := @RemoveClick; Parent := Grp; end; //##################################### // List of Items ItemList := TMUIListView.Create; with ItemList do begin List := TMUIList.Create; List.Font := MUIV_Font_Fixed; List.OnActiveChange := @ItemListSelect; Parent := Self; end; // ******************************* // List of Properties of the selected item ItemName := TMUIText.Create; ItemName.Parent := Self; PropPages := TMUIRegister.Create; with PropPages do begin Titles := ['Properties', 'Events']; Parent := Self; end; Grp := TMUIGroup.Create; with Grp do begin Frame := MUIV_Frame_None; Parent := PropPages; end; PropList := TMUIListView.Create; with PropList do begin List := TMUIList.Create; List.Font := MUIV_Font_Fixed; List.Format := 'BAR,P='#27'l' ; List.Title := #1; List.OnDisplay := @PropDisplay; List.OnActiveChange := @PropListSelect; Parent := Grp; end; Grp2 := TMUIGroup.Create; with Grp2 do begin Frame := MUIV_Frame_Group; FrameTitle := 'Set Property'; Parent := Grp; end; //############ Property Pages EditPages := TMUIGroup.Create; with EditPages do begin Frame := MUIV_Frame_None; PageMode := True; Parent := Grp2; end; // Empty Group for no properties to edit Grp := TMUIGroup.Create; Grp.Frame := MUIV_Frame_None; Grp.Parent := EditPages; With TMUIRectangle.Create do Parent := Grp; // Boolean Group for boolean properties Grp := TMUIGroup.Create; Grp.Frame := MUIV_Frame_None; Grp.Parent := EditPages; Grp.Horiz := True; BoolLabel := TMUIText.Create; with BoolLabel do begin Frame := MUIV_Frame_None; Contents := 'Test '; Parent := Grp; end; BoolSet := TMUICycle.Create; with BoolSet do begin Entries := ['False', 'True']; OnActiveChange := @SetBoolProp; Parent := Grp; end; // Integer Group for Integers to edit (might be extended for Special Values) Grp := TMUIGroup.Create; Grp.Horiz := True; Grp.Frame := MUIV_Frame_None; Grp.Parent := EditPages; IntLabel := TMUIText.Create; with IntLabel do begin Frame := MUIV_Frame_None; Contents := 'Test '; Parent := Grp; end; IntSet := TMUIString.Create; with IntSet do begin Accept := '1234567890-'; OnAcknowledge := @SetIntProp; Parent := Grp; end; // String Group to edit String properties Grp := TMUIGroup.Create; Grp.Frame := MUIV_Frame_None; Grp.Horiz := True; Grp.Parent := EditPages; StringLabel := TMUIText.Create; with StringLabel do begin Frame := MUIV_Frame_None; Contents := 'Test '; Parent := Grp; end; StrSet := TMUIString.Create; with StrSet do begin OnAcknowledge := @SetStringProp; Parent := Grp; end; // String Array Group to edit String Array properties Grp := TMUIGroup.Create; Grp.Frame := MUIV_Frame_None; Grp.Horiz := True; Grp.Parent := EditPages; StrArrayLabel := TMUIText.Create; with StrArrayLabel do begin Contents := 'Test '; Parent := Grp; end; with TMUIButton.Create('Edit') do begin OnClick := @OpenStrArrayWin; Parent := Grp; end; // Edit Menu strips properties Grp := TMUIGroup.Create; Grp.Frame := MUIV_Frame_None; Grp.Horiz := True; Grp.Parent := EditPages; MenuLabel := TMUIText.Create; with MenuLabel do begin Contents := 'Test '; Parent := Grp; end; with TMUIButton.Create('Create/Edit') do begin OnClick := @CreateMenuStrip; Parent := Grp; end; with TMUIButton.Create('Delete') do begin OnClick := @RemoveMenuStrip; Parent := Grp; end; // Include to File Grp := TMUIGroup.Create; with Grp do begin Frame := MUIV_Frame_None; Horiz := True; Parent := Grp2; end; IncludeProp := TMUICheckmark.Create; with IncludeProp do begin Disabled := True; OnSelected := @IncludeChange; Parent := Grp; end; with TMUIText.Create('Include in Source') do begin Frame := MUIV_Frame_None; Parent := Grp; end; //############ End Property Pages // ########### Start Event Stuff Grp := TMUIGroup.Create; with Grp do begin Frame := MUIV_Frame_None; Parent := PropPages; end; EventList := TMUIListView.Create; with EventList do begin List := TMUIList.Create; List.Font := MUIV_Font_Fixed; List.Format := 'BAR,P='#27'l' ; List.Title := #1; List.OnDisplay := @EventDisplay; List.OnActiveChange := @EventListSelect; OnDoubleClick := @EventListDblClick; Parent := Grp; end; Grp2 := TMUIGroup.Create; with Grp2 do begin Frame := MUIV_Frame_None; Horiz := True; Parent := Grp; end; EventLabel := TMUIText.Create; EventLabel.Parent := Grp2; EventName := TMUIString.Create; with EventName do begin OnAcknowledge := @SetEvent; Reject := ' ,.-+*!"§$%&/()=?''~^°^<>|@'; Parent := Grp2; end; AutoEvent := TMUIButton.Create('Auto'); with AutoEvent do begin OnClick := @AutoEventClick; ShowMe := False; Weight := 50; Parent := Grp2; end; EditEvent := TMUIButton.Create('Edit'); with EditEvent do begin OnClick := @EditEventClick; ShowMe := False; Weight := 50; Parent := Grp2; end; // ############# End Event Stuff // ############# Start Menu Entries MenuStrip := TMUIMenuStrip.Create; ME := TMUIMenu.Create; with ME do begin Title := 'Project'; Parent := MenuStrip end; with TMUIMenuItem.Create do begin Title := 'New'; OnTrigger := @NewClick; Parent := ME; end; with TMUIMenuItem.Create do begin Title := 'Load...'; OnTrigger := @LoadClick; Parent := ME; end; with TMUIMenuItem.Create do begin Title := 'Save...'; OnTrigger := @SaveClick; Parent := ME; end; with TMUIMenuItem.Create do begin Title := '-'; Parent := ME; end; with TMUIMenuItem.Create do begin Title := 'Export As Source'; OnTrigger := @ExportClick; Parent := ME; end; with TMUIMenuItem.Create do begin Title := '-'; Parent := ME; end; with TMUIMenuItem.Create do begin Title := 'Quit'; OnTrigger := @QuitClick; Parent := ME; end; // About ;) ME := TMUIMenu.Create; with ME do begin Title := 'About'; Parent := MenuStrip end; with TMUIMenuItem.Create do begin Title := 'About MUI...'; OnTrigger := @AboutMenuClick; Parent := ME; end; with TMUIMenuItem.Create do begin Title := '-'; Parent := ME; end; with TMUIMenuItem.Create do begin Title := 'Settings/MUI...'; OnTrigger := @ConfigMUIMenuClick; Parent := ME; end; // ############# End Menu Entries Tree := TItemTree.Create; Tree.Name := 'MUIApp'; TestApp := TMUIApplication.Create; TestApp.Title := ''; Tree.Data := TestApp; TestWin := TMUIWindow.Create; ItemWin := Tree.NewChild('Window1', TestWin); ItemWin.Properties.Add('Title'); TestWin.Title := 'Window1'; CurItem := Tree; if ParamCount > 0 then Tree.LoadFromFile(ParamStr(1)); end; // Destroy MainWindow destructor TMainWindow.Destroy; begin Tree.Free; ItemProps.Free; EventProps.Free; inherited; end; // Add Properties to Output Source as Assignment in the Sourcecode procedure AddProperties(Node: TItemNode; Ind: string; SL: TStringList); var PT : PTypeData; PI : PTypeInfo; I,J,n : Longint; PP : PPropList; Value: Integer; ValueS: string; Obj: TObject; EV: TEventHandler; begin // normal items Obj := Node.Data; PI := Obj.ClassInfo; PT := GetTypeData(PI); GetMem (PP, PT^.PropCount * SizeOf(Pointer)); J := GetPropList(PI, tkAny, PP); for I:=0 to J-1 do begin with PP^[i]^ do begin // Only include the Properties which are marked as changed if (Node.Properties.IndexOf(Name) < 0) and not (PropType^.Kind = tkMethod) then Continue; // Type of the Property case PropType^.Kind of // Events tkMethod: begin EV := MainWindow.FindEventHandler(Node, Name); if Assigned(EV) then begin SL.Add(Ind + Name + ' := @' + EV.Event + ';'); end; end; // Integer tkInteger: begin Value := GetOrdProp(Obj, PP^[i]); if Value <> Default then SL.Add(Ind + Name + ' := ' + IntToStr(Value) + ';'); end; // Boolean tkBool: begin Value := GetOrdProp(Obj, PP^[i]); if Boolean(Value) <> Boolean(Default) then SL.Add(Ind + Name + ' := ' + BoolToStr(Boolean(Value), True) + ';'); end; // String/AnsiString tkString, tkAString: begin ValueS := GetStrProp(Obj, PP^[i]); if ValueS <> '' then SL.Add(Ind + Name + ' := ''' + ValueS + ''';'); end; // DynArray have to be explicitly ... sadly tkDynArray: begin // Cycle.Entries if (Obj is TMUICycle) and (Name = 'Entries') then begin if Length(TMUICycle(Obj).Entries) > 0 then begin for n := 0 to High(TMUICycle(Obj).Entries) do begin if n = 0 then ValueS := '''' + TMUICycle(Obj).Entries[0] + '''' else ValueS := ValueS + ', ''' + TMUICycle(Obj).Entries[n] + ''''; end; SL.Add(Ind + Name + ' := [' + ValueS + '];'); end; end; // Register.Titles if (Obj is TMUIRegister) and (Name = 'Titles') then begin if Length(TMUIRegister(Obj).Titles) > 0 then begin for n := 0 to High(TMUIRegister(Obj).Titles) do begin if n = 0 then ValueS := TMUIRegister(Obj).Titles[0] else ValueS := ValueS + ', ''' + TMUIRegister(Obj).Titles[n] + ''''; end; SL.Add(Ind + Name + ' := [' + ValueS + '];'); end; end; end; end; end; end; FreeMem(PP); end; procedure CollectUnits(Base: TItemNode; SL: TStringList); var i: Integer; CL: TObject; begin Cl := Base.Data; for i := 0 to MUIComps.Count - 1 do begin if Cl.ClassName = MUIComps[i].MUIClass.ClassName then begin if SL.IndexOf(MUIComps[i].AUnit) < 0 then SL.Add(MUIComps[i].AUnit); Break; end; end; for i := 0 to Base.Count - 1 do CollectUnits(Base.Child[i], SL); end; procedure CollectFields(Indent: string; Base: TItemNode; SL: TStringList); var i: Integer; begin for i := 0 to Base.Count - 1 do begin SL.Add(Indent + Base.Child[i].Name + ': ' + Base.Child[i].Data.ClassName + ';'); CollectFields(Indent, Base.Child[i], SL); end; end; procedure CollectEventHeader(Indent: string; Base: TItemNode; SL: TStringList); var i: Integer; begin for i := 0 to Base.Events.Count - 1 do SL.Add(Indent + StringReplace(Base.Events[i].PlainHeader, '%name%.', '', [rfReplaceAll])); for i := 0 to Base.Count - 1 do CollectEventHeader(Indent, Base.Child[i], SL); end; procedure CollectInits(Indent: string; Base: TItemNode; SL: TStringList); var i: Integer; Item: TItemNode; Cl: TObject; begin for i := 0 to Base.Count - 1 do begin Item := Base.Child[i]; Cl := Item.Data; SL.Add(' ' + Item.Name + ' := ' + Cl.Classname + '.Create;'); SL.Add(' with ' + Item.Name + ' do'); SL.Add(' begin'); AddProperties(Item, ' ', SL); if Item.ParentIdent = '' then if Item.Parent.Data is TMUIWindow then SL.Add(' Parent := Self;') else SL.Add(' Parent := ' + Item.Parent.Name + ';'); SL.Add(' end;'); if Item.ParentIdent <> '' then begin if Item.Parent.Data is TMUIWindow then SL.Add(' ' + Item.ParentIdent + ' := ' + Item.Name + ';') else SL.Add(' ' + Item.Parent.Name + '.' + Item.ParentIdent + ' := ' + Item.Name + ';') end; SL.Add(' '); // CollectInits(Indent, Item, SL); end; end; procedure CollectEvents(Indent: string; Base: TItemNode; SL: TStringList); var i: Integer; begin // eventhandlers for i := 0 to Base.Events.Count - 1 do begin SL.Add(Base.Events[i].Text); SL.Add(''); end; for i := 0 to Base.Count - 1 do CollectEvents(Indent, Base.Child[i], SL); end; // Create the Source code from the settings procedure TMainWindow.CreateSource(FileName: string); var SL, UL, TL: TStringList; i, n, m: Integer; Ident, str: string; Win: TItemNode; MainUnits: string; begin SL := TStringList.Create; UL := TStringList.Create; TL := TStringList.Create; try MainUnits := 'MUIClass.Base'; for n := 0 to Tree.Count - 1 do begin if Tree.Child[n].Data is TMUIWindow then begin Win := Tree.Child[n]; UL.Clear; SL.Clear; Ident := Win.Name + 'Unit'; MainUnits := MainUnits + ', ' + Ident; SL.Add('unit ' + Ident + ';'); SL.Add('{$mode objfpc}{$H+}'); SL.Add('interface'); SL.Add('uses'); // UL.Add('MUIClass.Base'); UL.Add('MUIClass.Window'); UL.Add('MUIClass.Menu'); CollectUnits(Win, UL); for i := 0 to UL.Count - 1 do begin if i = 0 then str := ' ' + UL[0] else str := str + ', ' + UL[i]; end; SL.Add(str + ';'); SL.Add('type'); SL.Add(' T' + Win.Name + ' = class(TMUIWindow)'); CollectFields(' ', Win, SL); CollectEventHeader(' ', Win, SL); SL.Add(' constructor Create; override;'); SL.Add(' end;'); SL.Add('var'); SL.Add(' ' + Win.Name + ': T' + Win.Name + ';'); SL.Add('implementation'); UL.Clear; for m := 0 to Tree.Count - 1 do begin if (Tree.Child[m].Data is TMUIWindow) and (m <> n) then UL.Add(Tree.Child[m].Name + 'Unit'); end; if UL.Count > 0 then begin for i := 0 to UL.Count - 1 do begin if i = 0 then str := ' ' + UL[0] else str := str + ', ' + UL[i]; end; SL.Add('uses'); SL.Add(str + ';'); end; SL.Add(''); SL.Add('constructor T' + Win.Name + '.Create;'); SL.Add('begin'); SL.Add(' inherited;'); AddProperties(Win, ' ', SL); CollectInits(' ', Win, SL); SL.Add('end;'); SL.Add(''); CollectEvents(' ', Win, SL); // SL.Add(''); SL.Add('end.'); SL.SaveToFile(ExtractFilePath(Filename) + Ident + '.pas'); TL.Add(Win.Name); end; end; SL.Clear; // Main Program Ident := ChangeFileExt(ExtractFileName(Filename), ''); SL.Add('program ' + Ident + ';'); SL.Add('{$mode objfpc}{$H+}'); SL.Add('uses'); SL.Add(' ' + MainUnits + ';'); SL.Add(''); SL.Add('begin'); for i := 0 to TL.Count - 1 do SL.Add(' ' + TL[i] + ' := T' + TL[i] + '.Create;'); SL.Add(' with MUIApp do'); SL.Add(' begin'); AddProperties(Tree, ' ', SL); SL.Add(' end;'); SL.Add(' MUIApp.Run;'); SL.Add('end.'); SL.SaveToFile(ExtractFilePath(Filename) + Ident + '.pas'); finally UL.Free; SL.Free; TL.Free; end; end; // Save the Source File procedure TMainWindow.ExportClick(Sender: TObject); var FD: TFileDialog; begin FD := TFileDialog.Create; try FD.TitleText := 'Choose Name for Source file to export'; FD.FileName := IncludeTrailingPathDelimiter(DefaultExportPath) + 'MyProgram.pas'; FD.Pattern := '#?.pas'; FD.SaveMode := True; if FD.Execute then begin DefaultExportPath := FD.Directory; CreateSource(FD.FileName); end; finally FD.Free; end; end; // Update Item List from the Tree (build the Fake Tree) procedure TMainWindow.UpdateItemList; var i, OldActive: Integer; begin // remember which element was active before OldActive := ItemList.List.Active; // Block redrawing ItemList.List.Quiet := True; // remove all entries while ItemList.List.Entries > 0 do ItemList.List.Remove(MUIV_List_Remove_Last); // Updates the Nodes Texts and Numbers Tree.UpdateNodesText; // Insert the Nodes as Pseudo Tree for i := 0 to Tree.NodesText.Count - 1 do begin ItemList.List.InsertSingle(PChar(Tree.NodesText[i]), MUIV_List_Insert_Bottom); end; // ready to draw again ItemList.List.Quiet := False; // set the active element again MH_Set(ItemList.List.MUIObj, MUIA_List_Active, OldActive); EditPages.ActivePage := 0; // nothing to edit by default end; // Find the Eventhandler for the Given Object Node and EventName (On....) function TMainWindow.FindEventHandler(Obj: TItemNode; Event: string): TEventHandler; var i: Integer; begin Result := nil; for i := 0 to Obj.Events.Count - 1 do begin if Event = Obj.Events[i].Name then begin Result := Obj.Events[i]; Break; end; end; end; // extract Footprint of the needed Eventhandler for example: "procedure (Sender: TObject)" function GetParams(MT: PTypeData): TEventParams; var i, j: Integer; p: PByte; Str: string; Num: Integer; begin // Number of Params is easy, just take it ;) SetLength(Result, MT^.ParamCount); P := @(MT^.ParamList[0]); // Names and types of the Parameter you have to calculate yourself // 1 Byte Flags (like var/out/const) // 1 Byte NameLength, Number of Chars follow as Name // n Bytes Name // 1 Byte TypeLength, Number of Chars follow as Type // n Bytes TypeIdent // and that for every parameter for i := 0 to High(Result) do begin // Get the Flag Result[i].Style := PParamFlags(P)^; Inc(p, SizeOf(TParamFlags)); // // Number of chars to read for name Num := P^; Inc(P); // Read Chars an form the string Str := ''; for j := 1 to Num do begin Str := Str + Char(P^); Inc(P); end; Result[i].Name := str; // // number of Chars to read for Type Num := P^; Inc(P); // Read Chars and form the string Str := ''; for j := 1 to Num do begin Str := Str + Char(P^); Inc(P); end; Result[i].Typ := str; end; end; // Update Properties of a selected Item in the ItemList procedure TMainWindow.UpdateProperties; var PT, MT : PTypeData; PI : PTypeInfo; I,J,n : Longint; PP : PPropList; Obj: TObject; ItemProp: TItemProp; a, b: array of PChar; EV: TEVentHandler; PL: TEventParams; begin // Block Property and Event list PropList.List.Quiet := True; EventList.List.Quiet := True; // Clear Property and Event list while PropList.List.Entries > 0 do PropList.List.Remove(MUIV_List_Remove_Last); while EventList.List.Entries > 0 do EventList.List.Remove(MUIV_List_Remove_Last); EventProps.Clear; ItemProps.Clear; // Only make sense if a Item is selected and has an attached MUIClass Object if Assigned(CurItem) and Assigned(CurItem.Data) then begin //Special Properties, Name is not a real field, just for us to name the field later ItemProp := TItemProp.Create; ItemProp.Name := 'Name'; ItemProp.IsSpecial := True; ItemProp.Value := CurItem.Name; ItemProp.Active := False; ItemProps.Add(ItemProp); // normal Properties Obj := CurItem.Data; // Object to inspect PI := Obj.ClassInfo; PT := GetTypeData(PI); GetMem (PP, PT^.PropCount * SizeOf(Pointer)); J := GetPropList(PI, tkAny, PP); // List of published properties for I:=0 to J-1 do begin With PP^[i]^ do begin case PropType^.Kind of // ####################### Class tkClass: begin if LowerCase(Name) = 'menustrip' then begin ItemProp := TItemProp.Create; ItemProp.Name := Name; ItemProp.IsSpecial := False; ItemProp.Value := '<>'; ItemProp.Active := False; for n := 0 to CurItem.Count - 1 do begin if (LowerCase(CurItem[n].ParentIdent) = 'menustrip') then begin ItemProp.Value := '<' + CurItem[n].Name + '>'; ItemProp.Active := True; Break; end; end; ItemProps.Add(ItemProp); end else writeln(name, ' as class found ', GetObjectPropClass(Obj, Name).ClassName); end; // ####################### Method tkMethod: begin ItemProp := TItemProp.Create; ItemProp.Name := Name; MT := GetTypeData(PropType); PL := GetParams(MT); if MT^.MethodKind = mkFunction then ItemProp.Additional := 'function %name%(' else ItemProp.Additional := 'procedure %name%('; for n := 0 to High(PL) do begin if pfVar in PL[n].Style then ItemProp.Additional := ItemProp.Additional + 'var '; if pfConst in PL[n].Style then ItemProp.Additional := ItemProp.Additional + 'const '; if pfOut in PL[n].Style then ItemProp.Additional := ItemProp.Additional + 'out '; if n = High(PL) then ItemProp.Additional := ItemProp.Additional + PL[n].Name + ': ' + PL[n].Typ else ItemProp.Additional := ItemProp.Additional + PL[n].Name + ': ' + PL[n].Typ + '; '; end; ItemProp.Additional := ItemProp.Additional + ')'; ItemProp.IsSpecial := False; EV := FindEventHandler(CurItem, Name); if Assigned(Ev) then ItemProp.Value := Ev.Event else ItemProp.Value := ''; ItemProp.Active := Assigned(Ev); EventProps.Add(ItemProp); end; // ######################## Integer tkInteger: begin ItemProp := TItemProp.Create; ItemProp.Name := Name; ItemProp.IsSpecial := False; ItemProp.Value := IntToStr(GetOrdProp(Obj, PP^[i])); ItemProp.Active := CurItem.Properties.IndexOf(Name) >= 0; ItemProps.Add(ItemProp); end; // ####################### Boolean tkBool: begin ItemProp := TItemProp.Create; ItemProp.Name := Name; ItemProp.IsSpecial := False; ItemProp.Value := BoolToStr(Boolean(GetOrdProp(Obj, PP^[i])), True); ItemProp.Active := CurItem.Properties.IndexOf(Name) >= 0; ItemProps.Add(ItemProp); end; // ####################### String tkString, tkAString: begin ItemProp := TItemProp.Create; ItemProp.Name := Name; ItemProp.IsSpecial := False; ItemProp.Value := '''' + GetStrProp(Obj, PP^[i])+''''; ItemProp.Active := CurItem.Properties.IndexOf(Name) >= 0; ItemProps.Add(ItemProp); end; // ##################### DynArray (TStringArray) tkDynArray: begin if (Obj is TMUICycle) and (Name = 'Entries') then begin ItemProp := TItemProp.Create; ItemProp.Name := Name; ItemProp.IsSpecial := False; ItemProp.Value := '<Array ' + IntToStr(Length(TMUICycle(Obj).Entries)) + ' Entries>'; ItemProp.Active := CurItem.Properties.IndexOf(Name) >= 0; ItemProps.Add(ItemProp); end; if (Obj is TMUIRegister) and (Name = 'Titles') then begin ItemProp := TItemProp.Create; ItemProp.Name := Name; ItemProp.IsSpecial := False; ItemProp.Value := '<Array ' + IntToStr(Length(TMUIRegister(Obj).Titles)) + ' Entries>'; ItemProp.Active := CurItem.Properties.IndexOf(Name) >= 0; ItemProps.Add(ItemProp); end; end; //else // writeln(name, 'Not handled Type: ', PropType^.Kind); // still unknown Types needs Handler end; end; end; FreeMem(PP); end; // Faster Setting to the List we form an Array with all the names // for ItemList SetLength(A, ItemProps.Count + 1); for i := 0 to ItemProps.Count - 1 do A[i] := PChar(ItemProps[i].Name); A[High(A)] := nil; PropList.List.Insert(@a[0], ItemProps.Count, MUIV_List_Insert_Bottom); PropList.List.Quiet := False; // For EventList SetLength(B, EventProps.Count + 1); for i := 0 to EventProps.Count - 1 do B[i] := PChar(EventProps[i].Name); B[High(B)] := nil; EventList.List.Insert(@B[0], EventProps.Count, MUIV_List_Insert_Bottom); EventList.List.Quiet := False; // By default no property is selected -> EditPages is Off EditPages.ActivePage := 0; end; // Title names for the Property List and Event List var Title1: string = 'Property'; Title2: string = 'Value'; Title3: string = 'Event'; Title4: string = 'Handler'; // Display event for the Properties List procedure TMainWindow.PropDisplay(Sender: TObject; ToPrint: PPChar; Entry: PChar); var Idx: Integer; p: PLongInt; ItemProp: TItemProp; begin P := PLongInt(ToPrint); Dec(P); Idx := P^; if (Idx >= 0) and (Idx < ItemProps.Count) and Assigned(Entry) then begin ItemProp := ItemProps[Idx]; ToPrint[0] := PChar(ItemProp.DisplayName); ToPrint[1] := PChar(ItemProp.DisplayValue); end else begin ToPrint[0] := PChar(Title1); ToPrint[1] := PChar(Title2); end; end; // Display event for the Event List procedure TMainWindow.EventDisplay(Sender: TObject; ToPrint: PPChar; Entry: PChar); var Idx: Integer; p: PLongInt; EventProp: TItemProp; begin P := PLongInt(ToPrint); Dec(P); Idx := P^; if (Idx >= 0) and (Idx < EventProps.Count) and Assigned(Entry) then begin EventProp := EventProps[Idx]; ToPrint[0] := PChar(EventProp.DisplayName); ToPrint[1] := PChar(EventProp.DisplayValue); end else begin ToPrint[0] := PChar(Title3); ToPrint[1] := PChar(Title4); end; end; // Item Got selected -> show its Property procedure TMainWindow.ItemListSelect(Sender: TObject); var Idx: Integer; begin Idx := ItemList.List.Active; if (Idx >= 0) and (Idx < Tree.AllCount) then begin CurItem := Tree.AllChild[Idx]; ItemName.Contents := 'Properties of ' + CurItem.Name; if CurItem.Data is TMUIFamily then begin ChooseComp.Disabled := True; AddBtn.Contents := 'Add'; AddBtn.Disabled := True; RemBtn.Disabled := True; end else if CurItem.Data is TMUIApplication then begin ChooseComp.Disabled := True; AddBtn.Disabled := False; AddBtn.Contents := 'Add Window'; RemBtn.Disabled := True; end else begin ChooseComp.Disabled := False; AddBtn.Disabled := False; AddBtn.Contents := 'Add'; RemBtn.Disabled := False; end; end; UpdateProperties; end; // Property got selected -> show the Edit Panel for it procedure TMainWindow.PropListSelect(Sender: TObject); var Idx: Integer; PT : PTypeData; PI : PTypeInfo; I,J : Longint; PP : PPropList; Obj: TObject; PropName: string; begin BlockEvents := True; Idx := PropList.List.Active; if (Idx >= 0) and (Idx < ItemProps.Count) and Assigned(CurItem) and Assigned(CurItem.Data) then begin CurProp := ItemProps[Idx]; // if StrArrayWin.Open then StrArrayWin.Close; // special name! if CurProp.IsSpecial then begin // Name of Application not editable if CurItem.Data is TMUIApplication then begin EditPages.ActivePage := 0; IncludeProp.Disabled := True; Exit; end; PropName := CurItem.Name + '.' + CurProp.Name; StringLabel.Contents := PropName; StrSet.Reject := ' ,.-+*!"§$%&\/()=?''~^°^<>|@'; //-> do not allow chars not allowed in an Ident (will check later also the string again) StrSet.Contents := CurProp.Value; EditPages.ActivePage := 3; IncludeProp.Disabled := True; BlockEvents := False; Exit; end; Obj := CurItem.Data; PI := Obj.ClassInfo; PT := GetTypeData(PI); GetMem (PP, PT^.PropCount * SizeOf(Pointer)); J := GetPropList(PI, tkAny, PP); for I:=0 to J-1 do begin With PP^[i]^ do begin if Name = CurProp.Name then begin PropName := CurItem.Name + '.' + CurProp.Name; case PropType^.Kind of tkClass: begin if LowerCase(Name) = 'menustrip' then begin MenuLabel.Contents := PropName; EditPages.ActivePage := 5; end; end; // ################## Integer tkInteger: begin IntLabel.Contents := PropName; IntSet.Contents := IntToStr(GetOrdProp(Obj, PP^[i])); EditPages.ActivePage := 2; IncludeProp.Disabled := False; IncludeProp.Selected := CurProp.Active; end; // ################## Boolean tkBool: begin BoolLabel.Contents := PropName; if GetOrdProp(Obj, PP^[i]) = 0 then begin BoolSet.Active := 0 end else begin BoolSet.Active := 1; end; EditPages.ActivePage := 1; IncludeProp.Disabled := False; IncludeProp.Selected := CurProp.Active; end; // ################## String tkString, tkAString: begin StringLabel.Contents := PropName; StrSet.Reject := ''; StrSet.Contents := GetStrProp(Obj, PP^[i]); EditPages.ActivePage := 3; IncludeProp.Disabled := False; IncludeProp.Selected := CurProp.Active; end; // ################## dynamic arrays (TStringArray) tkDynArray: begin StrArrayLabel.Contents := PropName; StrArrayWin.Title := PropName; StrArrayWin.Obj := Obj; StrArrayWin.PropName := CurProp.Name; StrArrayWin.CurProp := CurProp; StrArrayWin.CurItem := CurItem; if (Obj is TMUICycle) and (CurProp.Name = 'Entries') then begin StrArrayWin.StrArray := TMUICycle(Obj).Entries; EditPages.ActivePage := 4; IncludeProp.Disabled := False; IncludeProp.Selected := CurProp.Active; end else if (Obj is TMUIRegister) and (CurProp.Name = 'Titles') then begin StrArrayWin.StrArray := TMUIRegister(Obj).Titles; EditPages.ActivePage := 4; IncludeProp.Disabled := False; IncludeProp.Selected := CurProp.Active; end else begin EditPages.ActivePage := 0; IncludeProp.Disabled := True; end; end; else begin EditPages.ActivePage := 0; IncludeProp.Disabled := True; end; end; Break; end; end; end; FreeMem(PP); end else begin EditPages.ActivePage := 0; IncludeProp.Disabled := True; end; BlockEvents := False; end; // Event in the List selected -> show edit for it procedure TMainWindow.EventListSelect(Sender: TObject); var Idx: Integer; EV: TEventHandler; begin BlockEvents := True; EV := Nil; Idx := EventList.List.Active; if (Idx >= 0) and (Idx <EventProps.Count) then begin CurEvent := EventProps[Idx]; EV := FindEventHandler(CurItem, CurEvent.Name); if Assigned(EV) then begin EventName.Contents := Ev.Event; AutoEvent.ShowMe := False; EditEvent.ShowMe := True; end else begin EventName.Contents := ''; AutoEvent.ShowMe := True; EditEvent.ShowMe := False; end; EventLabel.Contents := CurItem.Name + '.' + CurEvent.Name; EventName.Disabled := False; end else begin CurEvent := nil; EventLabel.Contents := ''; EventName.Contents := ''; EventName.Disabled := True; end; BlockEvents := False; end; // Event double clicked -> auto edit it, maybe also create it procedure TMainWindow.EventListDblClick(Sender: TObject); begin EventListSelect(Sender); // Select entry if EventName.Contents = '' then // if no Name given until now auto create it AutoEventClick(Sender); EditEventClick(Sender); // Edit the Eventhandler entry end; // User set a new EventHandler Name (fired on Enter press in the Edit or when AutoNaming is done) procedure TMainWindow.SetEvent(Sender: TObject); var Ev: TEventHandler; WinName, Value: string; SL: TStringList; SNode: TItemNode; begin if BlockEvents then Exit; if Assigned(CurEvent) then begin EV := FindEventHandler(CurItem, CurEvent.Name); Value := Trim(EventName.Contents); // if the name the user Entered is empty, we will remove the EventHandler if Value = '' then begin if Assigned(EV) then CurItem.Events.Remove(Ev); CurEvent.Value := ''; CurEvent.Active := False; EventList.List.Redraw(MUIV_List_Redraw_Active); AutoEvent.ShowMe := True; EditEvent.ShowMe := False; end else begin // Check if we got a valid ident if isValidIdent(Value) then begin // create the Eventhandler if not exists if not Assigned(Ev) then begin Ev := TEventHandler.Create; Ev.Name := CurEvent.Name; CurItem.Events.Add(Ev); end; Ev.Event := Value; WinName := 'Dummy'; SNode := CurItem; repeat if SNode.Data is TMUIWindow then begin WinName := SNode.Name; Break; end; SNode := SNode.Parent; until not Assigned(SNode); Ev.PlainHeader := StringReplace(CurEvent.Additional, '%name%', Value, []) + ';'; Ev.Header := StringReplace(CurEvent.Additional, '%name%', 'T' + WinName + '.' + Value, []) + ';'; // Eventhandler contents, or just replace the first line with the new header if EV.Text = '' then Ev.Text := EV.Header + #13#10 +'begin'#13#10#13#10+'end;' else begin SL := TStringList.Create; SL.Text := EV.Text; SL[0] := EV.Header; EV.Text := SL.Text; SL.Free; end; CurEvent.Value := Value; CurEvent.Active := True; EventList.List.Redraw(MUIV_List_Redraw_Active); AutoEvent.ShowMe := False; EditEvent.ShowMe := True; end else ShowMessage('''' + Value + ''' is not a valid method name.'); end; end; end; // Program decide how the event should be named // by default thats the name of the Item + Name of Event (without the On) procedure TMainWindow.AutoEventClick(Sender: TObject); var Val: string; begin if Assigned(CurItem) and Assigned(CurEvent) then begin Val := CurEvent.Name; if LowerCase(Copy(Val, 1, 2)) = 'on' then Delete(Val, 1, 2); Val := CurItem.Name + Val; EventName.Contents := Val; SetEvent(nil); end; end; // Edit the Eventhandler contents, the actual code for it procedure TMainWindow.EditEventClick(Sender: TObject); var SL: TStringList; EV: TEventHandler; TmpName: string; Num: Integer; Tmp: string; begin if not Assigned(CurItem) or not Assigned(CurEvent) then Exit; EV := FindEventHandler(CurItem, CurEvent.Name); if not Assigned(EV) then Exit; SL := TStringList.Create; try SL.Text := EV.Text; // explanation for user as comment SL.Insert(0,'// Edit the Eventhandler, save and close to return to MUIIDE.'#13#10'// Do NOT change/remove the first 3 lines.'); // Find a temp name which is not exisiting already, if someone got the crazy idea of starting 2 MUIIDEs ;-) Num := 0; repeat TmpName := 'T:MUIGUI_' + IntToStr(Num) + '.pas'; Inc(Num); until not FileExists(TmpName); // Save the current Eventhandler Text to the temp file SL.SaveToFile(TmpName); MUIApp.Iconified := True; // Hide the main application (or it would show bad redraw errors) // Run the Editor try SysUtils.ExecuteProcess(IDEPrefs.Editor, TmpName, []); except ShowMessage('Cant execute Editor: "' + IDEPrefs.Editor + '"'); MUIApp.Iconified := False; // get main application back Exit; end; MUIApp.Iconified := False; // get main application back if IDEPrefs.EditorMsg then ShowMessage('Press OK when you finished editing.'); try SL.LoadFromFile(TmpName); // load what the user did except ShowMessage('Unable to reload your changed file'); Exit; end; Tmp := SL[0]; if Copy(Tmp, 1,2) = '//' then SL.Delete(0); Tmp := SL[0]; if Copy(Tmp, 1,2) = '//' then SL.Delete(0); SL[0] := EV.Header; EV.Text := SL.Text; DeleteFile(TmpName); finally SL.Free; end; end; // Set Integer Property from the Edit Element procedure TMainWindow.SetIntProp(Sender: TObject); var Idx: Integer; begin if BlockEvents then Exit; Idx := PropList.List.Active; if (Idx >= 0) and (Idx < ItemProps.Count) and Assigned(CurItem) and Assigned(CurItem.Data) then begin CurProp := ItemProps[Idx]; // DestroyTestWin; if CurItem.Properties.IndexOf(CurProp.Name) < 0 then CurItem.Properties.Add(CurProp.Name); CurProp.Active := True; SetOrdProp(CurItem.Data, CurProp.Name, IntSet.IntegerValue); CurProp.Value := IntToStr(IntSet.IntegerValue); IncludeProp.Selected := True; PropList.List.Redraw(MUIV_List_Redraw_Active); if (CurItem.Data is TMUIFamily) and MenuEditor.Open then MenuEditor.Recreate; CreateTestWin; end; end; // set boolean property from the combobox procedure TMainWindow.SetBoolProp(Sender: TObject); var Idx: Integer; begin if BlockEvents then Exit; Idx := PropList.List.Active; if (Idx >= 0) and (Idx < ItemProps.Count) and Assigned(CurItem) and Assigned(CurItem.Data) then begin CurProp := ItemProps[Idx]; // DestroyTestWin; if CurItem.Properties.IndexOf(CurProp.Name) < 0 then CurItem.Properties.Add(CurProp.Name); SetOrdProp(CurItem.Data, CurProp.Name, BoolSet.Active); CurProp.Value := BoolToStr(Boolean(BoolSet.Active), True); CurProp.Active := True; IncludeProp.Selected := True; PropList.List.Redraw(MUIV_List_Redraw_Active); if (CurItem.Data is TMUIFamily) and MenuEditor.Open then MenuEditor.Recreate; CreateTestWin; // end; end; // Set string property from the Edit Component procedure TMainWindow.SetStringProp(Sender: TObject); var Idx: Integer; Str: string; begin if BlockEvents then Exit; Idx := PropList.List.Active; if (Idx >= 0) and (Idx < ItemProps.Count) and Assigned(CurItem) and Assigned(CurItem.Data) then begin CurProp := ItemProps[Idx]; // DestroyTestWin; if CurProp.IsSpecial then begin Str := StrSet.Contents; if IsValidIdent(Str) then CurItem.Name := Str else ShowMessage('''' + Str + ''' is not a valid identifier'); UpdateItemList; if (CurItem.Data is TMUIFamily) and MenuEditor.Open then MenuEditor.Recreate; end else begin if CurItem.Properties.IndexOf(CurProp.Name) < 0 then CurItem.Properties.Add(CurProp.Name); SetStrProp(CurItem.Data, CurProp.Name, StrSet.Contents); CurProp.Value := '''' + StrSet.Contents + ''''; CurProp.Active := True; IncludeProp.Selected := True; PropList.List.Redraw(MUIV_List_Redraw_Active); if (CurItem.Data is TMUIFamily) and MenuEditor.Open then MenuEditor.Recreate; end; CreateTestWin; // end; end; // Event for Include Checkbox/defines if the Property is included into the Source or not procedure TMainWindow.IncludeChange(Sender: TObject); begin CurProp.Active := IncludeProp.Selected; PropList.List.Redraw(MUIV_List_Redraw_Active); end; // Open TStringArray Edit Window to let the User edit the list of items // its configured already in the Property selection procedure procedure TMainWindow.OpenStrArrayWin(Sender: TObject); begin StrArrayWin.Show; end; procedure TMainWindow.CreateMenuStrip(Sender: TObject); var Node: TItemNode; NMenu: TMUIMenu; NName: string; i, Num: Integer; begin Node := nil; for i := 0 to CurItem.Count - 1 do begin if LowerCase(CurItem[i].ParentIdent) = 'menustrip' then begin Node := CurItem[i]; Break; end; end; if not Assigned(Node) then begin Num := 1; repeat NName := 'MenuStrip' + IntToStr(Num); Inc(Num); Until Tree.AllChildByName(NName) < 0; DestroyTestWin; Node := CurItem.NewOtherChild('MenuStrip', NName, TMUIMenuStrip.Create); Num := 1; repeat NName := 'Menu' + IntToStr(Num); Inc(Num); Until Tree.AllChildByName(NName) < 0; NMenu := TMUIMenu.Create; Node := Node.NewChild(NName, NMenu); NMenu.Title := NName; Node.Properties.Add('Title'); CreateTestWin; end; MenuEditor.Execute(Node); UpdateItemList; end; procedure TMainWindow.RemoveMenuStrip(Sender: TObject); var Node: TItemNode; i: Integer; begin Node := nil; for i := 0 to CurItem.Count - 1 do begin if LowerCase(CurItem[i].ParentIdent) = 'menustrip' then begin Node := CurItem[i]; Break; end; end; if Assigned(Node) then begin DestroyTestWin; Node.Free; CreateTestWin; UpdateItemList; end; end; procedure TMainWindow.MenuChangedEvent(Sender: TObject); begin DestroyTestWin; CreateTestWin; UpdateItemList; end; procedure TMainWindow.MenuSelectEvent(Sender: TObject); var i: Integer; begin if Assigned(MenuEditor.SelectedItem) then begin for i := 0 to Tree.AllCount - 1 do begin if Tree.AllChild[i] = MenuEditor.SelectedItem then begin if ItemList.List.Active <> i then ItemList.List.Active := i; Break; end; end; end; end; procedure TMainWindow.ClickEvent(Sender: TObject); var i: Integer; begin for i := 0 to Tree.AllCount - 1 do begin if Tree.AllChild[i].Data = Sender then begin if ItemList.List.Active <> i then ItemList.List.Active := i; Break; end; end; end; // Create the TestWindow and show to the user the current settings visually procedure TMainWindow.CreateTestWin; var Item: TItemNode; i: Integer; TestWin: TMUIWindow; begin for i := 0 to Tree.AllCount - 1 do begin Item := Tree.AllChild[i]; if Assigned(Item.Parent) and (not (Item.Data is TMUIWindow)) then begin if Item.ParentIdent <> '' then begin try SetObjectProp(Item.Parent.Data, Item.ParentIdent, Item.Data); except end; end else TMUIWithParent(Item.Data).Parent := TMUIWithParent(Item.Parent.Data); end; end; for i := 0 to Tree.Count - 1 do begin Item := Tree.Child[i]; TestWin := nil; if Item.Data is TMUIWindow then begin TestWin := TMUIWindow(Item.Data); TestWin.Show; end; end; Activate := True; end; // Remove Parent from the MUI object for a save Destruction of the TestWindow -> see there procedure RemoveParent(A: TItemNode); var i: Integer; begin if A.ParentIdent = '' then begin for i := 0 to A.Count - 1 do RemoveParent(A.Child[i]); if A.Data is TMUIWithParent then begin TMUIWithParent(A.Data).Parent := nil; end; end; end; // Destroy the TestWindow procedure TMainWindow.DestroyTestWin; var I: Integer; Item: TItemNode; Win: TMUIWindow; begin for i := 0 to Tree.Count - 1 do begin Item := Tree.Child[i]; if Item.Data is TMUIWindow then begin Win := TMUIWindow(Item.Data); if Win.HasObj then // is there something to destroy? begin Win.Close; // first close it (make it much faster when it does not need to redraw when we remove the childs) RemoveParent(Item); // every MUI item loose its parent Win.Parent := nil; // decouple the Window from the application Win.DestroyObject; // and gone end; end; end; end; // Show the Window, Update Item List and create the empty Window procedure TMainWindow.ShowEvent(Sender: TObject); begin UpdateItemList; ItemList.List.Active := 0; CreateTestWin; MenuEditor.OnMenuChanged := @MenuChangedEvent; // event for the menu editor to trigger recreation of itemlist MenuEditor.OnItemSelect := @MenuSelectEvent; // event for the menu editor to trigger recreation of itemlis end; // Checks if an object can have a child // (thats defined in MUIComponents, classname must fit! not only the type // because subclasses can be that they do not allow that, or only indirect) function CanHaveChild(Obj: TObject): Boolean; var i: Integer; begin Result := False; for i := 0 to MUIComps.Count - 1 do begin if Obj.ClassName = MUIComps[i].MUIClass.ClassName then begin Result := MUIComps[i].HasChild; Break; end; end; end; // Add the selected Component to the list and recreate the Window procedure TMainWindow.AddClick(Sender: TObject); var Idx: Integer; Num: Integer; NName: string; Child: TItemNode; begin // get active element Idx := ItemList.List.Active; if (Idx >= 0) and (Idx < Tree.AllCount) then begin // get the Item on this Element CurItem := Tree.AllChild[Idx]; if CurItem.Data is TMUIApplication then begin DestroyTestWin; Num := 1; repeat NName := 'Window' + IntToStr(Num); Inc(Num); Until Tree.AllChildByName(NName) < 0; Child := CurItem.NewChild(NName, TMUIWindow.Create); if IsPublishedProp(Child.Data, 'Contents') then begin Child.Properties.Add('Contents'); SetStrProp(Child.Data, 'Contents', NName); end; // update the pseudo Tree UpdateItemList; // create the Window with new component CreateTestWin; Exit; end; // Check if this element can have parents! while Assigned(CurItem) do begin if CanHaveChild(CurItem.Data) or (CurItem.Data is TMUIWindow) then Break; CurItem := CurItem.Parent; end; // if not assigned -> use the main Window as Parent if not Assigned(CurItem) then exit; //CurItem := Tree; // Which element to add Idx := ChooseComp.Active; if (Idx < 0) or (Idx > MUIComps.Count - 1) then Exit; // get the name of the component Num := 1; repeat NName := MUIComps[Idx].Name + IntToStr(Num); Inc(Num); Until Tree.AllChildByName(NName) < 0; // destroy window DestroyTestWin; // add the component Child := CurItem.NewChild(NName, MUIComps[Idx].MUIClass.Create); if IsPublishedProp(Child.Data, 'Contents') then begin Child.Properties.Add('Contents'); SetStrProp(Child.Data, 'Contents', NName); end; if Child.Data is TMUIArea then begin TMUIArea(Child.Data).OnClick := @ClickEvent; TMUIArea(Child.Data).OnSelected := @ClickEvent; end; // update the pseudo Tree UpdateItemList; // create the Window with new component CreateTestWin; end; end; // remove the selected item from the GUI procedure TMainWindow.RemoveClick(Sender: TObject); var Idx: Integer; begin // get the element to delete Idx := ItemList.List.Active; if (Idx >= 1) and (Idx < Tree.AllCount) then begin // destroy the Window DestroyTestWin; // CurItem := Tree.AllChild[Idx]; // remove the MUIClass object and all its childs CurItem.Data.Free; CurItem.Data := nil; // destroy the object CurItem.Free; UpdateItemList; // recreate the window CreateTestWin; end; end; // MainMenu Events procedure TMainWindow.NewClick(Sender: TObject); var TestWin: TMUIWindow; ItemWin: TItemNode; begin ProjName := ''; DestroyTestWin; Tree := TItemTree.Create; Tree.Name := 'MUIApp'; TestApp := TMUIApplication.Create; TestApp.Title := ''; Tree.Data := TestApp; TestWin := TMUIWindow.Create; ItemWin := Tree.NewChild('Window1', TestWin); ItemWin.Properties.Add('Title'); TestWin.Title := 'Window1'; CurItem := Tree; UpdateItemList; ItemList.List.Active := 0; CreateTestWin; end; procedure TMainWindow.LoadClick(Sender: TObject); var FD: TFileDialog; begin FD := TFileDialog.Create; try FD.TitleText := 'Choose Project to Load'; FD.FileName := IncludeTrailingPathDelimiter(DefaultExportPath) + 'MyProgram' + ProjectExtension; FD.Pattern := '#?' + ProjectExtension; FD.SaveMode := False; if FD.Execute then begin DefaultExportPath := FD.Directory; NewClick(nil); DestroyTestWin; ProjName := FD.FileName; Tree.LoadFromFile(FD.Filename); CurItem := Tree; if Tree.Count > 1 then begin // remove the Window, the loaded one will have a window, usually Tree.Child[0].Free; end; UpdateItemList; ItemList.List.Active := 0; CreateTestWin; end; finally FD.Free; end; // end; procedure TMainWindow.SaveClick(Sender: TObject); var FD: TFileDialog; begin FD := TFileDialog.Create; try FD.TitleText := 'Choose Name for your Project'; FD.FileName := IncludeTrailingPathDelimiter(DefaultProjectPath) + 'MyProgram' + ProjectExtension; FD.Pattern := '#?' + ProjectExtension; FD.SaveMode := True; if FD.Execute then begin DefaultProjectPath := FD.Directory; ProjName := ChangeFileExt(FD.Filename, ProjectExtension); Tree.SaveToFile(ProjName); end; finally FD.Free; end; // end; procedure TMainWindow.AboutMenuClick(Sender: TObject); begin MUIApp.AboutMUI(Self); end; procedure TMainWindow.ConfigMUIMenuClick(Sender: TObject); begin MUIApp.OpenConfigWindow(); end; procedure TMainWindow.QuitClick(Sender: TObject); begin Self.Close; end; procedure TMainWindow.SetProjName(AValue: string); begin FProjName := AValue; if FProjName = '' then Self.Title := 'MUIIDE - <New Project>' else Self.Title := 'MUIIDE - <' + ExtractFileName(FProjName) + '>'; end; end.
s := 'Hello!';
unit SAPMaterialReader; interface uses Classes, SysUtils, ComObj, CommUtils; type TSAPMaterialRecord = packed record sNumber: string; sName: string; dRecvTime: Double; sMRPType: string; // PD mrp, 外购 M0 mps 自制半成品 dMOQ: Double; // dSPQ: Double; // = '舍入值'; dLT_PD: Double; // = '计划交货时间'; dLT_M0: Double; // = '自制生产时间'; iLowestCode: Integer; // 低位码 sMRPer: string; sMRPerDesc: string; sBuyer: string; sMRPGroup: string; sPType: string; sAbc: string; sGroupName: string; sPlanNumber: string; sMMTypeDesc: string; end; PSAPMaterialRecord = ^TSAPMaterialRecord; TSAPMaterialReader = class private FList: TStringList; FFile: string; ExcelApp, WorkBook: Variant; FLogEvent: TLogEvent; procedure Open; procedure Log(const str: string); function GetCount: Integer; function GetItems(i: Integer): PSAPMaterialRecord; public constructor Create(const sfile: string; aLogEvent: TLogEvent = nil); destructor Destroy; override; procedure Clear; property Count: Integer read GetCount; property Items[i: Integer]: PSAPMaterialRecord read GetItems; function GetSAPMaterialRecord(const snumber: string): PSAPMaterialRecord; end; implementation { TSAPMaterialReader } constructor TSAPMaterialReader.Create(const sfile: string; aLogEvent: TLogEvent = nil); begin FFile := sfile; FLogEvent := aLogEvent; FList := TStringList.Create; Open; end; destructor TSAPMaterialReader.Destroy; begin Clear; FList.Free; inherited; end; procedure TSAPMaterialReader.Clear; var i: Integer; p: PSAPMaterialRecord; begin for i := 0 to FList.Count - 1 do begin p := PSAPMaterialRecord(FList.Objects[i]); Dispose(p); end; FList.Clear; end; function TSAPMaterialReader.GetCount: Integer; begin Result := FList.Count; end; function TSAPMaterialReader.GetItems(i: Integer): PSAPMaterialRecord; begin Result := PSAPMaterialRecord(FList.Objects[i]); end; function TSAPMaterialReader.GetSAPMaterialRecord(const snumber: string): PSAPMaterialRecord; var idx: Integer; begin idx := FList.IndexOf(snumber); if idx >= 0 then begin Result := PSAPMaterialRecord(FList.Objects[idx]); end else Result := nil; end; procedure TSAPMaterialReader.Log(const str: string); begin savelogtoexe(str); if Assigned(FLogEvent) then begin FLogEvent(str); end; end; function IndexOfCol(ExcelApp: Variant; irow: Integer; const scol: string): Integer; var i: Integer; s: string; begin Result := -1; for i := 1 to 50 do begin s := ExcelApp.Cells[irow, i].Value; if s = scol then begin Result := i; Break; end; end; end; procedure TSAPMaterialReader.Open; const CSNumber = '物料编码'; CSName = '物料描述'; CSRecvTime = '收货处理时间'; CSMRPType = 'MRP类型'; CSSPQ = '舍入值'; CSLT_PD = '计划交货时间'; CSLT_M0 = '自制生产时间'; CSLT_MOQ = '最小批量大小'; CSMRPGroup = 'MRP组'; CSPType = '采购类型'; CSAbc = 'ABC标识'; var iSheetCount, iSheet: Integer; sSheet: string; stitle1, stitle2, stitle3, stitle4, stitle5, stitle6: string; stitle: string; irow: Integer; snumber: string; aSAPMaterialRecordPtr: PSAPMaterialRecord; iColNumber: Integer; iColName: Integer; iColRecvTime: Integer; iColMRPType: Integer; iColSPQ: Integer; iColLT_PD: Integer; iColLT_M0: Integer; iColMOQ: Integer; iMRPGroup: Integer; iPType: Integer; iAbc: Integer; begin Clear; if not FileExists(FFile) then Exit; ExcelApp := CreateOleObject('Excel.Application' ); ExcelApp.Visible := False; ExcelApp.Caption := '应用程序调用 Microsoft Excel'; try WorkBook := ExcelApp.WorkBooks.Open(FFile); try iSheetCount := ExcelApp.Sheets.Count; for iSheet := 1 to iSheetCount do begin if not ExcelApp.Sheets[iSheet].Visible then Continue; ExcelApp.Sheets[iSheet].Activate; sSheet := ExcelApp.Sheets[iSheet].Name; Log(sSheet); irow := 1; stitle1 := ExcelApp.Cells[irow, 1].Value; stitle2 := ExcelApp.Cells[irow, 2].Value; stitle3 := ExcelApp.Cells[irow, 3].Value; stitle4 := ExcelApp.Cells[irow, 4].Value; stitle5 := ExcelApp.Cells[irow, 5].Value; stitle6 := ExcelApp.Cells[irow, 6].Value; stitle := stitle1 + stitle2 + stitle3 + stitle4 + stitle5 + stitle6; if stitle <> '工厂工厂描述物料编码物料描述物料类型物料类型描述' then begin Log(sSheet +' 不是 SAP导出物料 格式'); Continue; end; iColNumber := IndexOfCol(ExcelApp, irow, CSNumber); iColName := IndexOfCol(ExcelApp, irow, CSName); iColRecvTime := IndexOfCol(ExcelApp, irow, CSRecvTime); iColMRPType := IndexOfCol(ExcelApp, irow, CSMRPType); iColSPQ := IndexOfCol(ExcelApp, irow, CSSPQ); iColLT_PD := IndexOfCol(ExcelApp, irow, CSLT_PD); iColLT_M0 := IndexOfCol(ExcelApp, irow, CSLT_M0); iColMOQ := IndexOfCol(ExcelApp, irow, CSLT_MOQ); iMRPGroup := IndexOfCol(ExcelApp, irow, CSMRPGroup); iPType := IndexOfCol(ExcelApp, irow, CSPType); iAbc := IndexOfCol(ExcelApp, irow, CSAbc); if (iColNumber = -1) or (iColName = -1) or (iColRecvTime = -1) or (iColMRPType = -1) or (iColSPQ = -1) or (iColLT_PD = -1) or (iColLT_M0 = -1) or (iColMOQ = -1) or (iMRPGroup = -1) or (iPType = -1) or (iAbc = -1) then begin Log(sSheet +' 不是 SAP导出物料 格式'); Continue; end; irow := 2; snumber := ExcelApp.Cells[irow, iColNumber].Value; while snumber <> '' do begin aSAPMaterialRecordPtr := New(PSAPMaterialRecord); FList.AddObject(snumber, TObject(aSAPMaterialRecordPtr)); aSAPMaterialRecordPtr^.sNumber := snumber; aSAPMaterialRecordPtr^.sName := ExcelApp.Cells[irow, iColName].Value; aSAPMaterialRecordPtr^.dRecvTime := ExcelApp.Cells[irow, iColRecvTime].Value; aSAPMaterialRecordPtr^.sMRPType := ExcelApp.Cells[irow, iColMRPType].Value; aSAPMaterialRecordPtr^.dSPQ := ExcelApp.Cells[irow, iColSPQ].Value; aSAPMaterialRecordPtr^.dMOQ := ExcelApp.Cells[irow, iColMOQ].Value; aSAPMaterialRecordPtr^.dLT_PD := ExcelApp.Cells[irow, iColLT_PD].Value; aSAPMaterialRecordPtr^.dLT_M0 := ExcelApp.Cells[irow, iColLT_M0].Value; aSAPMaterialRecordPtr^.iLowestCode := 0; // 低位码,默认为1 aSAPMaterialRecordPtr^.sMRPGroup := ExcelApp.Cells[irow, iMRPGroup].Value; aSAPMaterialRecordPtr^.sPType := ExcelApp.Cells[irow, iPType].Value; aSAPMaterialRecordPtr^.sAbc := ExcelApp.Cells[irow, iAbc].Value; irow := irow + 1; snumber := ExcelApp.Cells[irow, iColNumber].Value; end; end; finally ExcelApp.ActiveWorkBook.Saved := True; //新加的,设置已经保存 WorkBook.Close; end; finally ExcelApp.Visible := True; ExcelApp.Quit; end; end; end.
// Demonstrates the "MultiDetailListItem" TListView appearance. // Install the SampleListViewMultiDetailApparancePackage before opening this form. unit MultiDetailMainFormU; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.ListView.Types, FMX.StdCtrls, FMX.ListView, Data.Bind.GenData, Fmx.Bind.GenData, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.ObjectScope, FMX.ListBox, FMX.TabControl, FMX.Objects, MultiDetailAppearanceU; type TForm594 = class(TForm) ToolBar1: TToolBar; ToggleEditMode: TSpeedButton; PrototypeBindSource1: TPrototypeBindSource; BindingsList1: TBindingsList; ListViewMultiDetail: TListView; LinkFillControlToField1: TLinkFillControlToField; SpeedButtonLiveBindings: TSpeedButton; ToolBar2: TToolBar; SpeedButtonFill: TSpeedButton; ImageRAD: TImage; procedure ToggleEditModeClick(Sender: TObject); procedure SpeedButtonFillClick(Sender: TObject); procedure SpeedButtonLiveBindingsClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form594: TForm594; implementation {$R *.fmx} procedure TForm594.SpeedButtonFillClick(Sender: TObject); var I: Integer; LItem: TListViewItem; begin // Code to fill TListView ListViewMultiDetail.BeginUpdate; try ListViewMultiDetail.Items.Clear; for I := 1 to 20 do begin LItem := ListViewMultiDetail.Items.Add; LItem.Text := Format('Text %d', [I]); // Update data managed by custom appearance LItem.Data[TMultiDetailAppearanceNames.Detail1] := Format('Detail1_%d', [I]); LItem.Data[TMultiDetailAppearanceNames.Detail2] := Format('Detail2_%d', [I]); LItem.Data[TMultiDetailAppearanceNames.Detail3] := Format('Detail3_%d', [I]); LItem.BitmapRef := ImageRAD.Bitmap; end; finally ListViewMultiDetail.EndUpdate; end; end; procedure TForm594.SpeedButtonLiveBindingsClick(Sender: TObject); begin LinkFillControlToField1.BindList.FillList; end; procedure TForm594.ToggleEditModeClick(Sender: TObject); begin ListViewMultiDetail.EditMode := not ListViewMultiDetail.EditMode; end; end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls; type TMessageAlertsForm = class(TForm) ToolBar1: TToolBar; Label1: TLabel; procedure btnStandardAlertClick(Sender: TObject); procedure btnMultiButtonAlertClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var MessageAlertsForm: TMessageAlertsForm; implementation {$R *.fmx} procedure TMessageAlertsForm.btnStandardAlertClick(Sender: TObject); begin { Show a standard alert with a single OK button } ShowMessage('Hello World!'); end; procedure TMessageAlertsForm.btnMultiButtonAlertClick(Sender: TObject); begin { Show a multiple-button alert that triggers different code blocks according to your input } case MessageDlg('Choose a button:', System.UITypes.TMsgDlgType.mtInformation, [ System.UITypes.TMsgDlgBtn.mbYes, System.UITypes.TMsgDlgBtn.mbNo, System.UITypes.TMsgDlgBtn.mbCancel ], 0) of { Detect which button was pushed and show a different message } mrYES: ShowMessage('You chose Yes'); mrNo: ShowMessage('You chose No'); mrCancel: ShowMessage('You chose Cancel'); end; end; end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Ported to Delphi by Michal Wojcik. // // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved. // Released under the terms of the GNU General Public License version 2 or later. {$H+} unit TestRunnerFixtureListener; interface uses FixtureListener, Counts, PageResult, Parse {, TestRunner}; type TTestRunnerFixtureListener = class(TInterfacedObject, IFixtureListener) private counts : TCounts; atStartOfResult : boolean; runner : TObject {TTestRunner}; currentPageResult : TPageResult; public constructor Create(runner : TObject {TTestRunner}); destructor Destroy; override; procedure tableFinished(table : TParse); procedure tablesFinished(count : TCounts); end; implementation uses SysUtils, FitServer, TestRunner; { TTestRunnerFixtureListener } constructor TTestRunnerFixtureListener.Create(runner : TObject {TTestRunner}); begin inherited Create; self.runner := runner; counts := TCounts.Create(); atStartOfResult := true; end; destructor TTestRunnerFixtureListener.Destroy(); begin counts.Free; inherited Destroy; end; procedure TTestRunnerFixtureListener.tableFinished(table : TParse); var pageTitle : string; data : string; indexOfFirstLineBreak : integer; begin try data := TFitServer.readTable(table); //TODO "UTF-8"; if (atStartOfResult) then begin indexOfFirstLineBreak := indexOf(#10, data) - 1; pageTitle := substring2(data, 0, indexOfFirstLineBreak); data := substring(data, indexOfFirstLineBreak + 1); currentPageResult := TPageResult.Create(pageTitle); atStartOfResult := false; end; currentPageResult.append(data); except on e : Exception do begin WriteLn(e.Message); //TODO e.printStackTrace(); end; end; end; procedure TTestRunnerFixtureListener.tablesFinished(count : TCounts); begin try currentPageResult.setCounts(count); (runner as TTestRunner).acceptResults(currentPageResult); atStartOfResult := true; counts.tally(count); except on e : Exception do begin WriteLn(e.Message); //TODO e.printStackTrace(); end; end; end; end.
unit F_IStream; interface uses Windows; type { OLE character and string types } TOleChar = WideChar; POleStr = PWideChar; PPOleStr = ^POleStr; POleStrList = ^TOleStrList; TOleStrList = array[0..65535] of POleStr; {$EXTERNALSYM Largeint} Largeint = Int64; {$EXTERNALSYM PROPID} PROPID = ULONG; PPropID = ^TPropID; TPropID = PROPID; { Class ID } PCLSID = PGUID; TCLSID = TGUID; IStream = interface; PStatStg = ^TStatStg; {$EXTERNALSYM tagSTATSTG} tagSTATSTG = record pwcsName: POleStr; dwType: Longint; cbSize: Largeint; mtime: TFileTime; ctime: TFileTime; atime: TFileTime; grfMode: Longint; grfLocksSupported: Longint; clsid: TCLSID; grfStateBits: Longint; reserved: Longint; end; TStatStg = tagSTATSTG; {$EXTERNALSYM STATSTG} STATSTG = TStatStg; {$EXTERNALSYM ISequentialStream} ISequentialStream = interface(IUnknown) ['{0c733a30-2a1c-11ce-ade5-00aa0044773d}'] function Read(pv: Pointer; cb: Longint; pcbRead: PLongint): HResult; stdcall; function Write(pv: Pointer; cb: Longint; pcbWritten: PLongint): HResult; stdcall; end; {$EXTERNALSYM IStream} IStream = interface(ISequentialStream) ['{0000000C-0000-0000-C000-000000000046}'] function Seek(dlibMove: Largeint; dwOrigin: Longint; var libNewPosition: Largeint): HResult; stdcall; function SetSize(libNewSize: Largeint): HResult; stdcall; function CopyTo(stm: IStream; cb: Largeint; out cbRead: Largeint; var cbWritten: Largeint): HResult; stdcall; function Commit(grfCommitFlags: Longint): HResult; stdcall; function Revert: HResult; stdcall; function LockRegion(libOffset: Largeint; cb: Largeint; dwLockType: Longint): HResult; stdcall; function UnlockRegion(libOffset: Largeint; cb: Largeint; dwLockType: Longint): HResult; stdcall; function Stat(var statstg: TStatStg; grfStatFlag: Longint): HResult; stdcall; function Clone(var stm: IStream): HResult; stdcall; end; {$EXTERNALSYM CreateStreamOnHGlobal} function CreateStreamOnHGlobal(hglob: HGlobal; fDeleteOnRelease: BOOL; var stm: IStream): HResult; stdcall; external 'ole32.dll' name 'CreateStreamOnHGlobal'; implementation end.
unit UFavorite; (* お気に入り *) (* Copyright (c) 2001,2002 hetareprog@hotmail.com *) interface uses Classes, SysUtils, StrUtils, Dialogs, Controls, UXMLSub; type TFavoriteList = class; (*-------------------------------------------------------*) TFavBase = class(TObject) protected changed: boolean; procedure SetName(const name: string); public FName: string; parent: TFavBase; constructor Create(parentNode: TFavBase); destructor Destroy; override; procedure Remove; procedure Delete(obj: TFavBase); virtual; property name: string read FName write SetName; end; (*-------------------------------------------------------*) TFavorite = class(TFavBase) public category: string; board: string; host: string; bbs: string; datName: string; URI: string; constructor Create(parentNode: TFavoriteList); destructor Destroy; override; end; (*-------------------------------------------------------*) TFavoriteList = class(TFavBase) protected list: TList; function GetCount: integer; function GetItems(index: integer): TFavBase; public expanded: boolean; constructor Create(parentNode: TFavoriteList); destructor Destroy; override; procedure Clear; procedure Add(obj: TFavBase); procedure Insert(index: integer; item: TFavBase); procedure Delete(obj: TFavBase); override; procedure FindDelete(const host, bbs, datName: string); function IndexOf(item: TFavBase): integer; function Find(const host, bbs, datName: string; strict: boolean = false): TFavorite; function IsChanged: boolean; procedure ClearChanged; property Count: integer read Getcount; property Items[index: integer]: TFavBase read GetItems; end; TFavorites = class(TFavoriteList) protected FSelected: integer; FTop: integer; procedure SetSelected(val: integer); procedure SetTop(val: integer); public constructor Create; function Load(const path: string): boolean; procedure Save(const path: string); property selected: integer read FSelected write SetSelected; property top: integer read FTop write SetTop; end; (*=======================================================*) implementation (*=======================================================*) constructor TFavBase.Create(parentNode: TFavBase); begin parent := parentNode; changed:= false; end; destructor TFavBase.Destroy; begin Remove; inherited; end; procedure TFavBase.Remove; begin if parent <> nil then begin parent.Delete(self); parent := nil; end; end; procedure TFavBase.Delete(obj: TFavBase); begin end; procedure TFavBase.SetName(const name: string); begin FName := name; changed := true; end; (*=======================================================*) constructor TFavorite.Create(parentNode: TFavoriteList); begin parent := parentNode; end; destructor TFavorite.Destroy; begin category := ''; board := ''; URI := ''; inherited; end; (*=======================================================*) constructor TFavoriteList.Create(parentNode: TFavoriteList); begin inherited Create(parentNode); list := TList.Create; end; destructor TFavoriteList.Destroy; begin Clear; list.Free; inherited Destroy; end; procedure TFavoriteList.Clear; begin while 0 < list.Count do TFavBase(list.Items[0]).Free; end; procedure TFavoriteList.Add(obj: TFavBase); begin if obj is TFavoriteList then begin if TFavoriteList(obj).parent <> self then begin TFavoriteList(obj).Remove; TFavoriteList(obj).parent := self; end; list.Add(obj); changed := true; end else if obj is TFavorite then begin if TFavorite(obj).parent <> self then begin TFavorite(obj).Remove; TFavorite(obj).parent := self; end; list.Add(obj); changed := true; end; end; procedure TFavoriteList.Insert(index: integer; item: TFavBase); begin if item is TFavoriteList then begin if TFavoriteList(item).parent <> self then begin TFavoriteList(item).Remove; TFavoriteList(item).parent := self; end; list.Insert(index, item); changed := true; end else if item is TFavorite then begin if TFavorite(item).parent <> self then begin TFavorite(item).Remove; TFavorite(item).parent := self; end; list.Insert(index, item); changed := true; end; end; procedure TFavoriteList.Delete(obj: TFavBase); var i: integer; begin i := list.IndexOf(obj); if i < 0 then exit; list.Delete(i); changed := true; end; procedure TFavoriteList.FindDelete(const host, bbs, datName: string); var item: TFavorite; begin item := nil; repeat if (item <> nil) and (item.parent <> nil) then begin item.parent.Delete(item); item.Free; end; item := Find(host, bbs, datName); until item = nil; end; function TFavoriteList.GetCount: integer; begin result := list.Count; end; function TFavoriteList.GetItems(index: integer): TFavBase; begin result := list.Items[index]; end; function TFavoriteList.IndexOf(item: TFavBase): integer; begin result := list.IndexOf(item); end; function TFavoriteList.Find(const host, bbs, datName: string; strict: boolean = false): TFavorite; var i: integer; item: TFavorite; begin for i := 0 to list.Count -1 do begin if Items[i] is TFavoriteList then begin result := (Items[i] as TFavoriteList).Find(host, bbs, datName); if (result <> nil) then exit; end else begin item := (Items[i] as TFavorite); if (item.bbs = bbs) and (item.datName = datName) and (not strict or (item.host = host)) then begin result := item; exit; end; end; end; result := nil; end; function TFavoriteList.IsChanged: boolean; var i: integer; begin if changed then begin result := true; exit; end; for i := 0 to list.Count -1 do begin if Items[i] is TFavoriteList then begin result := (Items[i] as TFavoriteList).IsChanged; if result then exit; end else begin result := (Items[i] as TFavorite).changed; if result then exit; end; end; result := false; end; procedure TFavoriteList.ClearChanged; var i: integer; begin changed := false; for i := 0 to list.Count -1 do begin if Items[i] is TFavoriteList then (Items[i] as TFavoriteList).ClearChanged else (Items[i] as TFavorite).changed := false; end; end; (*=======================================================*) constructor TFavorites.Create; begin inherited Create(nil); top := 0; selected := -1; FName := 'お気に入り'; end; (* *) function TFavorites.Load(const path: string): boolean; var favFolder: TFavoriteList; modified: boolean; procedure AddNode(parent: TFavoriteList; element: TXMLElement); var i: integer; el: TXMLElement; favNode: TFavorite; len: integer; begin favNode := nil; for i := 0 to element.Count -1 do begin el := element.Items[i]; if (el.elementType = xmleELEMENT) then begin if el.text = 'folder' then begin favFolder := TFavoriteList.Create(parent); try favFolder.FName := el.attrib.Values['name']; except end; try favFolder.expanded := (el.attrib.Values['expanded'] = 'true'); except end; parent.Add(favFolder); AddNode(favFolder, el); end else if el.text = 'item' then begin favNode := TFavorite.Create(parent); try favNode.FName := el.attrib.Values['name']; except end; try favNode.category := el.attrib.Values['category']; except end; try favNode.board := el.attrib.Values['board']; except end; try favNode.datName := el.attrib.Values['datName']; except end; try favNode.host := el.attrib.Values['host']; except end; try favNode.bbs := el.attrib.Values['bbs']; except end; try favNode.URI := el.attrib.Values['URI']; except end; (* ゴミを取る *) if AnsiStartsStr('http://', favNode.host) then begin favNode.host := Copy(favNode.host, 8, high(integer)); len := length(favNode.host); if (1 < len) and (favNode.host[len] = '/') then favNode.host := Copy(favNode.host, 1, len -1); modified := true; end; len := length(favNode.host); if (1 < len) and (favNode.host[len] = '/') then SetLength(favNode.host, len -1); parent.Add(favNode); end; (* しまった。datの形式を変えちゃった。ので置換えコード *) if favNode <> nil then favNode.datName := ChangeFileExt(favNode.datName, ''); end; end; end; var fstream: TFileStream; doc: TXMLDoc; elem: TXMLElement; i: integer; begin result := false; modified := false; fstream := nil; doc := nil; while true do try fstream := TFileStream.Create(path, fmOpenRead); doc := TXMLDoc.Create; doc.LoadFromStream(fstream); Clear; (* favoriteを探す *) for i := 0 to doc.Count -1 do begin elem := doc.Items[i]; if (elem.elementType = xmleELEMENT) and (elem.text = 'favorite') then begin try expanded := (elem.attrib.Values['expanded'] <> 'false'); except end; try top := StrToInt(elem.attrib.Values['top']); except end; try self.selected := StrToInt(elem.attrib.Values['selected']); except end; AddNode(self, elem); break; end; end; fstream.Free; doc.Free; result := true; break; except if fstream <> nil then fstream.Free; if doc <> nil then doc.Free; if not FileExists(path) then begin result := true; break; end; if MessageDlg('お気に入りの読み込みに失敗しました。' + #10 + '他のソフト等でfavorites.datを使用している場合は終了させて下さい。', mtError, [mbAbort, mbRetry], 0) = mrAbort then begin result := false; break; end; end; ClearChanged; (* データ修正用コードです *) if result and modified then Save(path); end; const TrueFalse: array[0..1] of string = ('false', 'true'); procedure TFavorites.Save(const path: string); var favFile: TStringList; procedure SetOutputList(listNode: TFavoriteList; indent: integer); var i: integer; begin for i := 0 to listNode.Count -1 do begin if TObject(listNode.Items[i]) is TFavorite then begin with TFavorite(listNode.Items[i]) do begin favFile.Add(StringOfChar(' ', indent * 2) + Format('<item name="%s" category="%s" board="%s" host="%s" bbs="%s" datname="%s"/>', [XMLQuoteEncode(name), XMLQuoteEncode(category), XMLQuoteEncode(board), XMLQuoteEncode(host), XMLQuoteEncode(bbs), XMLQuoteEncode(datName)])); end; end else if TObject(listNode.Items[i]) is TFavoriteList then begin with TFavoriteList(listNode.Items[i]) do begin favFile.Add(StringOfChar(' ', indent * 2) + Format('<folder name="%s" expanded="%s">', [XMLQuoteEncode(name), TrueFalse[Integer(expanded)]])); SetOutputList(TFavoriteList(listNode.Items[i]), indent + 1); favFile.Add(StringOfChar(' ', indent * 2) + '</folder>'); end; end; end; end; begin if not IsChanged then exit; favFile := TStringList.Create; favFile.Add(Format('<favorite top="%d" selected="%d">', [top, selected])); SetOutputList(self, 1); favFile.Add('</favorite>'); try favFile.SaveToFile(path); except end; favFile.Free; end; procedure TFavorites.SetSelected(val: integer); begin if FSelected <> val then begin FSelected := val; changed := true; end; end; procedure TFavorites.SetTop(val: integer); begin if FTop <> val then begin FTop := val; changed := true; end; end; end.
{$MODE OBJFPC}program Clean; uses SysUtils, CRT; Function ReadString(prompt : String):String; begin Write(prompt); ReadLn(result); end; Function ReadInt(prompt : String):Integer; var temp : String; num : Integer; begin temp := ReadString(prompt); while not TryStrToInt(temp,num) do begin WriteLn('Please enter a number from the menu :'); ReadLn(temp); end; result := num; end; function Options():Integer; var temp: String; num : Integer; begin WriteLn('Simple Calculator'); WriteLn('1: Addition'); WriteLn('2: Subtraction'); WriteLn('3: Multiplication'); WriteLn('4: Division'); WriteLn('5: Quit'); Write('Option: '); ReadLn(temp); while not TryStrToInt(temp,num) do begin WriteLn('Please enter a whole number :'); ReadLn(temp); end; result := num; end; procedure Calculate(option : Integer); var left,right : Integer; result:Double; op: array [1..5] of String; begin op[1] :='+'; op[2] :='-'; op[3] :='*'; op[4] :='/'; if option = 5 then begin WriteLn('Bye...'); end else begin left := ReadInt('Please enter a number :'); right := ReadInt('Please enter a number :'); case(option) of 1: begin result := (left,op[option],right); end; 2: begin result := (left-right); end; 3: begin result := (left*right); end; 4: begin result := (left/right); end; end; WriteLn(left,' ',op[option],' ',right,' = ',result:4:2); end; end; procedure Main(); var option : Integer; begin repeat ClrScr(); option := Options(); calculate(option); Delay(1500); until(option = 5); end; begin Main(); end.
unit uBaseCadastro; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uBase, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons, Data.DB, Vcl.Grids, Vcl.DBGrids, System.UITypes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Datasnap.DBClient, Datasnap.Provider, Vcl.Mask; type TfBaseCadastro = class(TfBase) pnlTitulo: TPanel; pnlCampos: TPanel; pnlInfo: TPanel; lblSalvar: TLabel; lblAlterar: TLabel; lblCancelar: TLabel; lblExcluir: TLabel; lblAtualizar: TLabel; lbtTotal: TLabel; dsCadastro: TDataSource; btnSalvar: TBitBtn; btnCancelar: TBitBtn; btnAlterar: TBitBtn; btnExcluir: TBitBtn; btnSair: TBitBtn; dbgCadastro: TDBGrid; procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnSairClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure dbgCadastroDblClick(Sender: TObject); procedure dbgCadastroKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnAlterarClick(Sender: TObject); private { Private declarations } protected procedure HabilitaBotoes(status: string);virtual; public { Public declarations } end; var fBaseCadastro: TfBaseCadastro; implementation {$R *.dfm} procedure TfBaseCadastro.FormCreate(Sender: TObject); begin inherited; HabilitaBotoes('SALVAR'); end; procedure TfBaseCadastro.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_F2) And (btnSalvar.Enabled) then begin btnSalvar.Click; end else if (Key = VK_F3) and (btnAlterar.Enabled) then begin btnAlterar.Click; end else if (Key = VK_F6) and (btnCancelar.Enabled) then begin btnCancelar.Click; end else if (Key = VK_F4) and (btnExcluir.Enabled) then begin btnExcluir.Click; end; end; procedure TfBaseCadastro.HabilitaBotoes(status: string); begin if status = 'ALTERAR' then begin btnSalvar.Enabled := False; btnCancelar.Enabled := True; btnAlterar.Enabled := True; btnExcluir.Enabled := True; end else if status = 'SALVAR' then begin btnSalvar.Enabled := True; btnCancelar.Enabled := False; btnAlterar.Enabled := False; btnExcluir.Enabled := False; end; end; procedure TfBaseCadastro.btnAlterarClick(Sender: TObject); begin inherited; HabilitaBotoes('SALVAR'); end; procedure TfBaseCadastro.btnCancelarClick(Sender: TObject); begin inherited; HabilitaBotoes('SALVAR'); LimparCampos; end; procedure TfBaseCadastro.btnExcluirClick(Sender: TObject); begin inherited; HabilitaBotoes('SALVAR'); if MessageDlg('Confirma a Exclusão do Registro?',mtConfirmation, [mbYes,mbNo],0) = mrNo then Abort; LimparCampos; end; procedure TfBaseCadastro.btnSairClick(Sender: TObject); begin inherited; Close; end; procedure TfBaseCadastro.dbgCadastroDblClick(Sender: TObject); begin inherited; if dbgCadastro.DataSource.DataSet.IsEmpty then begin ShowMessage('Não existem registros.'); HabilitaBotoes('SALVAR'); end; HabilitaBotoes('ALTERAR'); end; procedure TfBaseCadastro.dbgCadastroKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_RETURN then begin if dbgCadastro.DataSource.DataSet.IsEmpty then begin ShowMessage('Não existem registros.'); HabilitaBotoes('SALVAR'); end; HabilitaBotoes('ALTERAR'); end; end; end.
unit Model.Currency; interface uses Forms, Model.Interfaces, Model.IMyConnection, System.Generics.Collections, Spring.Collections, Spring.Data.ObjectDataset, Spring.Persistence.Criteria.Interfaces, Spring.Persistence.Criteria.Restrictions, Spring.Persistence.Criteria.OrderBy, MainDM; function CreateCurrencyModelClass: ICurrencyModelInterface; implementation uses System.SysUtils, Model.Declarations, Model.FormDeclarations; type TCurrencyModel = class (TInterfacedObject, ICurrencyModelInterface) private fCurrency: TCurrency; public function GetAllCurrencies(const filter : string) : IObjectList; function GetAllCurrenciesDS(const filter : string) : TObjectDataset; procedure AddCurrency(const newCurrency: TCurrency); function GetCurrency(const CurrencyId : Integer) : TCurrency; procedure UpdateCurrency(const Currency: TCurrency); procedure DeleteCurrency(const Currency: TCurrency); end; function CreateCurrencyModelClass: ICurrencyModelInterface; begin result:=TCurrencyModel.Create; end; { TCurrencyModel } procedure TCurrencyModel.AddCurrency(const newCurrency: TCurrency); begin end; procedure TCurrencyModel.DeleteCurrency(const Currency: TCurrency); begin DMMain.Session.Delete(Currency); end; function TCurrencyModel.GetAllCurrencies( const filter: string): IObjectList; var FCriteria : ICriteria<TCurrency>; begin FCriteria := DMMain.Session.CreateCriteria<TCurrency>; Result := FCriteria .Add(Restrictions.NotEq('IsDeleted', 1)) .OrderBy(TOrderBy.Asc('CurrencyId')).ToList as IObjectList; //Result := DMMain.Session.FindWhere<TCurrency>(ICriteria) as IObjectList; end; function TCurrencyModel.GetCurrency(const CurrencyId : Integer) : TCurrency; begin Result := DMMain.Session.FindOne<TCurrency>(CurrencyId); end; function TCurrencyModel.GetAllCurrenciesDS(const filter: string): TObjectDataset; begin Result := TObjectDataset.Create(Application); Result.DataList := GetAllCurrencies(filter); //DMMain.Session.FindAll<TCurrency> as IObjectList; Result.Open; end; procedure TCurrencyModel.UpdateCurrency(const Currency: TCurrency); begin DMMain.Session.Update(Currency); end; end.
unit frm_Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, t_Shp2PasProcessor; type TfrmMain = class(TForm) edtShpFile: TEdit; lblShpFile: TLabel; btnOpenShapeFile: TButton; edtOutputPath: TEdit; btnSelectOutputPath: TButton; lblOutputPath: TLabel; cbbAccuracy: TComboBox; lblLatLonAccuracy: TLabel; btnProcess: TButton; btnExit: TButton; dlgOpenFile: TOpenDialog; statBottom: TStatusBar; chkDoCompact: TCheckBox; procedure btnOpenShapeFileClick(Sender: TObject); procedure btnExitClick(Sender: TObject); procedure btnProcessClick(Sender: TObject); private FAbort: Boolean; FBusy: Boolean; procedure ConvertionProcess( const AShapeFile: string; const AOutPutPath: string; const ALatLonAccuracy: TLatLonAccuracy; const ADoCompactArray: Boolean; const AOnProcessMessages: TOnProgressMessages ); procedure OnProgressMessages( Sender: TObject; const AProcessed: Int64; out AAbort: Boolean ); public constructor Create(AOwner: TComponent); override; end; var frmMain: TfrmMain; implementation uses u_Shp2PasProcessor; {$R *.dfm} constructor TfrmMain.Create(AOwner: TComponent); begin inherited Create(AOwner); FAbort := False; FBusy := False; end; procedure TfrmMain.btnExitClick(Sender: TObject); begin FAbort := True; Application.ProcessMessages; Close; end; procedure TfrmMain.btnOpenShapeFileClick(Sender: TObject); begin if dlgOpenFile.Execute then begin edtShpFile.Text := dlgOpenFile.FileName; if edtOutputPath.Text = '' then begin edtOutputPath.Text := ChangeFileExt(dlgOpenFile.FileName, '_shp\'); end; end; end; procedure TfrmMain.OnProgressMessages( Sender: TObject; const AProcessed: Int64; out AAbort: Boolean ); begin AAbort := FAbort; if not FAbort then begin statBottom.Panels.Items[0].Text := 'Processed: ' + FloatToStrF(AProcessed, ffNumber, 12, 0) + ' shapes...'; end else begin statBottom.Panels.Items[0].Text := 'Aborted by user'; end; Application.ProcessMessages; end; procedure TfrmMain.btnProcessClick(Sender: TObject); begin if not FBusy then begin FBusy := True; btnProcess.Caption := 'Cancel'; ConvertionProcess( edtShpFile.Text, edtOutputPath.Text, TLatLonAccuracy(cbbAccuracy.ItemIndex), chkDoCompact.Checked, Self.OnProgressMessages ); FBusy := False; btnProcess.Caption := 'Process'; end else begin FAbort := True; end; end; procedure TfrmMain.ConvertionProcess( const AShapeFile: string; const AOutPutPath: string; const ALatLonAccuracy: TLatLonAccuracy; const ADoCompactArray: Boolean; const AOnProcessMessages: TOnProgressMessages ); var VOutputPath: string; VProcessor: TShp2PasProcessor; begin if AOutPutPath = '' then begin raise Exception.Create('Output Path is empty!'); end; VOutputPath := IncludeTrailingPathDelimiter(Trim(AOutPutPath)); if not ForceDirectories(VOutputPath) then begin raise Exception.Create(SysErrorMessage(GetLastError)); end; VProcessor := TShp2PasProcessor.Create( AShapeFile, AOutPutPath, ALatLonAccuracy, ADoCompactArray, AOnProcessMessages ); try VProcessor.Process; finally VProcessor.Free; end; end; end.
unit USender; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, IdCmdTCPServer, IdExplicitTLSClientServerBase, IdSMTPServer, IdTCPConnection, IdTCPClient, IdMessageClient, IdSMTPBase, IdMessage, IdSMTP, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IniFiles; type TSharedFunctions = record public class function SendMail(MailServer: string; MailSSL: bool; MailPort: Integer; MailUser: string; MailPassword: string; MailMessage: TIdMessage) : bool; static; end; implementation class function TSharedFunctions.SendMail(MailServer: string; MailSSL: bool; MailPort: Integer; MailUser: string; MailPassword: string; MailMessage: TIdMessage) : bool; var SMTPClient: TIdSMTP; IOSSL: TIdSSLIOHandlerSocketOpenSSL; begin Result := False; try try IOSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil); SMTPClient := TIdSMTP.Create(nil); SMTPClient.IOHandler := IOSSL; if (MailSSL) then begin SMTPClient.UseTLS := utUseRequireTLS; end; SMTPClient.Host := MailServer; SMTPClient.Port := MailPort; if ((MailUser <> '') and (MailPassword <> '')) then begin SMTPClient.Username := MailUser; SMTPClient.Password := MailPassword; end; SMTPClient.Connect; if (not SMTPClient.Connected) then exit; if ((MailUser <> '') and (MailPassword <> '')) then begin SMTPClient.Authenticate; end; SMTPClient.Send(MailMessage); Result := (SMTPClient.LastCmdResult.Code = '250'); SMTPClient.Disconnect(true); except end; finally FreeAndNil(MailMessage); FreeAndNil(SMTPClient); FreeAndNil(IOSSL); end; end; end.
unit uTweaks; {$mode delphi}{$H+} interface uses Classes, SysUtils, Registry, SPGetSid, uTasksTweak, uHost, dialogs, windows; type TActionTweak = (atRefresh = 0, atApply = 1, atCancel = 2); TTweakType = (ttRecommended = 0, ttLimited = 1, ttWarning = 2); PTweakRec = ^TTweakRec; TTweakRec = record ID: integer; Name: string[255]; Desc: string; TweakType: TTweakType; end; const TweaksWin10 : array [0..80] of TTweakRec = ( ( ID:101; Name:'Отключить кнопку показа пароля'; Desc:'На экране входа в систему при наборе пароля вы можете наблюдать кнопку с надписью "Показать пароль". Данная опция отключает ее.';TweakType: ttRecommended), ( ID:102; Name:'Отключить средство записи действий пользователя'; Desc:'Средство записи действий ведет учет действий пользователя. Данные созданные средством записи действий, могут быть использованы в системах обратной связи, например в отчетах об ошибках Windows, позволяющих разработчикам распознавать и устранять проблемы. Эти данные включают такие действия пользователя как ввод с клавиатры и ввод с помощью мыши, данные пользовательского интерфейса и снимки экрана.';TweakType: ttRecommended), ( ID:103; Name:'Отключить телеметрию (1 из 3)'; Desc:'Отключает службу диагностического отслеживания (DiagTrack). Данная служба позволяет собирать сведения о функциональных проблемах, связанных с компонентами Windows.';TweakType: ttRecommended), ( ID:104; Name:'Отключить телеметрию (2 из 3)'; Desc:'Отключает службу маршрутизации push-сообщений WAP (dmwappushservice)';TweakType: ttRecommended), ( ID:105; Name:'Отключить телеметрию (3 из 3)'; Desc:'Отключает встроенный в систему AutoLogger. Трассировка сессии AutoLogger записывает события которые происходят в самом начале процесса загрузки операционной системы. Приложения и драйверы устройств могут использовать сессию AutoLogger для захвата следов работы программы до входа пользователя в систему.';TweakType: ttRecommended), ( ID:106; Name:'Отключить WiFi Sense'; Desc:'';TweakType: ttRecommended), ( ID:107; Name:'Отключить WiFi Sense для моих контактов'; Desc:'';TweakType: ttRecommended), ( ID:108; Name:'Отключить доступ приложений Windows Store к беспроводным соединениям'; Desc:'Данная опция лишает все метро-приложения беспроводной связи (WiFi, Bluetooth, и т.д.). Это означает что некоторые приложения не смогут работать должным образом.';TweakType: ttLimited), ( ID:109; Name:'Отключить доступ приложений Windows Store для слабосвязных устройств'; Desc:'Если отключить этот параметр, необходимо будет вручную включать разрешения установленным приложениям, для доступа к беспроводной сети.';TweakType: ttLimited), ( ID:110; Name:'Отключить доступ в интернет Windows Media Digital Rights Managment (DRM)'; Desc:'Некоторые музыкальные и видео файлы имеют так называемую защиту DRM, которая гарантирует что эти файлы могуть быть воспроизведены только на компьютере (или телевизоре) и защищает файл от копирования. Если у вас есть файлы с DRM защитой не включайте данную опцию, иначе вы больше не сможете воспроизвести такие файлы.';TweakType: ttLimited), ( ID:111; Name:'Отключить "Защитник Windows" (Windows Defender)'; Desc:'Отключает встроенный в систему антивирус "Защитник Windows". Данную настройку рекомендуется включать только если у вас установлен другой антивирус.';TweakType: ttWarning), // Privacy ( ID:201; Name:'Отключить приложениям доступ к информации о пользователе.'; Desc:'';TweakType: ttRecommended), ( ID:202; Name:'Отключить отправку образцов рукописного ввода'; Desc:'';TweakType: ttRecommended), ( ID:203; Name:'Отключить отправку ошибок распознавания образцов рукописного ввода'; Desc:'';TweakType: ttRecommended), ( ID:204; Name:'Отключить сбор данных о совместимости приложений'; Desc:'Отключает сбор данных, отправку образцов и информации о совместимости приложений.';TweakType: ttRecommended), // ( ID:627; Name:'Отключить отправку образцов Защитника Windows'; Desc:'Отключает сбор данных и отправку образцов защитником Windows.';TweakType: ttRecommended), ( ID:205; Name:'Отключить сбор пользовательских данных (1 из 5)'; Desc:'Отключает принятие политики конфеденциальности.';TweakType: ttRecommended), ( ID:206; Name:'Отключить сбор пользовательских данных (2 из 5)'; Desc:'Microsoft собирает информацию о голосовых, рукописных и иных методов ввода, почерке, в том числе записи календаря и ваши контакты.';TweakType: ttRecommended), ( ID:207; Name:'Отключить сбор пользовательских данных (3 из 5)'; Desc:'Microsoft собирает информацию о голосовых, рукописных и иных методов ввода, почерке, в том числе записи календаря и ваши контакты.';TweakType: ttRecommended), ( ID:208; Name:'Отключить сбор пользовательских данных (4 из 5)'; Desc:'Microsoft собирает информацию о голосовых, рукописных и иных методов ввода, почерке, в том числе записи календаря и ваши контакты.';TweakType: ttRecommended), ( ID:209; Name:'Отключить сбор пользовательских данных (5 из 5)'; Desc:'Microsoft собирает информацию о голосовых, рукописных и иных методов ввода, почерке, в том числе записи календаря и ваши контакты.';TweakType: ttRecommended), ( ID:210; Name:'Отключить камеру на экране входа в систему'; Desc:'Отключает камеру на экране входа в систему.';TweakType: ttRecommended), ( ID:211; Name:'Отключить голосовой помощник Cortana'; Desc:'Отключает голосовой помощник Cortana и сбрасывает его настройки.';TweakType: ttRecommended), ( ID:212; Name:'Отключить передачу набраного текста'; Desc:'Windows 10 по умолчанию отправляет в Microsoft часть писем и набранного текста. Насколько эти данные анонимны и какая именно информация отправляется неизвестно.';TweakType: ttRecommended), ( ID:213; Name:'Отключить и сбросить идентификатор рекламы (1 из 3)'; Desc:'Отключает "умную рекламу", она создает и показывает рекламу на основе информации которую пользователь ранее искал или посещал.';TweakType: ttRecommended), ( ID:214; Name:'Отключить и сбросить идентификатор рекламы (2 из 3)'; Desc:'Отключает "умную рекламу", она создает и показывает рекламу на основе информации которую пользователь ранее искал или посещал.';TweakType: ttRecommended), ( ID:227; Name:'Отключить и сбросить идентификатор рекламы (3 из 3)'; Desc:'Отключает "умную рекламу", она создает и показывает рекламу на основе информации которую пользователь ранее искал или посещал.';TweakType: ttRecommended), ( ID:215; Name:'Отключить уведомления приложений'; Desc:'';TweakType: ttLimited), ( ID:216; Name:'Отключить приложениям доступ к календарю'; Desc:'';TweakType: ttLimited), ( ID:217; Name:'Отключить приложениям доступ к камере'; Desc:'';TweakType: ttLimited), ( ID:218; Name:'Отключить приложениям доступ к местоположению (1 из 2)'; Desc:'';TweakType: ttLimited), ( ID:219; Name:'Отключить приложениям доступ к местоположению (2 из 2)'; Desc:'';TweakType: ttLimited), ( ID:220; Name:'Отключить приложениям доступ к микрофону'; Desc:'';TweakType: ttLimited), ( ID:221; Name:'Отключить приложениям доступ к сообщениям'; Desc:'';TweakType: ttLimited), ( ID:222; Name:'Отключить биометрическое расширение'; Desc:'Отключение данной службы не позволит использовать приложениям в том числе и входу в систему использовать биометрические данные (например отпечаток пальца).';TweakType: ttLimited), ( ID:223; Name:'Отключить браузеру доступ к списку языков компьютера'; Desc:'';TweakType: ttLimited), ( ID:224; Name:'Отключить SmartScreen'; Desc:'Отключает фильтр URL - SmartScreen.';TweakType: ttWarning), ( ID:225; Name:'Отключить управление качеством ПО (SQM)'; Desc:'Software Quality Management (SQM) - управление качеством программного обеспечения';TweakType: ttRecommended), ( ID:226; Name:'Отключить SQMLogger'; Desc:'';TweakType: ttRecommended), // Location Services ( ID:301; Name:'Отключить функциональность отслеживания системы (1 из 2)'; Desc:'';TweakType: ttRecommended), ( ID:302; Name:'Отключить функциональность отслеживания системы (2 из 2)'; Desc:'';TweakType: ttRecommended), ( ID:303; Name:'Отключить функциональность отслеживания системы скриптами'; Desc:'';TweakType: ttRecommended), ( ID:304; Name:'Отключить датчики для определения местоположения'; Desc:'';TweakType: ttRecommended), // User Behaviour ( ID:401; Name:'Отключить телеметрию в приложениях (1 из 3)'; Desc:'Отключение этой функции приводит к тому что Windows больше не будет отсылать в Microsoft данные телеметрии, такие как данные программ, аварийные ситуации, ошибки входа в Windows и др.';TweakType: ttRecommended), ( ID:402; Name:'Отключить телеметрию в приложениях (2 из 3)'; Desc:'Отключение этой функции приводит к тому что Windows больше не будет отсылать в Microsoft данные телеметрии, такие как данные программ, аварийные ситуации, ошибки входа в Windows и др.';TweakType: ttRecommended), ( ID:403; Name:'Отключить телеметрию в приложениях (3 из 3)'; Desc:'Отключение этой функции приводит к тому что Windows больше не будет отсылать в Microsoft данные телеметрии, такие как данные программ, аварийные ситуации, ошибки входа в Windows и др.';TweakType: ttRecommended), // Windows Update ( ID:501; Name:'Отключить обновление Windows через децентрализованную сеть (1 из 3)'; Desc:'Децентрализованная сеть P2P - это сеть в которой обычно отсутсвует выделеный сервер и все участники обмена равны, а каждый участник является одновременно и сервером и клиентом.';TweakType: ttRecommended), ( ID:502; Name:'Отключить обновление Windows через децентрализованную сеть (2 из 3)'; Desc:'Децентрализованная сеть P2P - это сеть в которой обычно отсутсвует выделеный сервер и все участники обмена равны, а каждый участник является одновременно и сервером и клиентом.';TweakType: ttRecommended), ( ID:503; Name:'Отключить обновление Windows через децентрализованную сеть (3 из 3)'; Desc:'Децентрализованная сеть P2P - это сеть в которой обычно отсутсвует выделеный сервер и все участники обмена равны, а каждый участник является одновременно и сервером и клиентом.';TweakType: ttRecommended), ( ID:504; Name:'Отложить обновление Windows (1 из 2)'; Desc:'Некоторые выпуски Windows 10 позволяют отложить обновления на компьютере. Если вы откладываете обновления, новые функции Windows не будут загружаться или устанавливаться в течение нескольких месяцев. В отложенные обновления не входят обновления безопасности. Обратите внимание, что в этом случае вы не сможете получать новейшие возможности Windows, как только они станут доступны.';TweakType: ttLimited), ( ID:510; Name:'Отложить обновление Windows (2 из 2)'; Desc:'Некоторые выпуски Windows 10 позволяют отложить обновления на компьютере. Если вы откладываете обновления, новые функции Windows не будут загружаться или устанавливаться в течение нескольких месяцев. В отложенные обновления не входят обновления безопасности. Обратите внимание, что в этом случае вы не сможете получать новейшие возможности Windows, как только они станут доступны.';TweakType: ttLimited), ( ID:505; Name:'Отключить автоматический поиск драйверов через Windows Update (1 из 3)'; Desc:'При подключении нового устройства, больше не будет осуществлятся поиск подходящих драйверов на серверах Microsoft.';TweakType: ttLimited), ( ID:615; Name:'Отключить автоматический поиск драйверов через Windows Update (2 из 3)'; Desc:'При подключении нового устройства, больше не будет осуществлятся поиск подходящих драйверов на серверах Microsoft.'; TweakType: ttLimited), ( ID:616; Name:'Отключить автоматический поиск драйверов через Windows Update (3 из 3)'; Desc:'При подключении нового устройства, больше не будет осуществлятся поиск подходящих драйверов на серверах Microsoft.'; TweakType: ttLimited), ( ID:506; Name:'Отключить автоматическое обновление Windows (1 из 2)'; Desc:'Отключает автоматическое обновление Windows.';TweakType: ttWarning), ( ID:507; Name:'Отключить автоматическое обновление Windows (2 из 2)'; Desc:'Отключает автоматическое обновление Windows.';TweakType: ttWarning), ( ID:508; Name:'Отключить обновление Windows для других продуктов (Microsoft Office и д.р.)'; Desc:'Отключает получения обновлений для других продуктов с серверов Microsoft.';TweakType: ttWarning), ( ID:509; Name:'Отключить обновление баз-вирусов "Защитника Windows"'; Desc:'Защитник Windows больше не будет получать обновления вирусных баз из интернета.';TweakType: ttWarning), // Miscellaneous ( ID:601; Name:'Отключить запрос отзывов о Windows (1 из 2)'; Desc:'Устанавливает период формирования отзывов в значение: Никогда.';TweakType: ttRecommended), ( ID:602; Name:'Отключить запрос отзывов о Windows (2 из 2)'; Desc:'Устанавливает период формирования отзывов в значение: Никогда.';TweakType: ttRecommended), ( ID:603; Name:'Отключить расширение Windows 10 - "Поиск с Bing"'; Desc:'';TweakType: ttRecommended), ( ID:604; Name:'Отключить Microsoft OneDrive (1 из 2)'; Desc:'';TweakType: ttLimited), ( ID:608; Name:'Отключить Microsoft OneDrive (2 из 2)'; Desc:'';TweakType: ttLimited), ( ID:622; Name:'Убрать значек OneDrive из проводника'; Desc:'Этот параметр просто убирает значек OneDrive из проводника.'; TweakType: ttLimited), ( ID:605; Name:'Включить DoNotTrack в Edge'; Desc:'Отправлять запрос сайтам о том что вы не хотите раскрывать свое местоположение.';TweakType: ttLimited), ( ID:606; Name:'Отключить поиск в интернете для панели поиска'; Desc:'Если включить эту опцию, возможность поиска в Интернете на панели поиска Windows будет недоступна.';TweakType: ttLimited), ( ID:607; Name:'Отключить сенсор местоположения (GPS)'; Desc:'';TweakType: ttLimited), ( ID:619; Name:'Отключить Cortana'; Desc:''; TweakType: ttLimited), ( ID:609; Name:'Отключить Cortana в панели поиска'; Desc:'';TweakType: ttLimited), ( ID:610; Name:'Отключить интернет для поисковых запросов через меню'; Desc:'Поисковые запросы не будут выполняться в Интернете и результаты из Интернета не будут отображаться при выполнении пользователем поискового запроса.';TweakType: ttLimited), ( ID:611; Name:'Отключить использование ограниченных соединений'; Desc:'Если вы включаете этот параметр, поисковые запросы не будут выполняться в Интернете через лимитные подключения и результаты из Интернета не будут отображаться при выполнении пользователем поискового запроса.';TweakType: ttLimited), ( ID:612; Name:'Отключить передачу метаданных'; Desc:'Отключает автоматическое получение приложений и информацию о новых устройствах из интернета.';TweakType: ttWarning), ( ID:613; Name:'Отключить автоматическое обновление Магазина приложений'; Desc:'Отключает автоматическое обновление Магазина приложений и установленных приложений. Старые версии приложений могут содержать "дыры" в безопасности.';TweakType: ttLimited), ( ID:614; Name:'Отключить KMS client Online Activation'; Desc:''; TweakType: ttRecommended), ( ID:617; Name:'Отключить Windows Update Sharing'; Desc:''; TweakType: ttRecommended), ( ID:618; Name:'Отключить WiFi Sense (1 из 3)'; Desc:''; TweakType: ttRecommended), ( ID:620; Name:'Отключить WiFi Sense (2 из 3)'; Desc:'Отключить автоматическое подключение к открытым точкам Wi-Fi'; TweakType: ttRecommended), ( ID:621; Name:'Отключить WiFi Sense (3 из 3)'; Desc:'Отключить журналирование WiFi Sense'; TweakType: ttRecommended), ( ID:623; Name:'Отключить запланированные задания'; Desc:''; TweakType: ttRecommended), ( ID:624; Name:'Заблокировать шпионские Hosts (1 из 3)'; Desc:'Заблокировать наиболее известные шпионские домены'; TweakType: ttRecommended), ( ID:625; Name:'Заблокировать шпионские Hosts (2 из 3)'; Desc:'Заблокировать менее известные шпионские домены'; TweakType: ttRecommended), ( ID:626; Name:'Заблокировать шпионские Hosts (3 из 3)'; Desc:'Заблокировать все известные шпионские домены'; TweakType: ttRecommended) ); // ( ID:; Name:''; Desc:''), function UpdateTweak(ID: integer; Action: TActionTweak): boolean; implementation procedure ChangeKeyAttribute(stKey: string); label Finish; var lRetCode: LongWord; Key: HKey; sia: SID_IDENTIFIER_AUTHORITY; pAdministratorsSid: PSID; pInteractiveSid: PSID; dwAclSize: DWORD; pDacl: PACL; sd: SECURITY_DESCRIPTOR; begin if Win32Platform<>VER_PLATFORM_WIN32_NT then Exit; lRetCode := RegOpenKeyEx( HKEY_LOCAL_MACHINE, PChar(stKey), 0, WRITE_DAC or KEY_WOW64_64KEY, Key); if (lRetCode <> ERROR_SUCCESS) then Exit; pDacl := nil; sia.Value[0]:=0; sia.Value[1]:=0; sia.Value[2]:=0; sia.Value[3]:=0; sia.Value[4]:=0; sia.Value[5]:=5; pInteractiveSid := nil; pAdministratorsSid := nil; if not(AllocateAndInitializeSid( sia, 1, SECURITY_INTERACTIVE_RID, 0, 0, 0, 0, 0, 0, 0, pInteractiveSid)) then goto Finish; if not(AllocateAndInitializeSid( sia, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, pAdministratorsSid)) then goto Finish; dwAclSize := sizeof(ACL) + 2 * ( sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) ) + GetLengthSid(pInteractiveSid) + GetLengthSid(pAdministratorsSid); pDacl := PACL(HeapAlloc(GetProcessHeap(), 0, dwAclSize)); if not (InitializeAcl(pDacl^, dwAclSize, ACL_REVISION)) then goto Finish; if not (AddAccessAllowedAce( pDacl, ACL_REVISION, KEY_ALL_ACCESS, pInteractiveSid)) then goto Finish; if not(AddAccessAllowedAce( pDacl, ACL_REVISION, KEY_ALL_ACCESS, pAdministratorsSid)) then goto Finish; if not (InitializeSecurityDescriptor(@sd, SECURITY_DESCRIPTOR_REVISION)) then goto Finish; if not (SetSecurityDescriptorDacl(@sd, TRUE, pDacl, FALSE)) then goto Finish; lRetCode := RegSetKeySecurity( Key, SECURITY_INFORMATION(DACL_SECURITY_INFORMATION), @sd); if (lRetCode <> ERROR_SUCCESS) then showmessage('error'); Finish: RegCloseKey(Key); RegCloseKey(HKEY_LOCAL_MACHINE); if (pDacl <> nil) then HeapFree(GetProcessHeap(), 0, pDacl); if (pInteractiveSid <> nil) then FreeSid(pInteractiveSid); if (pAdministratorsSid <>nil) then FreeSid(pAdministratorsSid); end; function UpdateTweak(ID: integer; Action: TActionTweak): boolean; var Reg, Reg32: Registry.TRegistry; Val: string; ValueInt: integer; mask: integer; begin result := false; if Action = atRefresh then Reg:=TRegistry.Create(KEY_READ or KEY_WOW64_64KEY) else Reg:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_64KEY); try case ID of 101: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\CredUI', true); Val := 'DisablePasswordReveal'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 102: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\AppCompat', true); Val := 'DisableUAR'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 103: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('System\CurrentControlSet\Services\DiagTrack', true); Val := 'Start'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 4) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,4); atCancel: Reg.WriteInteger(Val,2); end; end; 104: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('System\CurrentControlSet\Services\dmwappushservice', true); Val := 'Start'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 4) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,4); atCancel: Reg.WriteInteger(Val,2); end; end; 105: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('System\CurrentControlSet\Control\WMI\AutoLogger\AutoLogger-Diagtrack-Listener', true); Val := 'Start'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); // echo «» > AutoLogger-Diagtrack-Listener.etl // cacls AutoLogger-Diagtrack-Listener.etl /d SYSTEM atCancel: Result := Reg.DeleteValue(Val); end; end; 106: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; // SID пользователя // Wow6432Node Reg.OpenKey('SOFTWARE\Microsoft\WcmSvc\wifinetworkmanager\features\'+GetCurrentUserSid, true); Val := 'FeatureStates'; mask := 1; // проверяем первый бит case Action of // 1 - Disable WiFi sense atRefresh: try try ValueInt := StrToInt(Reg.ReadString(Val)); except on Exception : EConvertError do ValueInt := 893; end; if ((ValueInt and mask) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: try try ValueInt := StrToInt(Reg.ReadString(Val)); except on Exception : EConvertError do ValueInt := 893; end; ValueInt := ValueInt xor Mask; Reg.WriteString(Val,IntToStr(ValueInt)); except on ERegistryException do end; atCancel: try try ValueInt := StrToInt(Reg.ReadString(Val)); except on Exception : EConvertError do ValueInt := 893; end; ValueInt := ValueInt or Mask; Reg.WriteString(Val,IntToStr(ValueInt)); except on ERegistryException do end; end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; // SID пользователя // Wow6432Node Reg32.OpenKey('SOFTWARE\Microsoft\WcmSvc\wifinetworkmanager\features\'+GetCurrentUserSid, true); Val := 'FeatureStates'; mask := 1; // проверяем первый бит case Action of // 1 - Disable WiFi sense atRefresh: try try ValueInt := StrToInt(Reg32.ReadString(Val)); except on Exception : EConvertError do ValueInt := 893; end; if ((ValueInt and mask) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: try try ValueInt := StrToInt(Reg32.ReadString(Val)); except on Exception : EConvertError do ValueInt := 893; end; ValueInt := ValueInt xor Mask; Reg32.WriteString(Val,IntToStr(ValueInt)); except on ERegistryException do end; atCancel: try try ValueInt := StrToInt(Reg32.ReadString(Val)); except on Exception : EConvertError do ValueInt := 893; end; ValueInt := ValueInt or Mask; Reg32.WriteString(Val,IntToStr(ValueInt)); except on ERegistryException do end; end; finally Reg32.Free; end; end; 107: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; // SID пользователя // Wow6432Node Reg.OpenKey('SOFTWARE\Microsoft\WcmSvc\wifinetworkmanager\features\'+GetCurrentUserSid, true); Val := 'FeatureStates'; mask := 64; // 1 shl 6; проверяем седьмой бит case Action of // 64 - Disable Wifi sense of my contact 7 atRefresh: try try ValueInt := StrToInt(Reg.ReadString(Val)); except on Exception : EConvertError do ValueInt := 893; end; if ((ValueInt and mask) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: try try ValueInt := StrToInt(Reg.ReadString(Val)); except on Exception : EConvertError do ValueInt := 893; end; ValueInt := ValueInt xor Mask; Reg.WriteString(Val,IntToStr(ValueInt)); except on ERegistryException do end; atCancel: try try ValueInt := StrToInt(Reg.ReadString(Val)); except on Exception : EConvertError do ValueInt := 893; end; ValueInt := ValueInt or Mask; Reg.WriteString(Val,IntToStr(ValueInt)); except on ERegistryException do end; end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; // SID пользователя // Wow6432Node Reg32.OpenKey('SOFTWARE\Microsoft\WcmSvc\wifinetworkmanager\features\'+GetCurrentUserSid, true); Val := 'FeatureStates'; mask := 64; // 1 shl 6; проверяем седьмой бит case Action of // 64 - Disable Wifi sense of my contact 7 atRefresh: try try ValueInt := StrToInt(Reg32.ReadString(Val)); except on Exception : EConvertError do ValueInt := 893; end; if ((ValueInt and mask) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: try try ValueInt := StrToInt(Reg32.ReadString(Val)); except on Exception : EConvertError do ValueInt := 893; end; ValueInt := ValueInt xor Mask; Reg32.WriteString(Val,IntToStr(ValueInt)); except on ERegistryException do end; atCancel: try try ValueInt := StrToInt(Reg32.ReadString(Val)); except on Exception : EConvertError do ValueInt := 893; end; ValueInt := ValueInt or Mask; Reg32.WriteString(Val,IntToStr(ValueInt)); except on ERegistryException do end; end; finally Reg32.Free; end; end; 108: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\{A8804298-2D5F-42E3-9531-9C8C39EB29CE}', true); Val := 'Value'; case Action of atRefresh: try if (Reg.ReadString(Val) = 'Deny') then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteString(Val,'Deny'); atCancel: Reg.WriteString(Val,'Allow'); end; end; 109: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\LooselyCoupled', true); Val := 'Value'; case Action of atRefresh: try if (Reg.ReadString(Val) = 'Deny') then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteString(Val,'Deny'); atCancel: Reg.WriteString(Val,'Allow'); end; end; 110: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\WMDRM', true); Val := 'DisableOnline'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 111: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows Defender', true); Val := 'DisableAntiSpyware'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 201: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\{C1D23ACC-752B-43E5-8448-8D0E519CD6D6}', true); Val := 'Value'; case Action of atRefresh: try if (Reg.ReadString(Val) = 'Deny') then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteString(Val,'Deny'); atCancel: Reg.WriteString(Val,'Allow'); end; end; 202: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\TabletPC', true); Val := 'PreventHandwritingDataSharing'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 203: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\HandwritingErrorReports', true); Val := 'PreventHandwritingErrorReports'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 204: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\AppCompat', true); Val := 'DisableInventory'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 205: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Personalization\Settings', true); Val := 'AcceptedPrivacyPolicy'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; end; 206: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\SettingSync\Groups\Language', true); Val := 'Enabled'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.WriteInteger(Val,1); end; end; 207: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\InputPersonalization', true); Val := 'RestrictImplicitInkCollection'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 208: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\InputPersonalization', true); Val := 'RestrictImplicitTextCollection'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 209: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\InputPersonalization\TrainedDataStore', true); Val := 'HarvestContacts'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.WriteInteger(Val,1); end; end; 210: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\Personalization', true); Val := 'NoLockScreenCamera'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 211: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\Windows Search', true); Val := 'AllowCortana'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; end; 212: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Input\TIPC', true); Val := 'Enabled'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; end; 213: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo', true); Val := 'Enabled'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; end; 214: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; // Wow6432Node Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo', true); Val := 'Enabled'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo', true); Val := 'Enabled'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Result := Reg32.DeleteValue(Val); end; finally Reg32.Free; end; end; 215: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\PushNotifications', true); Val := 'ToastEnabled'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; end; 216: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\{D89823BA-7180-4B81-B50C-7E471E6121A3}', true); Val := 'Value'; case Action of atRefresh: try if (Reg.ReadString(Val) = 'Deny') then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteString(Val,'Deny'); atCancel: Reg.WriteString(Val,'Allow'); end; end; 217: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\{E5323777-F976-4f5b-9B55-B94699C46E44}', true); Val := 'Value'; case Action of atRefresh: try if (Reg.ReadString(Val) = 'Deny') then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteString(Val,'Deny'); atCancel: Reg.WriteString(Val,'Allow'); end; end; 218: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\{BFFA794E4-F964-4FDB-90F6-51056BFE4B44}', true); Val := 'Value'; case Action of atRefresh: try if (Reg.ReadString(Val) = 'Deny') then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteString(Val,'Deny'); atCancel: Reg.WriteString(Val,'Allow'); end; end; 219: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows NT\CurrentVersion\Sensor\Permissons\{BFFA794E4-F964-4FDB-90F6-51056BFE4B44}', true); Val := 'SensorPermissionState'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; end; 220: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\{2EEF81BE-33FA-4800-9670-1CD474972C3F}', true); Val := 'Value'; case Action of atRefresh: try if (Reg.ReadString(Val) = 'Deny') then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteString(Val,'Deny'); atCancel: Reg.WriteString(Val,'Allow'); end; end; 221: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\{992AFA70-6F47-4148-B3E9-3003349C1548}', true); Val := 'Value'; case Action of atRefresh: try if (Reg.ReadString(Val) = 'Deny') then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteString(Val,'Deny'); atCancel: Reg.WriteString(Val,'Allow'); end; end; 222: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Biometrics', true); Val := 'Enabled'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; end; 223: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('Control Panel\International\User Profile', true); Val := 'HttpAcceptLanguageOptOut'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 224: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost', true); Val := 'EnableWebContentEvaluation'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; end; 225: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\SQMClient\Windows', true); Val := 'CEIPEnable'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.WriteInteger(Val,1); end; end; 226: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SYSTEM\CurrentControlSet\Control\WMI\AutoLogger\SQMLogger', true); Val := 'Start'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.WriteInteger(Val,1); end; end; 227: begin Reg.RootKey:=HKEY_CURRENT_USER; // Wow6432Node Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo', true); Val := 'Id'; case Action of atRefresh: try if (Reg.ReadString(Val)='') then result:=true; except on ERegistryException do result:=false; end; atApply: Reg.DeleteValue(Val); { atCancel: Result := Reg.DeleteValue(Val);} end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\AdvertisingInfo', true); Val := 'Id'; case Action of atRefresh: try if (Reg32.ReadString(Val)='') then result:=true; except on ERegistryException do result:=false; end; atApply: Reg32.DeleteValue(Val); {atCancel: Result := Reg32.DeleteValue(Val);} end; finally Reg32.Free; end; end; 301: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\LocationAndSensors', true); Val := 'DisableLocation'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 302: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\LocationAndSensors', true); Val := 'DisableWindowsLocationProvider'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 303: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\LocationAndSensors', true); Val := 'DisableLocationScripting'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 304: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\LocationAndSensors', true); Val := 'DisableSensors'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 401: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\DataCollection', true); Val := 'AllowTelemetry'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; { Для Pro версии нельзя отключить полностью телеметрию, работает только в значении 1 (отправка базовых данных): } end; 402: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection', true); Val := 'AllowTelemetry'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection', true); Val := 'AllowTelemetry'; case Action of atRefresh: try if result and (Reg32.ReadInteger(Val) = 0) then result := true else result := false; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Reg32.WriteInteger(Val,1); end; finally Reg32.Free; end; end; 403: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\AppCompat', true); Val := 'AITEnable'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; end; 501: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization', true); Val := 'SystemSettingsDownloadMode'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); // 0 или 3 atCancel: Reg.DeleteValue(Val); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_CURRENT_USER; // Wow6432Node Reg32.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization', true); Val := 'SystemSettingsDownloadMode'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Reg32.DeleteValue(Val); end; finally Reg32.Free; end; end; 502: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Config', true); Val := 'DODownloadMode'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); // 0 !!! Отключает atCancel: Result := Reg.DeleteValue(Val); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; // Wow6432Node Reg32.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Config', true); Val := 'DODownloadMode'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Reg32.DeleteValue(Val); end; finally Reg32.Free; end; end; 503: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\DeliveryOptimization', true); Val := 'DODownloadMode'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; end; 504: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate', true); Val := 'DeferUpgrade'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 505: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\DriverSearching', true); Val := 'DontSearchWindowsUpdate'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 506: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU', true); Val := 'NoAutoUpdate'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Result := Reg.DeleteValue(Val); end; end; 507: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('System\CurrentControlSet\Services\wuauserv', true); Val := 'Start'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 4) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,4); atCancel: Reg.WriteInteger(Val,3); end; end; 508: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; // Wow6432Node Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Services\7971f918-a847-4430-9279-4a52d1efe18d', true); Val := 'RegisteredWithAU'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.WriteInteger(Val,1); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Services\7971f918-a847-4430-9279-4a52d1efe18d', true); Val := 'RegisteredWithAU'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Reg32.WriteInteger(Val,1); end; finally Reg32.Free; end; end; 509: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\MRT', true); Val := 'DontOfferThroughWUAU'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Reg.WriteInteger(Val,0); end; end; 510: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Microsoft\WindowsUpdate\UX\Settings', true); Val := 'DeferUpgrade'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Reg.WriteInteger(Val,0); end; end; 601: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Siuf\Rules', true); Val := 'NumberOfSIUFInPeriod'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; end; 602: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Siuf\Rules', true); Val := 'PeriodInNanoSeconds'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := false; except on ERegistryException do result:=true; end; atApply: Result := Reg.DeleteValue(Val); atCancel: Reg.WriteInteger(Val,0); end; end; 603: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Search', true); Val := 'BingSearchEnabled'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Result := Reg.DeleteValue(Val); end; end; 604: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\OneDrive', true); Val := 'DisableFileSyncNGSC'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Reg.DeleteValue(Val); end; end; 605: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppContainer\Storage\microsoft.microsoftedge_8wekyb3d8bbwe\MicrosoftEdge\Main', true); Val := 'DoNotTrack'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Reg.WriteInteger(Val,0); end; end; 606: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\Windows Search', true); Val := 'DisableWebSearch'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Reg.DeleteValue(Val); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Policies\Microsoft\Windows\Windows Search', true); Val := 'DisableWebSearch'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,1); atCancel: Reg32.DeleteValue(Val); end; finally Reg32.Free; end; end; 607: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DeviceAccess\Global\{BFA794E4-F964-4FDB-90F6-51056BFE4B44}', true); Val := 'Value'; case Action of atRefresh: try if (Reg.ReadString(Val) = 'Deny') then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteString(Val,'Deny'); atCancel: Reg.WriteString(Val,'Allow'); end; end; // HKLM\System\CurrentControlSet\Control\Storage\EnabledDenyGP\DenyAllGPState 608: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('System\CurrentControlSet\Control\Storage\EnabledDenyGP', true); Val := 'DenyAllGPState'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Reg.WriteInteger(Val,0); end; end; 609: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Search', true); Val := 'CortanaEnabled'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.WriteInteger(Val,1); end; end; 610: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('Software\Policies\Microsoft\Windows\Windows Search', true); Val := 'ConnectedSearchUseWeb'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.DeleteValue(Val); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('Software\Policies\Microsoft\Windows\Windows Search', true); Val := 'ConnectedSearchUseWeb'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Reg32.DeleteValue(Val); end; finally Reg32.Free; end; end; 611: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('Software\Policies\Microsoft\Windows\Windows Search', true); Val := 'ConnectedSearchUseWebOverMeteredConnections'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.DeleteValue(Val); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('Software\Policies\Microsoft\Windows\Windows Search', true); Val := 'ConnectedSearchUseWebOverMeteredConnections'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Reg32.DeleteValue(Val); end; finally Reg32.Free; end; end; 612: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\Device Metadata', true); Val := 'PreventDeviceMetadataFromNetwork'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Reg.DeleteValue(Val); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Policies\Microsoft\Windows\Device Metadata', true); Val := 'PreventDeviceMetadataFromNetwork'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,1); atCancel: Reg32.DeleteValue(Val); end; finally Reg32.Free; end; end; 613: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\WindowsStore\WindowsUpdate', true); Val := 'AutoDownload'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 2) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,2); atCancel: Reg.DeleteValue(Val); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Policies\Microsoft\WindowsStore\WindowsUpdate', true); Val := 'AutoDownload'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 2) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,2); atCancel: Reg32.DeleteValue(Val); end; finally Reg32.Free; end; end; 614: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows NT\CurrentVersion\Software Protection Platform', true); Val := 'NoGenTicket'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 1) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,1); atCancel: Reg.WriteInteger(Val,0); end; end; 615: begin {Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DriverSearching', true); Val := 'SearchOrderConfig'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.WriteInteger(Val,1); end;} Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\DriverSearching', true); Val := 'SearchOrderConfig'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Reg32.WriteInteger(Val,1); end; finally Reg32.Free; end; end; 616: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsStore\WindowsUpdate\', true); Val := 'AutoDownload'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 2) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,2); atCancel: Reg.WriteInteger(Val,4); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsStore\WindowsUpdate', true); Val := 'AutoDownload'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 2) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,2); atCancel: Reg32.WriteInteger(Val,4); end; finally Reg32.Free; end; end; 617: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Config', true); Val := 'DODownloadMode'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.WriteInteger(Val,3); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Config', true); Val := 'DODownloadMode'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Reg32.WriteInteger(Val,3); end; finally Reg32.Free; end; end; 618: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Microsoft\WcmSvc\wifinetworkmanager\config', true); Val := 'AutoConnectAllowedOEM'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.WriteInteger(Val,1); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Microsoft\WcmSvc\wifinetworkmanager\config', true); Val := 'AutoConnectAllowedOEM'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Reg32.WriteInteger(Val,1); end; finally Reg32.Free; end; end; 619: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Microsoft\PolicyManager\default\Experience\AllowCortana', true); Val := 'value'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.DeleteValue(Val); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Microsoft\PolicyManager\default\Experience\AllowCortana', true); Val := 'value'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Reg32.DeleteValue(Val); end; finally Reg32.Free; end; end; 620: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Microsoft\PolicyManager\default\WiFi\AllowAutoConnectToWiFiSenseHotspots', true); Val := 'value'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.DeleteValue(Val); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Microsoft\PolicyManager\default\WiFi\AllowAutoConnectToWiFiSenseHotspots', true); Val := 'value'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Reg32.DeleteValue(Val); end; finally Reg32.Free; end; end; 621: begin Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Microsoft\PolicyManager\default\WiFi\AllowWiFiHotSpotReporting', true); Val := 'value'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.DeleteValue(Val); end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Microsoft\PolicyManager\default\WiFi\AllowWiFiHotSpotReporting', true); Val := 'value'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Reg32.DeleteValue(Val); end; finally Reg32.Free; end; end; 622: begin Reg.RootKey:=HKEY_CURRENT_USER; Reg.OpenKey('Software\Classes\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}\ShellFolder', true); Val := 'Attributes'; Mask := 1 shl 20; //21 бит case Action of atRefresh: try try ValueInt := Reg.ReadInteger(Val); except on ERegistryException do ValueInt := 4034920525; end; if ((ValueInt and mask) <> 0) then result := true; except on ERegistryException do result:=false; end; atApply: try try ValueInt := Reg.ReadInteger(Val); except on ERegistryException do ValueInt := 4034920525; end; ValueInt := ValueInt or Mask; Reg.WriteInteger(Val,ValueInt); except on ERegistryException do end; atCancel: try try ValueInt := Reg.ReadInteger(Val); except on ERegistryException do ValueInt := 4034920525; end; ValueInt := ValueInt xor Mask; Reg.WriteInteger(Val,ValueInt); except on ERegistryException do end; end; Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_CURRENT_USER; Reg32.OpenKey('Software\Classes\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}\ShellFolder', true); Val := 'Attributes'; Mask := 1 shl 20; //21 бит case Action of atRefresh: try try ValueInt := Reg32.ReadInteger(Val); except on ERegistryException do ValueInt := 4034920525; end; if ((ValueInt and mask) <> 0) then result := true; except on ERegistryException do result:=false; end; atApply: try try ValueInt := Reg32.ReadInteger(Val); except on ERegistryException do ValueInt := 4034920525; end; ValueInt := ValueInt or Mask; Reg32.WriteInteger(Val,ValueInt); except on ERegistryException do end; atCancel: try try ValueInt := Reg32.ReadInteger(Val); except on ERegistryException do ValueInt := 4034920525; end; ValueInt := ValueInt xor Mask; Reg32.WriteInteger(Val,ValueInt); except on ERegistryException do end; end; finally Reg32.Free; end; end; 623: begin case Action of atRefresh: result := not GetTasksIsEnabled; atApply: SetTasksStatus(False); atCancel: SetTasksStatus(True); // По умолчанию включено end; end; 624: begin try case Action of atRefresh: result := HostIsBlockNormal; atApply: SetHostBlockNormal; atCancel: SetHostNotBlockNormal; end; except on EFCreateError do MessageDlg(ApplicationName, 'Не удалось записать правила в hosts', mtError, [mbOK],''); end; end; 625: begin try case Action of atRefresh: result := HostIsBlockExtra; atApply: SetHostBlockExtra; atCancel: SetHostNotBlockExtra; end; except on EFCreateError do MessageDlg(ApplicationName, 'Не удалось записать правила в hosts', mtError, [mbOK],''); end; end; 626: begin // Все домены try case Action of atRefresh: result := HostIsBlockSuperExtra; atApply: SetHostBlockSuperExtra; atCancel: SetHostNotBlockSuperExtra; end; except on EFCreateError do MessageDlg(ApplicationName, 'Не удалось записать правила в hosts', mtError, [mbOK],''); end; end; { 627: begin ChangeKeyAttribute('SOFTWARE\Microsoft\Windows Defender\SpyNet'); Reg.RootKey:=HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Microsoft\Windows Defender\SpyNet', true); Val := 'SubmitSamplesConsent'; case Action of atRefresh: try if (Reg.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg.WriteInteger(Val,0); atCancel: Reg.WriteInteger(Val,1); end; { Reg32:=TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY); try Reg32.RootKey:=HKEY_LOCAL_MACHINE; Reg32.OpenKey('SOFTWARE\Microsoft\Windows Defender\SpyNet', true); Val := 'SubmitSamplesConsent'; case Action of atRefresh: try if (Reg32.ReadInteger(Val) = 0) then result := true; except on ERegistryException do result:=false; end; atApply: Reg32.WriteInteger(Val,0); atCancel: Reg32.WriteInteger(Val,1); end; finally Reg32.Free; end; end; } end; finally Reg.Free; end; end; end.
unit ULocalizerTests; interface {$I dws.inc} uses {$IFDEF WINDOWS} Windows, {$ENDIF} Classes, SysUtils, dwsXPlatformTests, dwsComp, dwsCompiler, dwsExprs, dwsTokenizer, dwsXPlatform, dwsFileSystem, dwsErrors, dwsUtils, Variants, dwsSymbols, dwsPascalTokenizer, dwsStrings, dwsStack, dwsJSON; type TLocalizerTests = class (TTestCase) private FCompiler : TDelphiWebScript; public procedure SetUp; override; procedure TearDown; override; procedure DoLocalize(Sender : TObject; const aString : UnicodeString; var Result : UnicodeString); published procedure SimpleTest; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------ // ------------------ TLocalizerTests ------------------ // ------------------ // SetUp // procedure TLocalizerTests.SetUp; begin FCompiler:=TDelphiWebScript.Create(nil); end; // TearDown // procedure TLocalizerTests.TearDown; begin FCompiler.Free; end; // DoLocalize // procedure TLocalizerTests.DoLocalize(Sender : TObject; const aString : UnicodeString; var Result : UnicodeString); begin Result:='['+aString+']'; end; // SimpleTest // procedure TLocalizerTests.SimpleTest; var prog : IdwsProgram; exec : IdwsProgramExecution; customLoc : TdwsCustomLocalizer; begin customLoc:=TdwsCustomLocalizer.Create(nil); try customLoc.OnLocalizeString:=DoLocalize; FCompiler.Config.Localizer:=customLoc; prog:=FCompiler.Compile('resourcestring hello="hello"; Print(hello);'); CheckEquals(0, prog.Msgs.Count, 'compile errors'); exec:=prog.CreateNewExecution; exec.Execute; CheckEquals('[hello]', exec.Result.ToString, 'localized'); exec.Localizer:=nil; exec.Execute; CheckEquals('hello', exec.Result.ToString, 'localizer off'); exec:=prog.CreateNewExecution; exec.Execute; CheckEquals('[hello]', exec.Result.ToString, 'localized2'); finally customLoc.Free; end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterTest('LocalizerTests', TLocalizerTests); end.
unit Exemplo1; interface uses System.Classes, System.SysUtils; type TFichaUsuario = class private FCodigo: integer; FNome: String; FData: TDateTime; FCargo: string; public procedure Exportar(pArquivo: string); published property Codigo: integer read FCodigo write FCodigo; property Nome: String read FNome write FNome; property Data: TDateTime read FData write FData; property Cargo: string read FCargo write FCargo; end; implementation { TFichaUsuario } procedure TFichaUsuario.Exportar(pArquivo: string); var lTexto : TStringList; begin lTexto := TStringList.Create; try lTexto.Add('Código: '+FCodigo.ToString); lTexto.Add('Nome: '+FNome); lTexto.Add('Data: '+FormatDateTime('DD/MM/YYYY',FData)); lTexto.Add('Cargo: '+FCargo); lTexto.SaveToFile(pArquivo); finally lTexto.Free; end; end; end.
unit GraficoVelas; interface uses GraficoZoom, GR32, Graphics, Classes, Tipos, DatosGrafico; type TGraficoVelas = class(TZoomGrafico) private FColorAlcista: TColor32; FColorBajista: TColor32; function GetColorAlcista: TColor; function GetColorBajista: TColor; procedure SetColorAlcista(const Value: TColor); procedure SetColorBajista(const Value: TColor); protected procedure PaintZoomGrafico(const iFrom, iTo: integer); override; function CreateDatosGrafico: TDatosGrafico; override; public constructor Create(AOwner: TComponent); override; procedure SetData(const PCambios, PCambiosMaximo, PCambiosMinimo: PArrayCurrency; const PFechas: PArrayDate); reintroduce; property ColorAlcista: TColor read GetColorAlcista write SetColorAlcista default clGreen; property ColorBajista: TColor read GetColorBajista write SetColorBajista default clRed; end; TDatosGraficoVelas = class(TDatosGrafico) private FPCambiosMaximo, FPCambiosMinimo: PArrayCurrency; YMaxTransformados, YMinTransformados: TArrayInteger; function GetCambioMaximo(index: integer): currency; function GetCambioMinimo(index: integer): currency; protected procedure RecalculateMaxMin(const fromPos, toPos: integer); override; public procedure SetDataMaximoMinimo(const PCambiosMaximo, PCambiosMinimo: PArrayCurrency); procedure RecalculateTransformados(const fromPos, toPos: integer); overload; override; property CambioMaximo[index: integer]: currency read GetCambioMaximo; property CambioMinimo[index: integer]: currency read GetCambioMinimo; property PCambiosMaximo: PArrayCurrency read FPCambiosMaximo; property PCambiosMinimo: PArrayCurrency read FPCambiosMinimo; end; implementation uses Grafico; { TGraficoVelas } constructor TGraficoVelas.Create(AOwner: TComponent); begin inherited Create(AOwner); ColorAlcista := clGreen; ColorBajista := clRed; ShowPositions := true; end; function TGraficoVelas.GetColorAlcista: TColor; begin result := WinColor(FColorAlcista); end; function TGraficoVelas.GetColorBajista: TColor; begin result := WinColor(FColorBajista); end; function TGraficoVelas.CreateDatosGrafico: TDatosGrafico; begin result := TDatosGraficoVelas.Create; result.PixelSize := 5; end; procedure TGraficoVelas.PaintZoomGrafico(const iFrom, iTo: integer); var x, y, yAyer: integer; xLeft, xRight: integer; i, j: integer; begin for i := iFrom + 1 to iTo do begin if Datos.IsCambio[i] then begin j := i - 1; while (j > 0) and (not Datos.IsCambio[j]) do dec(j); yAyer := Datos.YTransformados[j]; x := Datos.XTransformados[i]; y := Datos.YTransformados[i]; xLeft := x - 1; xRight := x + 2; if Datos.Cambio[j] >= Datos.Cambio[i] then begin Bitmap.PenColor := FColorBajista; Bitmap.FillRectS(xLeft, yAyer, xRight, y, FColorBajista); end else begin Bitmap.PenColor := FColorAlcista; Bitmap.FillRectS(xLeft, y, xRight, yAyer, FColorAlcista); end; Bitmap.LineS(x, TDatosGraficoVelas(Datos).YMaxTransformados[i], x, TDatosGraficoVelas(Datos).YMinTransformados[i], Bitmap.PenColor); end; end; end; procedure TGraficoVelas.SetData(const PCambios, PCambiosMaximo, PCambiosMinimo: PArrayCurrency; const PFechas: PArrayDate); begin TDatosGraficoVelas(Datos).SetDataMaximoMinimo(PCambiosMaximo, PCambiosMinimo); inherited SetData(PCambios, PFechas); end; procedure TGraficoVelas.SetColorAlcista(const Value: TColor); begin FColorAlcista := Color32(Value); end; procedure TGraficoVelas.SetColorBajista(const Value: TColor); begin FColorBajista := Color32(Value); end; { TDatosGraficoVelas } function TDatosGraficoVelas.GetCambioMaximo(index: integer): currency; begin result := FPCambiosMaximo^[index]; end; function TDatosGraficoVelas.GetCambioMinimo(index: integer): currency; begin result := FPCambiosMinimo^[index]; end; procedure TDatosGraficoVelas.RecalculateMaxMin(const fromPos, toPos: integer); var i, from: integer; max, min: Currency; begin from := fromPos; while (IsDataNull[from]) or (IsSinCambio[from]) or (FPCambiosMaximo^[from] = SIN_CAMBIO) or (FPCambiosMinimo^[from] = SIN_CAMBIO) or (FPCambiosMaximo^[from] = DataNull) or (FPCambiosMinimo^[from] = DataNull) do inc(from); FMax := FPCambiosMaximo^[from]; FMin := FPCambiosMinimo^[from]; for i := from to toPos do begin if IsCambio[i] then begin max := FPCambiosMaximo^[i]; if (max <> DataNull) and (max <> SIN_CAMBIO) then begin min := FPCambiosMinimo^[i]; if (min <> DataNull) and (min <> SIN_CAMBIO) then begin if FMax < max then FMax := max; if min < FMin then FMin := min; end; end; end; end; end; procedure TDatosGraficoVelas.RecalculateTransformados(const fromPos, toPos: integer); var i: integer; den, min: currency; begin inherited RecalculateTransformados(fromPos, toPos); min := Minimo; den := Maximo - min; for i := fromPos to toPos do begin if Cambio[i] = DataNull then begin YMaxTransformados[i] := DataNull; YMinTransformados[i] := DataNull; end else begin if (den = 0) or (IsSinCambio[i]) then begin YMaxTransformados[i] := SIN_CAMBIO_TRANSFORMADO; YMinTransformados[i] := SIN_CAMBIO_TRANSFORMADO; end else begin // Si Maximo - Minimo --> alto // valor - Minimo --> ? // valor = YMaxTransformados YMaxTransformados[i] := Alto - // El eje Y es negativo Round((FPCambiosMaximo^[i] - min) * Alto / den) + Top; // valor = YMinTransformados YMinTransformados[i] := Alto - // El eje Y es negativo Round((FPCambiosMinimo^[i] - min) * Alto / den) + Top; end; end; end; end; procedure TDatosGraficoVelas.SetDataMaximoMinimo(const PCambiosMaximo, PCambiosMinimo: PArrayCurrency); var num: integer; begin FPCambiosMaximo := PCambiosMaximo; FPCambiosMinimo := PCambiosMinimo; num := length(PCambiosMaximo^); SetLength(YMaxTransformados, num); SetLength(YMinTransformados, num); end; end.
unit unit2; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, SynEdit, Forms, Controls, Graphics, Dialogs, ExtCtrls, ComCtrls, StdCtrls, SynEditMarkupWordGroup, SynEditHighlighter, //SynHighlighterMiniPas2,//must before original SynHighlighterPas, SynHighlighterLFM, SynHighlighterPython, SynHighlighterHTML, SynHighlighterXML, SynHighlighterJScript; type TMarkupWordGroupAccess = class(TSynEditMarkupWordGroup) end; { TForm2 } TForm2 = class(TForm) btnConfig: TButton; PageControl1: TPageControl; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; SynEditMiniPas: TSynEdit; SynEditPas: TSynEdit; SynEditLFM: TSynEdit; SynEditDemoFold: TSynEdit; SynEditPython: TSynEdit; SynEditXML: TSynEdit; SynEditJS: TSynEdit; SynEditColorFold: TSynEdit; SynFreePascalSyn1: TSynFreePascalSyn; SynHTMLSyn1: TSynHTMLSyn; SynJScriptSyn1: TSynJScriptSyn; SynLFMSyn1: TSynLFMSyn; SynPythonSyn1: TSynPythonSyn; SynXMLSyn1: TSynXMLSyn; TabSheet1: TTabSheet; TabSheet2: TTabSheet; TabSheet3: TTabSheet; TabSheet4: TTabSheet; TabSheet5: TTabSheet; TabSheet6: TTabSheet; TabSheet7: TTabSheet; TabSheet8: TTabSheet; procedure btnConfigClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { private declarations } procedure AddMarkupFoldColors; procedure FillLfmToSynEdit2; procedure LeaveOnly(ASynEdit:TSynEdit); procedure SetHighlighter(ASynEdit:TSynEdit; HLClass: TSynCustomHighlighterClass); public { public declarations } end; var Form2: TForm2; implementation uses SynGutterFoldDebug, SynEditHighlighterFoldBase, SynEditMarkupFoldColoring, SynEditMarkupIfDef, foldhl, SynHighlighterBracket, uConfig ; {$R *.lfm} function ComponentToStringProc(Component: TComponent): string; var BinStream:TMemoryStream; StrStream: TStringStream; //s: string; begin BinStream := TMemoryStream.Create; try StrStream := TStringStream.Create(''); try BinStream.WriteComponent(Component); BinStream.Seek(0, soFromBeginning); ObjectBinaryToText(BinStream, StrStream); StrStream.Seek(0, soFromBeginning); Result:= StrStream.DataString; finally StrStream.Free; end; finally BinStream.Free end; end; { TForm2 } procedure TForm2.FormCreate(Sender: TObject); begin if self <> Form2 then exit; // avoid infinite loop with SynFreePascalSyn1 do begin //FoldConfig[ord(cfbtIfThen)].Modes:=[fmMarkup, fmOutline]; //.Enabled := True; FoldConfig[ord(cfbtIfThen)].SupportedModes:=[fmFold, fmMarkup, fmOutline]; //.Enabled := True; FoldConfig[ord(cfbtIfThen)].Modes:=[fmFold, fmMarkup, fmOutline]; //.Enabled := True; end; SynEditMiniPas.Lines.Assign( SynEditPas.Lines); { SynEditMiniPas.Highlighter := SynHighlighterMiniPas2.TSynPasSyn.Create(self); with SynHighlighterMiniPas2.TSynPasSyn(SynEditMiniPas.Highlighter) do begin FoldConfig[ord(cfbtIfThen)].SupportedModes:=[fmFold, fmMarkup, fmOutline]; //.Enabled := True; FoldConfig[ord(cfbtIfThen)].Modes:=[fmFold, fmMarkup, fmOutline]; //.Enabled := True; // FoldConfig[ord(cfbtCaseElse)].Enabled := True; // FoldConfig[ord(cfbtCaseElse)].Enabled := True; CaseLabelAttri.Background:= clYellow; //FoldConfig[ord(cfbtIfThen)].Enabled := True; CommentAttri.Foreground:=clTeal; DirectiveAttri.Foreground := clRed; end; } //================= INDIVIDUAL CHECK, so debug can be focused ================ //LeaveOnly(SynEditDemoFold); //LeaveOnly(SynEditLFM); //LeaveOnly(SynEditMiniPas); FillLfmToSynEdit2(); SetHighlighter(SynEditColorFold, TSynHighlighterBracket); SetHighlighter(SynEditDemoFold, TSynDemoHlFold); AddMarkupFoldColors(); end; procedure TForm2.btnConfigClick(Sender: TObject); begin frmConfig.ShowModal; end; procedure TForm2.AddMarkupFoldColors; var M : TSynEditMarkupFoldColors; i : integer; S : TSynEdit; Mi : TSynEditMarkupIfDef; begin for i := 0 to Pred(ComponentCount) do begin if Components[i] is TSynEdit then begin S := TSynEdit(Components[i]); if not (S.Highlighter is TSynCustomFoldHighlighter) then continue; S.LineHighlightColor.Background:=panel1.Color; TSynGutterFoldDebug.Create(S.RightGutter.Parts); //continue; //debug M := TSynEditMarkupFoldColors.Create(S); M.DefaultGroup := 0; S.MarkupManager.AddMarkUp(M); //if S.Highlighter.ClassNameIs('TSynPasSyn') then if S.Highlighter is SynHighlighterPas.TSynPasSyn then begin Mi := TSynEditMarkupIfDef.Create(S); //Mi.FoldView := S.FoldedTextBuffer); S.MarkupManager.AddMarkUp(Mi); Mi.Highlighter := TSynPasSyn(S.Highlighter); end; end; end; end; procedure TForm2.FillLfmToSynEdit2; var F : TForm2; var i : integer; S : TSynEdit; begin if self <> Form2 then exit; // avoid infinite loop if SynEditLFM = nil then exit; F := TForm2.Create(nil); for i := 0 to Pred(F.ComponentCount) do begin if F.Components[i] is TSynEdit then begin S := TSynEdit(F.Components[i]); S.Lines.Text := S.Name; end; end; SynEditLFM.Lines.Text := ComponentToStringProc(F); F.Free; //SynEditLFM.Highlighter := SynHighlighterLFM2.TSynLFMSyn.Create(self); end; procedure TForm2.LeaveOnly(ASynEdit: TSynEdit); var i : integer; S : TSynEdit; begin for i := Pred(ComponentCount) downto 0 do begin if Components[i] is TSynEdit then begin S := TSynEdit(Components[i]); if S <> ASynEdit then FreeAndNil(s); end; end; PageControl1.ActivePage := TTabSheet(ASynEdit.Parent); end; procedure TForm2.SetHighlighter(ASynEdit: TSynEdit; HLClass: TSynCustomHighlighterClass); begin if Assigned(ASynEdit) then ASynEdit.Highlighter := HLClass.Create(self); end; end.
unit GraphicCopy; interface uses Editor; procedure CopyGraphicToClipboard( Editor : TveEditor ); implementation uses Registry, Globals, ClipbrdGraphic; procedure CopyGraphicToClipboard( Editor : TveEditor ); var RegIniFile : TRegIniFile; ArtMaker : TveClipboarder; PixelsPerCell : integer; RulerString : string; Ruler : TveRuler; begin // get Registry Info RegIniFile := GetRegIniFile; try PixelsPerCell := RegIniFile.ReadInteger( 'GraphicCopy', 'PixelsPerCell', 24 ); RulerString := RegIniFile.ReadString( 'GraphicCopy', 'Rulers', '' ); finally RegIniFile.Free; end; if RulerString = 'Number' then begin Ruler := ruNumber end else if RulerString = 'LetterNumber' then begin Ruler := ruLetterNumber end else begin Ruler := ruNone; end; // use ArtMaker to make graphic ArtMaker := TveClipboarder.Create; try ArtMaker.Editor := Editor; ArtMaker.Rulers := Ruler; ArtMaker.PixelsPerCell := PixelsPerCell; ArtMaker.CopyToClipBoard; finally ArtMaker.Free; end; end; end.
unit fMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.ListBox; type TForm2 = class(TForm) Label1: TLabel; Button1: TButton; ListBox1: TListBox; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation uses {$IFDEF MSWINDOWS} Winapi.ShlObj, ComObj, Winapi.Windows, FMX.Platform.Win, {$ELSE} Macapi.Foundation, Macapi.CocoaTypes, {$ENDIF} IOUtils; {$R *.fmx} procedure TForm2.Button1Click(Sender: TObject); function GetDocumentDirectory : string; {$IFDEF MSWINDOWS} var szBuffer: array [0..MAX_PATH] of Char; begin OleCheck (SHGetFolderPath ( FmxHandleToHWND(Handle), CSIDL_MYDOCUMENTS, 0, 0, szBuffer)); Result := szBuffer; {$ELSE} var FileMgr : NSFileManager; URL : NSURL; Error : NSError; begin FileMgr := TNSFileManager.Create; URL := FileMgr.URLForDirectory(NSDocumentDirectory, NSUserDomainMask, nil, false, @Error); if Assigned(Error) then raise Exception.Create(Error.localizedDescription.UTF8String); Result := URL.path.UTF8String; {$ENDIF} end; var DocumentsPath, Filename : String; begin DocumentsPath := GetDocumentDirectory; Label1.Text := DocumentsPath; for Filename in TDirectory.GetDirectories(DocumentsPath) do Listbox1.Items.Add(Format('Folder : %s', [Filename])); for Filename in TDirectory.GetFiles(DocumentsPath) do Listbox1.Items.Add(Format('File : %s', [Filename])); end; end.
unit udpsocket; {$mode delphi} interface uses Classes, SysUtils, And_jni, AndroidWidget; type TOnReceived = procedure(Sender: TObject; content: string; remoteIP: string; remotePort: integer; out listening: boolean) of Object; {Draft Component code by "Lazarus Android Module Wizard" [9/24/2016 22:25:03]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jControl template} jUDPSocket = class(jControl) private FOnReceived: TOnReceived; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; function jCreate(): jObject; procedure jFree(); procedure Send(_ip: string; _port: integer; _message: string); procedure Listen(_port: integer; _bufferLen: integer); procedure StopListening(); procedure SetTimeout(_miliTimeout: integer); procedure GenEvent_OnUDPSocketReceived(Obj: TObject; content: string; fromIP: string; fromPort: integer; out listening: boolean); published property OnReceived: TOnReceived read FOnReceived write FOnReceived; end; function jUDPSocket_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; procedure jUDPSocket_jFree(env: PJNIEnv; _judpsocket: JObject); procedure jUDPSocket_Send(env: PJNIEnv; _judpsocket: JObject; _ip: string; _port: integer; _message: string); procedure jUDPSocket_AsyncListen(env: PJNIEnv; _judpsocket: JObject; _port: integer; _bufferLen: integer); procedure jUDPSocket_AsyncListenStop(env: PJNIEnv; _judpsocket: JObject); procedure jUDPSocket_SetTimeout(env: PJNIEnv; _judpsocket: JObject; _miliTimeout: integer); implementation {--------- jUDPSocket --------------} constructor jUDPSocket.Create(AOwner: TComponent); begin inherited Create(AOwner); //your code here.... end; destructor jUDPSocket.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject:= nil; end; end; //you others free code here...' inherited Destroy; end; procedure jUDPSocket.Init; begin if FInitialized then Exit; inherited Init; //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject := jCreate(); if FjObject = nil then exit; FInitialized:= True; end; function jUDPSocket.jCreate(): jObject; begin Result:= jUDPSocket_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis); end; procedure jUDPSocket.jFree(); begin //in designing component state: set value here... if FInitialized then jUDPSocket_jFree(gApp.jni.jEnv, FjObject); end; procedure jUDPSocket.Send(_ip: string; _port: integer; _message: string); begin //in designing component state: set value here... if FInitialized then jUDPSocket_Send(gApp.jni.jEnv, FjObject, _ip ,_port ,_message); end; procedure jUDPSocket.Listen(_port: integer; _bufferLen: integer); begin //in designing component state: set value here... if FInitialized then jUDPSocket_AsyncListen(gApp.jni.jEnv, FjObject, _port ,_bufferLen); end; procedure jUDPSocket.StopListening(); begin //in designing component state: set value here... if FInitialized then jUDPSocket_AsyncListenStop(gApp.jni.jEnv, FjObject); end; procedure jUDPSocket.SetTimeout(_miliTimeout: integer); begin //in designing component state: set value here... if FInitialized then jUDPSocket_SetTimeout(gApp.jni.jEnv, FjObject, _miliTimeout); end; procedure jUDPSocket.GenEvent_OnUDPSocketReceived(Obj: TObject; content: string; fromIP: string; fromPort: integer; out listening: boolean); begin if assigned(FOnReceived) then FOnReceived(Obj, content, fromIP, fromPort, listening); end; {-------- jUDPSocket_JNI_Bridge ----------} function jUDPSocket_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].j:= _Self; jCls:= Get_gjClass(env); jMethod:= env^.GetMethodID(env, jCls, 'jUDPSocket_jCreate', '(J)Ljava/lang/Object;'); Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); end; (* //Please, you need insert: public java.lang.Object jUDPSocket_jCreate(long _Self) { return (java.lang.Object)(new jUDPSocket(this,_Self)); } //to end of "public class Controls" in "Controls.java" *) procedure jUDPSocket_jFree(env: PJNIEnv; _judpsocket: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _judpsocket); jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V'); env^.CallVoidMethod(env, _judpsocket, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jUDPSocket_Send(env: PJNIEnv; _judpsocket: JObject; _ip: string; _port: integer; _message: string); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_ip)); jParams[1].i:= _port; jParams[2].l:= env^.NewStringUTF(env, PChar(_message)); jCls:= env^.GetObjectClass(env, _judpsocket); jMethod:= env^.GetMethodID(env, jCls, 'Send', '(Ljava/lang/String;ILjava/lang/String;)V'); env^.CallVoidMethodA(env, _judpsocket, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env,jParams[2].l); env^.DeleteLocalRef(env, jCls); end; procedure jUDPSocket_AsyncListen(env: PJNIEnv; _judpsocket: JObject; _port: integer; _bufferLen: integer); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _port; jParams[1].i:= _bufferLen; jCls:= env^.GetObjectClass(env, _judpsocket); jMethod:= env^.GetMethodID(env, jCls, 'AsyncListen', '(II)V'); env^.CallVoidMethodA(env, _judpsocket, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jUDPSocket_AsyncListenStop(env: PJNIEnv; _judpsocket: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _judpsocket); jMethod:= env^.GetMethodID(env, jCls, 'StopAsyncListen', '()V'); env^.CallVoidMethod(env, _judpsocket, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jUDPSocket_SetTimeout(env: PJNIEnv; _judpsocket: JObject; _miliTimeout: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _miliTimeout; jCls:= env^.GetObjectClass(env, _judpsocket); jMethod:= env^.GetMethodID(env, jCls, 'SetTimeout', '(I)V'); env^.CallVoidMethodA(env, _judpsocket, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; end.
unit LUX.Raytrace.Geometry; interface //#################################################################### ■ uses LUX, LUX.D1, LUX.D2, LUX.D3, LUX.Graph.Tree, LUX.Raytrace; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 TRayGround = class; TRaySphere = class; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRayGround TRayGround = class( TRayGeometry ) private protected ///// アクセス function GetLocalAABB :TSingleArea3D; override; ///// メソッド procedure _RayCast( var LocalRay_:TRayRay; var LocalHit_:TRayHit; const Len_:TSingleArea ); override; public end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRaySky TRaySky = class( TRayGeometry ) private protected ///// メソッド procedure _RayCast( var LocalRay_:TRayRay; var LocalHit_:TRayHit; const Len_:TSingleArea ); override; public end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRaySphere TRaySphere = class( TRayGeometry ) private protected _Radius :Single; ///// アクセス function GetLocalAABB :TSingleArea3D; override; ///// メソッド procedure _RayCast( var LocalRay_:TRayRay; var LocalHit_:TRayHit; const Len_:TSingleArea ); override; public constructor Create; override; ///// プロパティ property Radius :Single read _Radius write _Radius; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRayImplicit TRayImplicit = class( TRayGeometry ) private protected _IteraN :Integer; ///// メソッド function DistanceFunc( const P_:TdSingle3D ) :TdSingle; virtual; abstract; procedure _RayCast( var LocalRay_:TRayRay; var LocalHit_:TRayHit; const Len_:TSingleArea ); override; public constructor Create; override; ///// プロパティ property IteraN :Integer read _IteraN write _IteraN; function pDistanceFunc(const P_:TdSingle3D ) :TdSingle; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRayTorus TRayTorus = class( TRayImplicit ) private protected _LingR :Single; _PipeR :Single; ///// アクセス function GetLocalAABB :TSingleArea3D; override; ///// メソッド function DistanceFunc( const P_:TdSingle3D ) :TdSingle; override; public constructor Create; override; ///// プロパティ property LingR :Single read _LingR write _LingR; property PipeR :Single read _PipeR write _PipeR; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ uses System.SysUtils, System.Math; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRayGround //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private /////////////////////////////////////////////////////////////////////// アクセス function TRayGround.GetLocalAABB :TSingleArea3D; begin Result := TSingleArea3D.PoMax; with Result do begin Min.Y := 0; Max.Y := 0; end; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド procedure TRayGround._RayCast( var LocalRay_:TRayRay; var LocalHit_:TRayHit; const Len_:TSingleArea ); var T :Single; begin if ( LocalRay_.Ray.Pos.Y > 0 ) and ( LocalRay_.Ray.Vec.Y < 0 ) then begin T := LocalRay_.Ray.Pos.Y / -LocalRay_.Ray.Vec.Y; if T > 0 then begin with LocalRay_ do begin Len := T; end; with LocalHit_ do begin Obj := Self; Nor := TSingle3D.Create( 0, 1, 0 ); end; end; end; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRaySky //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド procedure TRaySky._RayCast( var LocalRay_:TRayRay; var LocalHit_:TRayHit; const Len_:TSingleArea ); begin with LocalRay_ do begin Len := Single.MaxValue; end; with LocalHit_ do begin Obj := Self; Nor := -LocalRay_.Ray.Vec; Tex.X := ( Pi + ArcTan2( +LocalRay_.Ray.Vec.Z, -LocalRay_.Ray.Vec.X ) ) / Pi2; Tex.Y := ArcCos( LocalRay_.Ray.Vec.Y ) / Pi; end; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRaySphere //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private /////////////////////////////////////////////////////////////////////// アクセス function TRaySphere.GetLocalAABB :TSingleArea3D; begin Result := TSingleArea3D.Create( -_Radius, +_Radius ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド procedure TRaySphere._RayCast( var LocalRay_:TRayRay; var LocalHit_:TRayHit; const Len_:TSingleArea ); var B, C, D, D2, T0, T1 :Single; begin with LocalRay_.Ray do begin B := DotProduct( Pos, Vec ); C := Pos.Siz2 - Pow2( _Radius ); end; D := Pow2( B ) - C; if D > 0 then begin D2 := Roo2( D ); T1 := -B + D2; if T1 > 0 then begin T0 := -B - D2; with LocalRay_ do begin if T0 > 0 then Len := T0 else Len := T1; end; with LocalHit_ do begin Obj := Self; Nor := LocalHit_.Pos.Unitor; end; end; end; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TRaySphere.Create; begin inherited; _Radius := 1; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRayImplicit //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド procedure TRayImplicit._RayCast( var LocalRay_:TRayRay; var LocalHit_:TRayHit; const Len_:TSingleArea ); var P0, P1 :TSingle3D; D0, D1, T0, T1 :Single; S :TValueSign; N :Integer; begin with LocalRay_ do begin if Len_.Min > 0 then Len := Len_.Min; P0 := Tip; D0 := DistanceFunc( P0 ).o; S := Sign( D0 ); T0 := S * D0; Len := Len + T0; end; for N := 1 to _IteraN do begin with LocalRay_ do begin P1 := Tip; D1 := DistanceFunc( P1 ).o; T1 := S * D1; Len := Len + T1; if Len > Len_.Max then Exit; end; if ( T1 < T0 ) and ( T1 < _EPSILON_ ) then begin with LocalHit_ do begin Obj := Self; Nor := Nabla( DistanceFunc, P1 ).Unitor; end; with LocalRay_ do begin Len := Len - D1 / DotProduct( LocalHit_.Nor, Ray.Vec ); end; Exit; end; T0 := T1; end; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public function TRayImplicit.pDistanceFunc(const P_:TdSingle3D) :TdSingle; begin Result := DistanceFunc(P_); end; constructor TRayImplicit.Create; begin inherited; _IteraN := 1024; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRayTorus //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TRayTorus.GetLocalAABB :TSingleArea3D; var R :Single; begin R := _LingR + _PipeR; Result := TSingleArea3D.Create( -R, -R, -_PipeR, +R, +R, +_PipeR ); end; /////////////////////////////////////////////////////////////////////// メソッド function TRayTorus.DistanceFunc( const P_:TdSingle3D ) :TdSingle; var A, B :TdSingle2D; begin A.X := P_.X; A.Y := P_.Y; B.X := A.Size - _LingR; B.Y := P_.Z; Result := B.Size - _PipeR; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TRayTorus.Create; begin inherited; _LingR := 2; _PipeR := 1; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化 finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化 end. //######################################################################### ■
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.Messaging.Resource; interface uses System.SysUtils, System.Classes, WiRL.Core.JSON, WiRL.Core.Attributes, WiRL.Core.Auth.Context, WiRL.http.Accept.MediaType, WiRL.Messaging.Message, WiRL.Messaging.Queue; type TWiRLMessagingResourceForToken<T: TWiRLCustomMessage, constructor> = class private protected [Context] Token: TWiRLAuthContext; public [Path('listen'), GET] [Produces(TMediaType.APPLICATION_JSON)] procedure Subscribe; [Path('myqueue'), GET] [Produces(TMediaType.APPLICATION_JSON)] function Consume: TJSONObject; end; implementation uses System.Generics.Collections; { TWiRLMessagingResourceForToken<T> } function TWiRLMessagingResourceForToken<T>.Consume: TJSONObject; var LCount: Integer; LArrayMessaggi: TJSONArray; begin LCount := -1; LArrayMessaggi := TJSONArray.Create; try TWiRLMessagingQueueForToken.Use<T>(Token, procedure (AQueue: TQueue<T>) var LMessage: T; begin LCount := AQueue.Count; while AQueue.Count > 0 do begin LMessage := AQueue.Dequeue; try LArrayMessaggi.Add(LMessage.ToJSON); finally LMessage.Free; end; end; end ); Result := TJSONObject.Create; try Result.AddPair('Count', TJSONNumber.Create(LCount)); Result.AddPair('Messages', LArrayMessaggi); except Result.Free; raise; end; except LArrayMessaggi.Free; raise; end; end; procedure TWiRLMessagingResourceForToken<T>.Subscribe; begin TWiRLMessagingQueueForToken.Create<T>(Token); end; end.
{******************************************************************************* Author(s): Henri Gourvest <hgourvest@progdigy.com> Olivier Guilbaud <oguilb@free.fr> The Original Code is the UIB code (version 2.1) The Initial Developer of the Original Code is Henri Gourvest <hgourvest@progdigy.com>. Portions created by the Initial Developer are Copyright (C) by the Initial Developer. All Rights Reserved. Description: ALFBX (Alcinoe FireBird Express) does for the Firebird API what Delphi does for the WINDOWS API! Create high performance client/server applications based on FireBird without the BDE or ODBC. Link : https://uib.svn.sourceforge.net/svnroot/uib (current code is from the trunk rev 382) http://www.progdigy.com/modules.php?name=UIB *******************************************************************************} unit Alcinoe.FBX.Consts; interface const cALFBXBreakLine = #13; cALFBXNewLine = #13#10; cALFBXTrue = 'True'; cALFBXFalse = 'False'; // UIB Errors cALFBX_INVALIDEIBVERSION = 'Incorrect Database Server version, check compiler options.'; cALFBX_CANTLOADLIB = 'Can''t load library: %s.'; cALFBX_DBHANDLEALREADYSET = 'Database handle already assigned, first disconnect database.'; cALFBX_TRANSACTIONNOTDEF = 'Transaction not assigned.'; cALFBX_DATABASENOTDEF = 'Database not assigned.'; cALFBX_QUERYNOTOPEN = 'Query not open.'; cALFBX_CASTERROR = 'Cast error.'; cALFBX_UNEXPECTEDERROR = 'Unexpected error.'; cALFBX_FIELDNUMNOTFOUND = 'Field num: %d not found.'; cALFBX_FIELDSTRNOTFOUND = 'Field "%s" not found.'; cALFBX_PARAMSTRNOTFOUND = 'Parameter "%s" not found.'; cALFBX_BLOBFIELDNOTFOUND = 'Blob field num: %d not found.'; cALFBX_FETCHBLOBNOTSET = 'FetchBlob property must be set to use this method.'; cALFBX_INDEXERROR = 'Index out of bound (%d)'; cALFBX_SIZENAME = 'Size name too big (%s)'; cALFBX_MUSTBEPREPARED = 'The query must be prepared first.'; cALFBX_MUSTBEOPEN = 'The query must be opened first.'; cALFBX_EXPLICITTRANS = 'Transaction must be started explicitly.'; cALFBX_EXCEPTIONNOTFOUND = 'Exception name %s, not found.'; cALFBX_EXPTIONREGISTERED = 'Exception: %d already registered'; cALFBX_NOAUTOSTOP = 'Transaction must be closed explicitly.'; cALFBX_NOGENERATOR = 'Generator %s not found.'; cALFBX_NOFIELD = 'Field not found.'; cALFBX_TABLESTRNOTFOUND = 'Table "%s" not found.'; cALFBX_DOMAINSTRNOTFOUND = 'Domain %s not found.'; cALFBX_PROCSTRNOTFOUND = 'Procedure %s not found.'; cALFBX_CACHEDFETCHNOTSET = 'CachedFetch property not set to True.'; cALFBX_PARSESQLDIALECT = 'Parse error: SET SQL DIALECT'; cALFBX_PARSESETNAMES = 'Parse error: SET NAMES'; cALFBX_CHARSETNOTFOUND = 'CharacterSet %s not found.'; cALFBX_UNEXPECTEDCASTERROR = 'Unexpected cast error.'; cALFBX_INVALIDUSERNAME = 'Invalid user name : "%s".'; cALFBX_SERVICESPARSING = 'Error while parsing Services API output.'; cALFBX_NOT_NULLABLE = 'Field "%s" is not nullable.'; implementation end.
unit WiRL.Wizards; interface uses ToolsAPI; resourcestring SName = 'WiRL Server Application Wizard'; SComment = 'Creates a new WiRL Server Application'; SAuthor = 'WiRL Development Team'; SGalleryCategory = 'WiRL Library'; SIDString = 'WiRL.Wizards'; type TWiRLServeProjectWizard = class(TNotifierObject, IOTAWizard, IOTARepositoryWizard, IOTARepositoryWizard60, IOTARepositoryWizard80, IOTAProjectWizard, IOTAProjectWizard100) public constructor Create; // IOTAWizard procedure Execute; procedure AfterSave; procedure BeforeSave; procedure Destroyed; procedure Modified; function GetIDString: string; function GetName: string; function GetState: TWizardState; // IOTARepositoryWizard function GetAuthor: string; function GetComment: string; function GetGlyph: Cardinal; function GetPage: string; // IOTARepositoryWizard60 function GetDesigner: string; // IOTARepositoryWizard80 function GetGalleryCategory: IOTAGalleryCategory; function GetPersonality: string; // IOTAProjectWizard100 function IsVisible(Project: IOTAProject): Boolean; end; procedure Register; implementation uses WiRL.Wizards.ProjectCreator; { TWiRLServeProjectWizard } constructor TWiRLServeProjectWizard.Create; var LCategoryServices: IOTAGalleryCategoryManager; begin inherited Create; LCategoryServices := BorlandIDEServices as IOTAGalleryCategoryManager; LCategoryServices.AddCategory(LCategoryServices.FindCategory(sCategoryRoot), SIDString, SGalleryCategory); end; {$REGION 'IOTAWizard'} procedure TWiRLServeProjectWizard.Execute; begin (BorlandIDEServices as IOTAModuleServices).CreateModule(TWiRLServerProjectCreator.Create); end; function TWiRLServeProjectWizard.GetIDString: string; begin Result := SIDString + '.Server'; end; function TWiRLServeProjectWizard.GetName: string; begin Result := SName; end; function TWiRLServeProjectWizard.GetState: TWizardState; begin Result := [wsEnabled]; end; procedure TWiRLServeProjectWizard.AfterSave; begin end; procedure TWiRLServeProjectWizard.BeforeSave; begin end; procedure TWiRLServeProjectWizard.Destroyed; begin end; procedure TWiRLServeProjectWizard.Modified; begin end; {$ENDREGION} {$REGION 'IOTARepositoryWizard'} function TWiRLServeProjectWizard.GetAuthor: string; begin Result := SAuthor; end; function TWiRLServeProjectWizard.GetComment: string; begin Result := SComment; end; function TWiRLServeProjectWizard.GetGlyph: Cardinal; begin { TODO : function TWiRLServeProjectWizard.GetGlyph: Cardinal; } Result := 0; end; function TWiRLServeProjectWizard.GetPage: string; begin Result := SGalleryCategory; end; {$ENDREGION} {$REGION 'IOTARepositoryWizard60'} function TWiRLServeProjectWizard.GetDesigner: string; begin Result := dAny; end; {$ENDREGION} {$REGION 'IOTARepositoryWizard80'} function TWiRLServeProjectWizard.GetGalleryCategory: IOTAGalleryCategory; begin Result := (BorlandIDEServices as IOTAGalleryCategoryManager).FindCategory(SIDString); end; function TWiRLServeProjectWizard.GetPersonality: string; begin Result := sDelphiPersonality; end; {$ENDREGION} {$REGION 'IOTAProjectWizard100'} function TWiRLServeProjectWizard.IsVisible(Project: IOTAProject): Boolean; begin Result := True; end; {$ENDREGION} procedure Register; begin RegisterPackageWizard(TWiRLServeProjectWizard.Create); end; end.
unit U_Exemplo04; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TF_Exemplo04 = class(TForm) Panel1: TPanel; MDocumento: TMemo; btnGerarDocto: TButton; procedure btnGerarDoctoClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var F_Exemplo04: TF_Exemplo04; implementation uses U_GeradorDocto, U_Linhas; {$R *.dfm} procedure TF_Exemplo04.btnGerarDoctoClick(Sender: TObject); var oGeradorDocto : TGeradorDocto; oLinha000 : TLinha000; oLinha001 : TLinha001; oLinha002 : TLinha002; oLinha003 : TLinha003; oLinha999 : TLinha999; nCont : Integer; begin MDocumento.Lines.Clear; //Cria o Documento oGeradorDocto := TGeradorDocto.Create(); try //Cria e Alimenta as Linhas do Documento oLinha000 := TLinha000.Create; oLinha000.DataGeracao := Now; oGeradorDocto.Add(oLinha000); oLinha001 := TLinha001.Create; oLinha001.NomeContador := 'Contador da Conference'; oLinha001.CRCContador := '1234567890'; oGeradorDocto.Add(oLinha001); oLinha002 := TLinha002.Create; oLinha002.NomeEmpresa := 'Minha Empresa de Testes'; oLinha002.CNPJ := '99999999999999'; oGeradorDocto.Add(oLinha002); for nCont := 1 to 5 do begin oLinha003 := TLinha003.Create; oLinha003.DataVenda := Now; oLinha003.NomeCliente := Format('Cliente %d', [nCont]); oLinha003.ValorVenda := nCont * 1.2; oGeradorDocto.Add(oLinha003); end; oLinha999 := TLinha999.Create; oGeradorDocto.Add(oLinha999); //Gera o Documento no Memo MDocumento.Lines.Text := oGeradorDocto.GerarDocumento; finally oGeradorDocto.Free; end; end; end.
unit PluginManager; interface uses Vcl.Forms, Vcl.Menus, Vcl.Controls, Vcl.StdCtrls, System.Classes, System.SysUtils, Winapi.Windows, System.Types, System.IOUtils, Generics.Collections, PluginUtils, PluginIntf, PluginFactory; type TPluginInfo = procedure(const APluginInfo: TVersionData) of object; TPluginManager = class strict private constructor Create; private FPluginInfo: TPluginInfo; FNamePathMap: TNamePathMap; FUnManagedPluginFactory: TUnManagedPluginFactory; class var FInstance: TPluginManager; published property OnPluginInfo: TPluginInfo read FPluginInfo write FPluginInfo; property UnManagedPluginFactory: TUnManagedPluginFactory read FUnManagedPluginFactory; public procedure ReadPlugins(const PluginsPath: string); class function GetInstance: TPluginManager; destructor Destroy; override; end; TNotifyEventWrapper = class(TComponent) private FProc: TProc<TObject>; public constructor Create(Owner: TComponent; Proc: TProc<TObject>); published procedure Event(Sender: TObject); end; TControlHelper = class Helper for TControl procedure AddOnClickHandler(AProc: TProc<TObject>); end; function CreateNotifyEvent(Owner: TComponent; Proc: TProc<TObject>) : TNotifyEvent; implementation { TPluginManager } constructor TPluginManager.Create; begin FNamePathMap := TNamePathMap.Create; FUnManagedPluginFactory := TUnManagedPluginFactory.Create; FUnManagedPluginFactory.NamePathMap := FNamePathMap; end; class function TPluginManager.GetInstance: TPluginManager; begin if FInstance = nil then FInstance := TPluginManager.Create; result := FInstance; end; procedure TPluginManager.ReadPlugins(const PluginsPath: string); var PluginFilePath: string; PluginFiles: TStringDynArray; AFileVersionData: TVersionData; begin PluginFiles := TDirectory.GetFiles(PluginsPath, '*.dll'); for PluginFilePath in PluginFiles do begin AFileVersionData := Default (TVersionData); AFileVersionData := TFileVersionData.GetFileVersionData(PluginFilePath); FNamePathMap.Add(AFileVersionData.OriginalFileName, PluginFilePath); if Assigned(FPluginInfo) then FPluginInfo(AFileVersionData); end; end; destructor TPluginManager.Destroy; begin inherited; FNamePathMap.Free; FUnManagedPluginFactory.Free; end; constructor TNotifyEventWrapper.Create(Owner: TComponent; Proc: TProc<TObject>); begin inherited Create(Owner); FProc := Proc; end; procedure TNotifyEventWrapper.Event(Sender: TObject); begin FProc(Sender); end; function CreateNotifyEvent(Owner: TComponent; Proc: TProc<TObject>) : TNotifyEvent; begin result := TNotifyEventWrapper.Create(Owner, Proc).Event; end; { TControlHelper } procedure TControlHelper.AddOnClickHandler(AProc: TProc<TObject>); begin OnClick := CreateNotifyEvent(Self, AProc); end; end.
unit FormMainUnit; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StdCtrls, Menus, ExtCtrls, DB; const StrAppTitle: string = 'Marine Adventures Order Entry'; type TDateOrder = (doMDY, doDMY, doYMD); TMainForm = class(TForm) MainPanel: TPanel; PrinterSetup: TPrinterSetupDialog; OrderBtn: TSpeedButton; BrowseBtn: TSpeedButton; PartsBtn: TSpeedButton; CloseBtn: TSpeedButton; HelpBtn: TSpeedButton; MainMenu: TMainMenu; FileMenu: TMenuItem; FilePrinterSetup: TMenuItem; FileExit: TMenuItem; FileNewOrder: TMenuItem; FilePrintReport: TMenuItem; PrintCustList: TMenuItem; PrintOrders: TMenuItem; PrintInvoice: TMenuItem; ViewMenu: TMenuItem; ViewOrders: TMenuItem; ViewPartsInventory: TMenuItem; ViewStayOnTop: TMenuItem; HelpMenu: TMenuItem; HelpAbout: TMenuItem; HelpContents: TMenuItem; PMStyles: TPopupMenu; Style11: TMenuItem; Style21: TMenuItem; Style31: TMenuItem; Button1: TButton; procedure BrowseCustOrd(Sender: TObject); procedure CloseApp(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BrowseParts(Sender: TObject); procedure ToggleStayonTop(Sender: TObject); procedure NewOrder(Sender: TObject); procedure HelpBtnClick(Sender: TObject); procedure PrinterSetupClick(Sender: TObject); procedure AboutClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private procedure UpdateAppCaption; procedure StyleClick(Sender: TObject); end; var MainForm: TMainForm; implementation uses WinHelpViewer, DataMod, {Data Module} BrCstOrd, {The Browse Orders by Customer form} BrParts, {The Browse Parts form} EdOrders, {The Edit Orders form} QryCust, {The Specify Date Range form} // PickRep, {The Report Selection form} About, {The About dialog box} IniFiles, {Delphi Unit for INI file support} PickInvc, Vcl.Themes; { The invoice number selection dialog } {$R *.dfm} function GetDateOrder(const DateFormat: string): TDateOrder; var I: Integer; begin Result := doMDY; I := 1; while I <= Length(DateFormat) do begin case Chr(Ord(DateFormat[I]) and $DF) of 'Y': Result := doYMD; 'M': Result := doMDY; 'D': Result := doDMY; else Inc(I); Continue; end; Exit; end; Result := doMDY; end; procedure TMainForm.BrowseCustOrd(Sender: TObject); begin case GetDateOrder(FormatSettings.ShortDateFormat) of doYMD: FormatSettings.ShortDateFormat := 'yy/mm/dd'; doMDY: FormatSettings.ShortDateFormat := 'mm/dd/yy'; doDMY: FormatSettings.ShortDateFormat := 'dd/mm/yy'; end; BrCustOrdForm.Show; end; procedure TMainForm.CloseApp(Sender: TObject); begin Close; end; procedure TMainForm.FormCreate(Sender: TObject); var Style: String; Item: TMenuItem; begin ClientWidth := CloseBtn.Left + CloseBtn.Width + 1; ClientHeight := CloseBtn.Top + CloseBtn.Height; MainPanel.Align := alClient; { position the form at the top of display } Left := 0; Top := 0; PMStyles.Items.Clear; for Style in TStyleManager.StyleNames do begin Item := TMenuItem.Create(Self); Item.Caption := Style; Item.OnClick := StyleClick; PMStyles.Items.Add(Item); end; UpdateAppCaption; end; procedure TMainForm.BrowseParts(Sender: TObject); begin BrPartsForm.Show; end; procedure TMainForm.ToggleStayonTop(Sender: TObject); begin with Sender as TMenuItem do begin Checked := not Checked; if Checked then MainForm.FormStyle := fsStayOnTop else MainForm.FormStyle := fsNormal; end; end; procedure TMainForm.UpdateAppCaption; begin self.Caption := StrAppTitle + ' (' + TStyleManager.ActiveStyle.Name + ')'; end; procedure TMainForm.NewOrder(Sender: TObject); begin EdOrderForm.Enter; end; procedure TMainForm.HelpBtnClick(Sender: TObject); begin Application.HelpCommand(HELP_CONTENTS, 0); end; procedure TMainForm.PrinterSetupClick(Sender: TObject); begin PrinterSetup.Execute; end; procedure TMainForm.StyleClick(Sender: TObject); var StyleName: String; begin StyleName := StringReplace(TMenuItem(Sender).Caption, '&', '', [rfReplaceAll, rfIgnoreCase]); TStyleManager.SetStyle(StyleName); UpdateAppCaption; end; procedure TMainForm.AboutClick(Sender: TObject); begin AboutBox.ShowModal; end; procedure TMainForm.FormDestroy(Sender: TObject); begin Application.HelpCommand(HELP_QUIT, 0); end; end.
unit ManagerPattern; {********************************************** Kingstar Delphi Library Copyright (C) Kingstar Corporation <Unit>ManagerPattern <What>示例Manager设计模式(Design Pattern) <How To>复制该文件,并重命名文件; 将TManager和TManagedItem替换为需要的新类名; 将Manager 替换为需要的变量名. <Written By> Huang YanLai <History> **********************************************} interface uses SysUtils, Classes; type // forward declare TManager = class; TManagedItem = class; TManager = class(TObject) private FItems: TList; function GetItems(index: Integer): TManagedItem; protected public constructor Create; Destructor Destroy;override; class procedure AddManagedItem(Item:TManagedItem); class procedure RemoveManagedItem(Item:TManagedItem); property Items[index : Integer] : TManagedItem read GetItems; published end; TManagedItem = class(TComponent) private protected public constructor Create(AOwner : TComponent); override; Destructor Destroy;override; //procedure Changed(Target:TObject); end; var Manager : TManager; implementation { TManager } constructor TManager.Create; begin FItems := TList.create; end; destructor TManager.Destroy; begin FreeAndNil(FItems); inherited; end; class procedure TManager.AddManagedItem(Item: TManagedItem); begin if Manager<>nil then if Manager.FItems<>nil then Manager.FItems.Add(Item); end; class procedure TManager.RemoveManagedItem(Item: TManagedItem); begin if Manager<>nil then if Manager.FItems<>nil then Manager.FItems.Remove(Item); end; function TManager.GetItems(index: Integer): TManagedItem; begin Result := TManagedItem(FItems[index]); end; { TManagedItem } constructor TManagedItem.Create(AOwner: TComponent); begin inherited; TManager.AddManagedItem(self); end; destructor TManagedItem.Destroy; begin TManager.RemoveManagedItem(self); inherited; end; initialization Manager := TManager.create; finalization FreeAndNil(Manager); end.
unit uRestClienteKorthWS; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IPPeerClient, REST.Types, REST.Client, REST.Authenticator.Basic, Data.Bind.Components, Data.Bind.ObjectScope; type TformRestClienteWSKorth = class(TForm) Label1: TLabel; Label2: TLabel; editUsuario: TEdit; Label3: TLabel; editSenha: TEdit; butnGet: TButton; RESTClient1: TRESTClient; RESTRequest1: TRESTRequest; RESTResponse1: TRESTResponse; HTTPBasicAuthenticator1: THTTPBasicAuthenticator; memoRetorno: TMemo; ComboBox1: TComboBox; Label4: TLabel; Label5: TLabel; editData1: TEdit; editData2: TEdit; Memo1: TMemo; procedure butnGetClick(Sender: TObject); procedure RESTRequest1AfterExecute(Sender: TCustomRESTRequest); procedure ComboBox1Change(Sender: TObject); private { Private declarations } procedure ResetRESTComponentsToDefaults; public { Public declarations } end; var formRestClienteWSKorth: TformRestClienteWSKorth; implementation {$R *.dfm} procedure TformRestClienteWSKorth.butnGetClick(Sender: TObject); begin memoRetorno.Lines.Clear; ResetRESTComponentsToDefaults; HTTPBasicAuthenticator1.Username := editUsuario.Text; HTTPBasicAuthenticator1.Password := editSenha.Text; RESTClient1.BaseURL := ComboBox1.Text; RESTClient1.Accept := 'application/json'; RESTClient1.ContentType := 'application/json'; RESTClient1.Authenticator := HTTPBasicAuthenticator1; case ComboBox1.ItemIndex of 1 : begin RESTRequest1.Params.AddItem('pdata1',editData1.Text,TRESTRequestParameterKind.pkHTTPHEADER); RESTRequest1.Params.AddItem('pdata2',editData2.Text,TRESTRequestParameterKind.pkHTTPHEADER); end; 2 : begin RESTRequest1.Params.AddItem('pdata1',editData1.Text,TRESTRequestParameterKind.pkGETorPOST); RESTRequest1.Params.AddItem('pdata2',editData2.Text,TRESTRequestParameterKind.pkGETorPOST); end; end; Screen.Cursor := crHourGlass; Application.ProcessMessages; // REST.Types RESTRequest1.Method := TRESTRequestMethod.rmGET; RESTRequest1.Execute; end; procedure TformRestClienteWSKorth.ComboBox1Change(Sender: TObject); begin editData1.Enabled := ComboBox1.ItemIndex > 0; editData2.Enabled := ComboBox1.ItemIndex > 0; end; procedure TformRestClienteWSKorth.ResetRESTComponentsToDefaults; begin RESTRequest1.ResetToDefaults; RESTClient1.ResetToDefaults; RESTResponse1.ResetToDefaults; end; procedure TformRestClienteWSKorth.RESTRequest1AfterExecute(Sender: TCustomRESTRequest); begin memoRetorno.Text := RESTResponse1.Content; // Memo1.Text := RESTResponse1.Headers.Text; Screen.Cursor := crDefault; Application.ProcessMessages; end; end.
program newtstub; uses sysutils, newt; { Процедура вывода заставки программы } procedure UI_ShowSplashScreen; var form : newtComponent; begin newtOpenWindow(10, 5, 41, 10, 'Контрольная работа'); form := newtForm(nil, nil, 0); newtFormAddComponents( form, newtLabel(1, 1, 'Дисциплина: Информатика (часть 3)'), newtLabel(1, 2, 'Студент: Коробейников П.А.'), newtLabel(1, 3, 'Группа: ВАИ-1-09'), newtLabel(1, 4, 'Тема: Создание БД Записная книжка'), newtButton(12, 6, 'Начать работу'), nil ); newtRunForm(form); newtFormDestroy(form); newtPopWindow; end; { Процедура вывода главного меню } procedure UI_ShowMainMenu; const ACTION_CREATE = 0; ACTION_CHOOSE = 1; ACTION_WORK = 2; ACTION_SEARCH = 3; ACTION_EXIT = 4; var form, listBox : newtComponent; p : ^pchar; s : pchar; i : integer; choices : array[ACTION_CREATE..ACTION_EXIT] of pchar; begin choices[ACTION_CREATE] := 'Создать записную книжку'; choices[ACTION_CHOOSE] := 'Выбрать текущую записную книжку'; choices[ACTION_WORK] := 'Работа с записной книжкой'; choices[ACTION_SEARCH] := 'Поиск по запросу'; choices[ACTION_EXIT] := 'Выход'; newtOpenWindow(10, 5, 41, 7, 'Главное меню'); listBox := newtListbox(1, 1, 5, NEWT_FLAG_RETURNEXIT or NEWT_FLAG_SCROLL); newtListboxSetWidth(listBox, 39); for i := ACTION_CREATE to ACTION_EXIT do newtListBoxAppendEntry(listBox, choices[i], @choices[i]); form := newtForm(nil, nil, NEWT_FLAG_RETURNEXIT); newtFormAddComponent(form, listBox); newtRunForm(form); newtFormDestroy(form); p := newtListboxGetCurrent(listBox); newtFinished; writeln(p^); s:=p^; for i := ACTION_CREATE to ACTION_EXIT do if p^ = choices[i] then break; case i of ACTION_CREATE: writeln('0'); ACTION_WORK: writeln('2'); end; halt; newtPopWindow; end; { Процедура вывода формы названия книги } procedure UI_ShowAddressBookNameForm; var form : newtComponent; begin newtOpenWindow(10, 5, 41, 7, 'Название адресной книги'); form := newtForm(nil, nil, 0); newtFormAddComponents( form, newtLabel(1, 1, 'Название: '), newtEntry(11, 1, nil, 29, nil, 0), newtButton(10, 3, 'ОК'), newtButton(20, 3, 'Отмена'), nil ); newtRunForm(form); newtFormDestroy(form); newtPopWindow; end; { Процедура вывода формы записи адресной книги } procedure UI_ShowAddressBookEntryForm; var form : newtComponent; begin newtOpenWindow(10, 5, 60, 12, 'Внести запись в книжку'); form := newtForm(nil, nil, 0); newtFormAddComponents( form, newtLabel(1, 1, 'Имя: '), newtEntry(18, 1, nil, 41, nil, 0), newtLabel(1, 2, 'Телефон: '), newtEntry(18, 2, nil, 41, nil, 0), newtLabel(1, 3, 'Сотовый телефон: '), newtEntry(18, 3, nil, 41, nil, 0), newtLabel(1, 4, 'Дата рождения: '), newtEntry(18, 4, nil, 41, nil, 0), newtLabel(1, 5, 'Email: '), newtEntry(18, 5, nil, 41, nil, 0), newtLabel(1, 6, 'ICQ: '), newtEntry(18, 6, nil, 41, nil, 0), newtButton(19, 8, 'ОК'), newtButton(29, 8, 'Отмена'), nil ); newtRunForm(form); newtFormDestroy(form); newtPopWindow; end; { Процедура вывода списка записей адресной книги } procedure UI_ShowAddressBookListForm; var form : newtComponent; begin { Implement me } end; { Процедура вывода окна сообщения } procedure UI_ShowMessageBox(title, message : pChar); var form : newtComponent; begin newtOpenWindow(10, 5, 40, 7, title); form := newtForm(nil, nil, 0); newtFormAddComponents( form, newtLabel(1, 1, message), newtButton(18, 3, 'ОК'), nil ); newtRunForm(form); newtFormDestroy(form); newtPopWindow; end; begin newtInit; newtCls; UI_ShowSplashScreen; UI_ShowMainMenu; UI_ShowAddressBookNameForm; UI_ShowAddressBookEntryForm; UI_ShowMessageBox('MessageBox Title', 'MessageBox Message!'); { Too long strings are hiccups: UI_ShowMessageBox('MessageBox Title', 'This message is too long! This message is too long! This message is too long! This message is too long! This message is too long! This message is too long!'); } newtFinished; end.
unit UCC_MPTool_OnLineOrderUtil; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,MSXML6_TLB, WinHTTP_TLB, uWindowsInfo, XMLDoc, XMLIntf,UUtil1; const httpRespOK = 200; //Status code from HTTP REST elRoot = 'OrderManagementServices'; ndAuthentication = 'AUTHENTICATION'; attrUserName = 'username'; attrPassword = 'password'; ndParameters = 'PARAMETERS'; ndParameter = 'PARAMETER'; attrParamName = 'name'; ndDocument = 'DOCUMENT'; //Get On-line Order List URL AWOrderListPHP = 'https://webservices.appraisalworld.com/ws/OrderManagementServices/get_order_list_cf.php'; AWOrderListParam = '?Username=%s&Password=%s'; //Get On-line Order Detail URL AWOrderDetailPHP = 'https://webservices.appraisalworld.com/ws/OrderManagementServices/get_order_cf.php'; AWOrderDetailParam = '?Username=%s&Password=%s&OrderId=%s'; //Grid column name _index = 1; _Type = 2; _OrderRef = 3; _Status = 4; _Address = 5; _AMC = 6; _ReportType = 7; _OrderDate = 8; _DueDate = 9; _RequestedBy = 10; _AmtInvoice = 11; _AmtPaid = 12; _OrderID = 13; //Status constants stNew = 0; stInProgress = 1; stDelayed = 2; stCompleted = 3; //Order Status oNew = 0; oUpdate = 1; oView = 2; oDelete = 3; oUnknown = 4; procedure CreateNodeAttribute(xmlDOC: IXMLDOMDocument3; node: IXMLDOMNode; attrName: String; attrValue: String); procedure CreateChildNode(xmlDoc: IXMLDOMDocument3;parent: IXMLDOMNode; nodeName: String; nodeText: String); function CreateXmlDomDocument(xml: String; var errMsg: String): IXMLDOMDocument3; function convertStrToDateStr(aStrDate: String): String; //Pam 07/01/2015 Return U.S. Date format when we have European DateTime Format String implementation procedure CreateNodeAttribute(xmlDOC: IXMLDOMDocument3; node: IXMLDOMNode; attrName: String; attrValue: String); var attr: IXMLDOMAttribute; begin attr := xmlDoc.createAttribute(attrName); attr.value := attrValue; node.attributes.setNamedItem(attr); end; procedure CreateChildNode(xmlDoc: IXMLDOMDocument3;parent: IXMLDOMNode; nodeName: String; nodeText: String); var childNode: IXMLDOMNode; begin childNode := xmlDoc.CreateNode(NODE_ELEMENT,nodeName,''); childNode.appendChild(xmlDoc.CreateTextNode(nodeText)); parent.appendChild(childNode); end; function CreateXmlDomDocument(xml: String; var errMsg: String): IXMLDOMDocument3; var xmlDoc: IXMLDOMDocument3; parseErr: IXMLDOMParseError; begin errMsg := ''; result := nil; xmlDoc := CoDomDocument60.Create; xmlDoc.setProperty('SelectionLanguage','XPath'); try xmlDoc.loadXML(xml); except on e: Exception do begin errMsg := e.Message; exit; end; end; parseErr := xmlDoc.parseError; if parseErr.errorCode <> 0 then begin errMsg := parseErr.reason; exit; end; result := xmlDoc; end; function convertStrToDateStr(aStrDate: String): String; //Pam 07/01/2015 Return U.S. Date format when we have European DateTime Format String var aDate: TDateTime; begin result := ''; if aStrDate <> '' then begin //Use VarToDateTime to convert European Date or any date time string to U.S DateTime string //This will work when we have yyyy-mm-dd hh:mm:ss aDate := VarToDateTime(aStrDate); if aDate > 0 then result := FormatDateTime('mm/dd/yyyy', aDate); end; end; end.
(* Copyright (c) 2012-2014, 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.Interception.HandlerPipeline; interface uses DSharp.Interception, Generics.Collections; type THandlerPipeline = class private FHandlers: TList<ICallHandler>; function GetCount: Integer; public constructor Create; overload; constructor Create(const Handlers: array of ICallHandler); overload; destructor Destroy; override; function Invoke(Input: IMethodInvocation; Target: TInvokeHandlerDelegate): IMethodReturn; property Count: Integer read GetCount; end; implementation { THandlerPipeline } constructor THandlerPipeline.Create; begin FHandlers := TList<ICallHandler>.Create; end; constructor THandlerPipeline.Create(const Handlers: array of ICallHandler); begin FHandlers := TList<ICallHandler>.Create; FHandlers.AddRange(Handlers); end; destructor THandlerPipeline.Destroy; begin FHandlers.Free; inherited; end; function THandlerPipeline.GetCount: Integer; begin Result := FHandlers.Count; end; function THandlerPipeline.Invoke(Input: IMethodInvocation; Target: TInvokeHandlerDelegate): IMethodReturn; var handlerIndex: Integer; begin if FHandlers.Count = 0 then begin Result := Target(input, nil); end else begin handlerIndex := 0; Result := FHandlers[0].Invoke(input, function: TInvokeHandlerDelegate begin Inc(handlerIndex); if handlerIndex < FHandlers.Count then begin Result := TInvokeHandlerDelegate(FHandlers[handlerIndex]); end else begin Result := Target; end; end); end; end; end.
unit AbstractApplication; interface uses Application, ApplicationServiceRegistries, ClientAccount, SysUtils, Classes; type TAbstractApplication = class abstract (TInterfacedObject, IApplication) public function GetApplicationServiceRegistries: IApplicationServiceRegistries; virtual; abstract; procedure SetApplicationServiceRegistries( Value: IApplicationServiceRegistries ); virtual; abstract; function GetClientAccount: TClientAccount; virtual; abstract; procedure SetClientAccount(ClientAccount: TClientAccount); virtual; abstract; property ServiceRegistries: IApplicationServiceRegistries read GetApplicationServiceRegistries write SetApplicationServiceRegistries; property ClientAccount: TClientAccount read GetClientAccount write SetClientAccount; end; implementation end.
(* 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.Core.RegularExpressions; interface uses {$IF COMPILERVERSION < 22} PerlRegEx; // download from http://www.regular-expressions.info/download/TPerlRegEx.zip {$ELSEIF COMPILERVERSION > 22} System.RegularExpressions; {$ELSE} RegularExpressions; {$IFEND} type {$IF COMPILERVERSION < 22} TRegEx = record public class function IsMatch(const Input, Pattern: string): Boolean; static; class function Replace(const Input, Pattern, Replacement: string): string; static; end; {$ELSEIF COMPILERVERSION > 22} TRegEx = System.RegularExpressions.TRegEx; {$ELSE} TRegEx = RegularExpressions.TRegEx; {$IFEND} implementation { TRegEx } {$IF COMPILERVERSION < 22} class function TRegEx.IsMatch(const Input, Pattern: string): Boolean; var LRegEx: TPerlRegEx; begin LRegEx := TPerlRegEx.Create(); try LRegEx.RegEx := UTF8Encode(Pattern); LRegEx.Subject := UTF8Encode(Input); Result := LRegEx.Match(); finally LRegEx.Free(); end; end; class function TRegEx.Replace(const Input, Pattern, Replacement: string): string; var LRegEx: TPerlRegEx; begin LRegEx := TPerlRegEx.Create(); try LRegEx.RegEx := UTF8Encode(Pattern); LRegEx.Subject := UTF8Encode(Input); LRegEx.Replacement := UTF8Encode(Replacement); LRegEx.ReplaceAll(); Result := UTF8ToString(LRegEx.Subject); finally LRegEx.Free(); end; end; {$IFEND} end.
unit ViewModel.Main.Types; interface uses FMX.Graphics, System.Classes, ViewModel.Types; type IViewModelMain = interface ['{5F9C41E0-ED9E-4C80-9166-503D0315A615}'] function getCustomerList: TStringList; function getComponentsRecord: TComponentsRecord; procedure getCustomer (const aID: Integer; var aCustomer: TCustomerTransientRecord); procedure deleteCustomer (const aID: Integer); property CustomerList: TStringList read getCustomerList; property ComponentsRecord: TComponentsRecord read getComponentsRecord; end; const NoCustomers = 'There are no customers'; NumOfCustomers ='%s customers'; implementation end.
(* Copyright (c) 2011-2012, Stefan Glienke All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of this library nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) unit DSharp.Core.Cache; interface uses Classes; type ICache<T: TPersistent, constructor> = interface function GetInstance: T; procedure SetInstance(const Value: T); procedure Restore; procedure Store; property Instance: T read GetInstance write SetInstance; end; TCache<T: TPersistent, constructor> = class(TInterfacedObject, ICache<T>) private FInstance: T; FStorage: T; function GetInstance: T; procedure SetInstance(const Value: T); public constructor Create(Instance: T); destructor Destroy; override; procedure Restore; procedure Store; property Instance: T read GetInstance write SetInstance; end; Cache<T: TPersistent, constructor> = record private FCache: ICache<T>; procedure EnsureInstance; function GetInstance: T; procedure SetInstance(const Value: T); public procedure Restore; procedure Store; class operator Implicit(const Value: Cache<T>): T; class operator Implicit(const Value: T): Cache<T>; property Instance: T read GetInstance write SetInstance; end; implementation { TCache<T> } constructor TCache<T>.Create(Instance: T); begin inherited Create(); FInstance := Instance; FStorage := T.Create(); end; destructor TCache<T>.Destroy; begin FStorage.Free(); inherited Destroy(); end; function TCache<T>.GetInstance: T; begin Result := FInstance; end; procedure TCache<T>.Restore; begin if Assigned(FInstance) then begin FInstance.Assign(FStorage); end; end; procedure TCache<T>.SetInstance(const Value: T); begin FInstance := Value; end; procedure TCache<T>.Store; begin if Assigned(FInstance) then begin FStorage.Assign(FInstance); end; end; { Cache<T> } procedure Cache<T>.EnsureInstance; begin if not Assigned(FCache) then begin FCache := TCache<T>.Create(Default(T)); end; end; function Cache<T>.GetInstance: T; begin EnsureInstance(); Result := FCache.Instance; end; class operator Cache<T>.Implicit(const Value: T): Cache<T>; begin Result.Instance := Value; end; class operator Cache<T>.Implicit(const Value: Cache<T>): T; begin Result := Value.Instance; end; procedure Cache<T>.Restore; begin EnsureInstance(); FCache.Restore(); end; procedure Cache<T>.SetInstance(const Value: T); begin EnsureInstance(); FCache.Instance := Value; end; procedure Cache<T>.Store; begin EnsureInstance(); FCache.Store(); end; end.
unit define_htmlparser; interface uses define_htmldom, html_helper_tag; type TDelimiters = set of Byte; TReaderState = (rsInitial, rsBeforeAttr, rsBeforeValue, rsInValue, rsInQuotedValue); PHtmlReader = ^THtmlReader; THtmlReaderEvent = procedure(AHtmlReader: PHtmlReader); PHtmlParser = ^THtmlParser; THtmlReader = record Position : Integer; NodeType : Integer; HtmlParser : PHtmlParser; IsEmptyElement : Boolean; Quotation : Word; State : TReaderState; PublicID : WideString; SystemID : WideString; Prefix : WideString; LocalName : WideString; NodeValue : WideString; HtmlStr : WideString; OnAttributeEnd : THtmlReaderEvent; OnAttributeStart: THtmlReaderEvent; OnCDataSection : THtmlReaderEvent; OnComment : THtmlReaderEvent; OnDocType : THtmlReaderEvent; OnElementEnd : THtmlReaderEvent; OnElementStart : THtmlReaderEvent; OnEndElement : THtmlReaderEvent; OnEntityReference: THtmlReaderEvent; OnNotation : THtmlReaderEvent; OnProcessingInstruction: THtmlReaderEvent; OnTextNode : THtmlReaderEvent; end; THtmlParser = record HtmlDocument : PHtmlDocDomNode; HtmlReader : PHtmlReader; CurrentNode : PHtmlDomNode; CurrentTag : PHtmlTag; // EntityList: TEntList; // HtmlTagList: THtmlTagList; // URLSchemes: TURLSchemes; end; implementation end.
unit MultCalc1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, FormExpr, Menus, ExtCtrls; const Nundo = 41; type TForm1 = class(TForm) ResultEdit: TEdit; SaveFor: TButton; XEdit: TEdit; YEdit: TEdit; ZEdit: TEdit; BX: TButton; BY: TButton; BZ: TButton; Label2: TLabel; Label4: TLabel; Label3: TLabel; Helplabel: TLabel; PopupMenu1: TPopupMenu; Undo1: TMenuItem; Redo1: TMenuItem; FIndex: TLabel; FExpr: TMemo; EvalByName: TButton; FName: TEdit; GetFor: TButton; RemoveFor: TButton; E1: TButton; E2: TButton; E3: TButton; CL: TButton; EvalByIndex: TButton; Index: TEdit; Label1: TLabel; RadioGroup1: TRadioGroup; procedure FormCreate(Sender: TObject); procedure SaveForClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure XEditChange(Sender: TObject); procedure YEditChange(Sender: TObject); procedure ZEditChange(Sender: TObject); procedure EvalByNameClick(Sender: TObject); procedure RemoveForClick(Sender: TObject); procedure GetForClick(Sender: TObject); procedure E1Click(Sender: TObject); procedure E2Click(Sender: TObject); procedure E3Click(Sender: TObject); procedure CLClick(Sender: TObject); procedure EvalByIndexClick(Sender: TObject); procedure RadioGroup1Click(Sender: TObject); private { Private declarations } X, Y, Z: Double; MyParser: TFormulaParser; // MyParser: TCStyleParser; ArgSeparator: char; AssignChar: string; public { Public declarations } end; var Form1: TForm1; implementation uses Math; {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); begin if DecimalSeparator = ',' then ArgSeparator := ';' else ArgSeparator := ','; RadioGroup1Click(Sender); MyParser := TFormulaParser.Create; // MyParser := TCStyleParser.Create; MyParser.DefineVariable('x', @X); MyParser.DefineVariable('y', @Y); MyParser.DefineVariable('z', @Z); X := StrToFloat(XEdit.Text); Y := StrToFloat(YEdit.Text); Z := StrToFloat(ZEdit.Text); end; procedure TForm1.FormDestroy(Sender: TObject); begin MyParser.Free; end; procedure TForm1.XEditChange(Sender: TObject); begin if Length(XEdit.Text) > 0 then X := StrToFloat(XEdit.Text) else X := 0; end; procedure TForm1.YEditChange(Sender: TObject); begin if Length(XEdit.Text) > 0 then Y := StrToFloat(yEdit.Text) else Y := 0; end; procedure TForm1.ZEditChange(Sender: TObject); begin if Length(XEdit.Text) > 0 then Z := StrToFloat(ZEdit.Text) else Z := 0; end; procedure TForm1.SaveForClick(Sender: TObject); procedure SetEditText(Edit: TEdit; X: Double); var OnCh: TNotifyEvent; begin OnCh := Edit.OnChange; Edit.OnChange := nil; Edit.Text := FloatToStr(X); Edit.OnChange := OnCh; end; var i: integer; begin i := MyParser.Formula(FName.Text, FExpr.Lines.Text); if i < 0 then FIndex.Caption := '-' else FIndex.Caption := IntToStr(i); end; procedure TForm1.RemoveForClick(Sender: TObject); begin MyParser.Formula(FName.Text, ''); end; procedure TForm1.GetForClick(Sender: TObject); begin FExpr.Lines.Text := MyParser.Text(FName.Text); if FExpr.Lines.Count < 1 then FIndex.Caption := '-' else FIndex.Caption := IntToStr(MyParser.Index(FName.Text)); end; procedure TForm1.CLClick(Sender: TObject); begin FName.Text := ''; FExpr.Lines.Clear(); end; procedure TForm1.E1Click(Sender: TObject); begin FName.Text := 'E1'; FExpr.Lines.Clear(); FExpr.Lines.Add('a'+AssignChar+'x*sin(y)+1'); FExpr.Lines.Add('1/a'); FExpr.Lines.Add('display(#)'); FExpr.Lines.Add('(a-#)*cos(x)'); SaveForClick(Sender); end; procedure TForm1.E2Click(Sender: TObject); begin FName.Text := 'E2'; FExpr.Lines.Clear(); FExpr.Lines.Add('y'+AssignChar+'x*++z'); FExpr.Lines.Add('++x*--z'); FExpr.Lines.Add('z'+AssignChar+'(y-#)/(y+#)'); SaveForClick(Sender); end; procedure TForm1.E3Click(Sender: TObject); begin FName.Text := 'E3'; FExpr.Lines.Clear(); FExpr.Lines.Add('y'+AssignChar+'1'); FExpr.Lines.Add('a'+AssignChar+'1'); FExpr.Lines.Add('ifgoto(--x'+ArgSeparator+'7'+ArgSeparator+'3)'); FExpr.Lines.Add('a'+AssignChar+'a*x'); FExpr.Lines.Add('display(a)'); FExpr.Lines.Add('goto(2)'); FExpr.Lines.Add('x'+AssignChar+'a'); FExpr.Lines.Add('display(y)'); FExpr.Lines.Add('++y'); FExpr.Lines.Add('ifgoto(y-10<0'+ArgSeparator+'8'+ArgSeparator+'if(y-10=0'+ArgSeparator+'12'+ArgSeparator+'10))'); FExpr.Lines.Add('z'+AssignChar+'--y*++x'); FExpr.Lines.Add('stop'); FExpr.Lines.Add('z'+AssignChar+'sin(x)*cos(y)'); FExpr.Lines.Add('goto(10)'); SaveForClick(Sender); end; procedure TForm1.EvalByNameClick(Sender: TObject); procedure SetEditText(Edit: TEdit; X: Double); var OnCh: TNotifyEvent; begin OnCh := Edit.OnChange; Edit.OnChange := nil; Edit.Text := FloatToStr(X); Edit.OnChange := OnCh; end; begin ResultEdit.Text := FloatToStr(MyParser.Eval(FName.Text)); SetEditText(XEdit, X); SetEditText(YEdit, Y); SetEditText(ZEdit, Z); end; procedure TForm1.EvalByIndexClick(Sender: TObject); procedure SetEditText(Edit: TEdit; X: Double); var OnCh: TNotifyEvent; begin OnCh := Edit.OnChange; Edit.OnChange := nil; Edit.Text := FloatToStr(X); Edit.OnChange := OnCh; end; var i,j: integer; begin Val(Index.Text,i,j); if i < 0 then exit; ResultEdit.Text := FloatToStr(MyParser.Eval(i)); SetEditText(XEdit, X); SetEditText(YEdit, Y); SetEditText(ZEdit, Z); end; procedure TForm1.RadioGroup1Click(Sender: TObject); begin if RadioGroup1.ItemIndex = 0 then begin AssignChar := ':=' // delphi format end else begin AssignChar := '='; // C/C++ format end; end; end.
unit ViewModel.EmployeeList; interface uses Model.Interfaces; function CreateEmployeeListViewModelClass: IEmployeeListViewModelInterface; implementation uses Model.Employee, Model.FormDeclarations, Model.ProSu.Interfaces, Model.ProSu.InterfaceActions, Model.ProSu.Provider, Model.ProSu.Subscriber; type TEmployeeListViewModel = class(TInterfacedObject, IEmployeeListViewModelInterface) private fModel: IEmployeeModelInterface; fProvider: IProviderInterface; fSubscriberToEdit: ISubscriberInterface; function GetModel: IEmployeeModelInterface; procedure SetModel(const newModel: IEmployeeModelInterface); //function GetLabelsText: TEmployeeListFormLabelsText; function GetProvider: IProviderInterface; function GetSubscriberToEdit: ISubscriberInterface; procedure SendNotification(const actions : TInterfaceActions); procedure SendErrorNotification (const errorType: TInterfaceErrors; const errorMessage: string); procedure NotificationFromProvider(const notifyClass : INotificationClass); public property Model: IEmployeeModelInterface read GetModel write SetModel; //property LabelsText: TEmployeeListFormLabelsText read GetLabelsText; property SubscriberToEdit: ISubscriberInterface read GetSubscriberToEdit; constructor Create; end; { TEmployeeViewModel } constructor TEmployeeListViewModel.Create; begin fProvider:=CreateProSuProviderClass; fModel := CreateEmployeeModelClass; //GetModel; end; {function TEmployeeListViewModel.GetLabelsText: TEmployeeListFormLabelsText; begin result := fModel.GetEmployeeListFormLabelsText; end;} function TEmployeeListViewModel.GetModel: IEmployeeModelInterface; begin result:=fModel; end; function TEmployeeListViewModel.GetProvider: IProviderInterface; begin result:=fProvider; end; function TEmployeeListViewModel.GetSubscriberToEdit: ISubscriberInterface; begin if not Assigned(fSubscriberToEdit) then fSubscriberToEdit := CreateProSuSubscriberClass; Result := fSubscriberToEdit; end; procedure TEmployeeListViewModel.NotificationFromProvider( const notifyClass: INotificationClass); begin end; procedure TEmployeeListViewModel.SendErrorNotification( const errorType: TInterfaceErrors; const errorMessage: string); var tmpErrorNotificationClass: TErrorNotificationClass; begin tmpErrorNotificationClass:=TErrorNotificationClass.Create; try tmpErrorNotificationClass.Actions:=errorType; tmpErrorNotificationClass.ActionMessage:=errorMessage; fProvider.NotifySubscribers(tmpErrorNotificationClass); finally tmpErrorNotificationClass.Free; end; end; procedure TEmployeeListViewModel.SendNotification(const actions: TInterfaceActions); var tmpNotification : TNotificationClass; begin tmpNotification := TNotificationClass.Create; try tmpNotification.Actions := actions; fProvider.NotifySubscribers(tmpNotification); finally tmpNotification.Free; end; end; procedure TEmployeeListViewModel.SetModel(const newModel: IEmployeeModelInterface); begin fModel:=newModel; end; function CreateEmployeeListViewModelClass: IEmployeeListViewModelInterface; begin result:=TEmployeeListViewModel.Create; end; end.
unit AqDrop.Core.Helpers.Rtti; interface uses System.TypInfo, System.Rtti; type TAqRtti = class strict private class var FImplementation: TAqRtti; class function GetImplementation: TAqRtti; static; private class procedure ReleaseImplementation; strict protected function DoGetType(const pType: PTypeInfo): TRttiType; virtual; abstract; function DoTryFindType(const pQualifiedName: string; out pType: TRttiType): Boolean; virtual; abstract; public function GetType(const pClass: TClass): TRttiType; overload; function GetType(const pType: PTypeInfo): TRttiType; overload; function FindType(const pQualifiedName: string): TRttiType; function TryFindType(const pQualifiedName: string; out pType: TRttiType): Boolean; class procedure SetImplementation(const pImplementation: TAqRtti); class function VerifyIfHasImplementationSetted: Boolean; class property &Implementation: TAqRtti read GetImplementation; end; {TODO -oTatu: levar esse helper para a sua própria unit} TRttiInterfaceTypeHelper = class helper for TRttiInterfaceType public function IsType(const pTypeInfo: PTypeInfo): Boolean; end; implementation uses System.SysUtils, AqDrop.Core.Exceptions, AqDrop.Core.Generics.Releaser; { TAqRtti } function TAqRtti.FindType(const pQualifiedName: string): TRttiType; begin if not DoTryFindType(pQualifiedName, Result) then begin raise EAqInternal.CreateFmt('It wasn''t possible to find the type %s.', [pQualifiedName]); end; end; function TAqRtti.GetType(const pClass: TClass): TRttiType; begin Result := GetType(pClass.ClassInfo); end; class function TAqRtti.GetImplementation: TAqRtti; begin if not Assigned(FImplementation) then begin raise EAqInternal.Create('No implementation provided for TAqRtti features.'); end; Result := FImplementation; end; function TAqRtti.GetType(const pType: PTypeInfo): TRttiType; begin Result := DoGetType(pType); end; class procedure TAqRtti.ReleaseImplementation; begin FreeAndNil(FImplementation); end; class procedure TAqRtti.SetImplementation(const pImplementation: TAqRtti); begin ReleaseImplementation; FImplementation := pImplementation; end; function TAqRtti.TryFindType(const pQualifiedName: string; out pType: TRttiType): Boolean; begin Result := DoTryFindType(pQualifiedName, pType); end; class function TAqRtti.VerifyIfHasImplementationSetted: Boolean; begin Result := Assigned(FImplementation); end; { TRttiInterfaceTypeHelper } function TRttiInterfaceTypeHelper.IsType(const pTypeInfo: PTypeInfo): Boolean; begin Result := (Handle = pTypeInfo) or (Assigned(BaseType) and BaseType.IsType(pTypeInfo)); end; initialization finalization TAqRtti.ReleaseImplementation; end.
unit TestConfig; interface uses Classes,ComCtrls,System.Generics.Collections, System.Generics.Defaults, ConfigBase; function TestModeByStr(const stest: string; const default: integer = 4): integer; type TProductConfig = class; TProductDictionary = class(TObjectDictionary<string, TProductConfig>) protected public constructor Create(); //procedure ValueNotify(const TValue: TProductConfig; Action: TCollectionNotification); override; end; TProductConfig= class(TStringDictionary) protected s_prodname: string; b_visible: boolean; t_parent: TProductConfig; t_children: TProductDictionary; protected procedure SetProdName(const sname: string); procedure SetParent(parent: TProductConfig); procedure ReduceOwnSetting(); procedure WriteToIni(var slines: TStrings); function IsVisible(): boolean; function GetChildrenCount(): integer; function GetProductId(): string; procedure SetProductId(cid: string); public constructor Create(); destructor Destroy(); override; procedure GetParentSettings(var tsetting: TStringDictionary); procedure GetFullSettings(var tsetting: TStringDictionary); procedure GetOwnSettings(var tsetting: TStringDictionary); procedure BuildTreeNode(trvnodes: TTreeNodes; trvNode: TTreeNode); function DepthLevel(): integer; function FindProduct(const sname: string): TProductConfig; function HasChild(const sname: string): boolean; function CreateChild(const sname: string): TProductConfig; function GetChild(const sname: string): TProductConfig; function AddChild(const child: TProductConfig): boolean; function TakeChild(const sname: string): TProductConfig; function UpdateChildName(const oldname, newname: string): boolean; function GetRootProduct(): TProductConfig; property ProductName: string read s_prodname write SetProdName; property ProductParent: TProductConfig read t_parent write SetParent; property ProductID: string read GetProductId write SetProductId; property ChildrenCount: integer read GetChildrenCount; property Visible: boolean read IsVisible write b_visible; end; TProductConfigurator = class(TConfigBase) protected t_prodroot: TProductConfig; t_prodcur: TProductConfig; t_idnamemap:TStringDictionary; t_products: TProductDictionary; protected function FindRootSettings(const secnames: TStrings; var sroot: string): boolean; function ReadFromIni(const sfile: string): boolean; override; function BuildProductFamily(): boolean; public constructor Create(); destructor Destroy(); override; procedure SetProductByName(const sname: string); procedure SetProductByID(const prodid: string); procedure UpdateTreeView(var trv: TTreeView; const bclear: boolean = true); procedure UpdateListView(var lsv: TListView; const bfull: boolean = false; const bsorted: boolean = false); //read all settings from a configuration file //write all settings into a configuration file //create a new product/family //update settings for a product/family //remove a a product/family //change parent of a product/family //show tree of the products/families in a GUI-component //property CurrentProduct: TProductConfig read t_curproduct write SetCurProduct; end; var ProductDictionary: TProductDictionary; implementation uses SysUtils, StrUtils, IniFiles; const CSTR_ARTICLE: string = 'ARTICLE_'; CSTR_VARIANT: string = 'VARIANTE_'; CSTR_FAMILY: string = 'FAMILY_'; CSTR_ROOT: string = 'ROOT_'; CSTR_GENERAL: string = 'GENERAL'; CSTR_VARIANT_PARENT: string = 'FAMILY'; CSTR_ARTICLE_PARENT: string = 'VARIANT'; CSTR_ID_STRING: string = 'ID_STRING'; //test mode: 0=HV_Test, 1=Rundlauftest, 2=PE_Test, 3=Dauertest, 4=Leistungstest CSTR_TEST_MODE: array[0..4] of string = ('HV', 'RLT', 'PE', 'DT','LT'); function TestModeByStr(const stest: string; const default: integer): integer; begin result := default; if not TryStrToInt(stest, result) then begin //try directly to get the number from stest result := IndexText(stest, CSTR_TEST_MODE); //map to a number if stest is given by text if result < 0 then result := default; //return default number if stest is unknown end; end; //procedure TProductFamily.ValueNotify(const TValue: TProductConfig; Action: TCollectionNotification); //begin // inherited ValueNotify(TValue, Action); // case Action of // cnAdded: TValue.SetParent(self); // cnRemoved: TValue.Free; // cnExtracted: TValue.SetParent(t_prodroot); // end; //end; constructor TProductDictionary.Create(); begin inherited Create(TOrdinalIStringComparer.Create); end; procedure TProductConfig.SetProdName(const sname: string); begin if assigned(t_parent) then t_parent.UpdateChildName(s_prodname, sname); s_prodname := sname; end; procedure TProductConfig.SetParent(parent: TProductConfig); begin if assigned(t_parent) then t_parent.TakeChild(s_prodname); t_parent := parent; end; procedure TProductConfig.ReduceOwnSetting(); var t_parentsetting: TStringDictionary; begin t_parentsetting := TStringDictionary.Create(); GetParentSettings(t_parentsetting); ReduceBy(t_parentsetting); t_parentsetting.Free(); end; //write current config and its child into a string list with ini-format procedure TProductConfig.WriteToIni(var slines: TStrings); var t_config: TProductConfig; s_key: string; begin slines.Add(''); slines.Add('[' + s_prodname + ']'); if assigned(t_parent) then begin if StartsText(CSTR_ARTICLE, s_prodname) then slines.Add(CSTR_ARTICLE_PARENT + '=' + t_parent.ProductName) else if (not StartsText(CSTR_ROOT, t_parent.ProductName)) then slines.Add(CSTR_VARIANT_PARENT + '=' + t_parent.ProductName) end; for s_key in self.Keys do slines.Add(s_key + '=' + self.Items[s_key]); for t_config in t_children.Values do t_config.WriteToIni(slines); end; //indicate if the config is visible function TProductConfig.IsVisible(): boolean; var t_config: TProductConfig; begin result := b_visible; if not b_visible then begin for t_config in t_children.Values do begin result := t_config.Visible; if result then break; end; end; end; function TProductConfig.GetChildrenCount(): integer; begin result := t_children.Count; end; //get identifer of current config function TProductConfig.GetProductId(): string; begin result := self.Items[CSTR_ID_STRING]; end; //set identifer of current config procedure TProductConfig.SetProductId(cid: string); begin self.AddOrSetValue(CSTR_ID_STRING, cid); end; constructor TProductConfig.Create(); begin inherited Create; b_visible := true; t_children := TProductDictionary.Create; t_parent := nil; end; destructor TProductConfig.Destroy(); begin Clear; t_children.Clear; t_children.Free; end; procedure TProductConfig.GetFullSettings(var tsetting: TStringDictionary); begin GetParentSettings(tsetting); tsetting.UpdateBy(self); end; procedure TProductConfig.GetOwnSettings(var tsetting: TStringDictionary); begin tsetting.UpdateBy(self); end; //build a tree node with its children procedure TProductConfig.BuildTreeNode(trvnodes: TTreeNodes; trvNode: TTreeNode); var t_curnode: TTreeNode; t_config: TProductConfig; begin if assigned(trvNode) then t_curnode := trvnodes.AddChild(trvNode, s_prodname) else t_curnode := trvnodes.Add(nil, s_prodname); for t_config in t_children.Values do t_config.BuildTreeNode(trvnodes, t_curnode); end; procedure TProductConfig.GetParentSettings(var tsetting: TStringDictionary); begin if assigned(t_parent) then begin t_parent.GetParentSettings(tsetting); tsetting.UpdateBy(t_parent); end; end; //return the depth level of this tree object. Root-Object has depth level 0 //its children have 1, grandchildren 2, and so an function TProductConfig.DepthLevel(): integer; begin if assigned(t_parent) then result := t_parent.DepthLevel() + 1 else result := 0; end; //find product configuration in this whole branch //return the product configuration if found, otherwise nil function TProductConfig.FindProduct(const sname: string): TProductConfig; var t_product: TProductConfig; begin result := nil; if SameText(s_prodname, sname) then result := self else begin for t_product in t_children.Values do begin result := t_product.FindProduct(sname); if assigned(result) then break; end; end; end; //return true if the the product configuration is found in children, otherwise false function TProductConfig.HasChild(const sname: string): boolean; begin result := t_children.ContainsKey(sname); end; function TProductConfig.CreateChild(const sname: string): TProductConfig; begin if HasChild(sname) then result := nil else begin result := TProductConfig.Create; result.ProductName := sname; result.ProductParent := self; t_children.add(sname, result); end; end; //return the product configuration with the given name in children if is found, other create a new one function TProductConfig.GetChild(const sname: string): TProductConfig; begin if HasChild(sname) then result := t_children.Items[sname] else result := nil; end; function TProductConfig.AddChild(const child: TProductConfig): boolean; begin result := false; if assigned(child) then begin if not self.HasChild(child.ProductName) then begin t_children.Add(child.ProductName, child); result := true; end; end; end; //take the child with the given name from children function TProductConfig.TakeChild(const sname: string): TProductConfig; var t_pair: TPair<string, TProductConfig>; begin t_pair := t_children.ExtractPair(sname); result := t_pair.Value; end; function TProductConfig.UpdateChildName(const oldname, newname: string): boolean; var t_config: TProductConfig; begin result := SameText(oldname, newname); if (t_children.ContainsKey(oldname) and (not t_children.ContainsKey(newname))) then begin t_config := TakeChild(oldname); t_children.Add(newname, t_config); result := true; end else; //todo: error message end; function TProductConfig.GetRootProduct(): TProductConfig; begin if assigned(t_parent) then result := t_parent.GetRootProduct else result := self; end; procedure TProductConfigurator.SetProductByName(const sname: string); begin t_prodcur := t_prodroot.FindProduct(sname); end; procedure TProductConfigurator.SetProductByID(const prodid: string); begin t_prodcur := t_prodroot.FindProduct(t_idnamemap.Items[prodid]); end; //find the first section whose name starts with CSTR_ROOT function TProductConfigurator.FindRootSettings(const secnames: TStrings; var sroot: string): boolean; var s_name: string; i_idx: integer; begin result := false; for s_name in secnames do begin if StartsText(CSTR_ROOT, s_name) then begin sroot := s_name; result := true; break; end; end; if not result then begin i_idx := secnames.IndexOf(CSTR_GENERAL); if (i_idx >= 0) then begin result := true; sroot := secnames[i_idx]; end; end; end; //read configs from a ini-file. Only the sections, which have names started //with CSTR_ROOT(first one), CSTR_FAMILY, CSTR_VARIANT and CSTR_ARTICLE. function TProductConfigurator.ReadFromIni(const sfile: string): boolean; var t_inifile: TIniFile; t_secnames, t_secvals: TStrings; s_name: string; t_config: TProductConfig; begin result := false; t_products.Clear; t_inifile := TIniFile.Create(sfile); t_secnames := TStringList.Create(); t_secvals := TStringList.Create(); t_inifile.ReadSections(t_secnames); if FindRootSettings(t_secnames, s_name) then begin t_inifile.ReadSectionValues(s_name, t_secvals); t_prodroot.ProductName := s_name; t_prodroot.UpdateBy(t_secvals); end; for s_name in t_secnames do begin if (StartsText(CSTR_VARIANT, s_name) or StartsText(CSTR_ARTICLE, s_name) or StartsText(CSTR_FAMILY, s_name)) then begin t_secvals.Clear(); t_inifile.ReadSectionValues(s_name, t_secvals); t_config := t_prodroot.CreateChild(s_name); result := assigned(t_config); if result then begin t_config.UpdateBy(t_secvals); t_products.AddOrSetValue(t_config.ProductName, t_config); t_idnamemap.AddOrSetValue(t_config.ProductID, t_config.ProductName); end else begin //todo: error message break; end; end; end; if result then result := BuildProductFamily(); t_secvals.Free(); t_secnames.Free(); t_inifile.Free(); end; function TProductConfigurator.BuildProductFamily(): boolean; var t_config, t_parent: TProductConfig; s_parent: string; begin for t_config in t_products.Values do begin t_parent := nil; if StartsText(CSTR_ARTICLE, t_config.ProductName) then begin if t_config.ContainsKey(CSTR_ARTICLE_PARENT) then begin s_parent := t_config.Items[CSTR_ARTICLE_PARENT]; if t_products.ContainsKey(s_parent) then t_parent := t_products.Items[s_parent]; end; end else if StartsText(CSTR_VARIANT, t_config.ProductName) then begin if t_config.ContainsKey(CSTR_VARIANT_PARENT) then begin s_parent := t_config.Items[CSTR_VARIANT_PARENT]; if t_products.ContainsKey(s_parent) then t_parent := t_products.Items[s_parent]; end; end; if assigned(t_parent) then begin if t_parent.AddChild(t_config) then t_config.ProductParent := t_parent; end else begin if t_prodroot.AddChild(t_config) then t_config.ProductParent := t_prodroot; end; end; result := true; end; constructor TProductConfigurator.Create(); begin inherited Create; t_prodroot := TProductConfig.Create; t_prodcur := t_prodroot; t_idnamemap := TStringDictionary.Create; t_products := TProductDictionary.Create; end; destructor TProductConfigurator.Destroy(); begin t_prodroot.Free; t_idnamemap.Free; t_products.Free; end; //show and update all configs in a tree view procedure TProductConfigurator.UpdateTreeView(var trv: TTreeView; const bclear: boolean); begin trv.Enabled := false; if bclear then begin trv.ClearSelection(); trv.Items.Clear(); end; t_prodroot.BuildTreeNode(trv.Items, nil); //GotoTreeNode(trv); trv.Enabled := true; end; //show and update the settings of current config in a list view procedure TProductConfigurator.UpdateListView(var lsv: TListView; const bfull: boolean; const bsorted: boolean); var t_litem: TListItem; t_settings: TStringDictionary; t_keys: TStringList; s_key: string; begin lsv.Enabled := false; lsv.Items.Clear(); t_settings := TStringDictionary.Create; if bfull then t_prodcur.GetFullSettings(t_settings) else t_prodcur.GetOwnSettings(t_settings); t_keys := TStringList.Create; t_keys.CaseSensitive := false; t_keys.Sorted := bsorted; for s_key in t_settings.Keys do t_keys.Add(s_key); for s_key in t_keys do begin t_litem := lsv.Items.Add(); t_litem.Caption := s_key; t_litem.SubItems.Add(t_settings.Items[s_key]); end; t_keys.Free; t_settings.Free; lsv.Enabled := true; end; initialization ProductDictionary := TProductDictionary.Create; finalization ProductDictionary.Free; end.
unit CFDIUtils; interface uses System.SysUtils, System.Variants, xmldom, XMLDoc, XMLIntf, Facturacion.Comprobante; const _TFD10_XSLT = './XSLT/cadenaoriginal_TFD_1_0.xslt'; _TFD11_XSLT = './XSLT/cadenaoriginal_TFD_1_1.xslt'; type TFEVersion = (v00, v20, v22, v30, v32, v33); TFELlavePrivada = record Ruta: String; Clave: String; end; TFECertificado = record Ruta: String; LlavePrivada: TFELlavePrivada; VigenciaInicio: TDateTime; VigenciaFin: TDateTime; NumeroSerie: String; RFCAlQuePertenece: string; end; TCFDI = class(TObject) private XMLDocument: IXmlDocument; function GetVersion: string; function GetCadenaOriginalTimbre: TCadenaUTF8; function GetFEVersion: TFEVersion; public constructor Create(XMLFileName: TFileName); overload; constructor Create(XMLData: string); overload; property Version: string read GetVersion; property FEVersion: TFEVersion read GetFEVersion; property CadenaOriginalTimbre: TCadenaUTF8 read GetCadenaOriginalTimbre; end; //function GetCadenOriginalTimbre(XMLFileName: string): TCadenaUTF8; //function GetCFDIVersion(XMLFileName: string): string; /// <summary> Calculamos el sello digital para la cadena original de la factura /// Es importante que en cualquier variable que almacenemos la cadena original /// sea del tipo TCadenaUTF8 para no perder la codificacion UTF8</summary> /// <param name="Certificado"> Certificado que sera utilizado para generar el sello</param> /// <param name="CadenaOriginal"> Cadenaorginal para genera el sello del comprobante</param> function GetSelloV33(Certificado: TFECertificado; const CadenaOriginal: TCadenaUTF8): TCadenaUTF8; implementation uses Facturacion.GeneradorSelloV33, Facturacion.OpenSSL, Facturacion.GeneradorCadenaOriginal; //function GetCadenOriginalTimbre(XMLFileName: string): TCadenaUTF8; //var // TFD: String; // TransformadorDeXML: TTransformadorDeXML; // Version: string; // XSLT: TCadenaUTF8; // // function GetTFD: String; // var // CFDI: IXmlDocument; // nodeP, nodeD: IXMLNode; // I,J: Integer; // begin // CFDI := LoadXMLDocument(XMLFileName); // CFDI.Active := True; // for I := 0 to CFDI.DocumentElement.ChildNodes.Count - 1 do // begin // nodeP := CFDI.DocumentElement.ChildNodes[I]; // if nodeP.NodeType = ntElement then // begin // if nodeP.NodeName = 'cfdi:Complemento' then // begin // for J := 0 to nodeP.ChildNodes.Count - 1 do // begin // nodeD := nodeP.ChildNodes[J]; // if nodeD.NodeName = 'tfd:TimbreFiscalDigital' then // begin // Result:= nodeD.XML; // end; // end; // end; // end; // end; // end; // //begin // Version := GetCFDIVersion(XMLFileName); // TFD := GetTFD; // if TFD <> EmptyStr then // begin // TransformadorDeXML := TTransformadorDeXML.Create; // try // if Version = '3.3' then // XSLT := TransformadorDeXML.obtenerXSLTDeRecurso(_TFD11_XSLT) // else // XSLT := TransformadorDeXML.obtenerXSLTDeRecurso(_TFD10_XSLT); // Result := UTF8Encode('|' + TransformadorDeXML.TransformarXML(TFD, XSLT) + '||'); // finally // FreeAndNil(TransformadorDeXML); // end; // end // else // Result:= EmptyAnsiStr; //end; // //function GetCFDIVersion(XMLFileName: string): string; //var // XMLDocument: IXmlDocument; //begin // Result := EmptyStr; // XMLDocument := LoadXMLDocument(XMLFileName); // XMLDocument.Active := True; // // Se utilizza 'Version' ya que a partir del CFDI 3.3 capitalizaron los atributos // if XMLDocument.ChildNodes.FindNode('Comprobante').HasAttribute('version') then // Result := VarToStrDef(XMLDocument.ChildNodes.FindNode('Comprobante').Attributes['version'], ''); // if XMLDocument.ChildNodes.FindNode('Comprobante').HasAttribute('Version') then // Result := VarToStrDef(XMLDocument.ChildNodes.FindNode('Comprobante').Attributes['Version'], ''); //end; function GetSelloV33(Certificado: TFECertificado; const CadenaOriginal: TCadenaUTF8): TCadenaUTF8; var OpenSSL: IOpenSSL; Sello: TGeneradorSelloV33; begin OpenSSL := TOpenSSL.Create; OpenSSL.AsignarLlavePrivada(Certificado.LlavePrivada.Ruta, Certificado.LlavePrivada.Clave); Sello := TGeneradorSelloV33.Create; Sello.Configurar(OpenSSL); Result := Sello.GenerarSelloDeFactura(CadenaOriginal) end; { TCFDI } constructor TCFDI.Create(XMLFileName: TFileName); begin XMLDocument := LoadXMLDocument(XMLFileName); XMLDocument.Active := True; end; constructor TCFDI.Create(XMLData: string); begin XMLDocument := LoadXMLData(XMLData); XMLDocument.Active := True; end; function TCFDI.GetCadenaOriginalTimbre: TCadenaUTF8; var TFD: String; TransformadorDeXML: TTransformadorDeXML; Version: string; XSLT: TCadenaUTF8; function GetTFD: String; var nodeP, nodeD: IXMLNode; I,J: Integer; begin for I := 0 to XMLDocument.DocumentElement.ChildNodes.Count - 1 do begin nodeP := XMLDocument.DocumentElement.ChildNodes[I]; if nodeP.NodeType = ntElement then begin if nodeP.NodeName = 'cfdi:Complemento' then begin for J := 0 to nodeP.ChildNodes.Count - 1 do begin nodeD := nodeP.ChildNodes[J]; if nodeD.NodeName = 'tfd:TimbreFiscalDigital' then begin Result:= nodeD.XML; end; end; end; end; end; end; begin TFD := GetTFD; if TFD <> EmptyStr then begin TransformadorDeXML := TTransformadorDeXML.Create; try if FEVersion = v33 then XSLT := TransformadorDeXML.obtenerXSLTDeRecurso(_TFD11_XSLT) else XSLT := TransformadorDeXML.obtenerXSLTDeRecurso(_TFD10_XSLT); Result := UTF8Encode('|' + TransformadorDeXML.TransformarXML(TFD, XSLT) + '||'); finally FreeAndNil(TransformadorDeXML); end; end else Result:= EmptyAnsiStr; end; function TCFDI.GetFEVersion: TFEVersion; begin if Version = EmptyStr then Result:= v00; if Version = '2.0' then Result:= v20; if Version = '2.2' then Result:= v22; if Version = '3.0' then Result:= v30; if Version = '3.2' then Result:= v32; if Version = '3.3' then Result:= v33; end; function TCFDI.GetVersion: string; begin Result := EmptyStr; // Se utilizza 'Version' ya que a partir del CFDI 3.3 capitalizaron los atributos if XMLDocument.ChildNodes.FindNode('Comprobante').HasAttribute('version') then Result := VarToStrDef(XMLDocument.ChildNodes.FindNode('Comprobante').Attributes['version'], ''); if XMLDocument.ChildNodes.FindNode('Comprobante').HasAttribute('Version') then Result := VarToStrDef(XMLDocument.ChildNodes.FindNode('Comprobante').Attributes['Version'], ''); end; end.
unit LaunchpadEndpoint; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Launchpad; type { ILaunchpadEndpoint } ILaunchpadEndpoint = interface(IInterface) ['{16A5EB17-DE7F-4D6A-BF4D-6E66647C36D8}'] function All: ILaunchpadList; function One(const Id: string): ILaunchpad; end; function NewLaunchpadEndpoint: ILaunchpadEndpoint; implementation uses Endpoint_Helper; const Endpoint = 'launchpads/'; type { TLaunchEndpoint } TLaunchEndpoint = class(TInterfacedObject, ILaunchpadEndpoint) function All: ILaunchpadList; function One(const Id: string): ILaunchpad; end; function NewLaunchpadEndpoint: ILaunchpadEndpoint; begin Result := TLaunchEndpoint.Create; end; { TLaunchEndpoint } function TLaunchEndpoint.All: ILaunchpadList; begin Result := NewLaunchpadList; EndpointToModel(Endpoint, Result); end; function TLaunchEndpoint.One(const Id: string): ILaunchpad; begin Result := NewLaunchpad; EndpointToModel(SysUtils.ConcatPaths([Endpoint, Id]), Result); end; end.
unit vectormathunit; interface uses sysutils, math, fastgeo; type TVector4d = record x, y, z, w: double; end; T3Matrix = array[0..2, 0..2] of double; T4Matrix = array[0..3, 0..3] of double; function Identity3Matrix: T3Matrix; function point3d(v: tvector4d): tpoint3d; overload; function point3d(v: tvector3d): tpoint3d; overload; function point3d(x, y, z: double): tpoint3d; overload; function vector3d(x, y, z: double): TVector3D; overload; function vector3d(const p: tpoint3D): TVector3D; overload; function vector3d(v: tvector4d): tvector3d; overload; function matrix(values: array of double): T3Matrix; function matrix4(values: array of double): T4Matrix; function make4matrix(w: tpoint3d): T4Matrix; overload; function make4matrix(w: t3matrix; p: tvector3d): T4Matrix; overload; function vector4d(w: tvector3d): tvector4d; overload; function vector4d(w: tpoint3d): tvector4d; overload; function vector4d(x, y, z, w: double): TVector4d; overload; function matmul(v: tvector3d; matrix: t3matrix): tvector3d; overload; function matmul(matrix: t4matrix; v: tvector4d): tvector4d; overload; function matmul(m1, m2: t3matrix): t3matrix; overload; function matmul(m1, m2: t4matrix): t4matrix; overload; function crossproduct(a, b: tvector3d): tvector3d; function VectorRotateAroundY(const v: TVector3D; alpha: Single): TVector3D; implementation function VectorRotateAroundY(const v: TVector3D; alpha: Single): TVector3D; var c, s: Extended; begin SinCos(alpha, s, c); Result.y := v.y; Result.x := c * v.x + s * v.z; Result.z := c * v.z - s * v.x; end; function vector3d(x, y, z: double): TVector3D; begin result.x := x; result.y := y; result.z := z; end; function vector4d(x, y, z, w: double): TVector4d; begin result.x := x; result.y := y; result.z := z; result.w := w; end; function vector3d(const p: tpoint3D): TVector3D; begin Move(p, result, sizeof(tpoint3d)); { result.x := p.x; result.y := p.y; result.z := p.z;} end; function point3d(v: tvector3d): tpoint3d; begin Move(v,result,SizeOf(TVector3d)); { result.x := v.x; result.y := v.y; result.z := v.z;} end; function point3d(v: tvector4d): tpoint3d; begin result.x := v.x / v.w; result.y := v.y / v.w; result.z := v.z / v.w; end; function point3d(x, y, z: double): tpoint3d; begin result.x := x; result.y := y; result.z := z; end; function Identity3Matrix: T3Matrix; begin result[0, 0] := 1; result[0, 1] := 0; result[0, 2] := 0; result[1, 0] := 0; result[1, 1] := 1; result[1, 2] := 0; result[2, 0] := 0; result[2, 1] := 0; result[2, 2] := 1; end; function std4matrix: t4matrix; begin result[0, 0] := 1; result[0, 1] := 0; result[0, 2] := 0; result[0, 3] := 0; result[1, 0] := 0; result[1, 1] := 1; result[1, 2] := 0; result[1, 3] := 0; result[2, 0] := 0; result[2, 1] := 0; result[2, 2] := 1; result[2, 3] := 0; result[3, 0] := 0; result[3, 1] := 0; result[3, 2] := 0; result[3, 3] := 1; end; function make4matrix(w: tpoint3d): T4Matrix; begin result := std4matrix; result[0, 0] := w.x; result[1, 1] := w.y; result[2, 2] := w.z; end; function make4matrix(w: t3matrix; p: tvector3d): T4Matrix; var x, y: integer; begin result := std4matrix; for y := 0 to 2 do for x := 0 to 2 do result[x, y] := w[x, y]; result[3, 0] := p.x; result[3, 1] := p.y; result[3, 2] := p.z; end; function vector4d(w: tpoint3d): tvector4d; begin result.x := w.x; result.y := w.y; result.z := w.z; result.w := 1; end; function vector4d(w: tvector3d): tvector4d; begin result.x := w.x; result.y := w.y; result.z := w.z; result.w := 1; end; function vector3d(v: tvector4d): tvector3d; begin result.x := v.x / v.w; result.y := v.y / v.w; result.z := v.z / v.w; end; function crossproduct(a, b: tvector3d): tvector3d; //Checks out okay begin result.x := (a.y * b.z) - (a.z * b.y); result.y := (a.z * b.x) - (a.x * b.z); result.z := (a.x * b.y) - (a.y * b.x); end; function matmul(v: tvector3d; matrix: t3matrix): tvector3d; begin result.x := v.x * matrix[0, 0] + v.y * matrix[1, 0] + v.z * matrix[2, 0]; result.y := v.x * matrix[0, 1] + v.y * matrix[1, 1] + v.z * matrix[2, 1]; result.z := v.x * matrix[0, 2] + v.y * matrix[1, 2] + v.z * matrix[2, 2]; end; function matmul(matrix: t4matrix; v: tvector4d): tvector4d; begin result.x := v.x * matrix[0, 0] + v.y * matrix[1, 0] + v.z * matrix[2, 0] + v.w * matrix[3, 0]; result.y := v.x * matrix[0, 1] + v.y * matrix[1, 1] + v.z * matrix[2, 1] + v.w * matrix[3, 1]; result.z := v.x * matrix[0, 2] + v.y * matrix[1, 2] + v.z * matrix[2, 2] + v.w * matrix[3, 2]; result.w := v.x * matrix[0, 3] + v.y * matrix[1, 3] + v.z * matrix[2, 3] + v.w * matrix[3, 3]; end; function matmul(m1, m2: t3matrix): t3matrix; var x, y, i: integer; begin for y := 0 to 2 do for x := 0 to 2 do begin result[x, y] := 0; for i := 0 to 2 do result[x, y] := result[x, y] + m1[x, i] * m2[i, y]; end; end; function matmul(m1, m2: t4matrix): t4matrix; var x, y, i: integer; begin for y := 0 to 3 do for x := 0 to 3 do begin result[x, y] := 0; for i := 0 to 3 do result[x, y] := result[x, y] + m1[x, i] * m2[i, y]; end; end; function matrix(values: array of double): T3Matrix; begin assert(length(values) = 9, '!!'); result[0, 0] := values[0]; result[1, 0] := values[1]; result[2, 0] := values[2]; result[0, 1] := values[3]; result[1, 1] := values[4]; result[2, 1] := values[5]; result[0, 2] := values[6]; result[1, 2] := values[7]; result[2, 2] := values[8]; end; function matrix4(values: array of double): T4Matrix; begin assert(length(values) = 16, '!!'); result[0, 0] := values[0]; result[1, 0] := values[1]; result[2, 0] := values[2]; result[3, 0] := values[3]; result[0, 1] := values[4]; result[1, 1] := values[5]; result[2, 1] := values[6]; result[3, 1] := values[7]; result[0, 2] := values[8]; result[1, 2] := values[9]; result[2, 2] := values[10]; result[3, 2] := values[11]; result[0, 3] := values[12]; result[1, 3] := values[13]; result[2, 3] := values[14]; result[3, 3] := values[15]; end; end.
unit View.PedidoVendaList; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, View.TemplateList, Data.DB, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Vcl.Menus, FireDAC.Comp.DataSet, FireDAC.Comp.Client, System.ImageList, Vcl.ImgList, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, Util.Enum, View.Template, Vcl.Mask, frxClass, frxDBSet; type TPedidoVendaListView = class(TTemplateListView) LBLID: TLabel; LBLNomeFantasia: TLabel; EDTID: TEdit; EDTValorTotal: TEdit; EDTRazaoSocial: TEdit; LBLRazaoSocial: TLabel; MIImprimir: TMenuItem; BTNImprimir: TButton; FRXPedidoVenda: TfrxReport; FRXDBPedidoVenda: TfrxDBDataset; FDPedidoVenda: TFDQuery; FDPedidoVendaItem: TFDQuery; FRXDBPedidoVendaItem: TfrxDBDataset; procedure BTNPesquisarClick(Sender: TObject); procedure DataSourceDataChange(Sender: TObject; Field: TField); procedure EDTValorTotalKeyPress(Sender: TObject; var Key: Char); procedure EDTValorTotalExit(Sender: TObject); procedure BTNImprimirClick(Sender: TObject); procedure MIImprimirClick(Sender: TObject); private public function CreateViewTemplate(AOperacao: TOperacao): TTemplateView; override; procedure CreateController; override; procedure Imprimir; end; var PedidoVendaListView: TPedidoVendaListView; implementation uses Controller.PedidoVenda, View.PedidoVenda, Util.View; {$R *.dfm} procedure TPedidoVendaListView.BTNImprimirClick(Sender: TObject); begin inherited; Imprimir; end; procedure TPedidoVendaListView.BTNPesquisarClick(Sender: TObject); var SB: TStringBuilder; begin inherited; SB := TStringBuilder.Create; try SB.Append('SELECT * '). Append('FROM ').Append(Controller.Model.DataBaseObject.View). Append(' WHERE 1 = 1 '); if StrToIntDef(EDTID.Text, 0) > 0 then begin SB.Append(' AND ID = ').Append(EDTID.Text); end; if not Trim(EDTRazaoSocial.Text).IsEmpty then begin SB.Append(' AND RazaoSocial LIKE ').Append(QuotedStr(Trim('%' + EDTRazaoSocial.Text + '%'))); end; if StrToFloatDef(EDTValorTotal.Text, 0) > 0 then begin SB.Append(' AND ValorTotal = ').Append(EDTValorTotal.Text); end; SB.Append(' ORDER BY ID '); FDQuery.Open(SB.ToString); finally FreeAndNil(SB); end; end; procedure TPedidoVendaListView.CreateController; begin inherited; if not Assigned(Controller) then Controller := TPedidoVendaController.Create; end; function TPedidoVendaListView.CreateViewTemplate(AOperacao: TOperacao): TTemplateView; begin Result := TPedidoVendaView.Create(Self); end; procedure TPedidoVendaListView.DataSourceDataChange(Sender: TObject; Field: TField); begin inherited; TNumericField(DataSource.DataSet.FieldByName('ValorTotal')).DisplayFormat := '###,##0.00'; end; procedure TPedidoVendaListView.EDTValorTotalExit(Sender: TObject); begin inherited; if not Trim(EDTValorTotal.Text).IsEmpty then EDTValorTotal.Text := FormatFloat(FormatoFloat, StrToFloatDef(EDTValorTotal.Text, 0)); end; procedure TPedidoVendaListView.EDTValorTotalKeyPress(Sender: TObject; var Key: Char); begin inherited; EditFloatKeyPress(Sender, Key); end; procedure TPedidoVendaListView.Imprimir; begin try try if (DataSource.DataSet.Active) and (not DataSource.DataSet.IsEmpty) then begin FDPedidoVenda.Close; FDPedidoVenda.SQL.Text := 'SELECT * FROM VWPedidoVendaPrint WHERE ID = :ID; '; FDPedidoVenda.ParamByName('ID').AsInteger := FDQuery.FieldByName('ID').AsInteger; FDPedidoVenda.Open; FDPedidoVendaItem.Close; FDPedidoVendaItem.SQL.Text := 'SELECT * FROM VWPedidoVendaItem WHERE IDPedidoVenda = :ID; '; FDPedidoVendaItem.ParamByName('ID').AsInteger := FDQuery.FieldByName('ID').AsInteger; FDPedidoVendaItem.Open; with FRXPedidoVenda do begin Clear; LoadFromFile(ExtractFilePath(Application.ExeName) + '..\..\Report\PedidoVenda.fr3'); PrepareReport(True); ReportOptions.Name := 'Visualização de Impressão: Pedido de Venda'; ShowReport(True); end; end; except on E: Exception do begin Application.MessageBox(PWideChar('Erro ao imprimir Pedido de Venda. Erro: ' + E.Message), 'Erro', MB_OK + MB_ICONERROR); end; end; finally end; end; procedure TPedidoVendaListView.MIImprimirClick(Sender: TObject); begin inherited; Imprimir; end; end.
unit lPush; interface uses System.SysUtils, System.Types, System.UITypes, System.Generics.Collections, System.Classes, System.Variants, FMX.Types, FMX.Forms, System.JSON, System.PushNotification, FMX.Layouts, FMX.Memo, FMX.StdCtrls {$IFDEF ANDROID} , FMX.PushNotification.Android, FMX.Platform.Android, Androidapi.JNI.Os, Androidapi.JNI.JavaTypes, Androidapi.Helpers {$ENDIF} {$IFDEF IOS} ,FMX.PushNotification.IOS {$ENDIF} ; const TPushPlatforms = pidiOSSimulator or pidAndroid or pidiOSDevice; type [ComponentPlatformsAttribute(TPushPlatforms)] TPushManager = class(TComponent) private FAppID: string; FActive: boolean; FPushService: TPushService; FServiceConnection: TPushServiceConnection; FOnMessage: TPushServiceConnection.TReceiveNotificationEvent; FOnPushReady: TNotifyEvent; FOnPushChange: TPushServiceConnection.TChangeEvent; FTimer: TTimer; function CheckPushReady: boolean; function GetPushReady: boolean; procedure OnTimer(Sender: TObject); procedure OnPushServiceChange(Sender: TObject; AChange: TPushService.TChanges); procedure OnReceiveNotification(Sender: TObject; const PushNotification: TPushServiceNotification); function GetActive: boolean; procedure SetActive(const Value: boolean); function GetDeviceID: string; function GetDeviceToken: string; procedure SetAppID(const Value: string); function GetStartupError: string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property DeviceID: string read GetDeviceID; property DeviceToken: string read GetDeviceToken; property Ready: boolean read GetPushReady; published property AppID: string read FAppID write SetAppID; property Active: boolean read GetActive write SetActive default False; property OnMessage: TPushServiceConnection.TReceiveNotificationEvent read FOnMessage write FOnMessage; property OnPushReady: TNotifyEvent read FOnPushReady write FOnPushReady; property OnPushChange: TPushServiceConnection.TChangeEvent read FOnPushChange write FOnPushChange; property StartupError: string read GetStartupError; end; {$IFDEF UNIT_REGISTRATION} procedure Register; {$ENDIF} implementation {$IFDEF UNIT_REGISTRATION} procedure Register; begin RegisterFmxClasses([TPushManager]); RegisterComponents('Mobile', [TPushManager]); end; {$ENDIF} { TPushManager } constructor TPushManager.Create(AOwner: TComponent); {$IFDEF ANDROID} var bundle: JBundle; iter: JIterator; key, value: string; {$ENDIF} begin inherited Create(AOwner); FAppId:= AppID; if (not (csDesigning in ComponentState)) then begin {$IFDEF ANDROID} FPushService:= TPushServiceManager.Instance.GetServiceByName(TPushService.TServiceNames.GCM); {$ENDIF} {$IFDEF IOS} FPushService:= TPushServiceManager.Instance.GetServiceByName(TPushService.TServiceNames.APS); {$ENDIF} FServiceConnection:= TPushServiceConnection.Create(FPushService); FServiceConnection.OnChange:= OnPushServiceChange; FServiceConnection.OnReceiveNotification:= OnReceiveNotification; {$IFDEF ANDROID} if assigned(MainActivity.getStartupGCM) then begin bundle:= MainActivity.getStartupGCM; if assigned(bundle) then begin iter:= bundle.keySet.iterator; while (iter.hasNext) do begin key:= JStringToString(iter.next.toString); value:= JStringToString(bundle.get(StringToJString(key)).toString); end; MainActivity.receiveGCM(bundle); end; end; {$ENDIF} end; end; destructor TPushManager.Destroy; begin FServiceConnection.Active:= false; FServiceConnection.Free; FPushService:= nil; if assigned(FTimer) then FreeAndNil(FTimer); inherited; end; function TPushManager.CheckPushReady: boolean; begin result:= GetPushReady; if result and assigned(FOnPushReady) then FOnPushReady(Self); end; function TPushManager.GetPushReady: boolean; begin result:= (DeviceID <> EmptyStr) and (DeviceToken <> EmptyStr); end; function TPushManager.GetStartupError: string; begin if assigned(FPushService) then result:= FPushService.StartupError else result:= EmptyStr; end; function TPushManager.GetDeviceID: string; begin if assigned(FPushService) then result:= FPushService.DeviceIDValue[TPushService.TDeviceIDNames.DeviceID] else result:= EmptyStr; end; function TPushManager.GetDeviceToken: string; begin if assigned(FPushService) then result:= FPushService.DeviceTokenValue[TPushService.TDeviceTokenNames.DeviceToken] else result:= EmptyStr; end; function TPushManager.GetActive: boolean; begin result:= FActive end; procedure TPushManager.SetActive(const Value: boolean); begin FActive:= Value; if (not (csDesigning in ComponentState)) and (not (csLoading in ComponentState)) then begin {$IFDEF ANDROID} if Value then FPushService.AppProps[TPushService.TAppPropNames.GCMAppID]:= FAppID; {$ENDIF} try FServiceConnection.Active:= Value; except //If a connection is not available, start timer to check it later end; if assigned(FPushService) and Value and (not CheckPushReady) then begin FTimer:= TTimer.Create(nil); FTimer.Interval:= 2000; FTimer.OnTimer:= Self.OnTimer; FTimer.Enabled:= true; end else FreeAndNil(FTimer); end; end; procedure TPushManager.SetAppID(const Value: string); var OldActive: boolean; begin OldActive:= Active; Active:= false; FAppID:= Value; Active:= OldActive; end; procedure TPushManager.OnPushServiceChange(Sender: TObject; AChange: TPushService.TChanges); begin if assigned(FOnPushChange) then FOnPushChange(Self, AChange); end; procedure TPushManager.OnReceiveNotification(Sender: TObject; const PushNotification: TPushServiceNotification); begin if assigned(FOnMessage) then FOnMessage(Sender, PushNotification) end; procedure TPushManager.OnTimer(Sender: TObject); begin FTimer.Enabled:= False; if FTimer.Interval < 60000 then FTimer.Interval:= FTimer.Interval + 1000; if not Ready then try FServiceConnection.Active:= true; FTimer.Enabled:= not CheckPushReady; except FTimer.Enabled:= True; end; end; end.
{ 普通版日志 } unit uXYSimpleLogger; interface uses Windows, Classes, SysUtils, StdCtrls, Messages, System.StrUtils, System.Contnrs,cxMemo; const WRITE_LOG_FLAG = 'xylog\'; // 记录日志默认目录 WRITE_LOG_FORMAT_DATE = 'yyyy-mm-dd'; // 日期 WRITE_LOG_FORMAT_TIME = 'hh:nn:ss.zzz'; // 时间 SHOW_LOG_ADD_TIME = True; // 日志显示容器是否添加时间 SHOW_LOG_TIME_FORMAT = 'yyyy/mm/dd hh:nn:ss.zzz'; // 日志显示添加时间的格式 SHOW_LOG_CLEAR_COUNT = 1000; // 日志显示容器最大显示条数 Suffix_name = '.txt'; //后缀名称 type TLogLevel = (LL_Info,LL_Notice,LL_Warning,LL_Error); type TXYSimpleLogger = class private FCSLock: TRTLCriticalSection; // 临界区 // FFileStream: TFileStream; //文件流 FLogShower: TComponent; // 日志显示容器 FLogDir: AnsiString; // 日志目录 FLogName: AnsiString; // 日志名称 FLogFlag: AnsiString; // 日志标识 FLogFileCout: Integer; //保存天数 protected procedure ShowLog(Log: AnsiString; const LogLevel: TLogLevel = LL_Info); procedure NewWriteTxt(filename: string; str: string); procedure OpenWriteTxt(filename: string; str: string); { *******根据扩展名遍历文件夹下的文件************* } procedure EnumFileInQueue(path: PAnsiChar; fileExt: string; fileList: TStringList); procedure log_del;// 删除过期的日志文件 public procedure WriteLog(Log: AnsiString; const LogLevel: TLogLevel = LL_Info); overload; constructor Create(LogFlag: AnsiString; LogDir: AnsiString = '')overload; constructor Create(LogFlag: AnsiString; LogDir: AnsiString;LogCount:Integer)overload; destructor Destroy; override; property LogFlag:AnsiString read FLogFlag write FLogFlag; property LogName:AnsiString read FLogName write FLogName; property LogFileCout:Integer read FLogFileCout write FLogFileCout; property LogShower: TComponent read FLogShower write FLogShower; end; var Log:TXYSimpleLogger; implementation { TXYSimpleLogger } constructor TXYSimpleLogger.Create(LogFlag: AnsiString; LogDir: AnsiString); begin Create(LogFlag,LogDir,365); // // InitializeCriticalSection(FCSLock); // if Trim(LogDir) = '' then // FLogDir := ExtractFilePath(ParamStr(0)) // else // FLogDir := LogDir; // if Trim(LogFlag) = '' then // FLogFlag := WRITE_LOG_FLAG // else // FLogFlag := LogFlag; // if Copy(FLogFlag, Length(FLogFlag), 1) <> '\' then // FLogFlag := FLogFlag + '\'; // // FLogDir := FLogDir + FLogFlag; // FLogName := LogFlag; // FLogFileCout := 365; // // if not DirectoryExists(FLogDir) then // if not ForceDirectories(FLogDir) then // begin // raise Exception.Create('日志路径错误,日志类对象不能被创建'); // end; // log_del; end; constructor TXYSimpleLogger.Create(LogFlag, LogDir: AnsiString; LogCount: Integer); begin if Trim(LogDir) = '' then FLogDir := ExtractFilePath(ParamStr(0)) else FLogDir := LogDir; if Trim(LogFlag) = '' then FLogFlag := WRITE_LOG_FLAG else FLogFlag := LogFlag; if Copy(FLogFlag, Length(FLogFlag), 1) <> '\' then FLogFlag := FLogFlag + '\'; FLogDir := FLogDir + FLogFlag; FLogName := LogFlag; FLogFileCout := LogCount; if not DirectoryExists(FLogDir) then if not ForceDirectories(FLogDir) then begin raise Exception.Create('日志路径错误,日志类对象不能被创建'); end; log_del; end; destructor TXYSimpleLogger.Destroy; begin // DeleteCriticalSection(FCSLock); inherited; end; procedure TXYSimpleLogger.EnumFileInQueue(path: PAnsiChar; fileExt: string; fileList: TStringList); var searchRec: TSearchRec; found: Integer; tmpStr: string; curDir: string; dirs: TQueue; pszDir: PAnsiChar; begin dirs := TQueue.Create; // 创建目录队列 dirs.Push(path); // 将起始搜索路径入队 pszDir := dirs.Pop; curDir := StrPas(pszDir); // 出队 { 开始遍历,直至队列为空(即没有目录需要遍历) } while (True) do begin // 加上搜索后缀,得到类似'c:\*.*' 、'c:\windows\*.*'的搜索路径 tmpStr := curDir + '\*.*'; // 在当前目录查找第一个文件、子目录 found := FindFirst(tmpStr, faAnyFile, searchRec); while found = 0 do // 找到了一个文件或目录后 begin // 如果找到的是个目录 if (searchRec.Attr and faDirectory) <> 0 then begin { 在搜索非根目录(C:\、D:\)下的子目录时会出现'.','..'的"虚拟目录" 大概是表示上层目录和下层目录吧。。。要过滤掉才可以 } if (searchRec.Name <> '.') and (searchRec.Name <> '..') then begin { 由于查找到的子目录只有个目录名,所以要添上上层目录的路径 searchRec.Name = 'Windows'; tmpStr:='c:\Windows'; 加个断点就一清二楚了 } tmpStr := curDir + '\' + searchRec.Name; { 将搜索到的目录入队。让它先晾着。 因为TQueue里面的数据只能是指针,所以要把string转换为PChar 同时使用StrNew函数重新申请一个空间存入数据,否则会使已经进 入队列的指针指向不存在或不正确的数据(tmpStr是局部变量)。 } dirs.Push(StrNew(PChar(tmpStr))); end; end else // 如果找到的是个文件 begin { Result记录着搜索到的文件数。可是我是用CreateThread创建线程 来调用函数的,不知道怎么得到这个返回值。。。我不想用全局变量 } // 把找到的文件加到Memo控件 if fileExt = '.*' then fileList.Add(curDir + '\' + searchRec.Name) else begin if SameText(RightStr(curDir + '\' + searchRec.Name, Length(fileExt)), fileExt) then fileList.Add(curDir + '\' + searchRec.Name); end; end; // 查找下一个文件或目录 found := FindNext(searchRec); end; { 当前目录找到后,如果队列中没有数据,则表示全部找到了; 否则就是还有子目录未查找,取一个出来继续查找。 } if dirs.Count > 0 then begin pszDir := dirs.Pop; curDir := StrPas(pszDir); StrDispose(pszDir); end else break; end; // 释放资源 dirs.Free; FindClose(searchRec); end; procedure TXYSimpleLogger.log_del; var fileNameList: TStringList; begin fileNameList := TStringList.Create; try if FLogFileCout > 0 then begin EnumFileInQueue(PAnsiChar(FLogDir), Suffix_name, fileNameList); fileNameList.Sort; while fileNameList.Count > FLogFileCout do begin DeleteFile(PChar(fileNameList[0])); WriteLog('DelLogFiel:' + fileNameList[0],TLogLevel.LL_Notice); fileNameList.Delete(0); end; end; finally fileNameList.Free; end; end; procedure TXYSimpleLogger.NewWriteTxt(filename, str: string); var F: Textfile; begin AssignFile(F, filename); { Assigns the Filename } ReWrite(F); { Create a new file named ek.txt } Writeln(F, str); Closefile(F); { Closes file F } end; procedure TXYSimpleLogger.OpenWriteTxt(filename, str: string); var F: Textfile; begin AssignFile(F, filename); { Assigns the Filename } // ReWrite(F); Append(F); { Opens the file for editing } Writeln(F, str); Closefile(F); { Closes file F } end; procedure TXYSimpleLogger.ShowLog(Log: AnsiString; const LogLevel: TLogLevel); var lineCount: Integer; begin if FLogShower = nil then Exit; if (FLogShower is TMemo) then begin if SHOW_LOG_ADD_TIME then Log := FormatDateTime(SHOW_LOG_TIME_FORMAT, Now) + ' ' + Log; lineCount := TMemo(FLogShower).Lines.Add(Log); // 滚屏到最后一行 SendMessage(TMemo(FLogShower).Handle, WM_VSCROLL, SB_LINEDOWN, 0); if lineCount >= SHOW_LOG_CLEAR_COUNT then TMemo(FLogShower).Clear; end else if (FLogShower is TcxMemo) then begin if SHOW_LOG_ADD_TIME then Log := FormatDateTime(SHOW_LOG_TIME_FORMAT, Now) + ' ' + Log; lineCount := TcxMemo(FLogShower).Lines.Add(Log); // 滚屏到最后一行 SendMessage(TcxMemo(FLogShower).Handle, WM_VSCROLL, SB_LINEDOWN, 0); if lineCount >= SHOW_LOG_CLEAR_COUNT then TcxMemo(FLogShower).Clear; end else raise Exception.Create('日志容器类型不支持:' + FLogShower.ClassName); end; procedure TXYSimpleLogger.WriteLog(Log: AnsiString; const LogLevel: TLogLevel); var ACompleteFileName: string; TmpValue,LogValue: AnsiString; begin // if not IniOptions.systemifLog then Exit; // EnterCriticalSection(FCSLock); LogValue := Log; try case LogLevel of TLogLevel.LL_Info: LogValue := '[Infor] ' + LogValue; TLogLevel.LL_Notice: LogValue := '[Notice] ' + LogValue; TLogLevel.LL_Warning: LogValue := '[Warning] ' + LogValue; TLogLevel.LL_Error: LogValue := '[Error] ' + LogValue; end; ShowLog(LogValue, LogLevel); TmpValue := FormatDateTime(WRITE_LOG_FORMAT_DATE, Now); TmpValue := FLogName + TmpValue; ACompleteFileName := FLogDir + TmpValue + Suffix_name; TmpValue := FormatDateTime(WRITE_LOG_FORMAT_TIME, Now) + ':' + LogValue; if FileExists(ACompleteFileName) then begin OpenWriteTxt(ACompleteFileName, TmpValue); end else begin NewWriteTxt(ACompleteFileName, TmpValue); end; finally // LeaveCriticalSection(FCSLock); end; end; initialization // Log:=TXYSimpleLogger.Create('HttpApi',ExtractFilePath(ParamStr(0)) +'Log\'); finalization if Log <> nil then Log.Free; end.
program DEMOPROG (output); begin write(); {single line comment} { multiple line comment } writeln(); end.
unit CRInfo; { ------------------------------------------------------------------------------ } interface { ------------------------------------------------------------------------------ } uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, StdCtrls, ExtCtrls, ComCtrls, EUSignCP; { ------------------------------------------------------------------------------ } type TCRForm = class(TForm) BasePanel: TPanel; DetailedContentPanel: TPanel; FieldsLabel: TLabel; DetailedPanel: TPanel; ContentPanel: TPanel; DataListView: TListView; DetailedBottomPanel: TPanel; SplitPanel: TPanel; DataLabel: TLabel; PrintRichEdit: TRichEdit; TextMemo: TMemo; DataMemo: TMemo; TopPanel: TPanel; UnderlineImage: TImage; TopLabel: TLabel; BottomPanel: TPanel; BottomUnderlineImage: TImage; OKButton: TButton; DataImageList: TImageList; TopImage: TImage; procedure DataListViewSelectItem(Sender: TObject; Item: TListItem; Selected: boolean); private procedure AddDataListViewItem(Caption, Text: AnsiString; IsHeader: boolean); procedure SetDetailInfo(Info: PEUCRInfo); public function ShowForm(Info: PEUCRInfo): Cardinal; end; { ------------------------------------------------------------------------------ } implementation { ------------------------------------------------------------------------------ } uses EUSignCPOwnUI; { ------------------------------------------------------------------------------ } {$R *.dfm} { ============================================================================== } procedure TCRForm.AddDataListViewItem(Caption, Text: AnsiString; IsHeader: boolean); var Item: TListItem; begin if ((AnsiString(Text) = '') and (not IsHeader)) then Exit; Item := DataListView.Items.Add(); Item.Caption := Caption; Item.SubItems.Add(Text); if IsHeader then begin Item.ImageIndex := 0; end else Item.ImageIndex := -1; end; { ------------------------------------------------------------------------------ } procedure TCRForm.DataListViewSelectItem(Sender: TObject; Item: TListItem; Selected: boolean); begin if Selected then begin DataMemo.Lines.Clear; DataMemo.Lines.Add(Item.SubItems.Strings[0]); end; if (Selected and (AnsiString(Item.SubItems.Strings[0]) <> '')) then begin DataMemo.Height := ((abs(DataMemo.Font.Height) + 2) * DataMemo.Lines.Count) + 10; DataMemo.SelStart := 0; DataMemo.SelLength := 0; DataLabel.Caption := Item.Caption + ':'; DetailedBottomPanel.Height := SplitPanel.Height + DataMemo.Height; DetailedBottomPanel.Visible := True; end else DetailedBottomPanel.Visible := False; end; { ------------------------------------------------------------------------------ } procedure TCRForm.SetDetailInfo(Info: PEUCRInfo); var SubjTypeStr: AnsiString; begin DataListView.Clear(); if (Info.Subject <> '') then begin AddDataListViewItem('Реквізити заявника', Info.Subject, True); end else AddDataListViewItem('Реквізити заявника відсутні', '', True); if (AnsiString(Info.SubjAddress) = '') and (AnsiString(Info.SubjPhone) = '') and (AnsiString(Info.SubjDNS) = '') and (AnsiString(Info.SubjEMail) = '') and (AnsiString(Info.SubjEDRPOUCode) = '') and (AnsiString(Info.SubjDRFOCode) = '') and (AnsiString(Info.SubjNBUCode) = '') and (AnsiString(Info.SubjSPFMCode) = '') and (AnsiString(Info.SubjOCode) = '') and (AnsiString(Info.SubjOUCode) = '') and (AnsiString(Info.SubjUserCode) = '') and (AnsiString(Info.CRLDistribPoint1) = '') and (AnsiString(Info.CRLDistribPoint2) = '') then begin AddDataListViewItem('Додаткові дані відсутні', '', True); end else begin AddDataListViewItem('Реквізити заявника', '', True); AddDataListViewItem('Адреса', Info.SubjAddress, False); AddDataListViewItem('Телефон', Info.SubjPhone, False); AddDataListViewItem('DNS-ім`я чи інше технічного засобу', Info.SubjDNS, False); AddDataListViewItem('Адреса електронної пошти', Info.SubjEMail, False); AddDataListViewItem('Код ЄДРПОУ', Info.SubjEDRPOUCode, False); AddDataListViewItem('Код ДРФО', Info.SubjDRFOCode, False); AddDataListViewItem('Ідентифікатор НБУ', Info.SubjNBUCode, False); AddDataListViewItem('Код СПФМ', Info.SubjSPFMCode, False); AddDataListViewItem('Код організації', Info.SubjOCode, False); AddDataListViewItem('Код підрозділу', Info.SubjOUCode, False); AddDataListViewItem('Код користувача', Info.SubjUserCode, False); AddDataListViewItem('Точка доступу до повних СВС ЦСК', Info.CRLDistribPoint1, False); AddDataListViewItem('Точка доступу до часткових СВС ЦСК', Info.CRLDistribPoint2, False); end; SubjTypeStr := 'Не вказаний'; if Info.SubjTypeExists then begin case Info.SubjType of EU_SUBJECT_TYPE_CA: SubjTypeStr := 'Сервер ЦСК'; EU_SUBJECT_TYPE_CA_SERVER: begin case Info.SubjSubType of EU_SUBJECT_CA_SERVER_SUB_TYPE_CMP: SubjTypeStr := 'Сервер CMP ЦСК'; EU_SUBJECT_CA_SERVER_SUB_TYPE_TSP: SubjTypeStr := 'Сервер TSP ЦСК'; EU_SUBJECT_CA_SERVER_SUB_TYPE_OCSP: SubjTypeStr := 'Сервер OCSP ЦСК'; end; end; EU_SUBJECT_TYPE_RA_ADMINISTRATOR: SubjTypeStr := 'Адміністратор реєстрації'; EU_SUBJECT_TYPE_END_USER: SubjTypeStr := 'Користувач'; end; end; AddDataListViewItem('Тип заявника', SubjTypeStr, True); if Info.CertTimesExists then begin AddDataListViewItem('Строк чинності сертифіката', '', True); AddDataListViewItem('Сертифікат чинний з', AnsiString(FormatDateTime('dd.mm.yyyy hh:nn:ss', SystemTimeToDateTime(Info.CertBeginTime))), False); AddDataListViewItem('Сертифікат чинний до', AnsiString(FormatDateTime('dd.mm.yyyy hh:nn:ss', SystemTimeToDateTime(Info.CertEndTime))), False); end else AddDataListViewItem('Строк чинності сертифіката', 'Відсутній', True); if Info.PrivKeyTimesExists then begin AddDataListViewItem('Строк дії особистого ключа', '', True); AddDataListViewItem('Час введення в дію ос. ключа', AnsiString(FormatDateTime('dd.mm.yyyy hh:nn:ss', SystemTimeToDateTime(Info.PrivKeyBeginTime))), False); AddDataListViewItem('Час виведення з дії ос. ключа', AnsiString(FormatDateTime('dd.mm.yyyy hh:nn:ss', SystemTimeToDateTime(Info.PrivKeyEndTime))), False); end else AddDataListViewItem('Строк дії особистого ключа', 'Відсутній', True); AddDataListViewItem('Параметри відкритого ключа', '', True); case Info.PublicKeyType of EU_CERT_KEY_TYPE_DSTU4145: begin AddDataListViewItem('Тип ключа', 'ДСТУ 4145-2002', False); AddDataListViewItem('Довжина ключа', IntToStr(Info.PublicKeyBits) + ' біт(а)', False); AddDataListViewItem('Відкритий ключ', Info.PublicKey, False); end; EU_CERT_KEY_TYPE_RSA: begin AddDataListViewItem('Тип ключа', 'RSA', False); AddDataListViewItem('Довжина ключа', IntToStr(Info.PublicKeyBits) + ' біт(а)', False); AddDataListViewItem('Модуль', Info.RSAModul, False); AddDataListViewItem('Експонента', Info.RSAExponent, False); end; end; AddDataListViewItem('Ідентифікатор відкритого ключа ЕЦП', Info.PublicKeyID, False); if (AnsiString(Info.ExtKeyUsages) = '') then begin AddDataListViewItem('Уточнене призначення ключів', 'Відсутнє', True); end else AddDataListViewItem('Уточнене призначення ключів', Info.ExtKeyUsages, True); if (AnsiString(Info.SignIssuer) <> '') then begin AddDataListViewItem('Дані про підпис запита', '', True); AddDataListViewItem('Реквізити ЦСК заявника', Info.SignIssuer, False); AddDataListViewItem('РН сертифіката заявника', Info.SignSerial, False); end else AddDataListViewItem('Запит самопідписаний', '', true); end; { ------------------------------------------------------------------------------ } function TCRForm.ShowForm(Info: PEUCRInfo): Cardinal; begin SetDetailInfo(Info); ShowModal(); ShowForm := EU_ERROR_NONE; end; { ============================================================================== } end.
unit mbDo02; { ULDO02.DPR ================================================================ File: mbDO02.PAS Library Call Demonstrated: cbDBitOut() for MetraBus cards Purpose: Sets the state of a single digital output bit. Demonstration: Configures FIRSTPORTA for output and writes a bit value to the port. Other Library Calls: cbErrHandling() Special Requirements: Board 1 must have a programmable digital I/O port. (c) Copyright 1995 - 2002, Measurement Computing Corp. All rights reserved. =========================================================================== } interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, cbw; type TfrmDIO = class(TForm) cmdQuit: TButton; MemoData: TMemo; chkBit0: TCheckBox; chkBit7: TCheckBox; chkBit6: TCheckBox; chkBit5: TCheckBox; chkBit4: TCheckBox; chkBit3: TCheckBox; chkBit2: TCheckBox; chkBit1: TCheckBox; LabelBoardNum: TLabel; EditBoardNum: TEdit; procedure cmdQuitClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure chkBit0Click(Sender: TObject); procedure EditBoardNumChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmDIO: TfrmDIO; implementation {$R *.DFM} var ULStat: Integer; PortType: Integer; BitNum: Integer; BitValue: Integer; ErrReporting: Integer; ErrHandling: Integer; RevLevel: Single; BoardNum: Integer = 1; procedure TfrmDIO.FormCreate(Sender: TObject); begin {declare Revision Level} RevLevel := CURRENTREVNUM; ULStat := cbDeclareRevision(RevLevel); { set up internal error handling for the Universal Library } ErrReporting := PRINTALL; {set Universal Library to print all errors} ErrHandling := STOPALL; {set Universal Library to stop on errors} ULStat := cbErrHandling(ErrReporting, ErrHandling); PortType := FIRSTPORTA; MemoData.Text := 'Use radio buttons to set digital bits...'; end; procedure TfrmDIO.chkBit0Click(Sender: TObject); begin { write BitValue to BitNum of FIRSTPORTA Parameters: BoardNum :the number used by CB.CFG to describe this board PortType :must be FIRSTPORTA or AUXPORT BitNum :the number of the bit to be set to BitValue BitValue :the value written to the port } BitNum := Integer((Sender As TCheckBox).Tag); BitValue := Integer((Sender As TCheckBox).Checked); PortType:=FIRSTPORTA; ULStat := cbDBitOut (BoardNum, PortType, BitNum, BitValue); If ULStat <> 0 then exit; MemoData.Text := 'The following bit and value was written to FIRSTPORTA:'; MemoData.Lines.Add (' '); MemoData.Lines.Add (Format('Bit number %d was set to the value %d', [BitNum, BitValue])); end; procedure TfrmDIO.cmdQuitClick(Sender: TObject); begin Close; end; procedure TfrmDIO.EditBoardNumChange(Sender: TObject); var x : integer; begin x := StrToInt(EditBoardNum.Text); if (x<1) or (x>15) then EditBoardNum.Text := '1'; BoardNum := StrToInt(EditBoardNum.Text); end; end.
unit Utils; {$MODE Delphi} {===========================================================================} interface {===========================================================================} const cSmallLetters : set of char = ['a'..'z']; cCapitalLetters : set of char = ['A'..'Z']; cDecode = 23; {---Textove operace-----------------------} function NSpaces (N: byte): string; function SkipEndSpaces (S: string): string; function SkipBegSpaces (S: string): string; function SkipAllSpaces (S: string): string; function Zarovnej (S: string; Kolik: integer): string; function IsDigit (Z: char): boolean; function BeginWith (S,Beg: string; CS: Boolean): Boolean; function NotCSPos (SubStr, S: string): Integer; function MyPos (SubStr, S: string; CS: Boolean): Integer; function DownCase (Z: Char): Char; function StrDownCase (S: string): string; function StrUpCase (S: string): string; function MySetLength (S: string; N: integer): string; function ZaUvozovkuj (S: string): string; function OdUvozovkuj (S: string): string; function DecodeChar (Ch: Char): Char; function DecodeStr (S: string): string; // Souborive operace function MyGetFileSize (FN: string): integer; function ExistsDir (Dir: string): Boolean; {===========================================================================} implementation uses SysUtils; {===========================================================================} {---------------------------------------------------------------------------} { ************************************ } { ******* TEXTOVE OPERACE ******** } { ************************************ } {---------------------------------------------------------------------------} {-----------------------------------------------------------------NSpaces---} { Fce vraci retezec obsahujici N mezer } function NSpaces (N: byte): string; var i : byte; Pom : string; begin {NSpaces} Pom := ''; for i := 1 to N do Pom := Pom + ' '; NSpaces := Pom; end; {NSpaces} {-----------------------------------------------------------SkipEndSpaces---} function SkipEndSpaces (S: string): string; var i: Byte; begin { SkipEndSpaces } i := Length (S); while (i>0) and (S[i] = ' ') do Dec (i); SkipEndSpaces := Copy (S,1,i); end; { SkipEndSpaces } {-----------------------------------------------------------SkipBegSpaces---} function SkipBegSpaces (S: string): string; var i, N: Byte; begin { SkipBegSpaces } i := 1; N := Length (S); while (i < N) and (S[i] = ' ') do Inc (i); SkipBegSpaces := Copy (S, i, N-i+1); end; { SkipBegSpaces } {-----------------------------------------------------------SkipAllSpaces---} function SkipAllSpaces (S: string): string; var i, N: Byte; Pom : string; begin { SkipAllSpaces } N := Length (S); Pom := ''; for i := 1 to N do if S[i] <> ' ' then Pom := Pom + S[i]; SkipAllSpaces := Pom; end; { SkipAllSpaces } {-----------------------------------------------------------------IsDigit---} function IsDigit (Z: char): boolean; begin {} if ((Z >= '0') and (Z <= '9')) then IsDigit := true else isDigit := false; end; {} {---------------------------------------------------------------BeginWith---} function BeginWith (S,Beg: string; CS: Boolean): Boolean; var PomS, PomBeg: string; begin BeginWith := false; if (Length (S) < Length (Beg)) then exit; if (CS) then begin BeginWith := ((Pos (Beg, S)) = 1); exit; end; { Neni to CaseSensitif } PomS := StrUpcase (S); PomBeg := StrUpcase (Beg); BeginWith := ((Pos (PomBeg, PomS)) = 1); end; {------------------------------------------------------------------NotCSPos---} { NECaseSensitivni obdoba fce POS} function NotCSPos (SubStr, S: string): Integer; var PomSubStr, PomS: string; begin { NotCSPos } PomSubStr := StrUpCase (SubStr); PomS := StrUpCase (S); NotCSPos := Pos (PomSubStr, PomS); end; { NotCSPos } {-------------------------------------------------------------------MyPos---} function MyPos (SubStr, S: string; CS: Boolean): Integer; begin { MyPos } if (CS) then MyPos := Pos (SubStr, S) else MyPos := NotCSPos (SubStr, S); end; { MyPos } {----------------------------------------------------------------DownCase---} function DownCase (Z: Char): Char; var Pom : Byte; aADiff: Byte; begin { DownCase } aADiff := Ord ('a') - Ord('A'); if Z in cCapitalLetters then begin {} Pom := Ord (Z); Inc (Pom, aADiff); Z := Chr (Pom); end; {} DownCase := Z; end; { DownCase } {-------------------------------------------------------------StrDownCase---} { Zmeni vsechna velka pismenka na male, ostatni znaky necha byt } function StrDownCase (S: string): string; var i, N: byte; Word: string; begin {StrDownCase} N := length (S); Word := ''; for i := 1 to N do Word := Word + DownCase (S[i]); StrDownCase := Word; end; {StrDownCase} {---------------------------------------------------------------StrUpCase---} { Zmeni vsechna mala pismenka na velke, ostatni znaky necha byt } function StrUpCase (S: string): string; var i, N: word; W: string; begin {StrUpCase} N := length (S); W := ''; for i := 1 to N do W := W + UpCase (S [i]); StrUpCase := W; end; {StrDownCase} {-------------------------------------------------------------MySetLength---} { Zarovna vstupni retezec S na N znaku - pokud to prebyva, tak to ufikne, pokud to chybi, tak to doplni nulama } function MySetLength (S: string; N: integer): string; var Len: integer; SS: string; begin { MySetLength } Len := Length (S); if (Len > N) then {Ufikneme} SS := Copy (S, 1, N); if (Len < N) then {Dopnime} SS := S + NSpaces (N-Len); if (Len = N) then {Nechame} SS := S; Result := SS; end; { MySetLength } {-------------------------------------------------------------------Zarovnej---} function Zarovnej (S: string; Kolik: integer): string; begin { Zarovnej } Result := format ('%-*.*s',[Kolik, Kolik, S]); end; { Zarovnej } {----------------------------------------------------------------ZaUvozovkuj---} function ZaUvozovkuj (S: string): string; begin { ZaUvozovkuj } Result := '"' + S + '"'; end; { ZaUvozovkuj } {----------------------------------------------------------------OdUvozovkuj---} function OdUvozovkuj (S: string): string; var N: integer; begin { OdUvozovkuj } Result := ''; if S = '' then exit; if (S[1] = '"') then S := Copy (S, 2, Length (S)-1); if S = '' then exit; N := Length (S); if (S[N] = '"') then S := Copy (S, 1, N-1); Result := S; end; { OdUvozovkuj } {------------------------------------------------------------------DecodeStr---} function DecodeStr (S: string): string; var i: integer; begin { DecodeStr } for i := 1 to Length (S) do S[i] := DecodeChar (S[i]); Result := S; end; { DecodeStr } {-----------------------------------------------------------------DecodeChar---} function DecodeChar (Ch: Char): Char; var C: Char; const // Ktere znaky ma nechati na pokoji ///Nechat : set of char = [#13, #10, #26];//, #246, #243, #230]; Nechat : set of char = [#10, #26];//, #246, #243, #230]; begin {DecodeChar} C := Ch; if ((C in Nechat) or (Chr (Ord (C) xor cDecode) in Nechat)) then Result := C else Result := Chr (Ord (C) xor cDecode); { if (not (C in Nechat)) then C := Chr (256 - Ord(Ch)); } end; {DecodeChar} {---------------------------------------------------------------------------} { **************************************************** } { ******* OSTATNI DROBNE PROCEDURKY A FCE ******** } { **************************************************** } {---------------------------------------------------------------------------} //------------------------------------------------------------------------------ // MyGetFileSize //------------------------------------------------------------------------------ function MyGetFileSize (FN: string): integer; var Res: integer; SR: TSearchRec; begin { MyGetFileSize } Res := FindFirst (FN, faAnyFile - faDirectory, SR); if (Res <> 0) then Result := -1 else Result := SR.Size; FindClose (SR); end; { MyGetFileSize } //------------------------------------------------------------------------------ // ExistsDir //------------------------------------------------------------------------------ function ExistsDir (Dir: string): Boolean; var SR: TSearchRec; begin { ExistsDir } if (Dir [Length (Dir)] <> '/') then Dir := Dir + '/'; Result := (FindFirst (Dir+'*.*', faAnyFile, SR) = 0); FindClose (SR); end; { ExistsDir } {===========================================================================} begin end.
unit FMX.ISMobilePhotoGallery; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.IOUtils, System.Messaging, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.Objects, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Effects, FMX.Utils, FMX.Surfaces, {$IFDEF ANDROID} Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.provider, Androidapi.JNI.JavaTypes, Androidapi.JNI.Net, Androidapi.JNI.App, AndroidAPI.jNI.OS, Androidapi.JNIBridge, FMX.Helpers.Android, IdUri, Androidapi.Helpers, FMX.Platform.Android, {$ENDIF} FMX.Platform; type TISTakePhoto = Procedure (Sender : TObject; aBitmap : TBitmap) Of Object; [ComponentPlatformsAttribute (pfidAndroid)] TISPhotoGallery = Class(TComponent) Private FRequestCode : Integer; FMsgID : Integer; FAllowMultiple : Boolean; FOnTakePhoto : TISTakePhoto; FOnCancel : TNotifyEvent; FOnError : TNotifyEvent; {$IFDEF ANDROID} procedure HandleActivityMessage(const Sender: TObject; const M: TMessage); Procedure OnActivityResult(RequestCode, ResultCode: Integer; Data: JIntent); {$ENDIF} Public Constructor Create(aOwner : TComponent); Override; Procedure TakePhotoFromGallery; Published Property AllowMultiple : Boolean Read FAllowMultiple Write FAllowMultiple; Property RequestCode : Integer Read FRequestCode Write FRequestCode; Property OnTakePhoto : TISTakePhoto Read FOnTakePhoto Write FOnTakePhoto; Property OnCancel : TNotifyEvent Read FOnCancel Write FOnCancel; Property OnError : TNotifyEvent Read FOnError Write FOnError; End; Procedure Register; implementation { TISPhotoGallery } constructor TISPhotoGallery.Create(aOwner: TComponent); begin inherited; FRequestCode := 1122; end; procedure TISPhotoGallery.TakePhotoFromGallery; {$IFDEF ANDROID} Var Intent : JIntent; {$ENDIF} begin {$IFDEF ANDROID} FMsgID := TMessageManager.DefaultManager.SubscribeToMessage(TMessageResultNotification, HandleActivityMessage); Intent := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_PICK); intent.setType(StringToJString('image/*')); intent.setAction(TjIntent.JavaClass.ACTION_GET_CONTENT); Intent.putExtra(TJIntent.JavaClass.EXTRA_ALLOW_MULTIPLE, FAllowMultiple); TAndroidHelper.Activity.startActivityForResult(Intent, FRequestCode); {$ENDIF} end; {$IFDEF ANDROID} procedure TISPhotoGallery.HandleActivityMessage(const Sender: TObject; const M: TMessage); begin if M is TMessageResultNotification then OnActivityResult(TMessageResultNotification(M).RequestCode, TMessageResultNotification(M).ResultCode, TMessageResultNotification(M).Value); end; Procedure TISPhotoGallery.OnActivityResult(RequestCode, ResultCode: Integer; Data: JIntent); procedure URI2Bitmap(const AURI: Jnet_Uri; const ABitmap: TBitmap); var Bitmap : JBitmap; Surface : TBitmapSurface; begin Bitmap := TJBitmapFactory.JavaClass.decodeStream(TAndroidHelper.Context.getContentResolver.openInputStream(AURI)); Surface := TBitmapSurface.Create; jBitmapToSurface(Bitmap, Surface); ABitmap.Assign(Surface); Surface.DisposeOf; if Assigned(FOnTakePhoto) then FOnTakePhoto(Self, ABitmap); end; Var I : Integer; Photo : TBitmap; begin TMessageManager.DefaultManager.Unsubscribe(TMessageResultNotification, FMsgID); if RequestCode = FRequestCode then begin if ResultCode = TJActivity.JavaClass.RESULT_OK then begin if Assigned(Data) Then Begin Photo := TBitmap.Create; If Assigned(Data.getClipData) then begin for I := 0 to Data.getClipData.getItemCount-1 do Begin URI2Bitmap(Data.getClipData.getItemAt(I).getUri, Photo); End; end Else if Assigned(Data.getData) then Begin URI2Bitmap(Data.getData, Photo); End; Photo.DisposeOf; End; end else if (ResultCode = TJActivity.JavaClass.RESULT_CANCELED) And Assigned(FOnCancel) then FOnCancel(Self); end Else if Assigned(FOnError) then FOnError(Self); end; {$ENDIF} Procedure Register; Begin RegisterComponents('Imperium Delphi', [TISPhotoGallery]); End; Initialization RegisterFMXClasses([TISPhotoGallery]); end.
unit OptionsForm; {$MODE Delphi} interface uses LCLIntf, LCLType, LMessages, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Buttons, OptionsPageForm; type TfrmOptions = class(TForm) btnOk: TBitBtn; btnCancel: TBitBtn; tvOptions: TTreeView; panCon: TScrollBox; procedure FormShow(Sender: TObject); procedure FormHide(Sender: TObject); procedure tvOptionsDeletion(Sender: TObject; Node: TTreeNode); procedure tvOptionsChange(Sender: TObject; Node: TTreeNode); private curForm: TOptionsPage; procedure SelectForm(f: TOptionsPage); public { Public declarations } end; var frmOptions: TfrmOptions; implementation {$R *.lfm} uses ExtLabelsForm; procedure TfrmOptions.FormShow(Sender: TObject); var f1: TOptionsPage; begin curForm := nil; f1 := TfrmExtLabels.Create(Application); f1.Parent := panCon; f1.Left := 0; f1.Top := 0; with tvOptions.Items.AddChild(nil, f1.LogicalPath) do Data := f1; end; procedure TfrmOptions.FormHide(Sender: TObject); begin tvOptions.Items.Clear; curForm := nil; end; procedure TfrmOptions.SelectForm(f: TOptionsPage); begin if Assigned(curForm) then curForm.Visible := False; curForm := f; if Assigned(curForm) then begin f.Visible := True; //lblShortDesc.Caption := f.Caption; //lblLongDesc.Caption := f.Hint; end; end; procedure TfrmOptions.tvOptionsDeletion(Sender: TObject; Node: TTreeNode); begin if Node.Data <> nil then TOptionsPage(Node.Data).Free; end; procedure TfrmOptions.tvOptionsChange(Sender: TObject; Node: TTreeNode); begin SelectForm(Node.Data); end; end.
(* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.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 GeckoSDK for Delphi. * * The Initial Developer of the Original Code is Takanori Ito. * Portions created by the Initial Developer are Copyright (C) 2004 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** *) unit nsGeckoStrings; interface uses nsConsts, nsTypes; type nsAString = ^nsStringContainer; nsString = nsAString; nsStringContainer = record v: Pointer; d1: Pointer; d2: Longword; d3: Pointer; end; nsACString = ^nsCStringContainer; nsCString = nsACString; nsCStringContainer = record v: Pointer; d1: Pointer; d2: Longword; d3: Pointer; end; nsAUTF8String = nsACString; nsUTF8String = nsAUTF8String; nsUTF8StringContainer = nsCStringContainer; IInterfacedString = interface; IInterfacedCString = interface; IInterfacedUTF8String = interface; IInterfacedString = interface ['{0FA36E7C-6CA9-4D02-AF23-B49F35047181}'] function Length: Longword; procedure Cut(cutStart, cutLength: Longword); procedure Assign(Source: IInterfacedString); overload; procedure Assign(const Source: nsAString); overload; procedure Assign(Source: WideString); overload; procedure Append(Source: IInterfacedString); overload; procedure Append(const Source: nsAString); overload; procedure Append(Source: WideString); overload; procedure Insert(Source: IInterfacedString; aPosition: Longword); overload; procedure Insert(const Source: nsAString; aPosition: Longword); overload; procedure Insert(Source: WideString; aPosition: Longword); overload; procedure Replace(aPosition, aLength: Longword; const Source: nsAString); overload; procedure Replace(aPosition, aLength: Longword; Source: IInterfacedString); overload; function AString: nsAString; function ToString: WideString; end; IInterfacedCString = interface ['{3207A765-52D6-4E1C-B0F1-8EC39DA4D8B4}'] function Length: Longword; procedure Cut(cutStart, cutLength: Longword); procedure Assign(Source: IInterfacedCString); overload; procedure Assign(const Source: nsACString); overload; procedure Assign(Source: AnsiString); overload; procedure Append(Source: IInterfacedCString); overload; procedure Append(const Source: nsACString); overload; procedure Append(Source: AnsiString); overload; procedure Insert(Source: IInterfacedCString; aPosition: Longword); overload; procedure Insert(const Source: nsACString; aPosition: Longword); overload; procedure Insert(Source: AnsiString; aPosition: Longword); overload; procedure Replace(aPosition, aLength: Longword; const Source: nsACString); overload; procedure Replace(aPosition, aLength: Longword; Source: IInterfacedCString); overload; function ACString: nsACString; function ToString: AnsiString; end; IInterfacedUTF8String = interface ['{100ABB7D-46A0-4BB2-B5BF-A94F9E53B78C}'] function Length: Longword; procedure Cut(cutStart, cutLength: Longword); procedure Assign(Source: IInterfacedUTF8String); overload; procedure Assign(const Source: nsAUTF8String); overload; procedure Assign(Source: UTF8String); overload; procedure Append(Source: IInterfacedUTF8String); overload; procedure Append(const Source: nsAUTF8String); overload; procedure Append(Source: UTF8String); overload; procedure Insert(Source: IInterfacedUTF8String; aPosition: Longword); overload; procedure Insert(const Source: nsAUTF8String; aPosition: Longword); overload; procedure Insert(Source: UTF8String; aPosition: Longword); overload; procedure Replace(aPosition, aLength: Longword; const Source: nsAUTF8String); overload; procedure Replace(aPosition, aLength: Longword; Source: IInterfacedUTF8String); overload; function AUTF8String: nsAUTF8String; function ToString: UTF8String; end; function Compare(const lhs, rhs: nsAString): Integer; overload; function Compare(const lhs, rhs: nsACString): Integer; overload; function NewString: IInterfacedString; overload; function NewString(src: PWideChar): IInterfacedString; overload; function NewString(src: WideString): IInterfacedString; overload; function NewString(src: nsAString): IInterfacedString; overload; function NewCString: IInterfacedCString; overload; function NewCString(src: PAnsiChar): IInterfacedCString; overload; function NewCString(src: AnsiString): IInterfacedCString; overload; function NewCString(src: nsACString): IInterfacedCString; overload; function NewUTF8String: IInterfacedUTF8String; overload; function NewUTF8String(src: PAnsiChar): IInterfacedUTF8String; overload; function NewUTF8String(src: UTF8String): IInterfacedUTF8String; overload; function NewUTF8String(src: nsAUTF8String): IInterfacedUTF8String; overload; function RelateString(src: nsAString; own: Boolean=False): IInterfacedString; function RelateCString(src: nsACString; own: Boolean=False): IInterfacedCString; function RelateUTF8String(src: nsAUTF8String; own: Boolean=False): IInterfacedUTF8String; implementation uses nsInit, nsMemory, nsError; function Compare(const lhs, rhs: nsAString): Integer; var p1, p2: PWideChar; l1, l2: Longword; begin l1 := NS_StringGetData(lhs, p1); l2 := NS_StringGetData(rhs, p2); while (l1>0) and (l2>0) do begin Result := Ord(p1^) - Ord(p2^); if Result <> 0 then Exit; Dec(l1); Dec(l2); Inc(p1); Inc(p2); end; Result := l1 - l2; end; function Compare(const lhs, rhs: nsACString): Integer; var p1, p2: PAnsiChar; l1, l2: Longword; begin l1 := NS_CStringGetData(lhs, p1); l2 := NS_CStringGetData(rhs, p2); while (l1>0) and (l2>0) do begin Result := Ord(p1^) - Ord(p2^); if Result <> 0 then Exit; Dec(l1); Dec(l2); Inc(p1); Inc(p2); end; Result := l1 - l2; end; type TIStringImpl = class(TInterfacedObject, IInterfacedString) FContainer: nsStringContainer; FString: nsString; FOwn: Boolean; public constructor Create; overload; constructor Create(src: PWideChar); overload; constructor Create(src: WideString); overload; constructor Create(src: nsAString); overload; constructor Relate(src: nsAString; own: Boolean); destructor Destroy; override; function Length: Longword; procedure Cut(cutStart, cutLength: Longword); procedure Assign(Source: IInterfacedString); overload; procedure Assign(const Source: nsAString); overload; procedure Assign(Source: WideString); overload; procedure Append(Source: IInterfacedString); overload; procedure Append(const Source: nsAString); overload; procedure Append(Source: WideString); overload; procedure Insert(Source: IInterfacedString; aPosition: Longword); overload; procedure Insert(const Source: nsAString; aPosition: Longword); overload; procedure Insert(Source: WideString; aPosition: Longword); overload; procedure Replace(aPosition, aLength: Longword; const Source: nsAString); overload; procedure Replace(aPosition, aLength: Longword; Source: IInterfacedString); overload; function AString: nsAString; function SIToString: WideString; function IInterfacedString.ToString = SIToString; end; function NewString: IInterfacedString; begin Result := TIStringImpl.Create; end; function NewString(src: PWideChar): IInterfacedString; begin Result := TIStringImpl.Create(src); end; function NewString(src: WideString): IInterfacedString; begin Result := TIStringImpl.Create(src); end; function NewString(src: nsAString): IInterfacedString; begin Result := TIStringImpl.Create(src); end; function RelateString(src: nsAString; own: Boolean): IInterfacedString; begin Result := TIStringImpl.Relate(src, own); end; constructor TIStringImpl.Create; begin inherited Create; if NS_FAILED(NS_StringContainerInit(FContainer)) then Error(reOutOfMemory); FOwn := True; FString := @FContainer; end; constructor TIStringImpl.Create(src: PWideChar); begin inherited Create; if NS_FAILED(NS_StringContainerInit(FContainer)) then Error(reOutOfMemory); FOwn := True; FString := @FContainer; Assign(src); //nsMemory.Free(src); end; constructor TIStringImpl.Create(src: WideString); begin inherited Create; if NS_FAILED(NS_StringContainerInit(FContainer)) then Error(reOutOfMemory); FOwn := True; FString := @FContainer; Assign(src); end; constructor TIStringImpl.Create(src: nsAString); begin inherited Create; if NS_FAILED(NS_StringContainerInit(FContainer)) then Error(reOutOfMemory); FOwn := True; FString := @FContainer; Assign(src); end; constructor TIStringImpl.Relate(src: nsAString; own: Boolean); begin inherited Create; FString := src; FOwn := own; end; destructor TIStringImpl.Destroy; begin if FOwn then NS_StringContainerFinish(FString^); inherited Destroy; end; function TIStringImpl.Length: Longword; var temp: PWideChar; begin Result := NS_StringGetData(FString, temp); //nsMemory.Free(temp); end; procedure TIStringImpl.Cut(cutStart, cutLength: Longword); begin NS_StringCutData(FString, cutStart, cutLength); end; procedure TIStringImpl.Assign(Source: IInterfacedString); begin NS_StringCopy(FString, Source.AString); end; procedure TIStringImpl.Assign(const Source: nsAString); begin NS_StringCopy(FString, Source); end; procedure TIStringImpl.Assign(Source: WideString); begin NS_StringSetData(FString, PWideChar(Source)); end; procedure TIStringImpl.Append(Source: IInterfacedString); begin NS_StringAppendData(FString, PWideChar(Source.ToString)); end; procedure TIStringImpl.Append(const Source: nsAString); var src2: IInterfacedString; begin src2 := NewString(Source); Append(src2); end; procedure TIStringImpl.Append(Source: WideString); var src2: IInterfacedString; begin src2 := NewString(Source); Append(src2); end; procedure TIStringImpl.Insert(Source: IInterfacedString; aPosition: Longword); begin NS_StringInsertData(FString, aPosition, PWideChar(Source.ToString)); end; procedure TIStringImpl.Insert(const Source: nsAString; aPosition: Longword); var src2: IInterfacedString; begin src2 := NewString(Source); Insert(src2, aPosition); end; procedure TIStringImpl.Insert(Source: WideString; aPosition: Longword); var src2: IInterfacedString; begin src2 := NewString(Source); Insert(src2, aPosition); end; procedure TIStringImpl.Replace(aPosition, aLength: Longword; Source: IInterfacedString); begin NS_StringSetDataRange(FString, aPosition, aLength, PWideChar(Source.ToString)); end; procedure TIStringImpl.Replace(aPosition, aLength: Longword; const Source: nsAString); var src2: IInterfacedString; begin src2 := NewString(Source); Replace(aPosition, aLength, Src2); end; function TIStringImpl.AString: nsAString; begin Result := FString; end; function TIStringImpl.SIToString: WideString; var p:PWideChar; l:Longword; begin l:=NS_StringGetData(FString,p); SetLength(Result,l); Move(p^,Result[1],l*2); end; type TICStringImpl = class(TInterfacedObject, IInterfacedCString) FContainer: nsCStringContainer; FString: nsCString; FOwn: Boolean; constructor Create; overload; constructor Create(src: AnsiString); overload; constructor Create(src: nsACString); overload; constructor Relate(src: nsACString; own: Boolean); overload; destructor Destroy; override; function Length: Longword; procedure Cut(cutStart, cutLength: Longword); procedure Assign(Source: IInterfacedCString); overload; procedure Assign(const Source: nsACString); overload; procedure Assign(Source: AnsiString); overload; procedure Append(Source: IInterfacedCString); overload; procedure Append(const Source: nsACString); overload; procedure Append(Source: AnsiString); overload; procedure Insert(Source: IInterfacedCString; aPosition: Longword); overload; procedure Insert(const Source: nsACString; aPosition: Longword); overload; procedure Insert(Source: AnsiString; aPosition: Longword); overload; procedure Replace(aPosition, aLength: Longword; const Source: nsACString); overload; procedure Replace(aPosition, aLength: Longword; Source: IInterfacedCString); overload; function ACString: nsACString; function ToAnsiString: AnsiString; function IInterfacedCString.ToString = ToAnsiString; end; TIUTF8StringImpl = class(TInterfacedObject, IInterfacedUTF8String) FContainer: nsCStringContainer; FString: nsCString; FOwn: Boolean; constructor Create; overload; constructor Create(src: UTF8String); overload; constructor Create(src: nsAUTF8String); overload; constructor Relate(src: nsAUTF8String; own: Boolean); overload; destructor Destroy; override; function Length: Longword; procedure Cut(cutStart, cutLength: Longword); procedure Assign(Source: IInterfacedUTF8String); overload; procedure Assign(const Source: nsAUTF8String); overload; procedure Assign(Source: UTF8String); overload; procedure Append(Source: IInterfacedUTF8String); overload; procedure Append(const Source: nsAUTF8String); overload; procedure Append(Source: UTF8String); overload; procedure Insert(Source: IInterfacedUTF8String; aPosition: Longword); overload; procedure Insert(const Source: nsAUTF8String; aPosition: Longword); overload; procedure Insert(Source: UTF8String; aPosition: Longword); overload; procedure Replace(aPosition, aLength: Longword; const Source: nsAUTF8String); overload; procedure Replace(aPosition, aLength: Longword; Source: IInterfacedUTF8String); overload; function AUTF8String: nsAUTF8String; function ToUTF8String: UTF8String; function IInterfacedUTF8String.ToString = ToUTF8String; end; function NewCString: IInterfacedCString; begin Result := TICStringImpl.Create; end; function NewCString(src: PAnsiChar): IInterfacedCString; begin Result := TICStringImpl.Create(src); end; function NewCString(src: AnsiString): IInterfacedCString; begin Result := TICStringImpl.Create(src); end; function NewCString(src: nsACString): IInterfacedCString; begin Result := TICStringImpl.Create(src); end; function RelateCString(src: nsACString; own: Boolean): IInterfacedCString; begin Result := TICStringImpl.Relate(src, own); end; function NewUTF8String: IInterfacedUTF8String; begin Result := TIUTF8StringImpl.Create; end; function NewUTF8String(src: PAnsiChar): IInterfacedUTF8String; begin Result := TIUTF8StringImpl.Create(src); end; function NewUTF8String(src: UTF8String): IInterfacedUTF8String; begin Result := TIUTF8StringImpl.Create(src); end; function NewUTF8String(src: nsAUTF8String): IInterfacedUTF8String; begin Result := TIUTF8StringImpl.Create(src); end; function RelateUTF8String(src: nsAUTF8String; own: Boolean): IInterfacedUTF8String; begin Result := TIUTF8StringImpl.Relate(src, own); end; constructor TICStringImpl.Create; begin inherited Create; if NS_FAILED(NS_CStringContainerInit(FContainer)) then Error(reOutOfMemory); FOwn := True; FString := @FContainer; end; constructor TICStringImpl.Create(src: AnsiString); begin inherited Create; if NS_FAILED(NS_CStringContainerInit(FContainer)) then Error(reOutOfMemory); FOwn := True; FString := @FContainer; Assign(src); end; constructor TICStringImpl.Create(src: nsACString); begin inherited Create; if NS_FAILED(NS_CStringContainerInit(FContainer)) then Error(reOutOfMemory); FOwn := True; FString := @FContainer; Assign(src); end; constructor TICStringImpl.Relate(src: nsACString; own: Boolean); begin inherited Create; FString := src; FOwn := own; end; destructor TICStringImpl.Destroy; begin if FOwn then NS_CStringContainerFinish(FString^); inherited Destroy; end; function TICStringImpl.Length: Longword; var temp: PAnsiChar; begin Result := NS_CStringGetData(FString, temp); end; procedure TICStringImpl.Cut(cutStart, cutLength: Longword); begin NS_CStringCutData(FString, cutStart, cutLength); end; procedure TICStringImpl.Assign(Source: IInterfacedCString); begin NS_CStringCopy(FString, Source.ACString); end; procedure TICStringImpl.Assign(const Source: nsACString); begin NS_CStringCopy(FString, Source); end; procedure TICStringImpl.Assign(Source: AnsiString); begin NS_CStringSetData(FString, PAnsiChar(Source)); end; procedure TICStringImpl.Append(Source: IInterfacedCString); var src2: PAnsiChar; begin NS_CStringGetData(Source.ACString, src2); NS_CStringAppendData(FString, src2); end; procedure TICStringImpl.Append(const Source: nsACString); var src2: PAnsiChar; begin NS_CStringGetData(Source, src2); NS_CStringAppendData(FString, src2); end; procedure TICStringImpl.Append(Source: AnsiString); begin NS_CStringAppendData(FString, PAnsiChar(Source)); end; procedure TICStringImpl.Insert(Source: IInterfacedCString; aPosition: Longword); var src2: PAnsiChar; begin NS_CStringGetData(Source.ACString, src2); NS_CStringInsertData(FString, aPosition, src2); end; procedure TICStringImpl.Insert(const Source: nsACString; aPosition: Longword); var src2: PAnsiChar; begin NS_CStringGetData(Source, src2); NS_CStringInsertData(FString, aPosition, src2); end; procedure TICStringImpl.Insert(Source: AnsiString; aPosition: Longword); begin NS_CStringInsertData(FString, aPosition, PAnsiChar(Source)); end; procedure TICStringImpl.Replace(aPosition, aLength: Longword; Source: IInterfacedCString); var src2: PAnsiChar; begin NS_CStringGetData(Source.ACString, src2); NS_CStringSetDataRange(FString, aPosition, aLength, src2); end; procedure TICStringImpl.Replace(aPosition, aLength: Longword; const Source: nsACString); var src2: PAnsiChar; begin NS_CStringGetData(Source, src2); NS_CStringSetDataRange(FString, aPosition, aLength, src2); end; function TICStringImpl.ACString: nsACString; begin Result := FString; end; function TICStringImpl.ToAnsiString: AnsiString; var p:PAnsiChar; l:Longword; begin l:=NS_CStringGetData(FString,p); SetLength(Result,l); Move(p^,Result[1],l); end; constructor TIUTF8StringImpl.Create; begin inherited Create; if NS_FAILED(NS_CStringContainerInit(FContainer)) then Error(reOutOfMemory); FOwn := True; FString := @FContainer; end; constructor TIUTF8StringImpl.Create(src: UTF8String); begin inherited Create; if NS_FAILED(NS_CStringContainerInit(FContainer)) then Error(reOutOfMemory); FOwn := True; FString := @FContainer; Assign(src); end; constructor TIUTF8StringImpl.Create(src: nsAUTF8String); begin inherited Create; if NS_FAILED(NS_CStringContainerInit(FContainer)) then Error(reOutOfMemory); FOwn := True; FString := @FContainer; Assign(src); end; constructor TIUTF8StringImpl.Relate(src: nsAUTF8String; own: Boolean); begin inherited Create; FString := src; FOwn := own; end; destructor TIUTF8StringImpl.Destroy; begin if FOwn then NS_CStringContainerFinish(FString^); inherited Destroy; end; function TIUTF8StringImpl.Length: Longword; var temp: PAnsiChar; begin Result := NS_CStringGetData(FString, temp); end; procedure TIUTF8StringImpl.Cut(cutStart: Cardinal; cutLength: Cardinal); begin NS_CStringCutData(FString, cutStart, cutLength); end; procedure TIUTF8StringImpl.Assign(Source: IInterfacedUTF8String); begin NS_CStringCopy(FString, Source.AUTF8String); end; procedure TIUTF8StringImpl.Assign(const Source: nsAUTF8String); begin NS_CStringCopy(FString, Source); end; procedure TIUTF8StringImpl.Assign(Source: UTF8String); begin NS_CStringSetData(FString, PAnsiChar(Source)); end; procedure TIUTF8StringImpl.Append(Source: IInterfacedUTF8String); begin NS_CStringAppendData(FString, PAnsiChar(Source.ToString)); end; procedure TIUTF8StringImpl.Append(const Source: nsAUTF8String); var src2: PAnsiChar; begin NS_CStringGetData(source, src2); NS_CStringAppendData(FString, src2); end; procedure TIUTF8StringImpl.Append(Source: UTF8String); begin NS_CStringAppendData(FString, PAnsiChar(Source)); end; procedure TIUTF8StringImpl.Insert(Source: IInterfacedUTF8String; aPosition: Longword); begin NS_CStringInsertData(FString, aPosition, PAnsiChar(Source.ToString)); end; procedure TIUTF8StringImpl.Insert(const Source: nsAUTF8String; aPosition: Longword); var src2: PAnsiChar; begin NS_CStringGetData(source, src2); NS_CStringInsertData(FString, aPosition, src2); end; procedure TIUTF8StringImpl.Insert(Source: UTF8String; aPosition: Longword); begin NS_CStringInsertData(FString, aPosition, PAnsiChar(Source)); end; procedure TIUTF8StringImpl.Replace(aPosition, aLength: Longword; Source: IInterfacedUTF8String); var src2: PAnsiChar; begin NS_CStringGetData(source.AUTF8String, src2); NS_CStringSetDataRange(FString, aPosition, aLength, src2); end; procedure TIUTF8StringImpl.Replace(aPosition, aLength: Longword; const Source: nsAUTF8String); var src2: PAnsiChar; begin NS_CStringGetData(source, src2); NS_CStringSetDataRange(FString, aPosition, aLength, src2); end; function TIUTF8StringImpl.AUTF8String: nsAUTF8String; begin Result := FString; end; function TIUTF8StringImpl.ToUTF8String:UTF8String; var p:PAnsiChar; l:Longword; begin l:=NS_CStringGetData(FString,p); SetLength(Result,l); Move(p^,Result[1],l); 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 correlation; interface uses Math, Sysutils, Ap; function PearsonCorrelation(const X : TReal1DArray; const Y : TReal1DArray; N : AlglibInteger):Double; function SpearmanRankCorrelation(X : TReal1DArray; Y : TReal1DArray; N : AlglibInteger):Double; implementation procedure RankX(var X : TReal1DArray; N : AlglibInteger);forward; (************************************************************************* Pearson product-moment correlation coefficient Input parameters: X - sample 1 (array indexes: [0..N-1]) Y - sample 2 (array indexes: [0..N-1]) N - sample size. Result: Pearson product-moment correlation coefficient -- ALGLIB -- Copyright 09.04.2007 by Bochkanov Sergey *************************************************************************) function PearsonCorrelation(const X : TReal1DArray; const Y : TReal1DArray; N : AlglibInteger):Double; var I : AlglibInteger; XMean : Double; YMean : Double; S : Double; XV : Double; YV : Double; T1 : Double; T2 : Double; begin XV := 0; YV := 0; if N<=1 then begin Result := 0; Exit; end; // // Mean // XMean := 0; YMean := 0; I:=0; while I<=N-1 do begin XMean := XMean+X[I]; YMean := YMean+Y[I]; Inc(I); end; XMean := XMean/N; YMean := YMean/N; // // numerator and denominator // S := 0; XV := 0; YV := 0; I:=0; while I<=N-1 do begin T1 := X[I]-XMean; T2 := Y[I]-YMean; XV := XV+AP_Sqr(T1); YV := YV+AP_Sqr(T2); S := S+T1*T2; Inc(I); end; if AP_FP_Eq(XV,0) or AP_FP_Eq(YV,0) then begin Result := 0; end else begin Result := S/(Sqrt(XV)*Sqrt(YV)); end; end; (************************************************************************* Spearman's rank correlation coefficient Input parameters: X - sample 1 (array indexes: [0..N-1]) Y - sample 2 (array indexes: [0..N-1]) N - sample size. Result: Spearman's rank correlation coefficient -- ALGLIB -- Copyright 09.04.2007 by Bochkanov Sergey *************************************************************************) function SpearmanRankCorrelation(X : TReal1DArray; Y : TReal1DArray; N : AlglibInteger):Double; begin X := DynamicArrayCopy(X); Y := DynamicArrayCopy(Y); RankX(X, N); RankX(Y, N); Result := PearsonCorrelation(X, Y, N); end; (************************************************************************* Internal ranking subroutine *************************************************************************) procedure RankX(var X : TReal1DArray; N : AlglibInteger); var I : AlglibInteger; J : AlglibInteger; K : AlglibInteger; T : AlglibInteger; Tmp : Double; TmpI : AlglibInteger; R : TReal1DArray; C : TInteger1DArray; begin // // Prepare // if N<=1 then begin X[0] := 1; Exit; end; SetLength(R, N-1+1); SetLength(C, N-1+1); I:=0; while I<=N-1 do begin R[I] := X[I]; C[I] := I; Inc(I); end; // // sort {R, C} // if N<>1 then begin i := 2; repeat t := i; while t<>1 do begin k := t div 2; if AP_FP_Greater_Eq(R[k-1],R[t-1]) then begin t := 1; end else begin Tmp := R[k-1]; R[k-1] := R[t-1]; R[t-1] := Tmp; TmpI := C[k-1]; C[k-1] := C[t-1]; C[t-1] := TmpI; t := k; end; end; i := i+1; until not (i<=N); i := N-1; repeat Tmp := R[i]; R[i] := R[0]; R[0] := Tmp; TmpI := C[i]; C[i] := C[0]; C[0] := TmpI; t := 1; while t<>0 do begin k := 2*t; if k>i then begin t := 0; end else begin if k<i then begin if AP_FP_Greater(R[k],R[k-1]) then begin k := k+1; end; end; if AP_FP_Greater_Eq(R[t-1],R[k-1]) then begin t := 0; end else begin Tmp := R[k-1]; R[k-1] := R[t-1]; R[t-1] := Tmp; TmpI := C[k-1]; C[k-1] := C[t-1]; C[t-1] := TmpI; t := k; end; end; end; i := i-1; until not (i>=1); end; // // compute tied ranks // I := 0; while I<=N-1 do begin J := I+1; while J<=N-1 do begin if AP_FP_Neq(R[J],R[I]) then begin Break; end; J := J+1; end; K:=I; while K<=J-1 do begin R[K] := 1+AP_Double((I+J-1))/2; Inc(K); end; I := J; end; // // back to x // I:=0; while I<=N-1 do begin X[C[I]] := R[I]; Inc(I); end; end; end.
(***************************************************************** * DECLARATIONS * *****************************************************************) program chapter1 (input, output); (* ... *) type (* ... *) BUILTINOP = (IFOP,WHILEOP,SETOP,BEGINOP,PLUSOP,MINUSOP, TIMESOP,DIVOP,EQOP,LTOP,GTOP,PRINTOP); VALUEOP = PLUSOP .. PRINTOP; CONTROLOP = IFOP .. BEGINOP; EXP = ^EXPREC; EXPLIST = ^EXPLISTREC; ENV = ^ENVREC; VALUELIST = ^VALUELISTREC; NAMELIST = ^NAMELISTREC; FUNDEF = ^FUNDEFREC; EXPTYPE = (VALEXP,VAREXP,APEXP); EXPREC = record case etype: EXPTYPE of VALEXP: (num: NUMBER); VAREXP: (varble: NAME); APEXP: (optr: NAME; args: EXPLIST) end; EXPLISTREC = record head: EXP; tail: EXPLIST end; VALUELISTREC = record head: NUMBER; tail: VALUELIST end; NAMELISTREC = record head: NAME; tail: NAMELIST end; ENVREC = record vars: NAMELIST; values: VALUELIST end; FUNDEFREC = record funname: NAME; formals: NAMELIST; body: EXP; nextfundef: FUNDEF end; var fundefs: FUNDEF; globalEnv: ENV; currentExp: EXP; userinput: array [1..MAXINPUT] of char; (* ... *) (***************************************************************** * DATA STRUCTURE OP'S * *****************************************************************) (* mkVALEXP - return an EXP of type VALEXP with num n *) function mkVALEXP (n: NUMBER): EXP; (* mkVAREXP - return an EXP of type VAREXP with varble nm *) function mkVAREXP (nm: NAME): EXP; (* mkAPEXP - return EXP of type APEXP w/ optr op and args el *) function mkAPEXP (op: NAME; el: EXPLIST): EXP; (* mkExplist - return an EXPLIST with head e and tail el *) function mkExplist (e: EXP; el: EXPLIST): EXPLIST; (* mkNamelist - return a NAMELIST with head n and tail nl *) function mkNamelist (nm: NAME; nl: NAMELIST): NAMELIST; (* mkValuelist - return an VALUELIST with head n and tail vl *) function mkValuelist (n: NUMBER; vl: VALUELIST): VALUELIST; (* mkEnv - return an ENV with vars nl and values vl *) function mkEnv (nl: NAMELIST; vl: VALUELIST): ENV; (* lengthVL - return length of VALUELIST vl *) function lengthVL (vl: VALUELIST): integer; (* lengthNL - return length of NAMELIST nl *) function lengthNL (nl: NAMELIST): integer; (***************************************************************** * NAME MANAGEMENT * *****************************************************************) (* fetchFun - get function definition of fname from fundefs *) function fetchFun (fname: NAME): FUNDEF; (* newFunDef - add new function fname w/ parameters nl, body e *) procedure newFunDef (fname: NAME; nl: NAMELIST; e: EXP); (* initNames - place all pre-defined names into printNames *) procedure initNames; (* install - insert new name into printNames *) function install (nm: NAMESTRING): NAME; (* prName - print name nm *) procedure prName (nm: NAME); (* primOp - translate NAME optr to corresponding BUILTINOP *) function primOp (optr: NAME): BUILTINOP; (***************************************************************** * INPUT * *****************************************************************) (* isDelim - check if c is a delimiter *) function isDelim (c: char): Boolean; (* skipblanks - return next non-blank position in userinput *) function skipblanks (p: integer): integer; (* matches - check if string nm matches userinput[s .. s+leng] *) function matches (s: integer; leng: NAMESIZE; (* reader - read char's into userinput; be sure input not blank *) procedure reader; (* readInput - read char's into userinput *) procedure readInput; (* nextchar - read next char - filter tabs and comments *) procedure nextchar (var c: char); (* readParens - read char's, ignoring newlines, to matching ')' *) procedure readParens; (* parseName - return (installed) NAME starting at userinput[pos]*) function parseName: NAME; (* isNumber - check if a number begins at pos *) function isNumber (pos: integer): Boolean; (* isDigits - check if sequence of digits begins at pos *) function isDigits (pos: integer): Boolean; (* parseVal - return number starting at userinput[pos] *) function parseVal: NUMBER; function parseEL: EXPLIST; forward; (* parseExp - return EXP starting at userinput[pos] *) function parseExp: EXP; var nm: NAME; el: EXPLIST; begin if userinput[pos] = '(' then begin (* APEXP *) pos := skipblanks(pos+1); (* skip '( ..' *) nm := parseName; el := parseEL; parseExp := mkAPEXP(nm, el) end else if isNumber(pos) then parseExp := mkVALEXP(parseVal) (* VALEXP *) else parseExp := mkVAREXP(parseName) (* VAREXP *) end; (* parseExp *) (* parseEL - return EXPLIST starting at userinput[pos] *) function parseEL; (* parseNL - return NAMELIST starting at userinput[pos] *) function parseNL: NAMELIST; (* parseDef - parse function definition at userinput[pos] *) function parseDef: NAME; (***************************************************************** * ENVIRONMENTS * *****************************************************************) (* emptyEnv - return an environment with no bindings *) function emptyEnv: ENV; (* bindVar - bind variable nm to value n in environment rho *) procedure bindVar (nm: NAME; n: NUMBER; rho: ENV); (* findVar - look up nm in rho *) function findVar (nm: NAME; rho: ENV): VALUELIST; (* assign - assign value n to variable nm in rho *) procedure assign (nm: NAME; n: NUMBER; rho: ENV); (* fetch - return number bound to nm in rho *) function fetch (nm: NAME; rho: ENV): NUMBER; (* isBound - check if nm is bound in rho *) function isBound (nm: NAME; rho: ENV): Boolean; (***************************************************************** * NUMBERS * *****************************************************************) (* prValue - print number n *) procedure prValue (n: NUMBER); (* isTrueVal - return true if n is a true (non-zero) value *) function isTrueVal (n: NUMBER): Boolean; (* applyValueOp - apply VALUEOP op to arguments in VALUELIST vl *) function applyValueOp (op: VALUEOP; vl: VALUELIST): NUMBER; (* arity - return number of arguments expected by op *) function arity (op: VALUEOP): integer; (* ... *) begin (* applyValueOp *) if arity(op) <> lengthVL(vl) then begin write('Wrong number of arguments to '); prName(ord(op)+1); writeln; goto 99 end; n1 := vl^.head; (* 1st actual *) if arity(op) = 2 then n2 := vl^.tail^.head; (* 2nd actual *) case op of PLUSOP: n := n1+n2; MINUSOP: n := n1-n2; TIMESOP: n := n1*n2; DIVOP: n := n1 div n2; EQOP: if n1 = n2 then n := 1 else n := 0; LTOP: if n1 < n2 then n := 1 else n := 0; GTOP: if n1 > n2 then n := 1 else n := 0; PRINTOP: begin prValue(n1); writeln; n := n1 end end; (* case *) applyValueOp := n end; (* applyValueOp *) (***************************************************************** * EVALUATION * *****************************************************************) (* eval - return value of expression e in local environment rho *) function eval (e: EXP; rho: ENV): NUMBER; var op: BUILTINOP; (* evalList - evaluate each expression in el *) function evalList (el: EXPLIST): VALUELIST; (* applyUserFun - look up definition of nm and apply to actuals *) function applyUserFun (nm: NAME; actuals: VALUELIST): NUMBER; (* applyCtrlOp - apply CONTROLOP op to args in rho *) function applyCtrlOp (op: CONTROLOP; args: EXPLIST): NUMBER; begin (* eval *) with e^ do case etype of VALEXP: eval := num; VAREXP: if isBound(varble, rho) then eval := fetch(varble, rho) else if isBound(varble, globalEnv) then eval := fetch(varble, globalEnv) else begin write('Undefined variable: '); prName(varble); writeln; goto 99 end; APEXP: if optr > numBuiltins then eval := applyUserFun(optr, evalList(args)) else begin op := primOp(optr); if op in [IFOP .. BEGINOP] then eval := applyCtrlOp(op, args) else eval := applyValueOp(op, evalList(args)) end end (* case and with *) end; (* eval *) (***************************************************************** * READ-EVAL-PRINT LOOP * *****************************************************************) begin (* chapter1 main *) initNames; globalEnv := emptyEnv; quittingtime := false; 99: while not quittingtime do begin reader; if matches(pos, 4, 'quit ') then quittingtime := true else if (userinput[pos] = '(') and matches(skipblanks(pos+1), 6, 'define ') then begin prName(parseDef); writeln end else begin currentExp := parseExp; prValue(eval(currentExp, emptyEnv)); writeln; writeln end end (* while *) end. (* chapter1 *)
unit RarView_u; interface Uses SysUtils, DFUnRar, Classes, Advanced; Type TRarFileInfo=Packed Record FileName,Pach:String; Size:LongWord; PackedSize:LongWord; CRC:LongWord; CreationTime, ModifyTime, AccessTime:TDateTime; Attr:String; End; Type TShowFileInfo=procedure (Sender:TObject;FileInfo:TRarFileInfo)Of Object; Type TRarViewer=Class(TComponent) Private dfUnRar:TDFUnRar; fArchiveFileName:String; FilterDir:String; fComment:String; DirList:TStringList; fOnShowInfo:TShowFileInfo; procedure FillDirectories(Sender: TObject; hdrData: TDFRARHeaderData; status: Integer); procedure ShowFiles(Sender: TObject; hdrData: TDFRARHeaderData; status: Integer); Public constructor Create; property FileName:String read fArchiveFileName write fArchiveFileName; property Dirs:TStringList read DirList write DirList; property OnShowFileInfo:TShowFileInfo read fOnShowInfo write fOnShowInfo; property Comment:String read fComment write fComment; procedure GetDirs; procedure GetFilesFromDir(Dir:String); procedure Free; destructor Destroy; End; implementation Constructor TRarViewer.Create; Begin dfUnRar:=TDFUnRar.Create(Self); DirList:=TStringList.Create; End; Procedure TRarViewer.GetDirs; Begin dfUnRar.FileName:=fArchiveFileName; fComment:=dfUnRar.ArchivComment; dfUnRar.OnFileProcessing:=FillDirectories; dfUnRar.Mode:=DFRAR_LIST; dfUnRar.StopProcessing:=False; dfUnRar.OverrideEvent:=OR_EVENT; dfUnRar.Extract; End; Procedure TRarViewer.GetFilesFromDir(Dir:String); Begin dfUnRar.FileName:=fArchiveFileName; FilterDir:=Dir; dfUnRar.OnFileProcessing:=ShowFiles; dfUnRar.Mode:=DFRAR_LIST; dfUnRar.StopProcessing:=False; dfUnRar.OverrideEvent:=OR_EVENT; dfUnRar.Extract; End; procedure TRarViewer.ShowFiles(Sender: TObject; hdrData: TDFRARHeaderData; status: Integer); Var FileInfo:TRarFileInfo; fAttr:String; begin If UpperCase(ExtractFileDir(hdrData.FileName))<>UpperCase(FilterDir) Then Exit; {showmessage(filterdir); showmessage(ExtractFileDir(hdrData.FileName));} If hdrData.FADirectory Then Exit; fAttr:=''; if hdrData.FAArchive then FAttr := FAttr + 'A'; if hdrData.FACompressed then FAttr := FAttr + 'C'; if hdrData.FADirectory then FAttr := FAttr + 'D'; if hdrData.FAHidden then FAttr := FAttr + 'H'; if hdrData.FANormal then FAttr := FAttr + 'N'; if hdrData.FAOffLine then FAttr := FAttr + 'O'; if hdrData.FAReadOnly then FAttr := FAttr + 'R'; if hdrData.FASystem then FAttr := FAttr + 'S'; if hdrData.FATempporary then FAttr := FAttr + 'T'; // FileInfo.FileName:=ExtractFileName(hdrData.FileName); FileInfo.Pach:=ExtractFilePath(hdrData.FileName); FileInfo.Size:=hdrData.UnpSize; FileInfo.PackedSize:=hdrData.PackSize; FileInfo.CRC:=StrToInt('$'+hdrData.FileCRC); FileInfo.CreationTime:=hdrData.FileTime; FileInfo.ModifyTime:=hdrData.FileTime; FileInfo.AccessTime:=hdrData.FileTime; FileInfo.Attr:=fAttr; If Assigned(fOnShowInfo) Then fOnShowInfo(Self,FileInfo); end; procedure TRarViewer.FillDirectories(Sender: TObject; hdrData: TDFRARHeaderData; status: Integer); var Root:String; begin Root:=Format(RootCaption,[ExtractFileName(fArchiveFileName)]); If DirList.Count=0 Then DirList.Add(Root); If Not TextInList(Root+'\'+ExtractFileDir(hdrData.FileName),DirList) Then DirList.Add(Root+'\'+ExtractFileDir(hdrData.FileName)) end; Procedure TRarViewer.Free; Begin If Self<> Nil Then Destroy; End; Destructor TRarViewer.Destroy; Begin dfUnRar.Free; DirList.Free; End; end.
unit uCodigoBarrasCanvas; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm1 = class(TForm) img1: TImage; btn1: TButton; procedure btn1Click(Sender: TObject); Procedure GerarCodigo(Codigo: String; Canvas : TCanvas); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btn1Click(Sender: TObject); begin GerarCodigo('4534838234858458483843843843', img1.Canvas); end; Procedure TForm1.GerarCodigo(Codigo: String; Canvas : TCanvas); { Procedimento para gerar a imagem de código de barras para ser impresso. Basta Colocar um componente tImage* no form e chamar o procedimento da seguinte forma: GerarCodigo('123456', image1.Canvas); *Na verdade você pode desenhar no canvas de qualquer componete, inclusive no componente qrImage para posterior impressão. } const digitos : array['0'..'9'] of string[5]= ('00110', '10001', '01001', '11000', '00101', '10100', '01100', '00011', '10010', '01010'); var s : string; i, j, x, t : Integer; begin // Gerar o valor para desenhar o código de barras // Caracter de início s := '0000'; for i := 1 to length(codigo) div 2 do for j := 1 to 5 do s := s + Copy(Digitos[codigo[i * 2 - 1]], j, 1) + Copy(Digitos[codigo[i * 2]], j, 1); // Caracter de fim s := s + '100'; // Desenhar em um objeto canvas // Configurar os parâmetros iniciais x := 0; // Pintar o fundo do código de branco Canvas.Brush.Color := clWhite; Canvas.Pen.Color := clWhite; Canvas.Rectangle(0,0, 2000, 79); // Definir as cores da caneta Canvas.Brush.Color := clBlack; Canvas.Pen.Color := clBlack; // Escrever o código de barras no canvas for i := 1 to length(s) do begin // Definir a espessura da barra t := strToInt(s[i]) * 2 + 1; // Imprimir apenas barra sim barra não (preto/branco - intercalado); if i mod 2 = 1 then Canvas.Rectangle(x, 0, x + t, 79); // Passar para a próxima barra x := x + t; end; //By Renato Félix de Almeida end; end.
program VirusSpread; (* DICTIONARY *) uses sysutils; const FILENAME = 'city.txt'; var Size : integer; InFile : TextFile; Map : array of array of char; i, j : integer; temp : char; VirusCount : integer; Days : integer; (* MAIN PROGRAM *) Begin //FILE INIT assign(InFile,FILENAME); reset(InFile); readln(InFile, Size); setlength(Map,Size,Size); VirusCount := 0; i := 0; j := 0; //INPUT while not eof(InFile) do begin read(InFile, temp); if (temp = 'H') OR (temp = 'U') then begin Map[i,j] := temp; j := j + 1; if temp = 'U' then VirusCount := VirusCount + 1; end; if j = Size then begin j := 0; i := i + 1; end; end; writeln('Matrix loaded!'); close(InFile); //PROSES Days := 0; while (VirusCount < Size*Size) do begin //Begin the spreading - marked by X. for i := 0 to Size-1 do begin for j := 0 to Size-1 do begin //If tile is 'U' (virus), then spread it to adjacent tiles, except out of bounds and already infected. if (Map[i,j] = 'U') then begin if ((i-1) >= 0) then begin if((Map[i-1,j] <> 'U') AND (Map[i-1,j] <> 'X')) then begin Map[i-1,j] := 'X'; VirusCount := VirusCount + 1; end; if ((j-1) >= 0) then begin if((Map[i-1,j-1] <> 'U') AND (Map[i-1,j-1] <> 'X')) then begin Map[i-1,j-1] := 'X'; VirusCount := VirusCount + 1; end; end; if ((j+1) < Size) then begin if((Map[i-1,j+1] <> 'U') AND (Map[i-1,j+1] <> 'X')) then begin Map[i-1,j+1] := 'X'; VirusCount := VirusCount + 1; end; end; end; if ((i+1) < Size) then begin if((Map[i+1,j] <> 'U') AND (Map[i+1,j] <> 'X')) then begin Map[i+1,j] := 'X'; VirusCount := VirusCount + 1; end; if ((j-1) >= 0) then begin if((Map[i+1,j-1] <> 'U') AND (Map[i+1,j-1] <> 'X')) then begin Map[i+1,j-1] := 'X'; VirusCount := VirusCount + 1; end; end; if ((j+1) < Size) then begin if((Map[i+1,j+1] <> 'U') AND (Map[i+1,j+1] <> 'X')) then begin Map[i+1,j+1] := 'X'; VirusCount := VirusCount + 1; end; end; end; if ((j-1) >= 0) then begin if((Map[i,j-1] <> 'U') AND (Map[i,j-1] <> 'X')) then begin Map[i,j-1] := 'X'; VirusCount := VirusCount + 1; end; end; if ((j+1) < Size) then begin if((Map[i,j+1] <> 'U') AND (Map[i,j+1] <> 'X')) then begin Map[i,j+1] := 'X'; VirusCount := VirusCount + 1; end; end; end; end; end; //Add a day, replace all Xs with Us. Days := Days + 1; for i:= 0 to Size-1 do begin for j := 0 to Size-1 do begin if(Map[i,j] = 'X') then Map[i,j] := 'U'; end; end; end; writeln('Lama waktu apocalypse adalah ', Days, ' hari'); End.
{ TServiceInfo Component Version 1.1 - Suite GLib Copyright (©) 2009, by Germán Estévez (Neftalí) Representa los servicios en un sistema ejecutando Windows. Utilización/Usage: Basta con "soltar" el componente y activarlo. Place the component in the form and active it. MSDN Info: http://msdn.microsoft.com/en-us/library/aa394418(VS.85).aspx ========================================================================= IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones, errores y/o cualquier otro tipo de sugerencia envíame un mail a: german_ral@hotmail.com IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements, errors and/or any another type of suggestion send a mail to: german_ral@hotmail.com ========================================================================= @author Germán Estévez (Neftalí) @web http://neftali.clubDelphi.com - http://neftali-mirror.site11.com/ @cat Package GLib } unit CServiceInfo; { ========================================================================= TServiceInfo.pas Componente ======================================================================== Historia de las Versiones ------------------------------------------------------------------------ 08/01/2010 * Creación. ========================================================================= Errores detectados no corregidos ========================================================================= } //========================================================================= // // I N T E R F A C E // //========================================================================= interface uses Classes, Controls, CWMIBase; type //: Clase para definir las propiedades del componente. TServiceProperties = class(TPersistent) private FAcceptPause:boolean; FAcceptStop:boolean; FCaption:string; FCheckPoint:Longword; FCreationClassName:string; FDescription:string; FDesktopInteract:boolean; FDisplayName:string; FErrorControl:string; FExitCode:Longword; FInstallDate:TDateTime; FName:string; FPathName:string; FProcessId:Longword; FServiceSpecificExitCode:Longword; FServiceType:string; FStarted:boolean; FStartMode:string; FStartName:string; FState:string; FStatus:string; FSystemCreationClassName:string; FSystemName:string; FTagId:Longword; FWaitHint:Longword; private public published property AcceptPause:boolean read FAcceptPause write FAcceptPause stored False; property AcceptStop:boolean read FAcceptStop write FAcceptStop stored False; property Caption:string read FCaption write FCaption stored False; property CheckPoint:Longword read FCheckPoint write FCheckPoint stored False; property CreationClassName:string read FCreationClassName write FCreationClassName stored False; property Description:string read FDescription write FDescription stored False; property DesktopInteract:boolean read FDesktopInteract write FDesktopInteract stored False; property DisplayName:string read FDisplayName write FDisplayName stored False; property ErrorControl:string read FErrorControl write FErrorControl stored False; property ExitCode:Longword read FExitCode write FExitCode stored False; property InstallDate:TDateTime read FInstallDate write FInstallDate stored False; property Name:string read FName write FName stored False; property PathName:string read FPathName write FPathName stored False; property ProcessId:Longword read FProcessId write FProcessId stored False; property ServiceSpecificExitCode:Longword read FServiceSpecificExitCode write FServiceSpecificExitCode stored False; property ServiceType:string read FServiceType write FServiceType stored False; property Started:boolean read FStarted write FStarted stored False; property StartMode:string read FStartMode write FStartMode stored False; property StartName:string read FStartName write FStartName stored False; property State:string read FState write FState stored False; property Status:string read FStatus write FStatus stored False; property SystemCreationClassName:string read FSystemCreationClassName write FSystemCreationClassName stored False; property SystemName:string read FSystemName write FSystemName stored False; property TagId:Longword read FTagId write FTagId stored False; property WaitHint:Longword read FWaitHint write FWaitHint stored False; end; //: Implementación para el acceso vía WMI a la clase Win32_Service TServiceInfo = class(TWMIBase) private FServiceProperties: TServiceProperties; protected //: Rellenar las propiedades. procedure FillProperties(AIndex:integer); override; // propiedad Active procedure SetActive(const Value: Boolean); override; //: Clase para el componente. function GetWMIClass():string; override; //: Obtener el root. function GetWMIRoot():string; override; //: Limpiar las propiedades procedure ClearProps(); override; public // redefinido el constructor constructor Create(AOwner: TComponent); override; //: destructor destructor Destroy; override; // Obtener <ErrorControl> como string function GetErrorControlAsString(FErrorControl:integer):string; //: Método para Terminar un proceso y todos sus threads. function InterrogateService(AInstanceProp:string; AInstanceValue:Variant):integer; //: Método para poner en marcha un servicio. function StartService(AInstanceProp:string; AInstanceValue:Variant):integer; //: Método para parar un servicio. function StopService(AInstanceProp:string; AInstanceValue:Variant):integer; //: Método para parusar un servicio. function PauseService(AInstanceProp:string; AInstanceValue:Variant):integer; //: Método para reanudar un servicio. function ResumeService(AInstanceProp:string; AInstanceValue:Variant):integer; //: Método para cambiar la forma de iniciar un servicio. function ChangeStartModeService(AInstanceProp:string; AInstanceValue:Variant; StartMode:string):integer; published // propiedades de la Service property ServiceProperties:TServiceProperties read FServiceProperties write FServiceProperties; end; // Constantes para la propiedad ErrorControl const ENUM_STRING_ERRORCONTROL_0 = 'Success'; ENUM_STRING_ERRORCONTROL_1 = 'Not Supported'; ENUM_STRING_ERRORCONTROL_2 = 'Access Denied'; ENUM_STRING_ERRORCONTROL_3 = 'Dependent Services Running'; ENUM_STRING_ERRORCONTROL_4 = 'Invalid Service Control'; ENUM_STRING_ERRORCONTROL_5 = 'Service Cannot Accept Control'; ENUM_STRING_ERRORCONTROL_6 = 'Service Not Active'; ENUM_STRING_ERRORCONTROL_7 = 'Service Request Timeout'; ENUM_STRING_ERRORCONTROL_8 = 'Unknown Failure'; ENUM_STRING_ERRORCONTROL_9 = 'Path Not Found'; ENUM_STRING_ERRORCONTROL_10 = 'Service Already Running'; ENUM_STRING_ERRORCONTROL_11 = 'Service Database Locked'; ENUM_STRING_ERRORCONTROL_12 = 'Service Dependency Deleted'; ENUM_STRING_ERRORCONTROL_13 = 'Service Dependency Failure'; ENUM_STRING_ERRORCONTROL_14 = 'Service Disabled'; ENUM_STRING_ERRORCONTROL_15 = 'Service Logon Failure'; ENUM_STRING_ERRORCONTROL_16 = 'Service Marked For Deletion'; ENUM_STRING_ERRORCONTROL_17 = 'Service No Thread'; ENUM_STRING_ERRORCONTROL_18 = 'Status Circular Dependency'; ENUM_STRING_ERRORCONTROL_19 = 'Status Duplicate Name'; ENUM_STRING_ERRORCONTROL_20 = 'Status Invalid Name'; ENUM_STRING_ERRORCONTROL_21 = 'Status Invalid Parameter'; ENUM_STRING_ERRORCONTROL_22 = 'Status Invalid Service Account'; ENUM_STRING_ERRORCONTROL_23 = 'Status Service Exists'; ENUM_STRING_ERRORCONTROL_24 = 'Service Already Paused'; //========================================================================= // // I M P L E M E N T A T I O N // //========================================================================= implementation uses {Generales} Forms, Types, Windows, SysUtils, WbemScripting_TLB, {GLib} UProcedures, UConstantes, Dialogs; { TService } {-------------------------------------------------------------------------------} // Limpiar las propiedades procedure TServiceInfo.ClearProps; begin Self.ServiceProperties.FAcceptPause := False; Self.ServiceProperties.FAcceptStop := False; Self.ServiceProperties.FCaption := STR_EMPTY; Self.ServiceProperties.FCheckPoint := 0; Self.ServiceProperties.FCreationClassName := STR_EMPTY; Self.ServiceProperties.FDescription := STR_EMPTY; Self.ServiceProperties.FDesktopInteract := False; Self.ServiceProperties.FDisplayName := STR_EMPTY; Self.ServiceProperties.FErrorControl := STR_EMPTY; Self.ServiceProperties.FExitCode := 0; Self.ServiceProperties.FInstallDate := 0; Self.ServiceProperties.FName := STR_EMPTY; Self.ServiceProperties.FPathName := STR_EMPTY; Self.ServiceProperties.FProcessId := 0; Self.ServiceProperties.FServiceSpecificExitCode := 0; Self.ServiceProperties.FServiceType := STR_EMPTY; Self.ServiceProperties.FStarted := False; Self.ServiceProperties.FStartMode := STR_EMPTY; Self.ServiceProperties.FStartName := STR_EMPTY; Self.ServiceProperties.FState := STR_EMPTY; Self.ServiceProperties.FStatus := STR_EMPTY; Self.ServiceProperties.FSystemCreationClassName := STR_EMPTY; Self.ServiceProperties.FSystemName := STR_EMPTY; Self.ServiceProperties.FTagId := 0; Self.ServiceProperties.FWaitHint := 0; end; //: Constructor del componente constructor TServiceInfo.Create(AOwner: TComponent); begin inherited; Self.FServiceProperties := TServiceProperties.Create(); Self.MSDNHelp := 'http://msdn.microsoft.com/en-us/library/aa394418(VS.85).aspx'; end; // destructor del componente destructor TServiceInfo.Destroy(); begin // liberar FreeAndNil(Self.FServiceProperties); inherited; end; // Obtener la clase function TServiceInfo.GetWMIClass(): string; begin Result := WIN32_SERVICE_CLASS; end; // Obtener Root function TServiceInfo.GetWMIRoot(): string; begin Result := STR_CIM2_ROOT; end; // Active procedure TServiceInfo.SetActive(const Value: Boolean); begin // método heredado inherited; end; //: Rellenar las propiedades del componente. procedure TServiceInfo.FillProperties(AIndex: integer); var v:variant; vNull:boolean; vp:TServiceProperties; begin // Llamar al heredado (importante) inherited; // Rellenar propiedades... vp := Self.ServiceProperties; GetWMIPropertyValue(Self, 'AcceptPause', v, vNull); vp.FAcceptPause := VariantBooleanValue(v, vNull); GetWMIPropertyValue(Self, 'AcceptStop', v, vNull); vp.FAcceptStop := VariantBooleanValue(v, vNull); GetWMIPropertyValue(Self, 'Caption', v, vNull); vp.FCaption := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'CheckPoint', v, vNull); vp.FCheckPoint := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'CreationClassName', v, vNull); vp.FCreationClassName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'Description', v, vNull); vp.FDescription := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'DesktopInteract', v, vNull); vp.FDesktopInteract := VariantBooleanValue(v, vNull); GetWMIPropertyValue(Self, 'DisplayName', v, vNull); vp.FDisplayName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'ErrorControl', v, vNull); vp.FErrorControl := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'ExitCode', v, vNull); vp.FExitCode := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'InstallDate', v, vNull); if not vNull then begin vp.FInstallDate := EncodeDate(StrToInt(Copy(v, 1, 4)),StrToInt(Copy(v, 5, 2)),StrToInt(Copy(v, 7, 2))); end; GetWMIPropertyValue(Self, 'Name', v, vNull); vp.FName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'PathName', v, vNull); vp.FPathName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'ProcessId', v, vNull); vp.FProcessId := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'ServiceSpecificExitCode', v, vNull); vp.FServiceSpecificExitCode := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'ServiceType', v, vNull); vp.FServiceType := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'Started', v, vNull); vp.FStarted := VariantBooleanValue(v, vNull); GetWMIPropertyValue(Self, 'StartMode', v, vNull); vp.FStartMode := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'StartName', v, vNull); vp.FStartName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'State', v, vNull); vp.FState := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'Status', v, vNull); vp.FStatus := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'SystemCreationClassName', v, vNull); vp.FSystemCreationClassName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'SystemName', v, vNull); vp.FSystemName := VariantStrValue(v, vNull); GetWMIPropertyValue(Self, 'TagId', v, vNull); vp.FTagId := VariantIntegerValue(v, vNull); GetWMIPropertyValue(Self, 'WaitHint', v, vNull); vp.FWaitHint := VariantIntegerValue(v, vNull); end; function TServiceInfo.InterrogateService(AInstanceProp: string; AInstanceValue: Variant): integer; var arr:TArrVariant; v:variant; begin SetLength(arr, 0); // Ejecutar el proceso ExecuteClassMethod(Self, AInstanceProp, AInstanceValue, 'InterrogateService', [], arr, [], [], v); Result := v; end; //: Método para poner en marcha un servicio. function TServiceInfo.StartService(AInstanceProp: string; AInstanceValue: Variant): integer; var arr:TArrVariant; v:variant; begin SetLength(arr, 0); // Ejecutar el proceso ExecuteClassMethod(Self, AInstanceProp, AInstanceValue, 'StartService', [], arr, [], [], v); Result := v; end; //: Método para parar un servicio. function TServiceInfo.StopService(AInstanceProp:string; AInstanceValue:Variant):integer; var arr:TArrVariant; v:variant; begin SetLength(arr, 0); // Ejecutar el proceso ExecuteClassMethod(Self, AInstanceProp, AInstanceValue, 'StopService', [], arr, [], [], v); Result := v; end; //: Método para Pausar un servicio. function TServiceInfo.PauseService(AInstanceProp:string; AInstanceValue:Variant):integer; var arr:TArrVariant; v:variant; begin SetLength(arr, 0); // Ejecutar el proceso ExecuteClassMethod(Self, AInstanceProp, AInstanceValue, 'PauseService', [], arr, [], [], v); Result := v; end; //: Método para reanudar un servicio. function TServiceInfo.ResumeService(AInstanceProp:string; AInstanceValue:Variant):integer; var arr:TArrVariant; v:variant; begin SetLength(arr, 0); // Ejecutar el proceso ExecuteClassMethod(Self, AInstanceProp, AInstanceValue, 'ResumeService', [], arr, [], [], v); Result := v; end; //: Método para cambiar la forma de iniciar un servicio. function TServiceInfo.ChangeStartModeService(AInstanceProp: string; AInstanceValue: Variant; StartMode: string): integer; var arr:TArrVariant; v:variant; begin SetLength(arr, 1); arr[0] := StartMode; // Ejecutar el proceso ExecuteClassMethod(Self, AInstanceProp, AInstanceValue, 'ChangeStartMode', ['StartMode'], arr, [ptIn], [wbemCimtypeString], v); Result := v; end; function TServiceInfo.GetErrorControlAsString(FErrorControl:integer): string; begin case FErrorControl of 0: Result := ENUM_STRING_ERRORCONTROL_0; 1: Result := ENUM_STRING_ERRORCONTROL_1; 2: Result := ENUM_STRING_ERRORCONTROL_2; 3: Result := ENUM_STRING_ERRORCONTROL_3; 4: Result := ENUM_STRING_ERRORCONTROL_4; 5: Result := ENUM_STRING_ERRORCONTROL_5; 6: Result := ENUM_STRING_ERRORCONTROL_6; 7: Result := ENUM_STRING_ERRORCONTROL_7; 8: Result := ENUM_STRING_ERRORCONTROL_8; 9: Result := ENUM_STRING_ERRORCONTROL_9; 10: Result := ENUM_STRING_ERRORCONTROL_10; 11: Result := ENUM_STRING_ERRORCONTROL_11; 12: Result := ENUM_STRING_ERRORCONTROL_12; 13: Result := ENUM_STRING_ERRORCONTROL_13; 14: Result := ENUM_STRING_ERRORCONTROL_14; 15: Result := ENUM_STRING_ERRORCONTROL_15; 16: Result := ENUM_STRING_ERRORCONTROL_16; 17: Result := ENUM_STRING_ERRORCONTROL_17; 18: Result := ENUM_STRING_ERRORCONTROL_18; 19: Result := ENUM_STRING_ERRORCONTROL_19; 20: Result := ENUM_STRING_ERRORCONTROL_20; 21: Result := ENUM_STRING_ERRORCONTROL_21; 22: Result := ENUM_STRING_ERRORCONTROL_22; 23: Result := ENUM_STRING_ERRORCONTROL_23; 24: Result := ENUM_STRING_ERRORCONTROL_24; else Result := STR_EMPTY; end; end; end.
//Only compile for the OS X platform. {$IF ( (NOT Defined(MACOS)) OR (Defined(IOS)) )} {$MESSAGE Fatal 'AT.MacOS.Folders.pas only compiles for the OS X platform.'} {$ENDIF} // ****************************************************************** // // Program Name : Angelic Tech Mac OS X Library // Program Version: 2017 // Platform(s) : OS X // Framework : None // // Filename : AT.MacOS.Folders.pas // File Version : 2017.04 // Date Created : 13-Apr-2017 // Author : Matthew Vesperman // // Description: // // Mac OS X folder routines. // // Revision History: // // v1.00 : Initial version // // ****************************************************************** // // COPYRIGHT © 2017 - PRESENT Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // // ****************************************************************** /// <summary> /// Contains routines that return folder paths for the Mac OS X /// platform. /// </summary> unit AT.MacOS.Folders; interface /// <summary> /// <para> /// Calculates the path to the application's data folder. /// </para> /// <para> /// If the ACommon parameter is true, then we return a path /// under /Users/Shared/Library, otherwise we return a path /// under the user's library folder. /// </para> /// </summary> /// <param name="AAppID"> /// The name of the folder to store the application's data. /// </param> /// <param name="ACommon"> /// Specifies whether you want the shared folder or the user's /// folder. /// </param> /// <returns> /// <para> /// A String containing the application's data path. /// </para> /// <para> /// /Users/Shared/Library/Application Support/(AAppId) or /// /Users/(User Name)/Library/Application Support/(AAppId) /// </para> /// </returns> function GetAppDataDirectory(AAppID: String = ''; ACommon: Boolean = False): String; /// <summary>Retrieves the path to the app bundle's executable folder. /// </summary> /// <returns>A String containing the path to the bundle's executable folder. /// </returns> function GetAppDirectory: String; /// <summary>Retrieves the path to the app bundle's folder. /// </summary> /// <returns>A String containing the path to the bundle's folder. /// </returns> function GetBundleDirectory: String; /// <summary> /// <para> /// Calculates the path to the application's documents folder. /// </para> /// <para> /// If the ACommon parameter is true, then we return a path /// under /Users/Shared/Documents, otherwise we return a path /// under the user's documents folder. /// </para> /// </summary> /// <param name="ADocPath"> /// The name of the app's document folder. If an empty string is /// passed then the Documents folder will be returned. /// </param> /// <param name="ACommon"> /// Specifies whether you want the shared folder or the user's /// folder. /// </param> /// <returns> /// <para> /// A String containing the application's documents folder. /// </para> /// <para> /// /Users/Shared/Documents/(ADocPath) or /Users/(User /// Name)/Documents /(ADocPath) /// </para> /// </returns> function GetDocumentDirectory(const ADocPath: String = ''; ACommon: Boolean = False): String; /// <summary>Retrieves the path to the current user's home folder. /// </summary> /// <returns>A String containing the path to the current user's home folder. /// </returns> function GetHomeDirectory: String; implementation uses System.IOUtils, System.SysUtils, Macapi.CoreFoundation, Macapi.Foundation, Macapi.Helpers, AT.MacOS.App; //Load from Foundation library... function NSHomeDirectory: Pointer; cdecl; external '/System/Library/Frameworks/Foundation.framework/Foundation' name _PU + 'NSHomeDirectory'; function GetAppDataDirectory(AAppID: String = ''; ACommon: Boolean = False): String; begin //Determine if we need Common or User path... if (ACommon) then Result := '/Users/Shared/Library' //Common path... else Result := TPath.GetLibraryPath; //User's path... //Build app data path string... Result := IncludeTrailingPathDelimiter(Result); Result := Format('%sApplication Support', [Result]); Result := IncludeTrailingPathDelimiter(Result); if (NOT AAppID.IsEmpty) then begin Result := Format('%s%s', [Result, AAppID]); Result := IncludeTrailingPathDelimiter(Result); end; //Make sure the path actually exists... TDirectory.CreateDirectory(Result); end; function GetAppDirectory: String; var ABundle: NSBundle; AValue: String; begin //Get a reference to the app's bundle... ABundle := GetAppBundle; //Retrieve the bundle's executable path... AValue := NSStrToStr(ABundle.executablePath); Result := ExtractFileDir(AValue); end; function GetBundleDirectory: String; var ABundle: NSBundle; AValue: String; begin //Get a reference to the app's bundle... ABundle := GetAppBundle; //Retrieve the bundle's path... AValue:= NSStrToStr(ABundle.bundlePath); Result := AValue; end; function GetDocumentDirectory(const ADocPath: String = ''; ACommon: Boolean = False): String; begin if (ACommon) then Result := '/Users/Shared/Documents' else Result := TPath.GetDocumentsPath; Result := IncludeTrailingPathDelimiter(Result); if (NOT ADocPath.IsEmpty) then begin Result := Format('%s%s', [Result, ADocPath]); Result := IncludeTrailingPathDelimiter(Result); TDirectory.CreateDirectory(Result); end; end; function GetHomeDirectory: String; begin //Retrieve and return the current user's home folder... Result := String(TNSString.Wrap(NSHomeDirectory).UTF8String); end; end.
unit IdVCLPosixSupplemental; interface {$I IdCompilerDefines.inc} uses IdCTypes; //tcp.hh type {Supplemental stuff from netinet/tcp.h} {$EXTERNALSYM tcp_seq} tcp_seq = TIdC_UINT32; {$EXTERNALSYM tcp_cc} tcp_cc = TIdC_UINT32; //* connection count per rfc1644 */ {$EXTERNALSYM tcp6_seq} tcp6_seq = tcp_seq; //* for KAME src sync over BSD*'s */' + {stuff that may be needed for various socket functions. Much of this may be platform specific. Defined in netinet/tcp.h} const {$IFDEF BSD} //for BSD-based operating systems such as FreeBSD and Mac OS X {$EXTERNALSYM TCP_MAXSEG} TCP_MAXSEG = $02; //* set maximum segment size */ {$EXTERNALSYM TCP_NOPUSH} TCP_NOPUSH = $04 platform; //* don't push last block of write */ {$EXTERNALSYM TCP_NOOPT} TCP_NOOPT = $08; //* don't use TCP options */ {$ENDIF} {$IFDEF FREEBSD} //specific to FreeBSD {$EXTERNALSYM TCP_MD5SIG} TCP_MD5SIG = $10 platform; //* use MD5 digests (RFC2385) */ {$EXTERNALSYM TCP_INFO} TCP_INFO = $20 platform; //* retrieve tcp_info structure */ {$EXTERNALSYM TCP_CONGESTION} TCP_CONGESTION = $40 platform; //* get/set congestion control algorithm */ {$ENDIF} {$IFDEF DARWIN} //specific to Mac OS X {$EXTERNALSYM TCP_KEEPALIVE} TCP_KEEPALIVE = $10 platform; //* idle time used when SO_KEEPALIVE is enabled */ {$EXTERNALSYM TCP_CONNECTIONTIMEOUT} TCP_CONNECTIONTIMEOUT = $20 platform; //* connection timeout */ {$EXTERNALSYM TCPOPT_EOL} TCPOPT_EOL = 0 platform; {$EXTERNALSYM TCPOPT_NOP} TCPOPT_NOP = 1 platform; {$EXTERNALSYM TCPOPT_MAXSEG} TCPOPT_MAXSEG = 2 platform; {$EXTERNALSYM TCPOLEN_MAXSEG} TCPOLEN_MAXSEG = 4 platform; {$EXTERNALSYM TCPOPT_WINDOW} TCPOPT_WINDOW = 3 platform; {$EXTERNALSYM TCPOLEN_WINDOW} TCPOLEN_WINDOW = 3 platform; {$EXTERNALSYM TCPOPT_SACK_PERMITTED} TCPOPT_SACK_PERMITTED = 4 platform; //* Experimental */ {$EXTERNALSYM TCPOLEN_SACK_PERMITTED} TCPOLEN_SACK_PERMITTED = 2 platform; {$EXTERNALSYM TCPOPT_SACK} TCPOPT_SACK = 5 platform; //* Experimental */ {$EXTERNALSYM TCPOLEN_SACK} TCPOLEN_SACK = 8 platform; //* len of sack block */ {$EXTERNALSYM TCPOPT_TIMESTAMP} TCPOPT_TIMESTAMP = 8 platform; {$EXTERNALSYM TCPOLEN_TIMESTAMP} TCPOLEN_TIMESTAMP = 10 platform; {$EXTERNALSYM TCPOLEN_TSTAMP_APPA} TCPOLEN_TSTAMP_APPA = (TCPOLEN_TIMESTAMP+2) platform; //* appendix A */ {$EXTERNALSYM TCPOPT_TSTAMP_HDR} TCPOPT_TSTAMP_HDR = ((TCPOPT_NOP shl 24) or (TCPOPT_NOP shl 16) or (TCPOPT_TIMESTAMP shl 8) or (TCPOLEN_TIMESTAMP)) platform; {$EXTERNALSYM MAX_TCPOPTLEN} MAX_TCPOPTLEN = 40 platform; //* Absolute maximum TCP options len */ {$EXTERNALSYM TCPOPT_CC} TCPOPT_CC = 11 platform; //* CC options: RFC-1644 */ {$EXTERNALSYM TCPOPT_CCNEW} TCPOPT_CCNEW = 12 platform; {$EXTERNALSYM TCPOPT_CCECHO} TCPOPT_CCECHO = 13 platform; {$EXTERNALSYM TCPOLEN_CC} TCPOLEN_CC = 6 platform; {$EXTERNALSYM TCPOLEN_CC_APPA} TCPOLEN_CC_APPA = (TCPOLEN_CC+2); {$EXTERNALSYM TCPOPT_CC_HDR} function TCPOPT_CC_HDR(const ccopt : Integer) : Integer; inline; const {$EXTERNALSYM TCPOPT_SIGNATURE} TCPOPT_SIGNATURE = 19 platform; //* Keyed MD5: RFC 2385 */ {$EXTERNALSYM TCPOLEN_SIGNATURE} TCPOLEN_SIGNATURE = 18 platform; //* Option definitions */ {$EXTERNALSYM TCPOPT_SACK_PERMIT_HDR} TCPOPT_SACK_PERMIT_HDR = ((TCPOPT_NOP shl 24) or (TCPOPT_NOP shl 16) or (TCPOPT_SACK_PERMITTED shl 8) or TCPOLEN_SACK_PERMITTED) platform; {$EXTERNALSYM TCPOPT_SACK_HDR} TCPOPT_SACK_HDR = ((TCPOPT_NOP shl 24) or (TCPOPT_NOP shl 16) or (TCPOPT_SACK shl 8)) platform; //* Miscellaneous constants */ {$EXTERNALSYM MAX_SACK_BLKS} MAX_SACK_BLKS = 6 platform; //* Max # SACK blocks stored at sender side */ {$EXTERNALSYM TCP_MAX_SACK} TCP_MAX_SACK = 3 platform; //* MAX # SACKs sent in any segment */ // /* // * Default maximum segment size for TCP. // * With an IP MTU of 576, this is 536, // * but 512 is probably more convenient. // * This should be defined as MIN(512, IP_MSS - sizeof (struct tcpiphdr)). // */ {$EXTERNALSYM TCP_MSS} TCP_MSS = 512 platform; // /* // * TCP_MINMSS is defined to be 216 which is fine for the smallest // * link MTU (256 bytes, SLIP interface) in the Internet. // * However it is very unlikely to come across such low MTU interfaces // * these days (anno dato 2004). // * Probably it can be set to 512 without ill effects. But we play safe. // * See tcp_subr.c tcp_minmss SYSCTL declaration for more comments. // * Setting this to "0" disables the minmss check. // */ {$EXTERNALSYM TCP_MINMSS} TCP_MINMSS = 216 platform; // /* // * TCP_MINMSSOVERLOAD is defined to be 1000 which should cover any type // * of interactive TCP session. // * See tcp_subr.c tcp_minmssoverload SYSCTL declaration and tcp_input.c // * for more comments. // * Setting this to "0" disables the minmssoverload check. // */ {$EXTERNALSYM TCP_MINMSSOVERLOAD} TCP_MINMSSOVERLOAD = 1000 platform; // * // * Default maximum segment size for TCP6. // * With an IP6 MSS of 1280, this is 1220, // * but 1024 is probably more convenient. (xxx kazu in doubt) // * This should be defined as MIN(1024, IP6_MSS - sizeof (struct tcpip6hdr)) // */ {$EXTERNALSYM TCP6_MSS} TCP6_MSS = 1024 platform; {$EXTERNALSYM TCP_MAXWIN} TCP_MAXWIN = 65535 platform; //* largest value for (unscaled) window */ {$EXTERNALSYM TTCP_CLIENT_SND_WND} TTCP_CLIENT_SND_WND = 4096 platform; //* dflt send window for T/TCP client */ {$EXTERNALSYM TCP_MAX_WINSHIFT} TCP_MAX_WINSHIFT = 14 platform; //* maximum window shift */ {$EXTERNALSYM TCP_MAXBURST} TCP_MAXBURST = 4 platform; //* maximum segments in a burst */ {$EXTERNALSYM TCP_MAXHLEN} TCP_MAXHLEN = ($f shl 2) platform; //* max length of header in bytes */ {$ENDIF} {$IFDEF LINUX} //specific to Linux {$EXTERNALSYM TCP_MAXSEG} TCP_MAXSEG = 2; //* Limit MSS */ {$EXTERNALSYM TCP_CORK} TCP_CORK = 3 platform; //* Never send partially complete segments */ {$EXTERNALSYM TCP_KEEPIDLE} TCP_KEEPIDLE = 4 platform //* Start keeplives after this period */ {$EXTERNALSYM TCP_KEEPINTVL} TCP_KEEPINTVL = 5 platform; //* Interval between keepalives */ {$EXTERNALSYM TCP_KEEPCNT} TCP_KEEPCNT = 6 platform; //* Number of keepalives before death */ {$EXTERNALSYM TCP_SYNCNT} TCP_SYNCNT = 7 platform; //* Number of SYN retransmits */ {$EXTERNALSYM TCP_LINGER2} TCP_LINGER2 = 8 platform; //* Life time of orphaned FIN-WAIT-2 state */ {$EXTERNALSYM TCP_DEFER_ACCEPT} TCP_DEFER_ACCEPT = 9 platform; //* Wake up listener only when data arrive */ {$EXTERNALSYM TCP_WINDOW_CLAMP} TCP_WINDOW_CLAMP = 10 platform; //* Bound advertised window */ {$EXTERNALSYM TCP_WINDOW_CLAMP} TCP_INFO = 11 platform; //* Information about this connection. */ {$EXTERNALSYM TCP_QUICKACK} TCP_QUICKACK = 12 platform; //* Block/reenable quick acks */ {$EXTERNALSYM TCP_CONGESTION} TCP_CONGESTION = 13 platform; //* Congestion control algorithm */ {$EXTERNALSYM TCP_MD5SIG} TCP_MD5SIG = 14 platform; //* TCP MD5 Signature (RFC2385) */ {$EXTERNALSYM TCP_COOKIE_TRANSACTIONS} TCP_COOKIE_TRANSACTIONS = 15 platform; //* TCP Cookie Transactions */ {$EXTERNALSYM TCP_THIN_LINEAR_TIMEOUTS} TCP_THIN_LINEAR_TIMEOUTS = 16 platform; //* Use linear timeouts for thin streams*/ {$EXTERNALSYM TCP_THIN_DUPACK} TCP_THIN_DUPACK = 17 platform; //* Fast retrans. after 1 dupack */ {$EXTERNALSYM TCPI_OPT_TIMESTAMPS} TCPI_OPT_TIMESTAMPS = 1; {$EXTERNALSYM TCPI_OPT_SACK} TCPI_OPT_SACK = 2; {$EXTERNALSYM TCPI_OPT_WSCALE} TCPI_OPT_WSCALE = 4; {$EXTERNALSYM TCPI_OPT_ECN} TCPI_OPT_ECN = 8; {$ENDIF} //udp.h {$IFDEF DARWIN} {$EXTERNALSYM UDP_NOCKSUM} UDP_NOCKSUM = $01; //* don't checksum outbound payloads */ {$ENDIF} {$IFDEF LINUX} //* UDP socket options */ {$EXTERNALSYM UDP_CORK} UDP_CORK = 1; //* Never send partially complete segments */ {$EXTERNALSYM UDP_ENCAP} UDP_ENCAP = 100; //* Set the socket to accept encapsulated packets */ //* UDP encapsulation types */ {$EXTERNALSYM UDP_ENCAP_ESPINUDP_NON_IKE} UDP_ENCAP_ESPINUDP_NON_IKE = 1; //* draft-ietf-ipsec-nat-t-ike-00/01 */ {$EXTERNALSYM UDP_ENCAP_ESPINUDP} UDP_ENCAP_ESPINUDP = 2; //* draft-ietf-ipsec-udp-encaps-06 */ {$ENDIF} implementation {$IFDEF DARWIN} function TCPOPT_CC_HDR(const ccopt : Integer) : Integer; inline; begin Result := (TCPOPT_NOP shl 24) or (TCPOPT_NOP shl 16) or (ccopt shl 8) or TCPOLEN_CC; end; {$ENDIF} end.
{------------------------------------------------------------------------------- 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. Code template generated with SynGen. The original code is: SynHighlighterCobol.pas, released 2002-08-26. Description: COBOL Syntax Parser/Highlighter The author of this file is Andrey Ustinov. Copyright (c) 2002 Software Mining, http://www.softwaremining.com/. Unicode translation by Maël Hörz. All rights reserved. Contributors to the SynEdit and mwEdit projects are listed in the Contributors.txt file. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL"), in which case the provisions of the GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. $Id: SynHighlighterCobol.pas,v 1.5.2.6 2006/05/21 11:59:35 maelh Exp $ You may retrieve the latest version of this file at the SynEdit home page, located at http://SynEdit.SourceForge.net -------------------------------------------------------------------------------} unit SynHighlighterCobol; {$I SynEdit.inc} interface uses System.SysUtils, System.Classes, System.Generics.Defaults, System.Generics.Collections, Vcl.Graphics, SynEditTypes, SynEditHighlighter, System.RegularExpressions, SynEditCodeFolding; type TtkTokenKind = ( tkBracket, tkKey, tkIndicator, tkComment, tkIdentifier, tkAIdentifier, tkPreprocessor, tkBoolean, tkNull, tkNumber, tkSpace, tkString, tkSequence, tkTagArea, tkDebugLines, tkUnknown); TRangeState = (rsUnknown, rsQuoteString, rsApostString, rsPseudoText, rsQuoteStringMayBe, rsApostStringMayBe, rsComment, rsDebug); type // TSynCobolSyn = class(TSynCustomHighlighter) //++ CodeFolding TSynCobolSyn = class(TSynCustomCodeFoldingHighlighter) //-- CodeFolding private fRange: TRangeState; fTokenID: TtkTokenKind; fIndicator: WideChar; fCodeStartPos: Integer; fCodeMediumPos: Integer; fCodeEndPos: Integer; fCommentAttri: TSynHighlighterAttributes; fIdentifierAttri: TSynHighlighterAttributes; fAIdentifierAttri: TSynHighlighterAttributes; fPreprocessorAttri: TSynHighlighterAttributes; fKeyAttri: TSynHighlighterAttributes; fNumberAttri: TSynHighlighterAttributes; fBooleanAttri: TSynHighlighterAttributes; fSpaceAttri: TSynHighlighterAttributes; fStringAttri: TSynHighlighterAttributes; fSequenceAttri: TSynHighlighterAttributes; fIndicatorAttri: TSynHighlighterAttributes; fTagAreaAttri: TSynHighlighterAttributes; fDebugLinesAttri: TSynHighlighterAttributes; fBracketAttri: TSynHighlighterAttributes; FKeywords: TDictionary<String, TtkTokenKind>; //++ CodeFolding RE_BlockBegin : TRegEx; RE_BlockEnd : TRegEx; //-- CodeFolding procedure DoAddKeyword(AKeyword: string; AKind: integer); function IdentKind(MayBe: PWideChar): TtkTokenKind; procedure IdentProc; procedure UnknownProc; procedure NullProc; procedure SpaceProc; procedure CRProc; procedure LFProc; procedure NumberProc; procedure PointProc; procedure StringOpenProc; procedure StringProc; procedure StringEndProc; procedure FirstCharsProc; procedure LastCharsProc; procedure CommentProc; procedure InlineCommentProc; procedure DebugProc; procedure BracketProc; protected function GetSampleSource: string; override; function IsFilterStored: Boolean; override; procedure NextProcedure; procedure SetCodeStartPos(Value: Integer); procedure SetCodeMediumPos(Value: Integer); procedure SetCodeEndPos(Value: Integer); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; class function GetLanguageName: string; override; class function GetFriendlyLanguageName: string; override; function GetRange: Pointer; override; procedure ResetRange; override; procedure SetRange(Value: Pointer); override; function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; override; function GetEol: Boolean; override; function GetTokenID: TtkTokenKind; function GetTokenAttribute: TSynHighlighterAttributes; override; function GetTokenKind: integer; override; function IsIdentChar(AChar: WideChar): Boolean; override; procedure Next; override; //++ CodeFolding procedure ScanForFoldRanges(FoldRanges: TSynFoldRanges; LinesToScan: TStrings; FromLine: Integer; ToLine: Integer); override; //-- CodeFolding published property CommentAttri: TSynHighlighterAttributes read fCommentAttri write fCommentAttri; property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri write fIdentifierAttri; property AreaAIdentifierAttri: TSynHighlighterAttributes read fAIdentifierAttri write fAIdentifierAttri; property PreprocessorAttri: TSynHighlighterAttributes read fPreprocessorAttri write fPreprocessorAttri; property KeyAttri: TSynHighlighterAttributes read fKeyAttri write fKeyAttri; property NumberAttri: TSynHighlighterAttributes read fNumberAttri write fNumberAttri; property BooleanAttri: TSynHighlighterAttributes read fBooleanAttri write fBooleanAttri; property BracketAttri: TSynHighlighterAttributes read fBracketAttri write fBracketAttri; property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri write fSpaceAttri; property StringAttri: TSynHighlighterAttributes read fStringAttri write fStringAttri; property SequenceAttri: TSynHighlighterAttributes read fSequenceAttri write fSequenceAttri; property IndicatorAttri: TSynHighlighterAttributes read fIndicatorAttri write fIndicatorAttri; property TagAreaAttri: TSynHighlighterAttributes read fTagAreaAttri write fTagAreaAttri; property DebugLinesAttri: TSynHighlighterAttributes read fDebugLinesAttri write fDebugLinesAttri; property AreaAStartPos: Integer read fCodeStartPos write SetCodeStartPos; property AreaBStartPos: Integer read fCodeMediumPos write SetCodeMediumPos; property CodeEndPos: Integer read fCodeEndPos write SetCodeEndPos; end; implementation uses SynEditMiscProcs, SynEditStrConst; const BooleanWords: string = 'false, true'; KeyWords: string = '3d, absent, abstract, accept, access, acquire, action, action-copy, ' + 'action-current-page, action-cut, action-delete, action-first-page, ' + 'action-hide-drag, action-last-page, action-next, action-next-page, ' + 'action-paste, action-previous, action-previous-page, action-undo, active-class, ' + 'actual, add, address, adjustable-columns, advancing, afp-5a, after, aligned, ' + 'alignment, all, allocate, allow, allowing, alphabet, alphabetic, ' + 'alphabetic-lower, alphabetic-upper, alphanumeric, alphanumeric-edited, also, ' + 'alter, alternate, and, any, apply, are, area, areas, area-value, arithmetic, ' + 'as, ascending, assembly-attributes, assembly-name, assign, at, attribute, ' + 'attributes, author, auto, auto-decimal, auto-hyphen-skip, automatic, ' + 'auto-minimize, auto-resize, auto-skip, auto-spin, autoterminate, ' + 'background-color, background-colour, background-high, background-low, ' + 'background-standard, backward, b-and, bar, based, beep, before, beginning, ' + 'bell, b-exor, binary, binary-double, binary-char, binary-long, binary-short, ' + 'bind, bit, bitmap, bitmap-end, bitmap-frame, bitmap-handle, bitmap-load, ' + 'bitmap-number, bitmap-start, bitmap-timer, bitmap-trailing, bitmap-width, bits, ' + 'blank, b-left, b-less, blink, blinking, blob, blob-file, blob-locator, block, ' + 'b-not, bold, boolean, b-or, bottom, box, boxed, b-right, browser, browsing, ' + 'bulk-addition, busy, buttons, b-xor, by, c01, c02, c03, c04, c05, c06, c07, ' + 'c08, c09, c10, c11, c12, calendar-font, call, called, cancel, cancel-button, ' + 'card-punch, card-reader, case, cassette, catch, cbl-ctr, ccol, cd, cell, ' + 'cell-color, cell-data, cell-font, cell-protection, cells, center, centered, ' + 'centered-headings, century-date, century-day, cf, class, class-attributes, ' + 'class-control, class-id, class-name, class-object, clear-selection, cline, ' + 'clines, clob, clob-file, clob-locator, clock-units, close, cobol, code, ' + 'code-set, coercion, col, collating, color, colors, colour, cols, column, ' + 'column-color, column-dividers, column-font, column-headings, column-protection, ' + 'columns, combo-box, comma, command-line, commit, commitment, common, ' + 'communication, comp, comp-0, comp-1, comp-2, comp-3, comp-4, comp-5, comp-6, ' + 'comp-7, comp-8, comp-9, comp-n, compression, computational, computational-0, ' + 'computational-1, computational-2, computational-3, computational-4, ' + 'computational-5, computational-6, computational-7, computational-8, ' + 'computational-9, computational-n, computational-x, compute, comp-x, com-reg, ' + 'condition-value, configuration, connect, console, constant, constrain, ' + 'constraints, constructor, contained, contains, content, continue, control-area, ' + 'controls, conversion, convert, converting, copy-selection, core-index, corr, ' + 'corresponding, count, create, creating, crt, crt-under, csize, csp, culture, ' + 'currency, current, current-date, cursor, cursor-col, cursor-color, ' + 'cursor-frame-width, cursor-row, cursor-x, cursor-y, custom-attribute, ' + 'custom-print-template, cycle, cyl-index, cyl-overflow, dashed, data, ' + 'database-key, database-key-long, data-columns, data-pointer, date, ' + 'date-and-time, date-compiled, date-entry, date-record, date-written, ' + 'davf-hhmmss, davf-hhmmsshh, davf-yymmdd, davf-yyyymmdd, davf-yyyymmddhhmmsshh, ' + 'day, day-and-time, day-of-week, db, db-access-control-key, dbclob, dbclob-file, ' + 'dbclob-locator, dbcs, db-data-name, db-exception, db-format-name, ' + 'db-record-name, db-set-name, db-status, dd, de, debug, debug-contents, ' + 'debugging, debug-item, debug-line, debug-name, debug-sub-1, debug-sub-2, ' + 'debug-sub-3, decimal, decimal-point, declaratives, default, default-button, ' + 'definition, delegate, delegate-id, delimited, delimiter, depending, descending, ' + 'descriptor, destination, destroy, detail, disable, disc, disconnect, ' + 'disjoining, disk, disp, display, display-1, display-2, display-3, display-4, ' + 'display-5, display-6, display-7, display-8, display-9, display-columns, ' + 'display-format, display-st, divide, divider-color, dividers, division, ' + 'dot-dash, dotted, double, down, drag-color, draw, drop, drop-down, drop-list, ' + 'duplicate, duplicates, dynamic, ebcdic, egcs, egi, echo, element, else, emi, ' + 'empty, empty-check, enable, enabled, encoding, encryption, end, end-accept, ' + 'end-add, end-call, end-compute, end-delete, end-disable, end-display, ' + 'end-divide, end-enable, end-evaluate, end-exec, end-chain, endif, end-if, ' + 'ending, end-invoke, end-modify, end-move, end-multiply, end-of-page, ' + 'end-perform, end-read, end-receive, end-return, end-rewrite, end-search, ' + 'end-send, end-set, end-start, end-string, end-subtract, end-transceive, ' + 'end-try, end-unstring, end-use, end-wait, end-write, end-xml, engraved, ' + 'ensure-visible, enter, entry, entry-field, entry-reason, enum, enum-id, ' + 'environment, environment-name, environment-value, eol, eop, eos, equal, equals, ' + 'error, escape, escape-button, esi, evaluate, event, event-action-fail, ' + 'event-pointer, event-type, every, exact, examine, exceeds, exception, ' + 'exception-object, exception-value, excess-3, exclusive, exec, execute, exhibit, ' + 'exit, exit-pushed, expand, expands, extend, extended, extended-search, ' + 'external, external-form, externally-described-key, f, factory, fd, fetch, ' + 'fh--fcd, fh--keydef, file, file-control, file-id, file-name, file-path, ' + 'file-pos, file-prefix, fill-color, fill-color2, filler, fill-percent, final, ' + 'finally, find, finish, finish-reason, first, fixed, flat, flat-buttons, float, ' + 'float-extended, floating, float-long, float-short, font, footing, for, ' + 'foreground-color, foreground-colour, forever, form, format, frame, framed, ' + 'free, from, full, full-height, function, function-id, function-pointer, ' + 'generate, get, giving, global, go, goback, go-back, goforward, go-forward, ' + 'gohome, go-home, gosearch, go-search, graphical, grdsrch-found, ' + 'grdsrch-not-found, grdsrch-wrapped, greater, grid, grid-searchall, ' + 'grid-searchcolumn, grid-searchforwards, grid-searchhidden, grid-searchignore, ' + 'grid-searchmatch, grid-searchmoves, grid-searchskip, grid-searchvisible, ' + 'grid-searchwrap, grip, group, group-usage, group-value, handle, has-childen, ' + 'heading, heading-color, heading-divider-color, heading-font, headings, heavy, ' + 'height, help-id, hidden-data, high, high-color, highlight, horizontal, ' + 'hot-track, hscroll, hscroll-pos, ch, chain, chaining, changed, char, character, ' + 'characters, chart, char-varying, check-box, checked, checking, icon, id, ' + 'identification, identified, if, ignore, ignoring, implements, in, include, ' + 'independent, index, index-1, index-2, index-3, index-4, index-5, index-6, ' + 'index-7, index-8, index-9, indexed, indic, indicate, indicator, indicators, ' + 'inheriting, inherits, initial, initialize, initialized, initiate, input, ' + 'input-output, inquire, insertion-index, insert-rows, inspect, installation, ' + 'instance, interface, interface-id, internal, into, intrinsic, invalid, invoke, ' + 'invoked, i-o, i-o-control, is, item, item-text, item-to-add, item-to-delete, ' + 'item-to-empty, item-value, japanese, jcllib, job, joining, just, justified, ' + 'kanji, keep, kept, key, keyboard, key-yy, label, label-offset, last, last-row, ' + 'layout-data, layout-manager, ld, leading, leading-shift, leave, left, ' + 'left-justify, leftline, left-text, length, length-check, less, like, lin, ' + 'linage, linage-counter, line, line-counter, lines, lines-at-root, link, ' + 'linkage, list-box, locale, locally, local-storage, lock, lock-holding, locking, ' + 'long-date, long-varbinary, long-varchar, low, low-color, lower, lowered, ' + 'lowlight, magnetic-tape, manual, mass-update, master-index, max-lines, ' + 'max-text, max-val, max-value, member, memory, menu, merge, message, messages, ' + 'metaclass, method, method-id, methods, min-val, min-value, mixed, modal, mode, ' + 'modeless, modified, modify, modless, module, modules, monitor-pointer, ' + 'more-labels, move, msg-begin-entry, multiline, multiple, multiply, multline, ' + 'mutex-pointer, name, named, namespace, namespace-prefix, national, ' + 'national-edited, native, navigate, negative, nested, new, newable, next, ' + 'next-item, nextpage, nchar, no, no-auto-default, no-autosel, no-box, ' + 'no-dividers, no-echo, no-f4, no-focus, no-group-tab, no-key-letter, nominal, ' + 'none, nonnumeric, normal, no-search, not, no-tab, note, notify, ' + 'notify-dblclick, notify-change, notify-selchange, no-updown, nstd-reels, null, ' + 'nulls, number, num-col-headings, num-columns, numeric, numeric-edited, ' + 'numeric-fill, num-rows, object, object-computer, object-id, object-reference, ' + 'object-storage, occurs, of, off, o-fill, ok-button, omitted, on, only, ' + 'oostackptr, open, operator, operator-id, optional, options, or, order, ' + 'organization, other, others, otherwise, output, overflow, overlapped, overline, ' + 'override, owner, packed-decimal, padding, page, page-counter, paged, ' + 'paged-at-end, paged-at-start, paged-empty, page-setup, page-size, palette, ' + 'panel-index, panel-style, panel-text, panel-widht, paragraph, parse, partial, ' + 'password, pend, perform, pf, ph, pic, picture, pixel, pixels, placement, ' + 'pl-sort-default, pl-sort-native, pl-sort-native-ignore-case, pl-sort-none, ' + 'plus, pointer, pop-up, pos, position, positioning, position-shift, positive, ' + 'prefixing, present, previous, print, print-control, printer, printer-1, ' + 'printing, print-no-prompt, print-preview, print-switch, prior, priority, ' + 'private, proc, procedure, procedure-pointer, procedures, proceed, process, ' + 'processing, profile, program, program-id, program-pointer, prompt, properties, ' + 'property, protected, prototype, public, purge, push-button, query-index, queue, ' + 'quote, quotes, radio-button, raise, raised, raising, random, range, rd, read, ' + 'readers, reading, read-only, realm, receive, reconnect, record, record-data, ' + 'recording, record-name, record-overflow, record-position, records, ' + 'record-to-add, record-to-delete, recover, recovery, recursive, redefine, ' + 'redefines, redefinition, reel, reference, references, refresh, region-color, ' + 'relation, relative, release, remainder, remarks, removal, renames, ' + 'reorg-criteria, repeated, replacing, report, reporting, reports, repository, ' + 'required, reread, rerun, reserve, reset, reset-grid, reset-list, reset-tabs, ' + 'resident, resizable, resource, restricted, result-set-locator, resume, ' + 'retaining, retrieval, retry, return, return-code, returning, return-unsigned, ' + 'reverse, reversed, reverse-video, rewind, rewrite, rf, rh, right, right-align, ' + 'right-justify, right-text, rimmed, rollback, rolling, rounded, row-color, ' + 'row-color-pattern, row-dividers, row-font, row-headings, rowid, row-protection, ' + 'run, s, s01, s02, s03, s04, s05, same, save-as, save-as-no-prompt, screen, ' + 'scroll, scroll-bar, sd, search, search-options, search-text, seconds, section, ' + 'secure, security, seek, segment, segment-limit, select, select-all, ' + 'selection-index, selection-text, selective, self, self-act, selfclass, ' + 'semaphore-pointer, send, sentence, separate, separation, separator, sequence, ' + 'sequential, session-id, set, shading, shadow, shared, sharing, shift-in, ' + 'shift-out, short-date, show-lines, show-none, show-sel-always, sign, signed, ' + 'signed-int, signed-long, signed-short, singleline, size, solid, sort, ' + 'sort-control, sort-core-size, sort-file-size, sort-merge, sort-message, ' + 'sort-mode-size, sort-option, sort-order, sort-return, sort-tape, sort-tapes, ' + 'sort-work, source, source-computer, sources, space-fill, special-names, ' + 'spinner, sql, square, standard, standard-1, standard-2, standard-3, standard-4, ' + 'start, starting, start-x, start-y, static, static-list, status, status-bar, ' + 'step, stop, stop-browser, store, string, strong, strong-name, style, subfile, ' + 'subprogram, sub-queue-1, sub-queue-2, sub-queue-3, sub-schema, subtract, ' + 'subwindow, suffixing, sum, super, suppress, switch, switch-1, switch-2, ' + 'switch-3, switch-4, switch-5, switch-6, switch-7, switch-8, symbol, symbolic, ' + 'sync, synchronized, sysin, sysipt, syslist, syslst, sysout, syspch, syspunch, ' + 'system, system-default, system-info, tab, table, tabs, tab-to-add, ' + 'tab-to-delete, tally, tallying, tape, tapes, tenant, terminal, terminal-info, ' + 'terminate, termination, termination-value, test, text, than, then, thread, ' + 'thread-local, thread-local-storage, thread-pointer, threads, through, thru, ' + 'thumb-position, tiled-headings, time, time-of-day, timeout, time-out, ' + 'time-record, times, timestamp, timestamp-offset, timestamp-offset-record, ' + 'timestamp-record, title, title-bar, title-position, to, tool-bar, top, totaled, ' + 'totaling, trace, track-area, track-limit, tracks, track-thumb, trailing, ' + 'trailing-shift, trailing-sign, transaction, transaction-status, transceive, ' + 'transform, transparent, transparent-color, tree-view, try, tvni-first-visible, ' + 'tvni-child, tvni-next, tvni-next-visible, tvni-parent, tvni-previous, ' + 'tvni-previous-visible, tvni-root, tvplace-first, tvplace-last, tvplace-sort, ' + 'type, typedef, u, ucs-4, unbounded, underline, underlined, unequal, unframed, ' + 'unit, units, universal, unlock, unsigned, unsigned-int, unsigned-long, ' + 'unsigned-short, unsorted, unstring, until, up, update, updaters, upon, upper, ' + 'upsi-0, upsi-1, upsi-2, upsi-3, upsi-4, upsi-5, upsi-6, upsi-7, usage, ' + 'usage-mode, use, user, user-default, use-return, use-tab, using, utf-16, utf-8, ' + 'v, valid, validate, validating, value, value-default, value-format, ' + 'value-multiple, value-picture, valuetype, valuetype-id, value-variable, ' + 'varbinary, variable, varying, version, vertical, very-heavy, virtual-width, ' + 'visible, vpadding, vscroll, vscroll-bar, vscrool-pos, vtop, wait, when, ' + 'when-compiled, wide, width, window, with, within, words, working-storage, wrap, ' + 'write, write-only, writers, write-verify, writing, xml, xml-code, ' + 'xml-declaration, xml-event, xml-ntext, xml-schema, xml-text, yyyyddd, yyyymmdd, ' + 'zero-fill'; PreprocessorWords: string = 'basis, cbl, control, copy, delete, eject, erase, ready, reload, ' + 'replace, skip1, skip2, skip3'; StringWords: string = 'file-limit, file-limits, high-value, high-values, limit, limits, low-value, low-values, ' + 'space, spaces, values, zero, zeroes, zeros'; // Ambigious means that a simple string comparision is not enough AmbigiousWords: string = ''; const StringChars: array[TRangeState] of WideChar = (#0, '"', '''', '=', '"', '''', #0, #0); procedure TSynCobolSyn.DoAddKeyword(AKeyword: string; AKind: integer); begin if not FKeywords.ContainsKey(AKeyword) then FKeywords.Add(AKeyword, TtkTokenKind(AKind)); end; function TSynCobolSyn.IdentKind(MayBe: PWideChar): TtkTokenKind; var I: Integer; LRun: Integer; S: String; begin fToIdent := MayBe; LRun := Run; while IsIdentChar(MayBe^) and (LRun <= fCodeEndPos) do begin Inc(MayBe); inc(LRun); end; fStringLen := Maybe - fToIdent; SetString(S, fToIdent, fStringLen); if FKeywords.ContainsKey(S) then begin Result := FKeywords[S]; if Result = tkUnknown then // handling of "ambigious" words begin if IsCurrentToken('label') then begin I := Run + Length('label'); while fLine[I] = ' ' do Inc(I); if (AnsiStrLComp(PWideChar(@fLine[I]), 'record', Length('record')) = 0) and (I + Length('record') - 1 <= fCodeEndPos) then Result := tkKey else Result := tkPreprocessor; end else Result := tkIdentifier; end; end else Result := tkIdentifier; end; procedure TSynCobolSyn.SpaceProc; begin fTokenID := tkSpace; repeat inc(Run); until not CharInSet(fLine[Run], [#1..#32]); end; procedure TSynCobolSyn.FirstCharsProc; var I: Integer; begin if IsLineEnd(Run) then NextProcedure else if Run < fCodeStartPos - 1 then begin fTokenID := tkSequence; repeat inc(Run); until (Run = fCodeStartPos - 1) or IsLineEnd(Run); end else begin fTokenID := tkIndicator; case fLine[Run] of '*', '/': fRange := rsComment; //JaFi 'D', 'd': fRange := rsDebug; //JaFi // '*', '/', 'D', 'd': fIndicator := fLine[Run]; //JaFi '-': if fRange in [rsQuoteStringMayBe, rsApostStringMayBe] then begin I := Run + 1; while fLine[I] = ' ' do Inc(I); if (AnsiStrLComp(PWideChar(@fLine[I]), PWideChar(StringOfChar(StringChars[fRange], 2)), 2) <> 0) or (I + 1 > fCodeEndPos) then fRange := rsUnknown; end; end; inc(Run); end; end; procedure TSynCobolSyn.LastCharsProc; begin if IsLineEnd(Run) then NextProcedure else begin fTokenID := tkTagArea; repeat inc(Run); until IsLineEnd(Run); end; end; procedure TSynCobolSyn.CommentProc; begin fIndicator := #0; fRange := rsUnknown; if IsLineEnd(Run) then NextProcedure else begin fTokenID := tkComment; repeat Inc(Run); until IsLineEnd(Run); // or (Run > fCodeEndPos); end; end; procedure TSynCobolSyn.InlineCommentProc; begin Inc(Run); fTokenID := tkUnknown; if fLine[Run] = '>' then begin fTokenID := tkComment; repeat Inc(Run); until IsLineEnd(Run); end else if not IsLineEnd(Run) then UnknownProc; end; procedure TSynCobolSyn.DebugProc; begin fIndicator := #0; fRange := rsUnknown; if IsLineEnd(Run) then NextProcedure else begin fTokenID := tkDebugLines; repeat Inc(Run); until IsLineEnd(Run) or (Run > fCodeEndPos); end; end; procedure TSynCobolSyn.PointProc; begin if (Run < fCodeEndPos) and CharInSet(FLine[Run + 1], ['0'..'9', 'e', 'E']) then NumberProc else UnknownProc; end; procedure TSynCobolSyn.NumberProc; function IsNumberChar: Boolean; begin case fLine[Run] of '0'..'9', '.', 'e', 'E', '-', '+': Result := True; else Result := False; end; end; var fFloat: Boolean; begin fTokenID := tkNumber; Inc(Run); fFloat := False; while IsNumberChar and (Run <= fCodeEndPos) do begin case FLine[Run] of '.': if not CharInSet(FLine[Run + 1], ['0'..'9', 'e', 'E']) then Break else fFloat := True; 'e', 'E': if not CharInSet(FLine[Run - 1], ['0'..'9', '.']) then Break else fFloat := True; '-', '+': begin if not fFloat or not CharInSet(FLine[Run - 1], ['e', 'E']) then Break; end; end; Inc(Run); end; end; procedure TSynCobolSyn.NullProc; begin fTokenID := tkNull; inc(Run); end; procedure TSynCobolSyn.CRProc; begin fTokenID := tkSpace; inc(Run); if fLine[Run] = #10 then inc(Run); end; procedure TSynCobolSyn.LFProc; begin fTokenID := tkSpace; inc(Run); end; procedure TSynCobolSyn.StringOpenProc; begin case fLine[Run] of '"': fRange := rsQuoteString; '''': fRange := rsApostString; else if fLine[Run + 1] = '=' then begin fRange := rsPseudoText; Inc(Run); end else begin UnknownProc; Exit; end; end; Inc(Run); StringProc; // fTokenID := tkString; end; procedure TSynCobolSyn.StringProc; begin fTokenID := tkString; if Run <= fCodeEndPos then repeat if (fLine[Run] = StringChars[fRange]) and ((fLine[Run] <> '=') or ((Run > 0) and (fLine[Run - 1] = '='))) then begin if (Run = fCodeEndPos) and (fRange in [rsQuoteString, rsApostString]) then Inc(fRange, 3) else begin fRange := rsUnknown; end; Inc(Run); Break; end; if not IsLineEnd(Run) then Inc(Run); until IsLineEnd(Run) or (Run > fCodeEndPos); end; procedure TSynCobolSyn.StringEndProc; begin if IsLineEnd(Run) then NextProcedure else begin fTokenID := tkString; if (fRange <> rsPseudoText) and (Run <= fCodeEndPos) then repeat if (fLine[Run] = StringChars[fRange]) then begin if fRange in [rsQuoteString, rsApostString] then Inc(Run) else begin Inc(Run, 2); Dec(fRange, 3); end; Break; end; Inc(Run); until IsLineEnd(Run) or (Run > fCodeEndPos); StringProc; end; end; constructor TSynCobolSyn.Create(AOwner: TComponent); begin inherited Create(AOwner); fCaseSensitive := False; // Create the keywords dictionary case-insensitive FKeywords := TDictionary<String, TtkTokenKind>.Create(TIStringComparer.Ordinal); fCommentAttri := TSynHighLighterAttributes.Create(SYNS_AttrComment, SYNS_FriendlyAttrComment); fCommentAttri.Style := [fsItalic]; fCommentAttri.Foreground := clGray; AddAttribute(fCommentAttri); fIdentifierAttri := TSynHighLighterAttributes.Create(SYNS_AttrIdentifier, SYNS_FriendlyAttrIdentifier); AddAttribute(fIdentifierAttri); fAIdentifierAttri := TSynHighLighterAttributes.Create(SYNS_AttrAreaAIdentifier, SYNS_FriendlyAttrAreaAIdentifier); fAIdentifierAttri.Foreground := clTeal; fAIdentifierAttri.Style := [fsBold]; AddAttribute(fAIdentifierAttri); fPreprocessorAttri := TSynHighLighterAttributes.Create(SYNS_AttrPreprocessor, SYNS_FriendlyAttrPreprocessor); fPreprocessorAttri.Foreground := clMaroon; AddAttribute(fPreprocessorAttri); fKeyAttri := TSynHighLighterAttributes.Create(SYNS_AttrReservedWord, SYNS_FriendlyAttrReservedWord); fKeyAttri.Style := [fsBold]; AddAttribute(fKeyAttri); fNumberAttri := TSynHighLighterAttributes.Create(SYNS_AttrNumber, SYNS_FriendlyAttrNumber); fNumberAttri.Foreground := clGreen; AddAttribute(fNumberAttri); fBooleanAttri := TSynHighLighterAttributes.Create(SYNS_AttrBoolean, SYNS_FriendlyAttrBoolean); fBooleanAttri.Foreground := clGreen; AddAttribute(fBooleanAttri); fBracketAttri := TSynHighLighterAttributes.Create(SYNS_AttrBrackets, SYNS_AttrBrackets); AddAttribute(fBracketAttri); fSpaceAttri := TSynHighLighterAttributes.Create(SYNS_AttrSpace, SYNS_FriendlyAttrSpace); AddAttribute(fSpaceAttri); fStringAttri := TSynHighLighterAttributes.Create(SYNS_AttrString, SYNS_FriendlyAttrString); fStringAttri.Foreground := clBlue; AddAttribute(fStringAttri); fSequenceAttri := TSynHighLighterAttributes.Create(SYNS_AttrSequence, SYNS_FriendlyAttrSequence); fSequenceAttri.Foreground := clDkGray; AddAttribute(fSequenceAttri); fIndicatorAttri := TSynHighLighterAttributes.Create(SYNS_AttrIndicator, SYNS_FriendlyAttrIndicator); fIndicatorAttri.Foreground := clRed; AddAttribute(fIndicatorAttri); fTagAreaAttri := TSynHighLighterAttributes.Create(SYNS_AttrTagArea, SYNS_FriendlyAttrTagArea); fTagAreaAttri.Foreground := clMaroon; AddAttribute(fTagAreaAttri); fDebugLinesAttri := TSynHighLighterAttributes.Create(SYNS_AttrDebugLines, SYNS_FriendlyAttrDebugLines); fDebugLinesAttri.Foreground := clDkGray; AddAttribute(fDebugLinesAttri); SetAttributesOnChange(DefHighlightChange); fDefaultFilter := SYNS_FilterCOBOL; fRange := rsUnknown; fIndicator := #0; fCodeStartPos := 7; fCodeMediumPos := 11; fCodeEndPos := 71; EnumerateKeywords(Ord(tkBoolean), BooleanWords, IsIdentChar, DoAddKeyword); EnumerateKeywords(Ord(tkKey), KeyWords, IsIdentChar, DoAddKeyword); EnumerateKeywords(Ord(tkPreprocessor), PreprocessorWords, IsIdentChar, DoAddKeyword); EnumerateKeywords(Ord(tkString), StringWords, IsIdentChar, DoAddKeyword); EnumerateKeywords(Ord(tkUnknown), AmbigiousWords, IsIdentChar, DoAddKeyword); //++ CodeFolding RE_BlockBegin := TRegEx.Create('\b^(IF |EVALUATE |EXEC |READ |WRITE |PERFORM |STRING |ACCEPT )\b', [roIgnoreCase]); RE_BlockEnd := TRegEx.Create('(END\-IF|END\-EVALUATE|END\-EXEC|END\-READ|END\-WRITE|END\-PERFORM|END\-STRING|END\-ACCEPT)', [roIgnoreCase]); //-- CodeFolding end; //++ CodeFolding Const FT_Standard = 1; // begin end, class end, record end FT_Comment = 11; FT_CodeDeclaration = 16; FT_CodeDeclarationWithBody = 17; FT_Implementation = 18; FT_Region: Integer = 99; procedure TSynCobolSyn.ScanForFoldRanges(FoldRanges: TSynFoldRanges; LinesToScan: TStrings; FromLine: Integer; ToLine: Integer); var Line: Integer; iList: TList<Integer>; CurLine: String; ok: Boolean; IsLastDot: Boolean; function BlockDelimiter(Line: Integer): Boolean; var Index: Integer; mcb: TMatchCollection; mce: TMatchCollection; match: TMatch; begin Result := False; mcb := RE_BlockBegin.Matches(CurLine); if mcb.Count > 0 then begin // Char must have proper highlighting (ignore stuff inside comments...) Index := mcb.Item[0].Index; if GetHighlighterAttriAtRowCol(LinesToScan, Line, Index) <> fCommentAttri then begin ok := False; // And ignore lines with both opening and closing chars in them for match in Re_BlockEnd.Matches(CurLine) do if (match.Index > Index) then begin OK := True; Break; end; // line ends with dot - it replaces END-XXX if not OK and IsLastDot then OK := True; if not OK then begin FoldRanges.StartFoldRange(Line + 1, FT_Standard); Result := True; end; end; end else begin mce := RE_BlockEnd.Matches(CurLine); if (mce.Count > 0) or IsLastDot then begin Index := 0; if mce.Count > 0 then Index := mce.Item[0].Index; if IsLastDot or (GetHighlighterAttriAtRowCol(LinesToScan, Line, Index) <> fCommentAttri) then begin FoldRanges.StopFoldRange(Line + 1, FT_Standard); Result := True; end; end; end; end; begin iList := TList<Integer>.Create; for Line := 0 to LinesToScan.Count - 1 do begin CurLine := Trim(LinesToScan[Line]); IsLastDot := Copy(CurLine, Length(CurLine), 1) = '.'; // Divisions if Pos(' DIVISION.', UpperCase(CurLine)) > 0 then begin FoldRanges.StopFoldRange(Line+1, FT_CodeDeclarationWithBody, 0); FoldRanges.StartFoldRange(Line + 1, FT_CodeDeclarationWithBody, 0); end else // Sections if Pos(' SECTION.', UpperCase(CurLine)) > 0 then begin FoldRanges.StopFoldRange(Line, FT_CodeDeclarationWithBody, 1); FoldRanges.StartFoldRange(Line +1, FT_CodeDeclarationWithBody, 1); end else // Standard XXX ... END-XXX ranges if not BlockDelimiter(Line) then FoldRanges.NoFoldInfo(Line + 1); end; // finally we end all open ranges FoldRanges.StopFoldRange(LinesToScan.Count, FT_CodeDeclarationWithBody, 1); FoldRanges.StopFoldRange(LinesToScan.Count, FT_CodeDeclarationWithBody, 0); iList.Free; end; //-- CodeFolding destructor TSynCobolSyn.Destroy; begin fKeywords.Free; inherited Destroy; end; procedure TSynCobolSyn.IdentProc; begin if CharInSet(fLine[Run], ['x', 'g', 'X', 'G']) and (Run < fCodeEndPos) and CharInSet(fLine[Run + 1], ['"', '''']) then begin Inc(Run); StringOpenProc; end else begin fTokenID := IdentKind((fLine + Run)); if (fTokenID = tkIdentifier) and (Run < fCodeMediumPos) then fTokenID := tkAIdentifier; inc(Run, fStringLen); while IsIdentChar(fLine[Run]) and (Run <= fCodeEndPos) do Inc(Run); end; end; procedure TSynCobolSyn.UnknownProc; begin fTokenID := tkUnknown; inc(Run); end; procedure TSynCobolSyn.Next; begin fTokenPos := Run; if fTokenPos < fCodeStartPos then FirstCharsProc else // case fIndicator of // '*', '/': CommentProc; // 'D', 'd': DebugProc; case fRange of rsComment: CommentProc; rsDebug: DebugProc; else if fTokenPos > fCodeEndPos then LastCharsProc else case fRange of rsQuoteString..rsApostStringMayBe: StringEndProc; else begin fRange := rsUnknown; NextProcedure; end; end; end; inherited; end; procedure TSynCobolSyn.NextProcedure; begin case fLine[Run] of #0: NullProc; #10: LFProc; #13: CRProc; '"': StringOpenProc; '''': StringOpenProc; '=': StringOpenProc; #1..#9, #11, #12, #14..#32: SpaceProc; '.': PointProc; '0'..'9': NumberProc; '-', 'A'..'Z', 'a'..'z': IdentProc; '(', ')': BracketProc; '*': InlineCommentProc; // comment *> to end of line else UnknownProc; end; end; function TSynCobolSyn.GetDefaultAttribute(Index: integer): TSynHighLighterAttributes; begin case Index of SYN_ATTR_COMMENT: Result := fCommentAttri; SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri; SYN_ATTR_KEYWORD: Result := fKeyAttri; SYN_ATTR_STRING: Result := fStringAttri; SYN_ATTR_WHITESPACE: Result := fSpaceAttri; else Result := nil; end; end; function TSynCobolSyn.GetEol: Boolean; begin Result := Run = fLineLen + 1; end; function TSynCobolSyn.GetTokenID: TtkTokenKind; begin Result := fTokenId; end; function TSynCobolSyn.GetTokenAttribute: TSynHighLighterAttributes; begin case GetTokenID of tkComment: Result := fCommentAttri; tkIdentifier: Result := fIdentifierAttri; tkAIdentifier: Result := fAIdentifierAttri; tkPreprocessor: Result := fPreprocessorAttri; tkKey: Result := fKeyAttri; tkBoolean: Result := fBooleanAttri; tkNumber: Result := fNumberAttri; tkSpace: Result := fSpaceAttri; tkString: Result := fStringAttri; tkSequence: Result := fSequenceAttri; tkIndicator: Result := fIndicatorAttri; tkTagArea: Result := fTagAreaAttri; tkDebugLines: Result := fDebugLinesAttri; tkUnknown: Result := fIdentifierAttri; tkBracket: Result := fBracketAttri; else Result := nil; end; end; function TSynCobolSyn.GetTokenKind: integer; begin Result := Ord(fTokenId); end; function TSynCobolSyn.GetSampleSource: string; begin Result := '000100* This is a sample file to be used to show all TSynCobolSyn''s'#13#10 + '000200* features.'#13#10 + '000300* This isn''t a valid COBOL program.'#13#10 + '000400'#13#10 + '000500* 1. Supported COBOL features.'#13#10 + '000600'#13#10 + '000700* 1.1 Sequence area.'#13#10 + '000800* First six columns in COBOL are reserved for enumeration'#13#10 + '000900* of source lines.'#13#10 + '001000* 1.2 Indicator area.'#13#10 + '001100* 7th column in COBOL is reserved for special markers like ''*'''#13#10 + '001200* or ''D''.'#13#10 + '001300* 1.3 Comment lines.'#13#10 + '001400* Any line started from ''*'' in 7th column is a comment.'#13#10 + '001500* No separate word highlighting will be done by the editor.'#13#10 + '001600* 1.4 Debug lines.'#13#10 + '001700D Any line started from ''D'' will be treated as containing debug'#13#10 + '001800D commands. No separate word highlighting will be done'#13#10 + '001900D by the editor.'#13#10 + '002000* 1.5 Tag area.'#13#10 + '002100* Only columns from 8th till 72th can be used for COBOL TAG_AREA'#13#10 + '002200* program. Columns beyond the 72th one may be used by some TAG_AREA'#13#10 + '002300* COBOL compilers to tag the code in some internal way. TAG_AREA'#13#10 + '002400* 1.6 Area A identifiers.'#13#10 + '002500* In area A (from 8th column till'#13#10 + '002600* 11th one) you should type only sections''/paragraphs'' names.'#13#10 + '002700* For example "SOME" is a section name:'#13#10 + '002800 SOME SECTION.'#13#10 + '002900* 1.7 Preprocessor directives.'#13#10 + '003000* For example "COPY" is a preprocessor directive:'#13#10 + '003100 COPY "PRD-DATA.SEL".'#13#10 + '003200* 1.8 Key words.'#13#10 + '003300* For example "ACCEPT" and "AT" are COBOL key words:'#13#10 + '003400 ACCEPT WS-ENTRY AT 2030.'#13#10 + '003500* 1.9 Boolean constants.'#13#10 + '003600* These are "TRUE" and "FALSE" constants. For example:'#13#10 + '003700 EVALUATE TRUE.'#13#10 + '003800* 1.10 Numbers.'#13#10 + '003900* Here are the examples of numbers:'#13#10 + '004000 01 WSV-TEST-REC.'#13#10 + '004100 03 WSV-INT-T PIC 9(5) VALUE 12345.'#13#10 + '004200 03 WSV-PRICES PIC 9(4)V99 COMP-3 VALUE 0000.33. '#13#10 + '004300 03 WSV-Z-PRICES PIC Z(5)9.99- VALUE -2.12. '#13#10 + '004400 03 WSV-STORE-DATE PIC 9(4)V99E99 VALUE 0001.33E02.'#13#10 + '004500* 1.11 String.'#13#10 + '004600* The following types of string are supported:'#13#10 + '004700* 1.11.1 Quoted string.'#13#10 + '004800 MOVE "The name of field is ""PRODUCT""" TO WS-ERR-MESS.'#13#10 + '004900 MOVE ''The name of field is ''''PRODUCT'''''' TO WS-ERR-MESS.'#13#10 + '005000* 1.11.2 Pseudo-text.'#13#10 + '005100 COPY'#13#10 + '005200 REPLACING ==+00001== BY +2'#13#10 + '005300 == 1 == BY -3.'#13#10 + '005400* 1.11.3 Figurative constants.'#13#10 + '005500* For example "SPACES" is figurative constant:'#13#10 + '005600 DISPLAY SPACES UPON CRT.'#13#10 + '005700* 1.12 Continued lines.'#13#10 + '005800* Only continued strings are supported. For example:'#13#10 + '005900 MOVE "The name of figurative constant field is'#13#10 + '006000-"SPACES" TO WS-ERR-MESS.'#13#10 + '006100* Or (a single quotation mark in 72th column):'#13#10 + '005900 MOVE "The name of figurative constant field is ""SPACES"'#13#10 + '006000-""" TO WS-ERR-MESS.'#13#10 + '006100'#13#10 + '006200* 2. Unsupported COBOL features.'#13#10 + '006300'#13#10 + '006400* 2.1 Continued lines.'#13#10 + '006500* Continuation of key words is not supported. For example,'#13#10 + '006600* the following COBOL code is valid but TSynCobolSyn won''t'#13#10 + '006700* highlight "VALUE" keyword properly:'#13#10 + '006800 03 WSV-STORE-DATE PIC 9(4)V99E99 VAL'#13#10 + '006900-UE 0001.33E02.'#13#10 + '007000* 2.2 Identifiers started from digits.'#13#10 + '007100* They are valid in COBOL but won''t be highlighted properly'#13#10 + '007200* by TSynCobolSyn. For example, "000-main" is a paragraph'#13#10 + '007300* name and should be highlighted as Area A identifier:'#13#10 + '007400 000-main.'#13#10 + '007500* 2.3 Comment entries in optional paragraphs'#13#10 + '007600* The so called comment-entries in the optional paragraphs'#13#10 + '007700* of the Identification Division are not supported and won''t'#13#10 + '007800* be highlighted properly.'; end; function TSynCobolSyn.IsFilterStored: Boolean; begin Result := fDefaultFilter <> SYNS_FilterCOBOL; end; function TSynCobolSyn.IsIdentChar(AChar: WideChar): Boolean; begin case AChar of '-', '_', '0'..'9', 'a'..'z', 'A'..'Z': Result := True; else Result := False; end; end; procedure TSynCobolSyn.SetCodeStartPos(Value: Integer); begin if Value <= fCodeMediumPos then fCodeStartPos := Value else fCodeStartPos := fCodeMediumPos; end; procedure TSynCobolSyn.SetCodeMediumPos(Value: Integer); begin if (fCodeStartPos <= Value) and (Value <= fCodeEndPos) then fCodeMediumPos := Value else if Value > fCodeEndPos then fCodeMediumPos := fCodeEndPos else fCodeMediumPos := fCodeStartPos; end; procedure TSynCobolSyn.SetCodeEndPos(Value: Integer); begin if Value > fCodeMediumPos then fCodeEndPos := Value else fCodeEndPos := fCodeMediumPos; end; class function TSynCobolSyn.GetLanguageName: string; begin Result := SYNS_LangCOBOL; end; procedure TSynCobolSyn.ResetRange; begin fRange := rsUnknown; end; procedure TSynCobolSyn.SetRange(Value: Pointer); begin fRange := TRangeState(Value); end; function TSynCobolSyn.GetRange: Pointer; begin Result := Pointer(fRange); end; class function TSynCobolSyn.GetFriendlyLanguageName: string; begin Result := SYNS_FriendlyLangCOBOL; end; procedure TSynCobolSyn.BracketProc; begin inc(Run); fTokenID := tkBracket; end; initialization RegisterPlaceableHighlighter(TSynCobolSyn); end.
unit SPRefMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Scanner, Menus, ExtDialogs, StdCtrls, ExtCtrls, LXScanner; type TfmMain = class(TForm) MainMenu1: TMainMenu; Scanner: TLXScanner; File1: TMenuItem; mnOpen: TMenuItem; N1: TMenuItem; mnExit: TMenuItem; OpenDialog: TOpenDialogEx; mmSQL: TMemo; Splitter1: TSplitter; lsTables: TListBox; lsProcs: TListBox; procedure mnExitClick(Sender: TObject); procedure mnOpenClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } Tables,Procedures : TStringList; procedure GetReferences; function isFollowTable(const keywordStr:string):boolean; function isFollowProc(const keywordStr:string):boolean; function inList(const s:string; const list:array of string): boolean; public { Public declarations } end; var fmMain: TfmMain; implementation {$R *.DFM} const needTableKeywordCount = 5; needTableKeywords : array[1..needTableKeywordCount] of string = ('from','insert','into','delete','update'); needSPKeywordCount = 2; needSPKeywords : array[1..needSPKeywordCount] of string = ('exec','execute'); sqlStateKeywordCount = 4; sqlStateKeywords : array[1..sqlStateKeywordCount] of string = ('select','insert','update','delete'); procedure TfmMain.FormCreate(Sender: TObject); begin Tables := TStringList.create; Procedures := TStringList.create; end; procedure TfmMain.mnExitClick(Sender: TObject); begin Close; end; procedure TfmMain.mnOpenClick(Sender: TObject); var fs : TFileStream; begin if OpenDialog.Execute then begin fs := TFileStream.Create(OpenDialog.fileName,fmOpenRead ); try Caption:=Application.Title+' - '+OpenDialog.fileName; Scanner.Analyze(fs); GetReferences; fs.Position:=0; mmSQL.Lines.LoadFromStream(fs); lsTables.Items.Assign(Tables); lsProcs.Items.Assign(Procedures); finally fs.free; end; end; end; procedure TfmMain.GetReferences; var i : integer; token : TLXToken; needTableName : boolean; needVar : boolean; needProc : boolean; begin Tables.clear; Procedures.clear; needTableName:=false; needProc := false; for i:=0 to Scanner.count-1 do begin token := Scanner.Token[i]; case token.Token of ttKeyword : begin needTableName := isFollowTable(token.Text); needProc := isFollowProc(token.Text); needVar:=false; end; ttIdentifier: begin if needTableName then begin tables.Add(token.Text); end else begin if needProc then Procedures.Add(token.Text); end; needTableName := false; needVar:=false; needProc := false; end; ttSpecialChar:begin needVar:=token.text='@'; needProc := false; end; ttComment: begin // do nothing end; else begin needVar:=false; needTableName := false; needProc := false; end; end; end; end; function TfmMain.inList(const s: string; const list: array of string): boolean; var i : integer; begin result := false; for i:=low(list) to high(list) do if CompareText(list[i],s)=0 then begin result := true; break; end; end; function TfmMain.isFollowTable(const keywordStr: string): boolean; begin result:=inList(keywordStr,needTableKeywords); end; function TfmMain.isFollowProc(const keywordStr: string): boolean; begin result:=inList(keywordStr,needSPKeywords); end; end.
//--------------------------------------------------------------- // Demo written by Daniele Teti <d.teti@bittime.it> //--------------------------------------------------------------- unit MainFormU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TMainForm = class(TForm) btnSimple: TButton; Memo1: TMemo; btnAddSets: TButton; btnIn: TButton; btnIntersect: TButton; btnSubtract: TButton; procedure btnSimpleClick(Sender: TObject); procedure btnAddSetsClick(Sender: TObject); procedure btnIntersectClick(Sender: TObject); procedure btnInClick(Sender: TObject); procedure btnSubtractClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} uses SetOfStrU; procedure TMainForm.btnInClick(Sender: TObject); begin var Set1: SetOfStr := ['one','two','three']; Memo1.Clear; Memo1.Lines.Add(BoolToStr('one' in Set1, True)); Memo1.Lines.Add(BoolToStr('two' in Set1, True)); Memo1.Lines.Add(BoolToStr('four' in Set1, True)); end; procedure TMainForm.btnIntersectClick(Sender: TObject); begin var Set1: SetOfStr := ['one','two','three']; var Set2: SetOfStr := ['two','three','four']; Memo1.Lines.Text := (Set1 * Set2).ToString; end; procedure TMainForm.btnSimpleClick(Sender: TObject); begin var Set1: SetOfStr := ['Hello','World','World']; var Set2 := Set1; Set1 := Set1 + 'NewValue'; Memo1.Lines.Add('Set1 => '); Memo1.Lines.Add(Set1.ToString); Memo1.Lines.Add(''); Memo1.Lines.Add('Set2 => '); Memo1.Lines.Add(Set2.ToString); end; procedure TMainForm.btnSubtractClick(Sender: TObject); begin var Set1: SetOfStr := ['one','two','three','four']; var Set2: SetOfStr := ['two','four']; Memo1.Lines.Text := (Set1 - Set2).ToString; end; procedure TMainForm.btnAddSetsClick(Sender: TObject); begin var Set2: SetOfStr := ['one','two','three']; var Set3: SetOfStr := ['two','three','four']; var Set4: SetOfStr := Set2 + Set3; Memo1.Lines.Text := Set4.ToString; end; end.
unit uLibrarySerializer; {$mode objfpc}{$H+} interface uses Classes, SysUtils, dom, XmlWrite, uLibrary, uSaxBase; type { TBaseSerializer } TBaseSerializer = class protected fXDoc: TXmlDocument; protected function AddRootNode(const aNodeName: string): TDomNode; function AddNode(const aNodeName: string; const aParentNode: TDomNode): TDomNode; function AddTextNode(const aNodeName, aNodeValue: string; const aParentNode: TDomNode): TDomNode; procedure AddAttribute(const aNode: TDomNode; const aAttrName, aAttrValue: string); end; { TLibrarySerializer } TLibrarySerializer = class(TBaseSerializer) private procedure ModuleSerialize(const aSublibrary: ISublibrary; const aParentNode: TDomNode; const aFolder: string); public procedure Serialize(const aLibrary: ILibrary); end; { TModuleDefineSerializer } TModuleDefineSerializer = class(TBaseSerializer) private procedure GroupsSerialize(const aGroups: IGroups; const aParentNode: TDomNode); procedure VarSerialize(const aVar: IVarDefine; const aParentNode: TDomNode); procedure DescriptionSerialize(const aDescription: IDescription; const aParentNode: TDomNode); procedure BitsSerialize(const aBits: IBits; const aParentNode: TDomNode); procedure PickListSerialize(const aPickList: IPickList; const aParentNode: TDomNode); procedure PresetsSerialize(const aPresets: IPresets; const aParentNode: TDomNode); procedure RegistersSerialize(const aRegisters: IRegisters; const aParentNode: TDomNode); public procedure Serialize(const aModule: IModule; const aFolder: string); end; implementation uses uSetting; { TBaseSerializer } function TBaseSerializer.AddRootNode(const aNodeName: string): TDomNode; begin Result := fXDoc.CreateElement(aNodeName); fXDoc.AppendChild(Result); end; function TBaseSerializer.AddNode(const aNodeName: string; const aParentNode: TDomNode): TDomNode; begin Result := fXDoc.CreateElement(aNodeName); aParentNode.AppendChild(Result); end; function TBaseSerializer.AddTextNode(const aNodeName, aNodeValue: string; const aParentNode: TDomNode): TDomNode; var TextNode: TDomNode; begin Result := AddNode(aNodeName, aParentNode); TextNode := fXDoc.CreateTextNode(Utf8Decode(aNodeValue)); Result.AppendChild(TextNode); end; procedure TBaseSerializer.AddAttribute(const aNode: TDomNode; const aAttrName, aAttrValue: string); begin TDOMElement(aNode).SetAttribute(aAttrName, aAttrValue); end; { TLibrarySerializer } procedure TLibrarySerializer.Serialize(const aLibrary: ILibrary); var P: Pointer; Folder: string; RootNode: TDomNode; begin for P in aLibrary do begin fXDoc := TXmlDocument.Create; try // Корневой элемент RootNode := AddRootNode(sLib); case aLibrary.ExtractKey(P) of slDeveloper: begin Folder := GetSetting.DeveloperLibrary + PathDelim; AddAttribute(RootNode, sTypeLib, 'developer'); end; slUser: begin Folder := GetSetting.UserLibrary + PathDelim; AddAttribute(RootNode, sTypeLib, 'user'); end; end; ModuleSerialize(aLibrary.ExtractData(P), RootNode, Folder); if FileExists(Folder + 'module.jlf') then RenameFile(Folder + 'module.jlf', Folder + 'module.bak'); WriteXMLFile(fXDoc, utf8ToAnsi(Folder + 'module.jlf')); finally fXDoc.Free; end; end; end; procedure TLibrarySerializer.ModuleSerialize(const aSublibrary: ISublibrary; const aParentNode: TDomNode; const aFolder: string); var P: Pointer; Uid: word; Module: IModule; Node: TDomNode; ModuleDefineSerializer: TModuleDefineSerializer; begin for P in aSubLibrary do begin Uid := aSublibrary.ExtractKey(P); Module := aSublibrary.ExtractData(P); Node := AddTextNode(sModule, Module.Name, aParentNode); AddAttribute(Node, sUid, IntToStr(Uid)); AddAttribute(Node, sTypeSignature, IntToStr(Ord(Module.TypeSignature))); AddAttribute(Node, sTypeBootloader, IntToStr(Ord(Module.TypeBootloader))); if Module.ModuleDefine <> nil then begin ModuleDefineSerializer := TModuleDefineSerializer.Create; try ModuleDefineSerializer.Serialize(Module, aFolder); finally ModuleDefineSerializer.Free; end; end; end; end; procedure TModuleDefineSerializer.GroupsSerialize(const aGroups: IGroups; const aParentNode: TDomNode); var Groups: IGroups; Node, GroupNode: TDomNode; GroupItem: IGroupItem; begin for Groups in aGroups.GroupsList do begin Node := AddNode(sGncSet, aParentNode); AddAttribute(Node, sName, Utf8ToAnsi(Groups.ShortDescription)); AddAttribute(Node, sImageIndex, Utf8ToAnsi(IntToStr(Groups.ImageIndex))); GroupsSerialize(Groups, Node); end; if aGroups.Group.Count > 0 then begin GroupNode := AddNode(sGncVar, aParentNode); for GroupItem in aGroups.Group do AddTextNode(sUid, GroupItem.VarDefine.Uid, GroupNode); end; end; procedure TModuleDefineSerializer.VarSerialize(const aVar: IVarDefine; const aParentNode: TDomNode); var Node, BitsNode, PickListNode: TDomNode; begin Node := AddNode(sVarDefine, aParentNode); AddAttribute(Node, sVer, aVar.Ver); AddAttribute(Node, sVarType, VarTypes.Keys[VarTypes.IndexOfData(aVar.VarType)]); AddTextNode(sIndex, IntTOStr(aVar.Index), Node); AddTextNode(sShortDescription, aVar.ShortDescription, Node); AddTextNode(sName, aVar.Name, Node); AddTextNode(sUid, aVar.Uid, Node); case aVar.ReadAlways of True: AddTextNode(sReadAlways, '1', Node); False: AddTextNode(sReadAlways, '0', Node); end; AddTextNode(sMultipler, IntToStr(aVar.Multipler), Node); AddTextNode(sAccess, IntToStr(Ord(aVar.Access)), Node); AddTextNode(sSynchronization, IntToStr(Ord(aVar.Synchronization)), Node); case aVar.SingleRequest of True: AddTextNode(sSingleRequest, '1', Node); False: AddTextNode(sSingleRequest, '0', Node); end; AddTextNode(sKind, IntToStr(Ord(aVar.Kind)), Node); AddTextNode(sUnit, aVar.Measure, Node); DescriptionSerialize(aVar.Description, Node); BitsNode := AddNode(sBits, Node); if aVar.Bits.Count > 0 then begin if aVar.Bits.Name <> '' then AddAttribute(BitsNode, sName, aVar.Bits.Name) else BitsSerialize(aVar.Bits, BitsNode); end; PickListNode := AddNode(sPickList, Node); if aVar.PickList.Count > 0 then begin if aVar.PickList.GetName <> '' then AddAttribute(PickListNode, sName, aVar.PickList.GetName) else PickListSerialize(aVar.Picklist, PickListNode); end; end; procedure TModuleDefineSerializer.DescriptionSerialize( const aDescription: IDescription; const aParentNode: TDomNode); var S: String; Node: TDomNode; begin Node := AddNode(sDescription, aParentNode); for S in aDescription do AddTextNode(sPara, S, Node); end; procedure TModuleDefineSerializer.BitsSerialize(const aBits: IBits; const aParentNode: TDomNode); var P: Pointer; Index: Byte; Bit: IBitDefine; Node: TDomNode; begin for P in aBits do begin Index := aBits.ExtractKey(P); Bit := aBits.ExtractData(P); Node := AddNode(sBitDefine, aParentNode); AddAttribute(Node, sVer, Bit.Ver); AddTextNode(sName, Bit.Name, Node); AddTextNode(sIndex, IntToStr(Index), Node); AddTextNode(sShortDescription, Bit.ShortDescription, Node); DescriptionSerialize(Bit.Description, Node); end; end; procedure TModuleDefineSerializer.PickListSerialize(const aPickList: IPickList; const aParentNode: TDomNode); var P: Pointer; Value: Word; PickItem: IPickItem; Node: TDomNode; begin for P in aPickList do begin Value := aPickList.ExtractKey(P); PickItem := aPickList.ExtractData(P); Node := AddNode(sPickItem, aParentNode); if PickItem.Ver <> '' then AddAttribute(Node, sVer, PickItem.Ver); AddTextNode(sName, PickItem.Name, Node); AddTextNode(sValue, IntToStr(Value), Node); AddTextNode(sShortDescription, PickItem.ShortDescription, Node); DescriptionSerialize(PickItem.Description, Node); end; end; procedure TModuleDefineSerializer.PresetsSerialize( const aPresets: IPresets; const aParentNode: TDomNode); var P: Pointer; Node, BitsNode, PickListNode: TDomNode; Bits: IBits; PickList: IPickList; begin Node := AddNode(sPresets, aParentNode); for P in aPresets.BitsSet do begin Bits := aPresets.BitsSet.ExtractData(P); BitsNode := AddNode(sBits, Node); AddAttribute(BitsNode, sName, aPresets.BitsSet.ExtractKey(P)); AddTextNode(sShortDescription, Bits.ShortDescription, BitsNode); BitsSerialize(Bits, BitsNode); end; for P in aPresets.PickLists do begin PickList := aPresets.PickLists.ExtractData(P); PickListNode := AddNode(sPickList, Node); AddAttribute(PickListNode, sName, aPresets.PickLists.ExtractKey(P)); AddTextNode(sShortDescription, PickList.ShortDescription, PickListNode); PickListSerialize(PickList, PickListNode); end; end; procedure TModuleDefineSerializer.RegistersSerialize(const aRegisters: IRegisters; const aParentNode: TDomNode); var Node, VarsNode: TDomNode; P, PP: Pointer; Vars: IVars; begin Node := AddNode(sRegisters, aParentNode); for P in aRegisters do begin VarsNode := AddNode(sVars, Node); Vars := aRegisters.ExtractData(P); case aRegisters.ExtractKey(P) of trHolding: AddAttribute(VarsNode, sArrayType, sHolding); trInput: AddAttribute(VarsNode, sArrayType, sInput); end; for PP in Vars do VarSerialize(Vars.ExtractData(PP), VarsNode); end; end; { TModuleDefineSerializer } procedure TModuleDefineSerializer.Serialize(const aModule: IModule; const aFolder: string); var RootNode: TDomNode; ConfigNode: TDomNode; // Groups: IGroups; begin fXDoc := TXmlDocument.Create; try // Корневой элемент RootNode := AddRootNode(sModule); PresetsSerialize(aModule.ModuleDefine.PreSets, RootNode); RegistersSerialize(aModule.ModuleDefine.Registers, RootNode); ConfigNode := AddNode(sConfiguration, RootNode); GroupsSerialize(aModule.ModuleDefine.Configuration, ConfigNode); if FileExists(aFolder + aModule.Name + '.jlb') then RenameFile(aFolder + aModule.Name + '.jlb', aFolder + aModule.Name + '.bak'); WriteXMLFile(fXDoc, utf8ToAnsi(aFolder + aModule.Name + '.jlb')); finally fXDoc.Free; end; end; end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2015 Vincent Parrett & Contributors } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} /// <summary> /// Using this unit will auto detect the platform you are compiling for and /// register the correct console unit. /// </summary> /// <remarks> /// <para> /// It is really just adding the correct unit DUnitX."PlatformName".Console /// Unit to the project via a compiler define. /// </para> /// <para> /// This cleans up the DPR uses by removing the need for {$IFDEF} /// statements in the project uses clause. If a {$IFDEF} is in the project /// uses clause and you add a new file Delphi does not know which area to /// put it in and has to guess. /// </para> /// <para> /// In versions prior to XE3 it would just remove {$IFDEF} statements /// completely from your code. /// <see href="http://qc.embarcadero.com/wc/qcmain.aspx?d=6294'" /> /// </para> /// </remarks> /// <seealso cref="DUnitX.Windows.Console" /> /// <seealso cref="DUnitX.MacOS.Console" /> /// <seealso_ cref="DUnitX.Linux.Console" /> /// <seealso cref="DUnitX.Loggers.Console" /> unit DUnitX.AutoDetect.Console; interface uses {$IF Defined(MSWINDOWS)} DUnitX.Windows.Console; {$ELSEIF Defined(MACOS) or Defined(OSX32)} // Simplification as MacOS console supports Ansi, and other terminals // on platforms other than windows typically support some form of // ANSI colors. DUnitX.MacOS.Console; {$ELSEIF Defined(LINUX) or Defined(ANDROID)} DUnitX.Linux.Console; {$ELSE} {$MESSAGE Error 'Unknown Platform for Console Writer'} {$IFEND} implementation end.
unit dmFiltroNoblementeAlza; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, dmFiltro, DB, kbmMemTable; type TFiltroNoblementeAlza = class(TFiltro) protected function ValorInFilter: boolean; override; public function GetDescripcion: string; override; end; implementation uses dmEstadoValores, dmFiltros; {$R *.dfm} { TNoblementeAlza } function TFiltroNoblementeAlza.GetDescripcion: string; begin result := 'Noblemente al alza'; end; function TFiltroNoblementeAlza.ValorInFilter: boolean; { Tot el paper ha d'estar a 0.25. El diner: A la primera baixa te que disminuir respect a la posició actual. La segona baixa ha de disminuir més que a la primera. A la primera alça ha d'aumentar el diner i a la segona encara més. } begin result := // Tot el paper ha d'estar a 0.25 (ValoresPAPEL.Value = 0.25) and (ValoresPAPEL_ALZA_DOBLE.Value = 0.25) and (ValoresPAPEL_ALZA_SIMPLE.Value = 0.25) and (ValoresPAPEL_BAJA_DOBLE.Value = 0.25) and (ValoresPAPEL_BAJA_SIMPLE.Value = 0.25) and // A la primera baixa te que disminuir respect a la posició actual. (ValoresDINERO_BAJA_SIMPLE.Value < ValoresDINERO.Value) and // La segona baixa ha de disminuir més que a la primera. (ValoresDINERO_BAJA_DOBLE.Value < ValoresDINERO_BAJA_SIMPLE.Value) and // A la primera alça ha d'aumentar el diner i a la segona encara més. (ValoresDINERO_ALZA_SIMPLE.Value > ValoresDINERO.Value) and (ValoresDINERO_ALZA_DOBLE.Value > ValoresDINERO_ALZA_SIMPLE.Value); end; initialization RegisterFiltro(TFiltroNoblementeAlza); finalization end.
unit ScriptRTTI; interface uses Classes, SysUtils, ObjAuto, TypInfo; type TScriptParam = record name: ShortString; tipo: TTypeInfo; end; TScriptParams = array of TScriptParam; TScriptMethod = record name: string; params: TScriptParams; hasReturn: boolean; return: PTypeInfo; end; TScriptMethods = array of TScriptMethod; EMethodNameNotFound = class(Exception); TScriptRTTI = class private FMethods: TScriptMethods; function NextParam(const Param: PParamInfo): PParamInfo; public constructor Create(const obj: TObject); function Find(const methodName: string): TScriptMethod; property Methods: TScriptMethods read FMethods; end; implementation const SHORT_LEN = sizeof(ShortString) - 1; { TScriptRTTI } constructor TScriptRTTI.Create(const obj: TObject); var VMT: Pointer; MethodInfo: Pointer; Count, CountProperties: Integer; method: PMethodInfoHeader; MethodHeader: PMethodInfoHeader; i: Integer; MethodName: string; Properties: TPropList; procedure Params(const i: integer); var headerEnd: Pointer; Params, Param: PParamInfo; numParams, j: integer; scriptParam: TScriptParam; begin // Check the length is greater than just that of the name if MethodHeader.Len <= SizeOf(TMethodInfoHeader) - SHORT_LEN + Length(MethodHeader.Name) then exit; headerEnd := Pointer(Integer(MethodHeader) + MethodHeader^.Len); // Get a pointer to the param info Params := PParamInfo(Integer(MethodHeader) + SizeOf(MethodHeader^) - SHORT_LEN + SizeOf(TReturnInfo) + Length(MethodHeader^.Name)); numParams := 0; // Loop over the parameters Param := Params; while Integer(Param) < Integer(headerEnd) do begin // Seems to be extra info about the return function, not sure what it means if (not (pfResult in Param.Flags)) and (Param.Name <> 'Self') then inc(numParams); Param := NextParam(Param); end; SetLength(FMethods[i].params, numParams); if numParams > 0 then begin Param := Params; j := 0; while Integer(Param) < Integer(headerEnd) do begin // Seems to be extra info about the return function, not sure what it means if (not (pfResult in Param.Flags)) and (Param.Name <> 'Self') then begin scriptParam.name := Param.Name; scriptParam.tipo := (Param.ParamType^)^; FMethods[i].params[j] := scriptParam; inc(j); end; // Find next param Param := NextParam(Param); end; end; end; procedure Return(const i: integer); var returnInfo: PReturnInfo; hasReturn: boolean; tipo: PTypeInfo; begin returnInfo := Pointer(MethodHeader); Inc(Integer(returnInfo), SizeOf(TMethodInfoHeader) - SHORT_LEN + Length(MethodName)); hasReturn := ReturnInfo^.ReturnType <> nil; FMethods[i].hasReturn := hasReturn; if hasReturn then begin tipo := (returnInfo^.ReturnType^); FMethods[i].return := tipo; end; end; begin inherited Create; // Inspirado en ObjAuto.GetMethodInfo(Obj, MethodName ); VMT := PPointer(obj)^; MethodInfo := PPointer(Integer(VMT) + vmtMethodTable)^; if MethodInfo <> nil then begin // Scan method and get string about each Count := PWord(MethodInfo)^; // Reservamos memoria para el número de métodos SetLength(FMethods, Count); Inc(Integer(MethodInfo), 2); method := MethodInfo; for i := 0 to Count - 1 do begin MethodHeader := method; MethodName := method^.Name; FMethods[i].name := MethodName; Params(i); Return(i); // FMethods[i].name := DescriptionOfMethod(obj, methodName); Inc(Integer(method), PMethodInfoHeader(method)^.Len); // Get next method end; end else Count := 0; // Añadimos las propiedades CountProperties := GetPropList(PTypeInfo(obj.ClassInfo), tkAny, @Properties); SetLength(FMethods, Count + CountProperties); Dec(CountProperties); for i := 0 to CountProperties do begin with FMethods[i + Count] do begin name := Properties[i]^.Name; params := nil; hasReturn := false; end; end; end; function TScriptRTTI.Find(const methodName: string): TScriptMethod; var i, num: integer; uMethodName: string; begin num := length(FMethods) - 1; uMethodName := UpperCase(methodName); for i := 0 to num do begin if UpperCase(FMethods[i].name) = uMethodName then begin result := FMethods[i]; exit; end; end; raise EMethodNameNotFound.Create(''); end; function TScriptRTTI.NextParam(const Param: PParamInfo): PParamInfo; begin Result := PParamInfo(Integer(Param) + SizeOf(TParamInfo) - SHORT_LEN + Length(Param^.Name)); end; end.
unit ArticleRepository; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ArticleModel; type IArticleRepository = interface procedure Add(Article: TArticle); function Build(Title, Description, Body: string; const Tags: array of string): TArticle; function GetAll: TArticles; function GetAllTags: TTags; function GetByAuthorSlug(Slug: string): TArticles; function GetByTag(Tag: string): TArticles; end; implementation end.
//---------------------------------------------------------------------------- // // Author : Jan Horn // Email : jhorn@global.co.za // Website : http://www.sulaco.co.za // http://home.global.co.za/~jhorn // Version : 1.03 // Date : 1 May 2001 // Changes : 28 July 2001 - Faster BGR to RGB swapping routine // 2 October 2001 - Added support for 24, 32bit TGA files // 28 April 2002 - Added support for compressed TGA files // // Description : A unit that used with OpenGL projects to load BMP, JPG and TGA // files from the disk or a resource file. // Usage : LoadTexture(Filename, TextureName, LoadFromResource); // // eg : LoadTexture('logo.jpg', LogoTex, TRUE); // will load a JPG texture from the resource included // with the EXE. File has to be loaded into the Resource // using this format "logo JPEG logo.jpg" // //---------------------------------------------------------------------------- unit Textures; interface uses Windows, OpenGL, Graphics, Classes, JPEG, SysUtils; function initLocking : boolean; function LoadQuakeTexture(path, name : string; var Texture : GLUINT; NoPicMip, NoMipMap : boolean) : boolean; function LoadTGATexture(Filename: String; var Texture: GLuint; LoadFromResource, LoadFromStream, NoPicMip, NoMipMap : Boolean): Boolean; function LoadTexture(Filename: String; var Texture: GLuint; LoadFromRes, LoadFromStream : Boolean): Boolean; overload; implementation uses Dialogs, global, Q3Pk3Read; // Swap bitmap format from BGR to RGB procedure SwapRGB(data : Pointer; Size : Integer); asm mov ebx, eax mov ecx, size @@loop : mov al,[ebx+0] mov ah,[ebx+2] mov [ebx+2],al mov [ebx+0],ah add ebx,3 dec ecx jnz @@loop end; // Create the Texture } function CreateTexture(Width, Height, Format : Word; pData : Pointer; NoPicMip, NoMipMap : boolean) : Integer; var Texture : GLuint; begin glGenTextures(1, @Texture); glBindTexture(GL_TEXTURE_2D, Texture); glEnable(GL_TEXTURE_2D); // glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); {Texture blends with object background} if NoPicMip then begin glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); end else begin glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); end; if NoMipMap then begin glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, 4, Width, Height, 0, Format, GL_UNSIGNED_BYTE, pData) end else begin // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D, 4, Width, Height, Format, GL_UNSIGNED_BYTE, pData); end; result := Texture; end; {------------------------------------------------------------------} { Load BMP textures } {------------------------------------------------------------------} function LoadBMPTexture(Filename: String; var Texture : GLuint; LoadFromResource, LoadFromStream, NoPicMip, NoMipMap : Boolean) : Boolean; var FileHeader: BITMAPFILEHEADER; InfoHeader: BITMAPINFOHEADER; Palette: array of RGBQUAD; BitmapFile: THandle; BitmapLength: LongWord; PaletteLength: LongWord; ReadBytes: LongWord; Width, Height : Integer; pData : Pointer; // used for loading from resource ResStream : TResourceStream; begin result :=FALSE; if LoadFromResource then // Load from resource begin try ResStream := TResourceStream.Create(hInstance, PChar(copy(Filename, 1, Pos('.', Filename)-1)), 'BMP'); ResStream.ReadBuffer(FileHeader, SizeOf(FileHeader)); // FileHeader ResStream.ReadBuffer(InfoHeader, SizeOf(InfoHeader)); // InfoHeader PaletteLength := InfoHeader.biClrUsed; SetLength(Palette, PaletteLength); ResStream.ReadBuffer(Palette, PaletteLength); // Palette Width := InfoHeader.biWidth; Height := InfoHeader.biHeight; BitmapLength := InfoHeader.biSizeImage; if BitmapLength = 0 then BitmapLength := Width * Height * InfoHeader.biBitCount Div 8; GetMem(pData, BitmapLength); ResStream.ReadBuffer(pData^, BitmapLength); // Bitmap Data ResStream.Free; except on EResNotFound do begin MessageBox(0, PChar('File not found in resource - ' + Filename), PChar('BMP Texture'), MB_OK); Exit; end else begin MessageBox(0, PChar('Unable to read from resource - ' + Filename), PChar('BMP Unit'), MB_OK); Exit; end; end; end else begin // Load image from file BitmapFile := CreateFile(PChar(Filename), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0); if (BitmapFile = INVALID_HANDLE_VALUE) then begin MessageBox(0, PChar('Error opening ' + Filename), PChar('BMP Unit'), MB_OK); Exit; end; // Get header information ReadFile(BitmapFile, FileHeader, SizeOf(FileHeader), ReadBytes, nil); ReadFile(BitmapFile, InfoHeader, SizeOf(InfoHeader), ReadBytes, nil); // Get palette PaletteLength := InfoHeader.biClrUsed; SetLength(Palette, PaletteLength); ReadFile(BitmapFile, Palette, PaletteLength, ReadBytes, nil); if (ReadBytes <> PaletteLength) then begin MessageBox(0, PChar('Error reading palette'), PChar('BMP Unit'), MB_OK); Exit; end; Width := InfoHeader.biWidth; Height := InfoHeader.biHeight; BitmapLength := InfoHeader.biSizeImage; if BitmapLength = 0 then BitmapLength := Width * Height * InfoHeader.biBitCount Div 8; // Get the actual pixel data GetMem(pData, BitmapLength); ReadFile(BitmapFile, pData^, BitmapLength, ReadBytes, nil); if (ReadBytes <> BitmapLength) then begin MessageBox(0, PChar('Error reading bitmap data'), PChar('BMP Unit'), MB_OK); Exit; end; CloseHandle(BitmapFile); end; // Bitmaps are stored BGR and not RGB, so swap the R and B bytes. SwapRGB(pData, Width*Height); Texture :=CreateTexture(Width, Height, GL_RGB, pData, NoPicMip, NoMipMap); FreeMem(pData); result :=TRUE; end; {------------------------------------------------------------------} { Load JPEG textures } {------------------------------------------------------------------} function LoadJPGTexture(Filename: String; var Texture: GLuint; LoadFromResource, LoadFromStream, NoPicMip, NoMipMap : Boolean): Boolean; var Data : Array of LongWord; W, Width : Integer; H, Height : Integer; BMP : TBitmap; JPG : TJPEGImage; C : LongWord; Line : ^LongWord; ResStream : TResourceStream; // used for loading from resource begin result :=FALSE; JPG:=TJPEGImage.Create; if LoadFromResource then // Load from resource begin try ResStream := TResourceStream.Create(hInstance, PChar(copy(Filename, 1, Pos('.', Filename)-1)), 'JPEG'); JPG.LoadFromStream(ResStream); ResStream.Free; except on EResNotFound do begin MessageBox(0, PChar('File not found in resource - ' + Filename), PChar('JPG Texture'), MB_OK); Exit; end else begin MessageBox(0, PChar('Couldn''t load JPG Resource - "'+ Filename +'"'), PChar('BMP Unit'), MB_OK); Exit; end; end; end else begin try if LoadFromStream then JPG.LoadFromStream(Pk3Zip.GetFileBytes(Filename)) else JPG.LoadFromFile(Filename); except MessageBox(0, PChar('Couldn''t load JPG - "'+ Filename +'"'), PChar('BMP Unit'), MB_OK); Exit; end; end; // Create Bitmap BMP:=TBitmap.Create; BMP.pixelformat:=pf32bit; BMP.width:=JPG.width; BMP.height:=JPG.height; BMP.canvas.draw(0,0,JPG); // Copy the JPEG onto the Bitmap Width :=BMP.Width; Height :=BMP.Height; SetLength(Data, Width*Height); For H:=0 to Height-1 do Begin Line :=BMP.scanline[Height-H-1]; // flip JPEG For W:=0 to Width-1 do Begin c:=Line^ and $FFFFFF; // Need to do a color swap Data[W+(H*Width)] :=(((c and $FF) shl 16)+(c shr 16)+(c and $FF00)) or $FF000000; // 4 channel. inc(Line); End; End; BMP.free; JPG.free; Texture :=CreateTexture(Width, Height, GL_RGBA, addr(Data[0]), NoPicMip, NoMipMap); result :=TRUE; end; {------------------------------------------------------------------} { Loads 24 and 32bpp (alpha channel) TGA textures } {------------------------------------------------------------------} function LoadTGATexture(Filename: String; var Texture: GLuint; LoadFromResource, LoadFromStream, NoPicMip, NoMipMap : Boolean): Boolean; var TGAHeader : packed record // Header type for TGA images FileType : Byte; ColorMapType : Byte; ImageType : Byte; ColorMapSpec : Array[0..4] of Byte; OrigX : Array [0..1] of Byte; OrigY : Array [0..1] of Byte; Width : Array [0..1] of Byte; Height : Array [0..1] of Byte; BPP : Byte; ImageInfo : Byte; end; TGAFile : File; bytesRead : Integer; image : Pointer; {or PRGBTRIPLE} CompImage : Pointer; Width, Height : Integer; ColorDepth : Integer; ImageSize : Integer; BufferIndex : Integer; currentByte : Integer; CurrentPixel : Integer; I : Integer; Front: ^Byte; Back: ^Byte; Temp: Byte; ResStream : TResourceStream; // used for loading from resource memory: TMemoryStream; // Copy a pixel from source to dest and Swap the RGB color values procedure CopySwapPixel(const Source, Destination : Pointer); asm push ebx mov bl,[eax+0] mov bh,[eax+1] mov [edx+2],bl mov [edx+1],bh mov bl,[eax+2] mov bh,[eax+3] mov [edx+0],bl mov [edx+3],bh pop ebx end; begin result :=FALSE; GetMem(Image, 0); if LoadFromResource then // Load from resource begin try ResStream := TResourceStream.Create(hInstance, PChar(copy(Filename, 1, Pos('.', Filename)-1)), 'TGA'); ResStream.ReadBuffer(TGAHeader, SizeOf(TGAHeader)); // FileHeader result :=TRUE; except on EResNotFound do begin MessageBox(0, PChar('File not found in resource - ' + Filename), PChar('TGA Texture'), MB_OK); Exit; end else begin MessageBox(0, PChar('Unable to read from resource - ' + Filename), PChar('BMP Unit'), MB_OK); Exit; end; end; end else begin if FileExists(Filename) then begin AssignFile(TGAFile, Filename); Reset(TGAFile, 1); // Read in the bitmap file header BlockRead(TGAFile, TGAHeader, SizeOf(TGAHeader)); result :=TRUE; end else if LoadFromStream then begin memory := Pk3Zip.GetFileBytes(Filename); memory.ReadBuffer(TGAHeader, SizeOf(TGAHeader)); result :=TRUE; end else begin MessageBox(0, PChar('File not found - ' + Filename), PChar('TGA Texture'), MB_OK); Exit; end; end; if Result = TRUE then begin Result :=FALSE; // Only support 24, 32 bit images if (TGAHeader.ImageType <> 2) AND { TGA_RGB } (TGAHeader.ImageType <> 10)then { Compressed RGB } begin Result := False; if not LoadFromStream then CloseFile(tgaFile); MessageBox(0, PChar('Couldn''t load "'+ Filename +'". Only 24 and 32bit TGA supported.'), PChar('TGA File Error'), MB_OK); Exit; end; // Don't support colormapped files if TGAHeader.ColorMapType <> 0 then begin Result := False; if not LoadFromStream then CloseFile(TGAFile); MessageBox(0, PChar('Couldn''t load "'+ Filename +'". Colormapped TGA files not supported.'), PChar('TGA File Error'), MB_OK); Exit; end; // Get the width, height, and color depth Width := TGAHeader.Width[0] + TGAHeader.Width[1] * 256; Height := TGAHeader.Height[0] + TGAHeader.Height[1] * 256; ColorDepth := TGAHeader.BPP; ImageSize := Width*Height*(ColorDepth div 8); if ColorDepth < 24 then begin Result := False; if not LoadFromStream then CloseFile(TGAFile); MessageBox(0, PChar('Couldn''t load "'+ Filename +'". Only 24 and 32 bit TGA files supported.'), PChar('TGA File Error'), MB_OK); Exit; end; GetMem(Image, ImageSize); if TGAHeader.ImageType = 2 then // Standard 24, 32 bit TGA file begin if LoadFromResource then // Load from resource begin try ResStream.ReadBuffer(Image^, ImageSize); ResStream.Free; except MessageBox(0, PChar('Unable to read from resource - ' + Filename), PChar('BMP Unit'), MB_OK); Exit; end; end else // Read in the image from file begin if LoadFromStream then begin bytesRead := memory.Read(image^, ImageSize); //bytesRead := length(image^); end else BlockRead(TGAFile, image^, ImageSize, bytesRead); if bytesRead <> ImageSize then begin Result := False; if not LoadFromStream then CloseFile(TGAFile); MessageBox(0, PChar('Couldn''t read file "'+ Filename +'".'), PChar('TGA File Error'), MB_OK); Exit; end end; // TGAs are stored BGR and not RGB, so swap the R and B bytes. // 32 bit TGA files have alpha channel and gets loaded differently if TGAHeader.BPP = 24 then begin for I :=0 to Width * Height - 1 do begin Front := Pointer(Integer(Image) + I*3); Back := Pointer(Integer(Image) + I*3 + 2); Temp := Front^; Front^ := Back^; Back^ := Temp; end; Texture :=CreateTexture(Width, Height, GL_RGB, Image, NoPicMip, NoMipMap); end else begin for I :=0 to Width * Height - 1 do begin Front := Pointer(Integer(Image) + I*4); Back := Pointer(Integer(Image) + I*4 + 2); Temp := Front^; Front^ := Back^; Back^ := Temp; end; Texture :=CreateTexture(Width, Height, GL_RGBA, Image, NoPicMip, NoMipMap); end; end; // Compressed 24, 32 bit TGA files if TGAHeader.ImageType = 10 then begin ColorDepth :=ColorDepth DIV 8; CurrentByte :=0; CurrentPixel :=0; BufferIndex :=0; if LoadFromResource then // Load from resource begin try GetMem(CompImage, ResStream.Size-sizeOf(TGAHeader)); ResStream.ReadBuffer(CompImage^, ResStream.Size-sizeOf(TGAHeader)); // load compressed date into memory ResStream.Free; except MessageBox(0, PChar('Unable to read from resource - ' + Filename), PChar('BMP Unit'), MB_OK); Exit; end; end else begin if LoadFromStream then begin GetMem(CompImage, memory.Size-sizeOf(TGAHeader)); bytesRead := memory.Read(CompImage^, memory.Size-sizeOf(TGAHeader)); //bytesRead := length(image^); end else begin GetMem(CompImage, FileSize(TGAFile)-sizeOf(TGAHeader)); BlockRead(TGAFile, CompImage^, FileSize(TGAFile)-sizeOf(TGAHeader), BytesRead); // load compressed data into memory end; if LoadFromStream and (bytesRead <> memory.Size-sizeOf(TGAHeader)) then begin Result := False; memory.Free; MessageBox(0, PChar('Couldn''t read file "'+ Filename +'".'), PChar('TGA File Error'), MB_OK); Exit; end else if not LoadFromStream and (bytesRead <> FileSize(TGAFile)-sizeOf(TGAHeader)) then begin Result := False; CloseFile(TGAFile); MessageBox(0, PChar('Couldn''t read file "'+ Filename +'".'), PChar('TGA File Error'), MB_OK); Exit; end end; // Extract pixel information from compressed data repeat Front := Pointer(Integer(CompImage) + BufferIndex); Inc(BufferIndex); if Front^ < 128 then begin For I := 0 to Front^ do begin CopySwapPixel(Pointer(Integer(CompImage)+BufferIndex+I*ColorDepth), Pointer(Integer(image)+CurrentByte)); CurrentByte := CurrentByte + ColorDepth; inc(CurrentPixel); end; BufferIndex :=BufferIndex + (Front^+1)*ColorDepth end else begin For I := 0 to Front^ -128 do begin CopySwapPixel(Pointer(Integer(CompImage)+BufferIndex), Pointer(Integer(image)+CurrentByte)); CurrentByte := CurrentByte + ColorDepth; inc(CurrentPixel); end; BufferIndex :=BufferIndex + ColorDepth end; until CurrentPixel >= Width*Height; try if ColorDepth = 3 then Texture :=CreateTexture(Width, Height, GL_RGB, Image, NoPicMip, NoMipMap) else Texture :=CreateTexture(Width, Height, GL_RGBA, Image, NoPicMip, NoMipMap); except Texture := 0; end; end; Result := TRUE; if LoadFromStream then memory.Free else CloseFile(TGAFile); try FreeMem(Image); except ; end; end; end; {------------------------------------------------------------------} { Determines file type and sends to correct function } {------------------------------------------------------------------} function LoadTexture(Filename: String; var Texture : GLuint; LoadFromRes, LoadFromStream, NoPicMip, NoMipMap : Boolean) : Boolean; overload; begin result := false; // ShowMessage(FileName); if copy(Uppercase(filename), length(filename)-3, 4) = '.BMP' then result :=LoadBMPTexture(Filename, Texture, LoadFromRes, LoadFromStream, NoPicMip, NoMipMap); if copy(Uppercase(filename), length(filename)-3, 4) = '.JPG' then result := LoadJPGTexture(Filename, Texture, LoadFromRes, LoadFromStream, NoPicMip, NoMipMap); if copy(Uppercase(filename), length(filename)-3, 4) = '.TGA' then result := LoadTGATexture(Filename, Texture, LoadFromRes, LoadFromStream, NoPicMip, NoMipMap); if result = false then ShowMessage(filename); end; function initLocking : boolean; var extensionStr : string; begin if Pos('GL_EXT_compiled_vertex_array', extensionStr) = 0 then begin // glLockArraysEXT := wglGetProcAddress('glLockArraysEXT'); // glUnLockArraysEXT := wglGetProcAddress('glUnLockArraysEXT'); result := true; end else result := false; end; function LoadTextureFromStream(Stream: TStream; var Texture: GLuint; NoPicMip, NoMipMap : Boolean): Boolean; var FileHeader: BITMAPFILEHEADER; InfoHeader: BITMAPINFOHEADER; Palette: array of RGBQUAD; BitmapLength: LongWord; PaletteLength: LongWord; Width, Height : Integer; pData : Pointer; p,j,ExpandBMP,Rmask,Gmask,Bmask : Integer; Format : Word; begin Stream.Position := 0; Stream.ReadBuffer(FileHeader, SizeOf(FileHeader)); // FileHeader Stream.ReadBuffer(InfoHeader, SizeOf(InfoHeader)); // InfoHeader PaletteLength := InfoHeader.biClrUsed; case InfoHeader.biBitCount of 1,4: begin ExpandBMP := InfoHeader.biBitCount; InfoHeader.biBitCount := 8; end; else ExpandBMP := 0; end; case InfoHeader.biCompression of 0: // BI_RGB begin case InfoHeader.biBitCount of 15,16: begin Rmask := $7c00; GMask := $03e0; BMask := $001f; end; // assuming big endian 24: begin Rmask := $ff; GMask := $ff00; Bmask := $ff0000; end; 32: begin Rmask := $ff0000; Gmask := $ff00; Bmask := $ff; end; end; end; 1, // BI_RLE8 2: // BI_RLE4 raise EInvalidGraphic.create('Compressed Bitmaps not handled'); 3: // BI_BitFields begin case InfoHeader.biBitCount of 15,16,32: begin Stream.ReadBuffer(Rmask,sizeof(Rmask)); Stream.ReadBuffer(Gmask,sizeof(Gmask)); Stream.ReadBuffer(Bmask,sizeof(Bmask)); end; end; end; end; if (InfoHeader.biBitCount=24) then Format := GL_RGB else Format := GL_RGBA; SetLength(Palette, PaletteLength); Stream.ReadBuffer(Palette, PaletteLength); // Palette Width := InfoHeader.biWidth; Height := InfoHeader.biHeight; BitmapLength := InfoHeader.biSizeImage; if BitmapLength = 0 then BitmapLength := Width * Height * InfoHeader.biBitCount Div 8; GetMem(pData, BitmapLength); try Stream.ReadBuffer(pData^, BitmapLength); // Bitmap Data // Bitmaps are stored BGR and not RGB, so swap the R and B bytes. if (Rmask<>$ff0000) then SwapRGB(pData, Width*Height); if (InfoHeader.biBitCount=32) then begin SwapRGB(pData,Width*Height); end; Texture :=CreateTexture(Width, Height, format, pData, NoPicMip, NoMipMap); finally FreeMem(pData); end; end; function LoadQuakeTexture(path, name : string; var Texture : GLUINT; NoPicMip, NoMipMap : boolean) : boolean; var ext, fullname, s : string; k, i: integer; JPG : TJPEGImage; BMP : TBitmap; Data : Array of LongWord; W, Width : Integer; H, Height : Integer; Line : ^LongWord; C : LongWord; begin try result := false; ext := ExtractFileExt(name); if (ext <> '.tga') and (ext <> '.jpg') and (ext <> '.bmp') then ext := ''; if Length(ext) > 0 then name := Copy(name, 1, Length(name)-4); // remove ext k := 0; while k < Pk3Zip.BASE_PATH.count do begin // thực ra không cần tìm từng file, vì hàm LoadTexture đã check rồi fullname := path + name + '.tga'; if FileExists(fullname) then begin result := LoadTexture(fullname, Texture, false, false, NoPicMip, NoMipMap); Break; end; fullname := path + name + '.jpg'; if FileExists(fullname) then begin result := LoadTexture(fullname, Texture, false, false, NoPicMip, NoMipMap); Break; end; fullname := path + name + '.bmp'; if FileExists(fullname) then begin result := LoadTexture(fullname, Texture, false, false, NoPicMip, NoMipMap); Break; end; // load in pk3 file // for I := 0 to length(Pk3Zip.FILES_IN_PK3) - 1 do fullname := path + name + '.tga'; if Pk3Zip.GetFileName(fullname) then begin result := LoadTexture(fullname, Texture, false, true, NoPicMip, NoMipMap); // result := LoadTextureFromStream(Pk3Zip.ReadFileInPK3(pk3, fullname), Texture, NoPicMip, NoMipMap); Break; end; fullname := path + name + '.jpg'; if Pk3Zip.GetFileName(fullname) then begin result := LoadTexture(fullname, Texture, false, true, NoPicMip, NoMipMap); Break; end; fullname := path + name + '.bmp'; if Pk3Zip.GetFileName(fullname) then begin result := LoadTexture(fullname, Texture, false, true, NoPicMip, NoMipMap); Break; end; path := Pk3Zip.BASE_PATH.Strings[k]; inc(k); end; if not Result then Texture := 0; except ext := ext; end; end; {------------------------------------------------------------------} { Determines file type and sends to correct function } {------------------------------------------------------------------} function LoadTexture(Filename: String; var Texture : GLuint; LoadFromRes, LoadFromStream : Boolean) : Boolean; begin if copy(Uppercase(filename), length(filename)-3, 4) = '.BMP' then LoadBMPTexture(Filename, Texture, LoadFromRes, LoadFromStream, false, false); if copy(Uppercase(filename), length(filename)-3, 4) = '.JPG' then LoadJPGTexture(Filename, Texture, LoadFromRes, LoadFromStream, false, false); if copy(Uppercase(filename), length(filename)-3, 4) = '.TGA' then LoadTGATexture(Filename, Texture, LoadFromRes, LoadFromStream, false, false); end; end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Actions, Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan, Vcl.StdCtrls, Vcl.Buttons, System.UITypes, Math, MMSystem, uWaveApi, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.Imaging.pngimage; type TWaveFormGenerator = reference to function(Period: Float): Float; TADSR = record Attack: Cardinal; Decay: Cardinal; Sustain: Extended; Release: Cardinal; end; TPreset = record Amplitude: Extended; WaveFormGenerator: TWaveFormGenerator; ModFreq: Extended; ModMultiplier: Extended; ADSR: TADSR; end; TWave = class(TComponent) public Preset: TPreset; private function GetAmplitudeEnvelope(Milliseconds: Float; ReleaseMilliseconds: Float): Float; public function GetWaveGenerator(Frequency: Float; KeyIsReleasedFunc: TFunc<Boolean>): TWaveGenerator; end; TWaveSet = TWave; TfrMain = class(TForm) imgKeyboard: TImage; tmrWaveRepaint: TTimer; pbWave: TPaintBox; Panel1: TPanel; eValue: TEdit; labelControlValue: TLabel; tbAmplitude: TTrackBar; labelAmplitude: TLabel; rgWaveForm: TRadioGroup; gbFM: TGroupBox; labelFMMultiplier: TLabel; labelFMFrequency: TLabel; tbModMultiplier: TTrackBar; tbModFreq: TTrackBar; gbADSR: TGroupBox; labelSustain: TLabel; labelAttack: TLabel; labelDecay: TLabel; labelRelease: TLabel; pbADSR: TPaintBox; tbSustain: TTrackBar; tbAttack: TTrackBar; tbDecay: TTrackBar; tbRelease: TTrackBar; tvWaves: TTreeView; btnPresetAdd: TButton; btnPresetDelete: TButton; procedure FormCreate(Sender: TObject); procedure OnUIChange(Sender: TObject); procedure pbWavePaint(Sender: TObject); procedure tmrWaveRepaintTimer(Sender: TObject); procedure pbADSRPaint(Sender: TObject); procedure btnPresetAddClick(Sender: TObject); procedure btnPresetDeleteClick(Sender: TObject); procedure tvWavesChange(Sender: TObject; Node: TTreeNode); procedure FormDestroy(Sender: TObject); const PaintWaveFrequency = 3; vkCodePaint = $FFFF; private Keyboard: array [0..255] of Boolean; KeysAndNoteIds: array [0..255] of Cardinal; KeysAndFrequencies: array [0..255] of Float; Wave: TWave; LastNoteTime: Cardinal; LastNoteFrequency: Float; PaintWaveFunc: TGetWaveVal; procedure OnAppMessage(var Msg: TMsg; var Handled: Boolean); procedure OnKeyDown(var vkCode: Cardinal); procedure OnKeyUp(var vkCode: Cardinal); procedure InitWaveFormGenerators(); procedure InitKeyFrequencies(); procedure UpdateUI; procedure OnControlMouseEnter(Sender: TObject); procedure PrepareUI; function GetControlValue(C: TControl): Variant; function GetWaveGenerator(Frequency: Float; KeyIsReleasedFunc: TFunc<Boolean> = nil): TWaveGenerator; function GetLastNoteTime: Cardinal; procedure PlayNote(vkCode: Cardinal); function GetTrackBarValue(tb: TTrackBar): Float; procedure StopNote(vkCode: Cardinal); procedure OnKeyUpDown(var Msg: TMsg; var Handled: Boolean); function GetControlDrawRect(Control: TControl): TRect; procedure CleanUpPaintBox(pb: TPaintBox); private Preset: TPreset; end; var frMain: TfrMain; implementation {$R *.dfm} type TWaveFormGeneratorType = (wfSine, wfTriangle, wfSaw, wfFlat, wfCosine); var WaveFormGenerators: array[Low(TWaveFormGeneratorType)..High(TWaveFormGeneratorType)] of TWaveFormGenerator; procedure TfrMain.FormCreate(Sender: TObject); begin FillChar(Keyboard, Length(Keyboard), False); FillChar(KeysAndNoteIds, Length(KeysAndNoteIds), 0); Wave := TWaveSet.Create(Self); PaintWaveFunc := GetWaveGenerator(3)(0); LastNoteFrequency := 440; LastNoteTime := timeGetTime; InitWaveFormGenerators(); InitKeyFrequencies(); PrepareUI(); Application.OnMessage := OnAppMessage; end; procedure TfrMain.FormDestroy(Sender: TObject); var vkCode: Byte; begin for vkCode := Low(Keyboard) to Low(Keyboard) do StopNote(vkCode); Sleep(500); end; type TLocalControl = class(TControl); procedure TfrMain.PrepareUI(); var C: TComponent; begin for C in Self do if C is TControl then TLocalControl(C).OnMouseEnter := OnControlMouseEnter; tvWaves.FullExpand(); tvWaves.Selected := tvWaves.Items.GetFirstNode(); UpdateUI(); end; procedure TfrMain.OnUIChange(Sender: TObject); begin OnControlMouseEnter(Sender); UpdateUI(); pbADSR.Repaint(); end; procedure TfrMain.UpdateUI(); begin Preset.WaveFormGenerator := WaveFormGenerators[TWaveFormGeneratorType(rgWaveForm.ItemIndex)]; Preset.Amplitude := GetControlValue(tbAmplitude); Preset.ModFreq := GetControlValue(tbModFreq); Preset.ModMultiplier := GetControlValue(tbModMultiplier); Preset.ADSR.Attack := GetControlValue(tbAttack); Preset.ADSR.Decay := GetControlValue(tbDecay); Preset.ADSR.Sustain := GetControlValue(tbSustain); Preset.ADSR.Release := GetControlValue(tbRelease); end; function TfrMain.GetControlValue(C: TControl): Variant; var tbVal: Variant; begin if C is TTrackBar then tbVal := GetTrackBarValue(TTrackBar(C)); if (C = tbAmplitude) or (C = tbSustain) then Result := tbVal else if C = tbModFreq then Result := Power(tbVal, 6) * 1000 else if C = tbModMultiplier then Result := 1 + Power(tbVal, 6) * 8 else if (C = tbAttack) or (C = tbDecay) then Result := 1 + Round(Power(tbVal, 2) * 1999) else if C = tbRelease then Result := 1 + Round(Power(tbVal, 3) * 4999); end; function TfrMain.GetTrackBarValue(tb: TTrackBar): Float; begin Result := (tb.Position - tb.Min) / (tb.Max - tb.Min) end; procedure TfrMain.OnAppMessage(var Msg: TMsg; var Handled: Boolean); begin case Msg.message of WM_KEYDOWN, WM_KEYUP: OnKeyUpDown(Msg, Handled); end; end; procedure TfrMain.OnKeyUpDown(var Msg: TMsg; var Handled: Boolean); var vkCode: Cardinal; Down: Boolean; begin vkCode := Msg.wParam; if vkCode = 0 then Exit(); Assert(vkCode in [0..255]); Down := Msg.message = WM_KEYDOWN; if Keyboard[vkCode] = Down then Exit(); Keyboard[vkCode] := Down; if Down then OnKeyDown(vkCode) else OnKeyUp(vkCode); Handled := vkCode <> 0; end; procedure TfrMain.OnKeyDown(var vkCode: Cardinal); begin if KeysAndFrequencies[vkCode] > 0 then begin StopNote(vkCode); PlayNote(vkCode); end; end; procedure TfrMain.OnKeyUp(var vkCode: Cardinal); begin end; procedure TfrMain.StopNote(vkCode: Cardinal); begin if KeysAndNoteIds[vkCode] > 0 then begin TWaveApi.Stop(KeysAndNoteIds[vkCode]); KeysAndNoteIds[vkCode] := 0; end; end; procedure TfrMain.PlayNote(vkCode: Cardinal); begin LastNoteFrequency := KeysAndFrequencies[vkCode]; LastNoteTime := timeGetTime; KeysAndNoteIds[vkCode] := TWaveApi.Play(Wave.GetWaveGenerator( KeysAndFrequencies[vkCode], function(): Boolean begin Result := not Keyboard[vkCode]; if Result then Assert(True); end )); KeysAndNoteIds[vkCode] := TWaveApi.Play(GetWaveGenerator( KeysAndFrequencies[vkCode], function(): Boolean begin Result := not Keyboard[vkCode]; if Result then Assert(True); end )); end; function TfrMain.GetWaveGenerator(Frequency: Float; KeyIsReleasedFunc: TFunc<Boolean>): TWaveGenerator; var ReleaseMilliseconds: Float; GetAmplEnvelope: TGetWaveVal; GetWaveVal: TGetWaveVal; begin if not Assigned(KeyIsReleasedFunc) then KeyIsReleasedFunc := function(): Boolean begin Result := False; end; ReleaseMilliseconds := 0; GetAmplEnvelope := function (Milliseconds: Float): Float begin if Milliseconds < Preset.ADSR.Attack then Result := 0.0001 + Milliseconds / Preset.ADSR.Attack else if Milliseconds < Preset.ADSR.Attack + Preset.ADSR.Decay then Result := 1 - (1 - Preset.ADSR.Sustain) * (Milliseconds - Preset.ADSR.Attack) / Preset.ADSR.Decay else if ReleaseMilliseconds = 0 then Result := Preset.ADSR.Sustain else Result := Preset.ADSR.Sustain * (1 - Power((Milliseconds - ReleaseMilliseconds) / Preset.ADSR.Release, 2)); if Result < 0 then Result := 0; end; Result := function(Milliseconds: Float): TGetWaveVal var MustPlayPeriod: Float; begin if (ReleaseMilliseconds > 0) and (Milliseconds > ReleaseMilliseconds + Preset.ADSR.Release) then Exit(nil); MustPlayPeriod := Preset.ADSR.Attack + Preset.ADSR.Decay; if (Milliseconds > MustPlayPeriod) and (ReleaseMilliseconds = 0) and KeyIsReleasedFunc() then ReleaseMilliseconds := Milliseconds; Result := GetWaveVal; end; GetWaveVal := function(Milliseconds: Float): Float var FreqEnvelope: Float; AmplEnvelope: Float; begin AmplEnvelope := GetAmplEnvelope(Milliseconds); FreqEnvelope := Power( Preset.ModMultiplier, WaveFormGenerators[wfSine](Preset.ModFreq * Milliseconds / 1000) ); Result := Preset.WaveFormGenerator(Frequency * Milliseconds / 1000 * FreqEnvelope) * Preset.Amplitude * AmplEnvelope; end; end; procedure TfrMain.tmrWaveRepaintTimer(Sender: TObject); begin pbWave.Repaint(); end; procedure TfrMain.pbWavePaint(Sender: TObject); var C: TCanvas; SemiAmplitude, HCenter: Integer; X: Integer; DrawRect: TRect; function GetY(): Integer; var Time: Cardinal; begin Time := Round(GetLastNoteTime() * LastNoteFrequency / PaintWaveFrequency) div 1000; Result := Round(HCenter - SemiAmplitude * PaintWaveFunc(Time * 1000 + 1000 * X / (DrawRect.Width - 1))); end; begin DrawRect := GetControlDrawRect(pbWave); HCenter := DrawRect.CenterPoint.Y; SemiAmplitude := DrawRect.Height div 2; CleanUpPaintBox(pbWave); C := pbWave.Canvas; C.Pen.Color := clGray; C.MoveTo(DrawRect.Left, DrawRect.Top); C.LineTo(DrawRect.Left, DrawRect.Bottom); C.MoveTo(DrawRect.Right, HCenter); C.LineTo(DrawRect.Left, HCenter); C.Pen.Color := clBlue; X := 0; C.MoveTo(X + DrawRect.Left, GetY()); for X := 1 to DrawRect.Width - 1 do C.LineTo(X + DrawRect.Left, GetY()); end; function TfrMain.GetControlDrawRect(Control: TControl): TRect; var H, W, GapX, GapY: Integer; begin H := Control.Height; W := Control.Width; GapX := W div 20; GapY := H div 10; Result := Rect(GapX, GapY, W - GapX, H - GapY); end; procedure TfrMain.CleanUpPaintBox(pb: TPaintBox); begin pb.Canvas.Brush.Color := clCream; pb.Canvas.FillRect(pb.ClientRect); end; procedure TfrMain.pbADSRPaint(Sender: TObject); var DrawRect: TRect; Quarter, Amp: Integer; C: TCanvas; X, Y: Integer; begin DrawRect := GetControlDrawRect(pbADSR); Quarter := DrawRect.Width div 4; CleanUpPaintBox(pbADSR); C := pbADSR.Canvas; C.Pen.Color := clGray; C.MoveTo(DrawRect.Left, DrawRect.Top); C.LineTo(DrawRect.Left, DrawRect.Bottom); C.LineTo(DrawRect.Right, DrawRect.Bottom); C.Pen.Color := clBlue; X := DrawRect.Left; Y := DrawRect.Bottom; C.MoveTo(X, Y); X := X + Round(Quarter * GetTrackBarValue(tbAttack)); Amp := Round(DrawRect.Height * GetTrackBarValue(tbAmplitude)); Y := DrawRect.Bottom - Amp; C.LineTo(X, Y); X := X + Round(Quarter * GetTrackBarValue(tbDecay)); Amp := Round(Amp * GetTrackBarValue(tbSustain)); Y := DrawRect.Bottom - Amp; C.LineTo(X, Y); X := X + Quarter; C.LineTo(X, Y); X := X + Round(Quarter * GetTrackBarValue(tbRelease)); Y := DrawRect.Bottom; C.LineTo(X, Y); end; function TfrMain.GetLastNoteTime(): Cardinal; begin Result := MMSystem.timeGetTime - LastNoteTime; end; procedure TfrMain.OnControlMouseEnter(Sender: TObject); var Value: Extended; begin if Sender is TTrackBar then TWinControl(Sender).SetFocus(); if not (Sender is TTrackBar) then Exit(); Value := GetControlValue(TControl(Sender)); eValue.Text := Format('%10.10f', [Value]); end; procedure TfrMain.InitKeyFrequencies(); function Arr(const A: TArray<Cardinal>): TArray<Cardinal>; begin Result := A; end; var I: Integer; Freq, NoteStep: Extended; vkCode: Cardinal; begin for I := 0 to High(KeysAndFrequencies) do KeysAndFrequencies[I] := 0; NoteStep := Power(2, 1/12); Freq := 220; KeysAndFrequencies[vkA] := Freq / NoteStep; for vkCode in Arr([ vkZ, vkS, vkX, vkC, vkF, vkV, vkG, vkB, vkN, vkJ, vkM, vkK, vkComma, vkL, vkPeriod, vkSlash, vkQuote ]) do begin KeysAndFrequencies[vkCode] := Freq; Freq := Freq * NoteStep; end; Freq := 440; KeysAndFrequencies[vk1] := Freq / NoteStep; for vkCode in Arr([ vkQ, vk2, vkW, vkE, vk4, vkR, vk5, vkT, vkY, vk7, vkU, vk8, vkI, vk9, vkO, vkP, vkMinus, vkLeftBracket, vkEqual, vkRightBracket ]) do begin KeysAndFrequencies[vkCode] := Freq; Freq := Freq * NoteStep; end; end; procedure TfrMain.InitWaveFormGenerators(); begin WaveFormGenerators[wfSine] := function(Period: Float): Float begin Result := Sin(2*Pi * Period); end; WaveFormGenerators[wfTriangle] := function(Period: Float): Float begin Period := Frac(Period); if Period < 0.25 then Result := Period * 4 else if Period < 0.75 then Result := 2 - Period * 4 else Result := (-1 + Period) * 4; end; WaveFormGenerators[wfSaw] := function(Period: Float): Float begin Result := -1 + Frac(Period) * 2; end; WaveFormGenerators[wfFlat] := function(Period: Float): Float begin if Frac(Period) < 0.5 then Result := 1.0 else Result := -1.0; end; WaveFormGenerators[wfCosine] := function(Period: Float): Float begin Result := Cos(2*Pi * Period); end; end; procedure TfrMain.btnPresetAddClick(Sender: TObject); begin if not Assigned(tvWaves.Selected) then tvWaves.Selected := tvWaves.Items.GetFirstNode(); tvWaves.Items.AddChild(tvWaves.Selected, (tvWaves.Items.Count + 1).ToString()); tvWaves.Selected.Expand(True); end; procedure TfrMain.btnPresetDeleteClick(Sender: TObject); var N: TTreeNode; begin N := tvWaves.Selected; tvWaves.Items.Delete(N); // end; { procedure TfrMain.InitTreeView(); //var // N: TTreeNode; begin tvWaves.Items.Clear(); // N := tvWaves.Selected; // // tvWaves.Items.Delete(N); // end; } procedure TfrMain.tvWavesChange(Sender: TObject; Node: TTreeNode); begin btnPresetDelete.Enabled := Node <> tvWaves.Items.GetFirstNode; end; { TWave } function TWave.GetAmplitudeEnvelope(Milliseconds: Float; ReleaseMilliseconds: Float): Float; begin if Milliseconds < Preset.ADSR.Attack then Result := 0.0001 + Milliseconds / Preset.ADSR.Attack else if Milliseconds < Preset.ADSR.Attack + Preset.ADSR.Decay then Result := 1 - (1 - Preset.ADSR.Sustain) * (Milliseconds - Preset.ADSR.Attack) / Preset.ADSR.Decay else if ReleaseMilliseconds = 0 then Result := Preset.ADSR.Sustain else Result := Preset.ADSR.Sustain * (1 - Power((Milliseconds - ReleaseMilliseconds) / Preset.ADSR.Release, 2)); if Result < 0 then Result := 0; end; function TWave.GetWaveGenerator(Frequency: Float; KeyIsReleasedFunc: TFunc<Boolean>): TWaveGenerator; begin end; end.
unit RepositorioRetornoNFe; interface uses DB, Repositorio; type TRepositorioRetornoNFe = class(TRepositorio) 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; protected function IsInsercao(Objeto :TObject) :Boolean; override; function IsComponente :Boolean; override; protected procedure SetParametros (Objeto :TObject ); override; end; implementation uses RetornoNFe, SysUtils; { TRepositorioRetornoNFe } function TRepositorioRetornoNFe.Get(Dataset: TDataSet): TObject; begin result := TRetornoNFe.Create(Dataset.FieldByName('codigo_nota_fiscal').AsInteger, Dataset.FieldByName('status').AsString, Dataset.FieldByName('motivo').AsString); end; function TRepositorioRetornoNFe.GetIdentificador(Objeto: TObject): Variant; begin result := TRetornoNFe(Objeto).CodigoNotaFiscal; end; function TRepositorioRetornoNFe.GetNomeDaTabela: String; begin result := 'notas_fiscais_nfe_retorno'; end; function TRepositorioRetornoNFe.GetRepositorio: TRepositorio; begin result := TRepositorioRetornoNFe.Create; end; function TRepositorioRetornoNFe.IsComponente: Boolean; begin result := true; end; function TRepositorioRetornoNFe.IsInsercao(Objeto: TObject): Boolean; begin result := true; end; procedure TRepositorioRetornoNFe.SetParametros(Objeto: TObject); var RetornoNFe :TRetornoNFe; begin RetornoNFe := (Objeto as TRetornoNFe); inherited SetParametro('codigo_nota_fiscal', RetornoNFe.CodigoNotaFiscal); inherited SetParametro('status', RetornoNFe.Status); inherited SetParametro('motivo', RetornoNFe.Motivo); end; function TRepositorioRetornoNFe.SQLGet: String; begin result := ' select * from '+self.GetNomeDaTabela+' where codigo_nota_fiscal = :codigo_nota_fiscal '; end; function TRepositorioRetornoNFe.SQLGetAll: String; begin result := ' select * from '+ self.GetNomeDaTabela+' order by codigo_nota_fiscal '; end; function TRepositorioRetornoNFe.SQLRemover: String; begin result := 'delete from '+self.GetNomeDaTabela+' where codigo_nota_fiscal = :codigo_nota_fiscal '; end; function TRepositorioRetornoNFe.SQLSalvar: String; begin result := 'update or insert into '+self.GetNomeDaTabela+' (codigo_nota_fiscal, status, motivo) '+ 'values (:codigo_nota_fiscal, :status, :motivo) '; end; end.
(*--------------------------------------------------------*) (* Übung 2 (BSP. 2. Sortieren von 3 Zahlen) *) (* Entwickler: Neuhold Michael *) (* Datum: 17.10.2018 *) (* Verson: 1.0 *) (* Lösungsidee: Schrittweises sortieren von drei Zahlen *) (* nur mit Verzweigungen. *) (*--------------------------------------------------------*) PROGRAM Sortieren; VAR a,b,c,h : INTEGER; (* h...Hilfsvariable für Wertetausch *) BEGIN WriteLn('<#----- SORT 3 NUMBERS -----#>'); WriteLn('Bitte geben Sie 3 Werte ein!'); ReadLn(a,b,c); IF a > b THEN BEGIN (* 1. Sortierschritt *) h := b; b := a; a := h; END; IF b > c THEN BEGIN (* 2. Sortierschritt *) h := c; c := b; b := h; END; IF a > b THEN BEGIN (* 3. Sortierschritt *) h := b; b := a; a := h; END; WriteLn('Hier die Zahlen in aufsteigender Reihenfolge:', a,b,c); END.
unit UCL.Utils; interface uses VCL.Graphics, VCL.GraphUtil, Winapi.Windows; // Color utils function BrightenColor(aColor: TColor; Delta: Integer): TColor; function GetTextColorFromBackground(BackgroundColor: TColor): TColor; function ChangeColor(aColor: TColor; Base: Single): TColor; implementation { COLOR UTILS } function BrightenColor(aColor: TColor; Delta: Integer): TColor; var H, S, L: Word; begin ColorRGBToHLS(aColor, H, L, S); // VCL.GraphUtil L := L + Delta; Result := ColorHLSToRGB(H, L, S); end; function GetTextColorFromBackground(BackgroundColor: TColor): TColor; var C: Integer; R, G, B: Byte; begin C := ColorToRGB(BackgroundColor); R := GetRValue(C); G := GetGValue(C); B := GetBValue(C); if 0.299 * R + 0.587 * G + 0.114 * B > 186 then Result := clBlack else Result := clWhite; end; function ChangeColor(aColor: TColor; Base: Single): TColor; var C: Integer; R, G, B: Byte; begin C := ColorToRGB(aColor); R := Round(GetRValue(C) * Base); G := Round(GetGValue(C) * Base); B := Round(GetBValue(C) * Base); Result := RGB(R, G, B); end; end.
{******************************************************************************} { } { Icon Fonts ImageList: An extended ImageList for Delphi/VCL } { to simplify use of Icons (resize, colors and more...) } { } { Copyright (c) 2019-2023 (Ethea S.r.l.) } { Author: Carlo Barazzetta } { Contributors: } { Nicola Tambascia } { Luca Minuti } { } { https://github.com/EtheaDev/IconFontsImageList } { } {******************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {******************************************************************************} unit IconFontsItems; interface {$INCLUDE IconFontsImageList.inc} uses Classes , ImgList , Windows , Graphics {$IFDEF D10_4+} , System.UITypes {$ENDIF} {$IFDEF HiDPISupport} , Messaging {$ENDIF} {$IFDEF GDI+} , Winapi.GDIPOBJ , Winapi.GDIPAPI {$ENDIF} , Controls , Forms; resourcestring ERR_ICONFONTS_VALUE_NOT_ACCEPTED = 'Value %s not accepted!'; const DEFAULT_OPACITY = 255; DEFAULT_DISABLE_FACTOR = 100; ZOOM_DEFAULT = 100; type TIconFontItem = class; TIconFontItems = class; TIconFont = class(TObject) private FFontName: TFontName; FFontIconDec: Integer; FFontColor: TColor; FMaskColor: TColor; FOpacity: Byte; FIconName: string; FDisabledFactor: Byte; public function GetBitmap(const AWidth, AHeight: Integer; const AFontName: TFontName; AFontIconDec: Integer; const AFontColor, AMaskColor: TColor; const AEnabled: Boolean = True; const ADisabledFactor: Byte = DEFAULT_DISABLE_FACTOR; const AOpacity: Byte = DEFAULT_OPACITY; const AZoom: Integer = ZOOM_DEFAULT): TBitmap; procedure Assign(Source: TIconFont); {$IFDEF GDI+} procedure PaintToGDI(const AGraphics: TGPGraphics; const X, Y, AWidth, AHeight: Single; const AFontName: TFontName; AFontIconDec: Integer; const AFontColor: TColor; const AEnabled: Boolean = True; const ADisabledFactor: Byte = DEFAULT_DISABLE_FACTOR; const AOpacity: Byte = DEFAULT_OPACITY; const AZoom: Integer = ZOOM_DEFAULT); {$ENDIF} procedure PaintTo(const ACanvas: TCanvas; const X, Y, AWidth, AHeight: Integer; const AFontName: TFontName; AFontIconDec: Integer; const AFontColor, AMaskColor: TColor; const AEnabled: Boolean = True; const ADisabledFactor: Byte = DEFAULT_DISABLE_FACTOR; const AZoom: Integer = ZOOM_DEFAULT); end; TIconFontItem = class(TCollectionItem) private FIconFont: TIconFont; FFontName: TFontName; FFontIconDec: Integer; FFontColor: TColor; FMaskColor: TColor; FIconName: string; procedure SetFontColor(const AValue: TColor); procedure SetFontName(const AValue: TFontName); procedure SetMaskColor(const AValue: TColor); procedure SetIconName(const AValue: string); procedure SetFontIconHex(const AValue: string); procedure SetFontIconDec(const AValue: Integer); function GetFontIconDec: Integer; function GetFontIconHex: string; procedure Changed; function GetCharacter: WideString; function GetCategory: string; function GetName: string; procedure SetCategory(const Value: string); procedure SetName(const Value: string); function ExtractCategory(const S: String): String; function ExtractName(const S: String): String; procedure BuildIconName(const ACategory, AName: String); function StoreFontColor: Boolean; function StoreMaskColor: Boolean; function StoreFontName: Boolean; function GetIconFont: TIconFont; function GetIconFontItems: TIconFontItems; protected procedure SetIndex(Value: Integer); override; public function GetBitmap(const AWidth, AHeight: Integer; const AEnabled: Boolean; AOpacity: Byte = DEFAULT_OPACITY; const ADisabledFactor: Byte = DEFAULT_DISABLE_FACTOR; const AZoom: Integer = ZOOM_DEFAULT): TBitmap; {$IFDEF GDI+} procedure PaintTo(const ACanvas: TCanvas; const X, Y, AWidth, AHeight: Integer; const AEnabled: Boolean = True; const ADisabledFactor: Byte = DEFAULT_DISABLE_FACTOR; const AOpacity: Byte = DEFAULT_OPACITY; const AZoom: Integer = ZOOM_DEFAULT); {$ELSE} procedure PaintTo(const ACanvas: TCanvas; const X, Y, AWidth, AHeight: Integer; out AMaskColor: TColor; const AEnabled: Boolean = True; const ADisabledFactor: Byte = DEFAULT_DISABLE_FACTOR; const AZoom: Integer = ZOOM_DEFAULT); {$ENDIF} function GetDisplayName: string; override; constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; function FontNameOfIcon: TFontName; property Character: WideString read GetCharacter; property IconFontItems: TIconFontItems read GetIconFontItems; property IconFont: TIconFont read GetIconFont; property Name: string read GetName write SetName; property Category: string read GetCategory write SetCategory; published property FontIconDec: Integer read GetFontIconDec write SetFontIconDec stored true default 0; property FontIconHex: string read GetFontIconHex write SetFontIconHex stored false; property FontName: TFontName read FFontName write SetFontName stored StoreFontName; property FontColor: TColor read FFontColor write SetFontColor stored StoreFontColor; property MaskColor: TColor read FMaskColor write SetMaskColor stored StoreMaskColor; property IconName: string read FIconName write SetIconName; end; TIconFontItemChangedProc = procedure (Sender: TIconFontItem) of object; TCheckFontNameProc = procedure (const AFontName: TFontName) of object; TGetOwnerAttributesProc = procedure (out AFontName: TFontName; out AFontColor, AMaskColor: TColor) of object; {TIconFontItems} TIconFontItems = class(TOwnedCollection) private FOnItemChanged: TIconFontItemChangedProc; FOnCheckFont: TCheckFontNameProc; FGetOwnerAttributes: TGetOwnerAttributesProc; FOwnerFontName: TFontName; FOwnerFontColor: TColor; FOwnerMaskColor: TColor; procedure UpdateOwnerAttributes; function GetItem(AIndex: Integer): TIconFontItem; procedure SetItem(AIndex: Integer; const Value: TIconFontItem); procedure ItemChanged(const AItem: TIconFontItem); function IsCharAvailable(const ABitmap: TBitmap; const AFontIconDec: Integer): Boolean; protected public constructor Create(const AOwner: TPersistent; const ItemClass: TCollectionItemClass; const AOnItemChanged: TIconFontItemChangedProc; const AOnCheckFont: TCheckFontNameProc; const AGetOwnerAttributes: TGetOwnerAttributesProc); procedure UpdateIconsAttributes(const AFontColor, AMaskColor: TColor; const AFontName: TFontName = ''); //Single Icon Method function AddIcon(const AChar: Integer; const AIconName: string; const AFontName: TFontName = ''; const AFontColor: TColor = clDefault; const AMaskColor: TColor = clNone): TIconFontItem; overload; function AddIcon(const AChar: WideChar; const AFontName: TFontName = ''; const AFontColor: TColor = clDefault; const AMaskColor: TColor = clNone): TIconFontItem; overload; function AddIcon(const AChar: Integer; const AFontName: TFontName = ''; const AFontColor: TColor = clDefault; const AMaskColor: TColor = clNone): TIconFontItem; overload; //Multiple icons methods function AddIcons(const AFrom, ATo: WideChar; const AFontName: TFontName = ''; const AFontColor: TColor = clDefault; AMaskColor: TColor = clNone; const ACheckValid: Boolean = False): Integer; overload; function AddIcons(const AFrom, ATo: Integer; const AFontName: TFontName = ''; const AFontColor: TColor = clDefault; AMaskColor: TColor = clNone; const ACheckValid: Boolean = False): Integer; overload; function AddIcons(const ASourceString: WideString; const AFontName: TFontName = ''): Integer; overload; function Add: TIconFontItem; procedure Assign(Source: TPersistent); override; function Insert(AIndex: Integer): TIconFontItem; procedure Delete(AIndex: Integer); function GetIconByName(const AIconName: string): TIconFontItem; function IndexOf(const S: string): Integer; virtual; property Items[Index: Integer]: TIconFontItem read GetItem write SetItem; default; end; function IsFontIconValidValue(const AFontIconDec: Integer): Boolean; implementation uses SysUtils , IconFontsUtils , Math , ComCtrls {$IFDEF DXE3+} , System.Character , Themes {$ENDIF} {$IFDEF GDI+} , Winapi.CommCtrl {$ENDIF} , StrUtils ; const CATEGORY_SEP = '\'; function IsFontIconValidValue(const AFontIconDec: Integer): Boolean; begin Result := ((AFontIconDec >= $0000) and (AFontIconDec <= $D7FF)) or ((AFontIconDec >= $E000) and (AFontIconDec < $FFFF)) or //D800 to DFFF are reserved for code point values for Surrogate Pairs ((AFontIconDec >= $010000) and (AFontIconDec <= $10FFFF)); //Surrogate Pairs end; {$IFDEF GDI+} function GPColor(Col: TColor; Alpha: Byte): TGPColor; type TInvRGBQUAD = packed record rgbRed: Byte; rgbGreen: Byte; rgbBlue: Byte; rgbReserved: Byte; end; var rec: TInvRGBQuad; rec2: TRGBQuad; ciCol: Cardinal; begin { This will get the RGB color from a system colour, then we can convert this value to a GDI+ colour } rec := TInvRGBQuad(Col); if rec.rgbReserved = 128 then // $80 then {or =128} begin ciCol := $80000000 XOR DWORD(Col); ciCol := GetSysColor(ciCol); rec2 := TRGBQuad(ciCol); { Could also just use REC here, and pass Blue where red is requested, and Red where blue is requested, should probably still result in the same effect } Result := MakeColor(Alpha, rec2.rgbRed, rec2.rgbGreen, rec2.rgbBlue); end else Result := MakeColor(Alpha, rec.rgbRed, rec.rgbGreen, rec.rgbBlue); end; {$ENDIF} { TIconFontItem } procedure TIconFontItem.Assign(Source: TPersistent); begin if Source is TIconFontItem then begin FFontName := TIconFontItem(Source).FFontName; FFontIconDec := TIconFontItem(Source).FFontIconDec; FFontColor := TIconFontItem(Source).FFontColor; FMaskColor := TIconFontItem(Source).FMaskColor; FIconName := TIconFontItem(Source).FIconName; end else inherited Assign(Source); end; constructor TIconFontItem.Create(Collection: TCollection); begin inherited Create(Collection); FIconFont := TIconFont.Create; FFontIconDec := 0; FFontColor := clDefault; FMaskColor := clNone; end; destructor TIconFontItem.Destroy; begin FIconFont.Free; inherited Destroy; end; function TIconFontItem.StoreFontColor: Boolean; begin IconFontItems.UpdateOwnerAttributes; Result := (FFontColor <> IconFontItems.FOwnerFontColor) and (FFontColor <> clDefault); end; function TIconFontItem.StoreFontName: Boolean; begin IconFontItems.UpdateOwnerAttributes; Result := (FFontName <> IconFontItems.FOwnerFontName) and (FFontName <> ''); end; function TIconFontItem.StoreMaskColor: Boolean; begin IconFontItems.UpdateOwnerAttributes; Result := (FMaskColor <> IconFontItems.FOwnerMaskColor) and (FMaskColor <> clNone); end; function TIconFontItem.GetBitmap(const AWidth, AHeight: Integer; const AEnabled: Boolean; AOpacity: Byte = DEFAULT_OPACITY; const ADisabledFactor: Byte = DEFAULT_DISABLE_FACTOR; const AZoom: Integer = ZOOM_DEFAULT): TBitmap; var LFontColor, LMaskColor: TColor; LFontName: TFontName; begin //Default values from ImageList if not supplied from Item IconFontItems.UpdateOwnerAttributes; if FMaskColor <> clNone then LMaskColor := FMaskColor else LMaskColor := IconFontItems.FOwnerMaskColor; if FFontColor <> clDefault then LFontColor := FFontColor else LFontColor := IconFontItems.FOwnerFontColor; if not AEnabled then LFontColor := GrayscaleColor(LFontColor); LFontName := FontNameOfIcon; if Assigned(IconFontItems.FOnCheckFont) then IconFontItems.FOnCheckFont(LFontName); Result := FIconFont.GetBitmap(AWidth, AHeight, LFontName, FFontIconDec, LFontColor, LMaskColor, AEnabled, ADisabledFactor, AOpacity, AZoom); end; function TIconFontItem.GetName: string; begin Result := ExtractName(FIconName); end; function TIconFontItem.GetCategory: string; begin Result := ExtractCategory(FIconName); end; procedure TIconFontItem.SetCategory(const Value: string); begin BuildIconName(Value, Name); end; function TIconFontItem.GetCharacter: WideString; begin {$IFDEF DXE3+} {$WARN SYMBOL_DEPRECATED OFF} Result := ConvertFromUtf32(FFontIconDec); {$WARN SYMBOL_DEPRECATED ON} {$ELSE} Result := WideChar(FFontIconDec); {$ENDIF} end; function TIconFontItem.GetDisplayName: string; begin Result := Format('%s - Hex: %s%s', [FFontName, FontIconHex, ifthen(FIconName<>'', ' - ('+FIconName+')', '')]); end; function TIconFontItem.GetFontIconDec: Integer; begin Result := FFontIconDec; end; function TIconFontItem.GetFontIconHex: string; begin if FFontIconDec <> 0 then Result := RightStr('0000'+IntToHex(FFontIconDec, 1),5) else Result := ''; end; function TIconFontItem.GetIconFont: TIconFont; begin Result := FIconFont; end; function TIconFontItem.GetIconFontItems: TIconFontItems; begin Result := TIconFontItems(Collection); end; {$IFDEF GDI+} procedure TIconFontItem.PaintTo(const ACanvas: TCanvas; const X, Y, AWidth, AHeight: Integer; const AEnabled: Boolean = True; const ADisabledFactor: Byte = DEFAULT_DISABLE_FACTOR; const AOpacity: Byte = DEFAULT_OPACITY; const AZoom: Integer = ZOOM_DEFAULT); {$ELSE} procedure TIconFontItem.PaintTo(const ACanvas: TCanvas; const X, Y, AWidth, AHeight: Integer; out AMaskColor: TColor; const AEnabled: Boolean = True; const ADisabledFactor: Byte = DEFAULT_DISABLE_FACTOR; const AZoom: Integer = ZOOM_DEFAULT); {$ENDIF} var LFontColor: TColor; LFontName: TFontName; {$IFDEF GDI+} LGPGraphics: TGPGraphics; {$ENDIF} begin //Default values from ImageList if not supplied from Item IconFontItems.UpdateOwnerAttributes; {$IFNDEF GDI+} if FMaskColor <> clNone then AMaskColor := FMaskColor else AMaskColor := IconFontItems.FOwnerMaskColor; {$ENDIF} if FFontColor <> clDefault then LFontColor := FFontColor else LFontColor := IconFontItems.FOwnerFontColor; if not AEnabled then LFontColor := GrayscaleColor(LFontColor); LFontName := FontNameOfIcon; {$IFDEF GDI+} LGPGraphics := TGPGraphics.Create(ACanvas.Handle); try LGPGraphics.SetSmoothingMode(SmoothingModeAntiAlias); FIconFont.PaintToGDI(LGPGraphics, X, Y, AWidth, AHeight, LFontName, FFontIconDec, LFontColor, AEnabled, ADisabledFactor, AOpacity, AZoom); finally LGPGraphics.Free; end; {$ELSE} FIconFont.PaintTo(ACanvas, X, Y, AWidth, AHeight, LFontName, FFontIconDec, LFontColor, AMaskColor, AEnabled, ADisabledFactor, AZoom); {$ENDIF} end; procedure TIconFontItem.SetFontColor(const AValue: TColor); begin if AValue <> FFontColor then begin FFontColor := AValue; Changed; end; end; function TIconFontItem.ExtractName(const S: String): String; var LPos: Integer; begin LPos := Pos(CATEGORY_SEP, S); if LPos > 0 then Result := Copy(S, LPos+1, MaxInt) else Result := S; end; function TIconFontItem.FontNameOfIcon: TFontName; begin if FFontName <> '' then Result := FFontName else Result := IconFontItems.FOwnerFontName; end; function TIconFontItem.ExtractCategory(const S: String): String; var LPos: Integer; begin LPos := Pos(CATEGORY_SEP, S); if LPos > 0 then Result := Copy(S, 1, LPos-1) else Result := ''; end; procedure TIconFontItem.BuildIconName(const ACategory, AName: String); begin if ACategory <> '' then IconName := ACategory + CATEGORY_SEP + AName else IconName := AName; end; procedure TIconFontItem.SetName(const Value: string); begin BuildIconName(Category, Value); end; procedure TIconFontItem.SetFontIconDec(const AValue: Integer); begin if AValue <> FFontIconDec then begin if not IsFontIconValidValue(AValue) then raise Exception.CreateFmt(ERR_ICONFONTS_VALUE_NOT_ACCEPTED,[IntToHex(AValue, 1)]); FFontIconDec := AValue; Changed; end; end; procedure TIconFontItem.SetFontIconHex(const AValue: string); begin try if (Length(AValue) = 4) or (Length(AValue) = 5) then FontIconDec := StrToInt('$' + AValue) else if (Length(AValue) = 0) then FontIconDec := 0 else raise Exception.CreateFmt(ERR_ICONFONTS_VALUE_NOT_ACCEPTED,[AValue]); except On E: EConvertError do raise Exception.CreateFmt(ERR_ICONFONTS_VALUE_NOT_ACCEPTED,[AValue]) else raise; end; end; procedure TIconFontItem.SetFontName(const AValue: TFontName); begin if AValue <> FFontName then begin FFontName := AValue; Changed; end; end; procedure TIconFontItem.SetIconName(const AValue: string); begin FIconName := AValue; end; procedure TIconFontItem.SetIndex(Value: Integer); begin if Value <> Index then begin inherited; Changed; end; end; procedure TIconFontItem.SetMaskColor(const AValue: TColor); begin if AValue <> FMaskColor then begin FMaskColor := AValue; Changed; end; end; procedure TIconFontItem.Changed; begin if Assigned(Collection) then IconFontItems.ItemChanged(Self); end; { TIconFontItems } function TIconFontItems.Add: TIconFontItem; begin Result := TIconFontItem(inherited Add); end; function TIconFontItems.AddIcons(const AFrom, ATo: Integer; const AFontName: TFontName; const AFontColor: TColor; AMaskColor: TColor; const ACheckValid: Boolean): Integer; var LChar: Integer; LIsValid: Boolean; LBitmap: TBitmap; begin LBitmap := nil; try if ACheckValid then begin LBitmap := TBitmap.Create; LBitmap.Width := 10; LBitmap.Height := 10; with LBitmap.Canvas do begin Font.Name := AFontName; Font.Height := 10; Font.Color := clBlack; Brush.Color := clWhite; end; end; Result := 0; for LChar := AFrom to ATo do begin if ACheckValid then LIsValid := IsFontIconValidValue(LChar) and IsCharAvailable(LBitmap, LChar) else LIsValid := IsFontIconValidValue(LChar); if LIsValid then begin AddIcon(LChar, AFontName, AFontColor, AMaskColor); Inc(Result); end; end; finally LBitmap.Free; end; end; procedure TIconFontItems.Assign(Source: TPersistent); begin (* if (Source is TIconFontItems) then begin TControl(Owner).StopDrawing(True); try inherited; finally IconFontsImageList.StopDrawing(False); end; IconFontsImageList.RecreateBitmaps; end else *) inherited; end; constructor TIconFontItems.Create(const AOwner: TPersistent; const ItemClass: TCollectionItemClass; const AOnItemChanged: TIconFontItemChangedProc; const AOnCheckFont: TCheckFontNameProc; const AGetOwnerAttributes: TGetOwnerAttributesProc); begin FOnItemChanged := AOnItemChanged; FOnCheckFont := AOnCheckFont; FGetOwnerAttributes := AGetOwnerAttributes; inherited Create(AOwner, ItemClass); end; procedure TIconFontItems.Delete(AIndex: Integer); begin inherited Delete(AIndex); ItemChanged(nil); end; function TIconFontItems.GetIconByName(const AIconName: string): TIconFontItem; var I: Integer; LIconFontItem: TIconFontItem; begin Result := nil; for I := 0 to Count -1 do begin LIconFontItem := Items[I]; if SameText(LIconFontItem.IconName, AIconName) then begin Result := LIconFontItem; Break; end; end; end; function TIconFontItems.GetItem(AIndex: Integer): TIconFontItem; begin Result := TIconFontItem(inherited GetItem(AIndex)); end; function TIconFontItems.IndexOf(const S: string): Integer; begin for Result := 0 to Count - 1 do if SameText(Items[Result].IconName, S) then Exit; Result := -1; end; function TIconFontItems.Insert(AIndex: Integer): TIconFontItem; begin Result := TIconFontItem(inherited Insert(AIndex)); ItemChanged(Result); end; procedure TIconFontItems.SetItem(AIndex: Integer; const Value: TIconFontItem); begin inherited SetItem(AIndex, Value); end; procedure TIconFontItems.UpdateIconsAttributes(const AFontColor, AMaskColor: TColor; const AFontName: TFontName = ''); var I: Integer; LIconFontItem: TIconFontItem; begin if (AFontColor <> clNone) and (AMaskColor <> clNone) then begin for I := 0 to Count -1 do begin LIconFontItem := Items[I]; if AFontName <> '' then LIconFontItem.FontName := AFontName; LIconFontItem.FontColor := AFontColor; LIconFontItem.MaskColor := AMaskColor; end; end; end; procedure TIconFontItems.UpdateOwnerAttributes; begin FGetOwnerAttributes(FOwnerFontName, FOwnerFontColor, FOwnerMaskColor); end; procedure TIconFontItems.ItemChanged(const AItem: TIconFontItem); begin if Assigned(FOnItemChanged) then FOnItemChanged(AItem); end; function TIconFontItems.IsCharAvailable( const ABitmap: TBitmap; const AFontIconDec: Integer): Boolean; var Cnt: DWORD; len: Integer; buf : array of WORD; I: Integer; S: WideString; msBlank, msIcon: TMemoryStream; LIsSurrogate: Boolean; LRect: TRect; begin Result := False; if Assigned(ABitmap) then begin LIsSurrogate := (AFontIconDec >= $010000) and (AFontIconDec <= $10FFFF); if LIsSurrogate then begin //To support surrogate Characters I cannot use GetGlyphIndicesW so I'm drawing the Character on a Canvas and //check if is already blank: this method is quite slow LRect := Rect(0,0, ABitmap.Width, ABitmap.Height); ABitmap.Canvas.FillRect(LRect); msBlank := TMemoryStream.Create; msIcon := TMemoryStream.Create; try ABitmap.SaveToStream(msBlank); {$IFDEF DXE3+} {$WARN SYMBOL_DEPRECATED OFF} S := ConvertFromUtf32(AFontIconDec); {$WARN SYMBOL_DEPRECATED ON} ABitmap.Canvas.TextOut(0, 0, S); {$ELSE} S := WideChar(AFontIconDec); TextOutW(ABitmap.Canvas.Handle, 0, 0, PWideChar(S), 1); {$ENDIF} ABitmap.SaveToStream(msIcon); Result := not ((msBlank.Size = msIcon.Size) and CompareMem(msBlank.Memory, msIcon.Memory, msBlank.Size)); finally msBlank.Free; msIcon.Free; end; end else begin //Check for non surrogate pairs, using GetGlyphIndices S := WideChar(AFontIconDec); len := Length(S); SetLength( buf, len); {$IFDEF D2010+} Cnt := GetGlyphIndicesW( ABitmap.Canvas.Handle, PWideChar(S), len, @buf[0], GGI_MARK_NONEXISTING_GLYPHS); {$ELSE} {$WARN SUSPICIOUS_TYPECAST OFF} Cnt := GetGlyphIndicesW( ABitmap.Canvas.Handle, PAnsiChar(S), len, @buf[0], GGI_MARK_NONEXISTING_GLYPHS); {$ENDIF} if Cnt > 0 then begin for i := 0 to Cnt-1 do Result := buf[i] <> $FFFF; end; end; end; end; function TIconFontItems.AddIcons(const AFrom, ATo: WideChar; const AFontName: TFontName; const AFontColor: TColor; AMaskColor: TColor; const ACheckValid: Boolean): Integer; begin Result := AddIcons(Ord(AFrom), Ord(ATo), AFontName, AFontColor, AMaskColor, ACheckValid); end; function TIconFontItems.AddIcons(const ASourceString: WideString; const AFontName: TFontName): Integer; {$IFDEF DXE3+} var LChar: UCS4Char; I, L, ICharLen: Integer; {$ENDIF} begin Result := 0; {$IFDEF DXE3+} L := Length(ASourceString); I := 1; while I <= L do begin {$WARN SYMBOL_DEPRECATED OFF} if IsSurrogate(ASourceString[I]) then begin LChar := ConvertToUtf32(ASourceString, I, ICharLen); end else begin ICharLen := 1; LChar := UCS4Char(ASourceString[I]); end; {$WARN SYMBOL_DEPRECATED ON} AddIcon(Ord(LChar), AFontName); Inc(I, ICharLen); Inc(Result); end; {$ENDIF} end; function TIconFontItems.AddIcon(const AChar: Integer; const AIconName: string; const AFontName: TFontName = ''; const AFontColor: TColor = clDefault; const AMaskColor: TColor = clNone): TIconFontItem; begin Result := Add; try Result.IconName := AIconName; Result.FontIconDec := AChar; if AFontColor <> clDefault then Result.FontColor := AFontColor; if AMaskColor <> clNone then Result.MaskColor := AMaskColor; except Delete(Result.Index); raise; end; end; function TIconFontItems.AddIcon(const AChar: WideChar; const AFontName: TFontName; const AFontColor, AMaskColor: TColor): TIconFontItem; begin Result := AddIcon(Ord(AChar), '', AFontName, AFontColor, AMaskColor); end; function TIconFontItems.AddIcon(const AChar: Integer; const AFontName: TFontName; const AFontColor, AMaskColor: TColor): TIconFontItem; begin Result := AddIcon(AChar, '', AFontName, AFontColor, AMaskColor); end; { TIconFont } procedure TIconFont.Assign(Source: TIconFont); begin FFontName := Source.FFontName; FFontIconDec := Source.FFontIconDec; FFontColor := Source.FFontColor; FMaskColor := Source.FMaskColor; FOpacity := Source.FOpacity; FIconName := Source.FIconName; FDisabledFactor := Source.FDisabledFactor; end; function TIconFont.GetBitmap(const AWidth, AHeight: Integer; const AFontName: TFontName; AFontIconDec: Integer; const AFontColor, AMaskColor: TColor; const AEnabled: Boolean = True; const ADisabledFactor: Byte = DEFAULT_DISABLE_FACTOR; const AOpacity: Byte = DEFAULT_OPACITY; const AZoom: Integer = ZOOM_DEFAULT): TBitmap; {$IFDEF GDI+} var LGraphics: TGPGraphics; {$ENDIF} begin Result := TBitmap.Create; Result.PixelFormat := pf32bit; {$IFDEF GDI+} if TStyleManager.IsCustomStyleActive then Result.Canvas.Brush.Color := StyleServices.GetSystemColor(clWindow) else Result.Canvas.Brush.Color := ColorToRGB(clWindow); Result.SetSize(AWidth, AHeight); {$ELSE} {$IFDEF DXE+} Result.alphaFormat := afIgnored; Result.SetSize(AWidth, AHeight); {$ELSE} Result.Width := AWidth; Result.Height := AHeight; {$ENDIF} {$ENDIF} {$IFDEF GDI+} LGraphics := TGPGraphics.Create(Result.Canvas.Handle); try LGraphics.SetSmoothingMode(SmoothingModeAntiAlias); PaintToGDI(LGraphics, 0, 0, AWidth, AHeight, AFontName, AFontIconDec, AFontColor, AEnabled, ADisabledFactor, AOpacity, AZoom); finally LGraphics.Free; end; {$ELSE} PaintTo(Result.Canvas, 0, 0, AWidth, AHeight, AFontName, AFontIconDec, AFontColor, AMaskColor, AEnabled, ADisabledFactor, AZoom); {$ENDIF} end; procedure TIconFont.PaintTo(const ACanvas: TCanvas; const X, Y, AWidth, AHeight: Integer; const AFontName: TFontName; AFontIconDec: Integer; const AFontColor, AMaskColor: TColor; const AEnabled: Boolean = True; const ADisabledFactor: Byte = DEFAULT_DISABLE_FACTOR; const AZoom: Integer = ZOOM_DEFAULT); var S: WideString; LX, LY: Integer; LRect: TRect; LFontColor: TColor; LFontHeight: Integer; begin if not AEnabled then LFontColor := DisabledColor(AFontColor, Round(DEFAULT_DISABLE_FACTOR * ADisabledFactor / 255)) else LFontColor := AFontColor; with ACanvas do begin Font.Name := AFontName; LFontHeight := Round(AHeight * AZoom / ZOOM_DEFAULT); Font.Height := LFontHeight; Font.Color := LFontColor; Brush.Color := AMaskColor; LRect.Left := X; LRect.Top := Y; {$IFDEF DXE8+} LRect.Width := AWidth; LRect.Height := AHeight; {$ELSE} LRect.Right := X + AWidth; LRect.Bottom := Y + AHeight; {$ENDIF} FillRect(LRect); if AZoom <> 100 then begin LX := Round((X + AWidth - (AZoom / ZOOM_DEFAULT * AWidth)) / 2); LY := Round((Y + AHeight - (AZoom / ZOOM_DEFAULT * AHeight)) / 2); end else begin LX := X; LY := Y; end; {$IFDEF DXE3+} {$WARN SYMBOL_DEPRECATED OFF} S := ConvertFromUtf32(AFontIconDec); {$WARN SYMBOL_DEPRECATED ON} TextOut(LX, LY, S); {$ELSE} S := WideChar(AFontIconDec); TextOutW(ACanvas.Handle, LX, LY, PWideChar(S), 1); {$ENDIF} end; end; {$IFDEF GDI+} procedure TIconFont.PaintToGDI(const AGraphics: TGPGraphics; const X, Y, AWidth, AHeight: Single; const AFontName: TFontName; AFontIconDec: Integer; const AFontColor: TColor; const AEnabled: Boolean = True; const ADisabledFactor: Byte = DEFAULT_DISABLE_FACTOR; const AOpacity: Byte = DEFAULT_OPACITY; const AZoom: Integer = ZOOM_DEFAULT); var LSolidBrush: TGPSolidBrush; LBounds: TGPRectF; LFont: TGPFont; LFontColor: TColor; LPoint: TGPPointF; S: WideString; LFontSize: Single; begin LSolidBrush := nil; LFont := nil; try LBounds.X := X; LBounds.Y := Y; LBounds.Width := AWidth; LBounds.Height := AHeight; if not AEnabled then LFontColor := DisabledColor(AFontColor, Round(DEFAULT_DISABLE_FACTOR * ADisabledFactor / 255)) else LFontColor := AFontColor; LSolidBrush := TGPSolidBrush.Create(GPColor(LFontColor, AOpacity)); LFontSize := AHeight * AZoom / ZOOM_DEFAULT; LFont := TGPFont.Create(AFontName, LFontSize, FontStyleRegular, UnitPixel); AGraphics.SetSmoothingMode(SmoothingModeAntiAlias); AGraphics.SetTextRenderingHint(TextRenderingHintAntiAlias); if AZoom <> 100 then begin LPoint.X := ((LBounds.X + AWidth - (AZoom / ZOOM_DEFAULT * AWidth)) / 2) - ((AZoom / ZOOM_DEFAULT * AWidth) / 6); LPoint.Y := (LBounds.Y + AHeight - (AZoom / ZOOM_DEFAULT * AHeight)) / 2; end else begin LPoint.X := LBounds.X - (AWidth / 6); //Offset to align character to left LPoint.Y := LBounds.Y; end; {$WARN SYMBOL_DEPRECATED OFF} S := ConvertFromUtf32(AFontIconDec); {$WARN SYMBOL_DEPRECATED ON} AGraphics.DrawString(S, Length(S), LFont, LPoint, LSolidBrush); finally LFont.Free; LSolidBrush.Free; end; end; {$ENDIF} end.
unit UTokenizerTests; interface {$I dws.inc} uses {$IFDEF WINDOWS} Windows, {$ENDIF} Classes, SysUtils, dwsXPlatformTests, dwsComp, dwsTokenizer, dwsXPlatform, dwsErrors, dwsUtils, dwsPascalTokenizer; type TTokenizerTests = class (TTestCase) private FMsgs : TdwsCompileMessageList; FSourceFile : TSourceFile; public procedure SetUp; override; procedure TearDown; override; published procedure EmptyTokenBuffer; procedure IgnoreDecimalSeparator; procedure TokenizerSpecials; procedure NoCurlyComments; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ type // TTokenBufferWrapper // TTokenBufferWrapper = class public Buffer : TTokenBuffer; end; // ------------------ // ------------------ TTokenizerTests ------------------ // ------------------ // SetUp // procedure TTokenizerTests.SetUp; begin FMsgs:=TdwsCompileMessageList.Create; FSourceFile:=TSourceFile.Create; end; // TearDown // procedure TTokenizerTests.TearDown; begin FSourceFile.Free; FMsgs.Free; end; // EmptyTokenBuffer // procedure TTokenizerTests.EmptyTokenBuffer; var w : TTokenBufferWrapper; s : UnicodeString; begin w:=TTokenBufferWrapper.Create; try CheckEquals('', w.Buffer.ToStr, 'ToStr function'); s:='dummy'; w.Buffer.ToStr(s); CheckEquals('', s, 'ToStr procedure'); s:='dummy'; w.Buffer.ToUpperStr(s); CheckEquals('', s, 'ToUpperStr'); CheckEquals(#0, w.Buffer.LastChar, 'LastChar'); finally w.Free; end; end; // IgnoreDecimalSeparator // procedure TTokenizerTests.IgnoreDecimalSeparator; var w : TTokenBufferWrapper; dc : Char; begin w:=TTokenBufferWrapper.Create; dc:=GetDecimalSeparator; try w.Buffer.AppendChar('1'); w.Buffer.AppendChar('.'); w.Buffer.AppendChar('5'); SetDecimalSeparator('.'); CheckEquals(1.5, w.Buffer.ToFloat, 'With dot'); SetDecimalSeparator(','); CheckEquals(1.5, w.Buffer.ToFloat, 'With comma'); SetDecimalSeparator('P'); CheckEquals(1.5, w.Buffer.ToFloat, 'With P'); finally SetDecimalSeparator(dc); w.Free; end; end; // TokenizerSpecials // procedure TTokenizerTests.TokenizerSpecials; var rules : TPascalTokenizerStateRules; t : TTokenizer; begin FMsgs.Clear; FSourceFile.Code:='@ @= %= ^ ^= $( ? | || & &&'; rules:=TPascalTokenizerStateRules.Create; t:=rules.CreateTokenizer(FMsgs); try t.BeginSourceFile(FSourceFile); CheckTrue(t.TestDelete(ttAT), '@'); CheckTrue(t.TestDelete(ttAT_ASSIGN), '@='); CheckTrue(t.TestDelete(ttPERCENT_ASSIGN), '%='); CheckTrue(t.TestDelete(ttCARET), '^'); CheckTrue(t.TestDelete(ttCARET_ASSIGN), '^='); CheckTrue(t.TestDelete(ttDOLLAR), '$'); CheckTrue(t.TestDelete(ttBLEFT), '('); CheckTrue(t.TestDelete(ttQUESTION), '?'); CheckTrue(t.TestDelete(ttPIPE), '|'); CheckTrue(t.TestDelete(ttPIPEPIPE), '||'); CheckTrue(t.TestDelete(ttAMP), '&'); CheckTrue(t.TestDelete(ttAMPAMP), '&&'); CheckTrue(t.TestAny([ttNAME])=ttNone, 'Any at end'); CheckTrue(t.TestDeleteAny([ttNAME])=ttNone, 'DeleteAny at end'); t.EndSourceFile; finally t.Free; rules.Free; end; end; // NoCurlyComments // procedure TTokenizerTests.NoCurlyComments; var rules : TPascalTokenizerStateRules; t : TTokenizer; begin FSourceFile.Code:='{ /* { */ }'; rules:=TPascalTokenizerStateRules.Create; t:=rules.CreateTokenizer(FMsgs); try CheckTrue(rules.CurlyComments, 'curly comments by default'); rules.CurlyComments:=False; CheckFalse(rules.CurlyComments, 'curly comments cleared'); t.BeginSourceFile(FSourceFile); CheckTrue(t.TestDelete(ttCLEFT), '{'); CheckTrue(t.TestDelete(ttCRIGHT), '}'); t.EndSourceFile; rules.CurlyComments:=True; CheckTrue(rules.CurlyComments, 'curly comments reset'); t.BeginSourceFile(FSourceFile); CheckFalse(t.HasTokens, 'skip curly comment'); t.EndSourceFile; finally t.Free; rules.Free; end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterTest('TokenizerTests', TTokenizerTests); end.
unit Facade.Client.Client; interface uses Facade.Facade.Facade; type TClient = class public class function ClientCode(AFacade: TFacade): string; end; implementation { TClient } class function TClient.ClientCode(AFacade: TFacade): string; begin Result := AFacade.Operation; end; end.
unit ui.color; interface uses Types; type PColor32 = ^TColor32; TColor32 = type Cardinal; PColor32Array = ^TColor32Array; TColor32Array = array [0..0] of TColor32; TArrayOfColor32 = array of TColor32; {$IFNDEF RGBA_FORMAT} TColor32Component = (ccBlue, ccGreen, ccRed, ccAlpha); {$ELSE} TColor32Component = (ccRed, ccGreen, ccBlue, ccAlpha); {$ENDIF} TColor32Components = set of TColor32Component; PColor32Entry = ^TColor32Entry; TColor32Entry = packed record case Integer of {$IFNDEF RGBA_FORMAT} 0: (B, G, R, A: Byte); {$ELSE} 0: (R, G, B, A: Byte); {$ENDIF} 1: (ARGB: TColor32); 2: (Planes: array[0..3] of Byte); 3: (Components: array[TColor32Component] of Byte); end; PColor32EntryArray = ^TColor32EntryArray; TColor32EntryArray = array [0..0] of TColor32Entry; TArrayOfColor32Entry = array of TColor32Entry; PColor = ^TColor; TColor = -$7FFFFFFF-1..$7FFFFFFF; COLORREF = DWORD; TColorRef = DWORD; PRGBTriple = ^TRGBTriple; TRGBTriple = packed record rgbtBlue: Byte; rgbtGreen: Byte; rgbtRed: Byte; end; TRGBLine = array[Word] of TRGBTriple; pRGBLine = ^TRGBLine; PRGBPixel = ^TRGBPixel; TRGBPixel = packed record B: Byte; G: Byte; R: Byte; end; PRGBQuad = ^TRGBQuad; TRGBQuad = packed record rgbBlue: Byte; rgbGreen: Byte; rgbRed: Byte; rgbReserved: Byte; end; function GetRValue(rgb: DWORD): Byte; inline; function GetGValue(rgb: DWORD): Byte; inline; function GetBValue(rgb: DWORD): Byte; inline; function RGB(r, g, b: Byte): COLORREF; inline; function CMYK(c, m, y, k: Byte): COLORREF; inline; function Color32(R, G, B: Byte; A: Byte = $FF): TColor32; overload; function Gray32(Intensity: Byte; Alpha: Byte = $FF): TColor32; procedure Color32ToRGB(AColor32: TColor32; var R, G, B: Byte); procedure Color32ToRGBA(AColor32: TColor32; var R, G, B, A: Byte); function Color32Components(R, G, B, A: Boolean): TColor32Components; function RedComponent(AColor32: TColor32): Integer; {$IFDEF USEINLINING} inline; {$ENDIF} function GreenComponent(AColor32: TColor32): Integer; {$IFDEF USEINLINING} inline; {$ENDIF} function BlueComponent(AColor32: TColor32): Integer; {$IFDEF USEINLINING} inline; {$ENDIF} function AlphaComponent(AColor32: TColor32): Integer; {$IFDEF USEINLINING} inline; {$ENDIF} function Intensity(AColor32: TColor32): Integer; {$IFDEF USEINLINING} inline; {$ENDIF} function InvertColor(AColor32: TColor32): TColor32; {$IFDEF USEINLINING} inline; {$ENDIF} function SetAlpha(AColor32: TColor32; NewAlpha: Integer): TColor32; {$IFDEF USEINLINING} inline; {$ENDIF} implementation function GetRValue(rgb: DWORD): Byte; begin Result := Byte(rgb); end; function GetGValue(rgb: DWORD): Byte; begin Result := Byte(rgb shr 8); end; function GetBValue(rgb: DWORD): Byte; begin Result := Byte(rgb shr 16); end; function CMYK(c, m, y, k: Byte): COLORREF; begin Result := (k or (y shl 8) or (m shl 16) or (c shl 24)); end; function RGB(r, g, b: Byte): COLORREF; begin Result := (r or (g shl 8) or (b shl 16)); end; function Color32(R, G, B: Byte; A: Byte = $FF): TColor32; overload; {$IFDEF USENATIVECODE} begin Result := (A shl 24) or (R shl 16) or (G shl 8) or B; {$ELSE} asm MOV AH, A SHL EAX, 16 MOV AH, DL MOV AL, CL {$ENDIF} end; function Gray32(Intensity: Byte; Alpha: Byte = $FF): TColor32; begin Result := TColor32(Alpha) shl 24 + TColor32(Intensity) shl 16 + TColor32(Intensity) shl 8 + TColor32(Intensity); end; procedure Color32ToRGB(AColor32: TColor32; var R, G, B: Byte); begin R := (AColor32 and $00FF0000) shr 16; G := (AColor32 and $0000FF00) shr 8; B := AColor32 and $000000FF; end; procedure Color32ToRGBA(AColor32: TColor32; var R, G, B, A: Byte); begin A := AColor32 shr 24; R := (AColor32 and $00FF0000) shr 16; G := (AColor32 and $0000FF00) shr 8; B := AColor32 and $000000FF; end; function Color32Components(R, G, B, A: Boolean): TColor32Components; const ccR : array[Boolean] of TColor32Components = ([], [ccRed]); ccG : array[Boolean] of TColor32Components = ([], [ccGreen]); ccB : array[Boolean] of TColor32Components = ([], [ccBlue]); ccA : array[Boolean] of TColor32Components = ([], [ccAlpha]); begin Result := ccR[R] + ccG[G] + ccB[B] + ccA[A]; end; function RedComponent(AColor32: TColor32): Integer; begin Result := (AColor32 and $00FF0000) shr 16; end; function GreenComponent(AColor32: TColor32): Integer; begin Result := (AColor32 and $0000FF00) shr 8; end; function BlueComponent(AColor32: TColor32): Integer; begin Result := AColor32 and $000000FF; end; function AlphaComponent(AColor32: TColor32): Integer; begin Result := AColor32 shr 24; end; function Intensity(AColor32: TColor32): Integer; begin // (R * 61 + G * 174 + B * 21) / 256 Result := ( (AColor32 and $00FF0000) shr 16 * 61 + (AColor32 and $0000FF00) shr 8 * 174 + (AColor32 and $000000FF) * 21 ) shr 8; end; function InvertColor(AColor32: TColor32): TColor32; begin TColor32Entry(Result).R := $FF - TColor32Entry(AColor32).R; TColor32Entry(Result).G := $FF - TColor32Entry(AColor32).G; TColor32Entry(Result).B := $FF - TColor32Entry(AColor32).B; TColor32Entry(Result).A := TColor32Entry(AColor32).A; end; function SetAlpha(AColor32: TColor32; NewAlpha: Integer): TColor32; begin if NewAlpha < 0 then NewAlpha := 0 else if NewAlpha > $FF then NewAlpha := $FF; Result := (AColor32 and $00FFFFFF) or (TColor32(NewAlpha) shl 24); end; end.
unit notificationmanager; {$mode delphi} interface uses Classes, SysUtils, And_jni, AndroidWidget; type TPendingFlag = (pfUpdateCurrent, pfCancelCurrent); TNotificationPriority = (npDefault, npLow, npHigh, npMin, npMax); {Draft Component code by "Lazarus Android Module Wizard" [2/3/2015 17:14:54]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jControl template} jNotificationManager = class(jControl) private FId: integer; FTitle: string; FSubject: string; FBody: string; FIConIdentifier: string; // ../res/drawable ex: 'ic_launcher' FLightsColor: TARGBColorBridge; FAutoCancel: boolean; FOngoing: boolean; FPendingFlag: TPendingFlag; protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; function jCreate(): jObject; procedure jFree(); procedure Cancel(_id: integer); procedure CancelAll(); procedure SetLightsColorAndTimes(_color: TARGBColorBridge; _onMills: integer; _offMills: integer); //TFPColorBridgeArray procedure SetLightsColor(_lightsColor: TARGBColorBridge); procedure SetLightsEnable(_enable: boolean); procedure SetOngoing(_value: boolean); procedure SetContentIntent(_intent: jObject); overload; procedure SetContentIntent(_intent: jObject; _broadcastRequestCode: integer); overload; procedure SetContentIntent(_packageName: string; _activityClassName: string); overload; procedure SetContentIntent(_packageName: string; _activityClassName: string; dataName: string; dataValue: string); overload; procedure SetIconIdentifier(_iconIdentifier: string); procedure SetTitle(_title: string); procedure SetSubject(_subject: string); procedure SetBody(_body: string); procedure SetId(_id: integer); procedure Notify(); procedure SetAutoCancel(_value: boolean); procedure SetPendingFlag(_flag: TPendingFlag); procedure SetPriority(_priority: TNotificationPriority); published property Id: integer read FId write SetId; property Title: string read FTitle write SetTitle; property Subject: string read FSubject write SetSubject; property Body: string read FBody write SetBody; property IconIdentifier: string read FIConIdentifier write SetIconIdentifier; property LightsColor: TARGBColorBridge read FLightsColor write SetLightsColor; property AutoCancel: boolean read FAutoCancel write SetAutoCancel; property Ongoing: boolean read FOngoing write SetOngoing; property PendingFlag: TPendingFlag read FPendingFlag write SetPendingFlag; end; function jNotificationManager_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; procedure jNotificationManager_jFree(env: PJNIEnv; _jnotificationmanager: JObject); procedure jNotificationManager_Cancel(env: PJNIEnv; _jnotificationmanager: JObject; _id: integer); procedure jNotificationManager_CancelAll(env: PJNIEnv; _jnotificationmanager: JObject); procedure jNotificationManager_SetLightsColorAndTime(env: PJNIEnv; _jnotificationmanager: JObject; _color: integer; _onMills: integer; _offMills: integer); procedure jNotificationManager_SetLightsEnable(env: PJNIEnv; _jnotificationmanager: JObject; _enable: boolean); procedure jNotificationManager_SetOngoing(env: PJNIEnv; _jnotificationmanager: JObject; _value: boolean); procedure jNotificationManager_SetContentIntent(env: PJNIEnv; _jnotificationmanager: JObject; _intent: jObject);overload; procedure jNotificationManager_SetContentIntent(env: PJNIEnv; _jnotificationmanager: JObject; _intent: jObject; _broadcastRequestCode: integer);overload; procedure jNotificationManager_SetContentIntent(env: PJNIEnv; _jnotificationmanager: JObject; _packageName: string; _activityClassName: string);overload; procedure jNotificationManager_SetContentIntent(env: PJNIEnv; _jnotificationmanager: JObject; _packageName: string; _activityClassName: string; dataName: string; dataValue: string);overload; procedure jNotificationManager_SetIconIdentifier(env: PJNIEnv; _jnotificationmanager: JObject; _iconIdentifier: string); procedure jNotificationManager_SetTitle(env: PJNIEnv; _jnotificationmanager: JObject; _title: string); procedure jNotificationManager_SetSubject(env: PJNIEnv; _jnotificationmanager: JObject; _subject: string); procedure jNotificationManager_SetBody(env: PJNIEnv; _jnotificationmanager: JObject; _body: string); procedure jNotificationManager_SetId(env: PJNIEnv; _jnotificationmanager: JObject; _id: integer); procedure jNotificationManager_Notify(env: PJNIEnv; _jnotificationmanager: JObject);overload; procedure jNotificationManager_SetAutoCancel(env: PJNIEnv; _jnotificationmanager: JObject; _value: boolean); procedure jNotificationManager_SetPendingFlag(env: PJNIEnv; _jnotificationmanager: JObject; _flag: integer); procedure jNotificationManager_SetPriority(env: PJNIEnv; _jnotificationmanager: JObject; _priority: integer); implementation {--------- jNotificationManager --------------} constructor jNotificationManager.Create(AOwner: TComponent); begin inherited Create(AOwner); //your code here.... FId:= 1001; FTitle:= 'Lamw'; FSubject:='Hello'; FBody:= 'Lamw: Hello System Notification ...'; FIConIdentifier:= 'ic_launcher'; FLightsColor:= colbrDefault; FAutoCancel:= True; FOngoing:= False; FPendingFlag:= pfUpdateCurrent; end; destructor jNotificationManager.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject:= nil; end; end; //you others free code here...' inherited Destroy; end; procedure jNotificationManager.Init; begin if FInitialized then Exit; inherited Init; //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject := jCreate(); if FjObject = nil then exit; jNotificationManager_SetId(gApp.jni.jEnv, FjObject, FId); if FAutoCancel <> False then jNotificationManager_SetAutoCancel(gApp.jni.jEnv, FjObject, FAutoCancel); if FTitle <> '' then jNotificationManager_SetTitle(gApp.jni.jEnv, FjObject,FTitle); if FSubject <> '' then jNotificationManager_SetSubject(gApp.jni.jEnv, FjObject, FSubject); if FBody <> '' then jNotificationManager_SetBody(gApp.jni.jEnv, FjObject, FBody); if FIconIdentifier <> '' then jNotificationManager_SetIconIdentifier(gApp.jni.jEnv, FjObject, FIconIdentifier); if FLightsColor <> colbrDefault then jNotificationManager_SetLightsColorAndTime(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FLightsColor) ,-1 ,-1); if FOngoing <> False then jNotificationManager_SetOngoing(gApp.jni.jEnv, FjObject, FOngoing); if FPendingFlag <> pfUpdateCurrent then jNotificationManager_SetPendingFlag(gApp.jni.jEnv, FjObject, Ord(FPendingFlag)); FInitialized:= True; end; function jNotificationManager.jCreate(): jObject; begin Result:= jNotificationManager_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis); end; procedure jNotificationManager.jFree(); begin //in designing component state: set value here... if FInitialized then jNotificationManager_jFree(gApp.jni.jEnv, FjObject); end; procedure jNotificationManager.Cancel(_id: integer); begin //in designing component state: set value here... if FInitialized then jNotificationManager_Cancel(gApp.jni.jEnv, FjObject, _id); end; procedure jNotificationManager.CancelAll(); begin //in designing component state: set value here... if FInitialized then jNotificationManager_CancelAll(gApp.jni.jEnv, FjObject); end; procedure jNotificationManager.SetLightsColorAndTimes(_color: TARGBColorBridge; _onMills: integer; _offMills: integer); var tempColor: TARGBColorBridge; begin //in designing component state: set value here... FLightsColor:= _color; if FInitialized then begin tempColor:= _color; if tempColor = colbrDefault then tempColor:= colbrBlue; jNotificationManager_SetLightsColorAndTime(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, tempColor) ,_onMills ,_offMills); end; end; procedure jNotificationManager.SetLightsColor(_lightsColor: TARGBColorBridge); var tempColor: TARGBColorBridge; begin //in designing component state: set value here... FLightsColor:= _lightsColor; if FInitialized then begin tempColor:= _lightsColor; if tempColor = colbrDefault then tempColor:= colbrBlue; jNotificationManager_SetLightsColorAndTime(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, tempColor), -1 , -1); end; end; procedure jNotificationManager.SetLightsEnable(_enable: boolean); begin //in designing component state: set value here... if FInitialized then jNotificationManager_SetLightsEnable(gApp.jni.jEnv, FjObject, _enable); end; procedure jNotificationManager.SetOngoing(_value: boolean); begin //in designing component state: set value here... FOngoing:= _value; if FInitialized then jNotificationManager_SetOngoing(gApp.jni.jEnv, FjObject, _value); end; procedure jNotificationManager.SetContentIntent(_intent: jObject); begin //in designing component state: set value here... if FInitialized then jNotificationManager_SetContentIntent(gApp.jni.jEnv, FjObject, _intent); end; procedure jNotificationManager.SetContentIntent(_intent: jObject; _broadcastRequestCode: integer); begin //in designing component state: set value here... if FInitialized then jNotificationManager_SetContentIntent(gApp.jni.jEnv, FjObject, _intent ,_broadcastRequestCode); end; procedure jNotificationManager.SetContentIntent(_packageName: string; _activityClassName: string); begin //in designing component state: set value here... if FInitialized then jNotificationManager_SetContentIntent(gApp.jni.jEnv, FjObject, _packageName ,_activityClassName); end; procedure jNotificationManager.SetContentIntent(_packageName: string; _activityClassName: string; dataName: string; dataValue: string); begin //in designing component state: set value here... if FInitialized then jNotificationManager_SetContentIntent(gApp.jni.jEnv, FjObject, _packageName ,_activityClassName ,dataName ,dataValue); end; procedure jNotificationManager.SetIconIdentifier(_iconIdentifier: string); begin //in designing component state: set value here... FIconIdentifier:= _iconIdentifier; if FInitialized then jNotificationManager_SetIconIdentifier(gApp.jni.jEnv, FjObject, _iconIdentifier); end; procedure jNotificationManager.SetTitle(_title: string); begin //in designing component state: set value here... FTitle:= _title; if FInitialized then jNotificationManager_SetTitle(gApp.jni.jEnv, FjObject, _title); end; procedure jNotificationManager.SetSubject(_subject: string); begin //in designing component state: set value here... FSubject:= _subject; if FInitialized then jNotificationManager_SetSubject(gApp.jni.jEnv, FjObject, _subject); end; procedure jNotificationManager.SetBody(_body: string); begin //in designing component state: set value here... FBody:= _body; if FInitialized then jNotificationManager_SetBody(gApp.jni.jEnv, FjObject, _body); end; procedure jNotificationManager.SetId(_id: integer); begin //in designing component state: set value here... FId:= _id; if FInitialized then jNotificationManager_SetId(gApp.jni.jEnv, FjObject, _id); end; procedure jNotificationManager.Notify(); begin //in designing component state: set value here... if FInitialized then jNotificationManager_Notify(gApp.jni.jEnv, FjObject); end; procedure jNotificationManager.SetAutoCancel(_value: boolean); begin //in designing component state: set value here... FAutoCancel:= _value; if FInitialized then jNotificationManager_SetAutoCancel(gApp.jni.jEnv, FjObject, _value); end; procedure jNotificationManager.SetPendingFlag(_flag: TPendingFlag); begin //in designing component state: set value here... FPendingFlag:= _flag; if FInitialized then jNotificationManager_SetPendingFlag(gApp.jni.jEnv, FjObject, Ord(_flag)); end; procedure jNotificationManager.SetPriority(_priority: TNotificationPriority); begin //in designing component state: set value here... if FInitialized then jNotificationManager_SetPriority(gApp.jni.jEnv, FjObject, Ord(_priority) ); end; {-------- jNotificationManager_JNI_Bridge ----------} function jNotificationManager_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].j:= _Self; jCls:= Get_gjClass(env); jMethod:= env^.GetMethodID(env, jCls, 'jNotificationManager_jCreate', '(J)Ljava/lang/Object;'); Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); end; (* //Please, you need insert: public java.lang.Object jNotificationManager_jCreate(long _Self) { return (java.lang.Object)(new jNotificationManager(this,_Self)); } //to end of "public class Controls" in "Controls.java" *) procedure jNotificationManager_jFree(env: PJNIEnv; _jnotificationmanager: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V'); env^.CallVoidMethod(env, _jnotificationmanager, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_Cancel(env: PJNIEnv; _jnotificationmanager: JObject; _id: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _id; jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'Cancel', '(I)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_CancelAll(env: PJNIEnv; _jnotificationmanager: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'CancelAll', '()V'); env^.CallVoidMethod(env, _jnotificationmanager, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetLightsEnable(env: PJNIEnv; _jnotificationmanager: JObject; _enable: boolean); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].z:= JBool(_enable); jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetLightsEnable', '(Z)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetLightsColorAndTime(env: PJNIEnv; _jnotificationmanager: JObject; _color: integer; _onMills: integer; _offMills: integer); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _color; jParams[1].i:= _onMills; jParams[2].i:= _offMills; jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetLightsColorAndTime', '(III)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetOngoing(env: PJNIEnv; _jnotificationmanager: JObject; _value: boolean); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].z:= JBool(_value); jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetOngoing', '(Z)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetContentIntent(env: PJNIEnv; _jnotificationmanager: JObject; _intent: jObject); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= _intent; jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetContentIntent', '(Landroid/content/Intent;)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetContentIntent(env: PJNIEnv; _jnotificationmanager: JObject; _intent: jObject; _broadcastRequestCode: integer); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= _intent; jParams[1].i:= _broadcastRequestCode; jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetContentIntent', '(Landroid/content/Intent;I)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetContentIntent(env: PJNIEnv; _jnotificationmanager: JObject; _packageName: string; _activityClassName: string); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_packageName)); jParams[1].l:= env^.NewStringUTF(env, PChar(_activityClassName)); jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetContentIntent', '(Ljava/lang/String;Ljava/lang/String;)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env,jParams[1].l); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetContentIntent(env: PJNIEnv; _jnotificationmanager: JObject; _packageName: string; _activityClassName: string; dataName: string; dataValue: string); var jParams: array[0..3] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_packageName)); jParams[1].l:= env^.NewStringUTF(env, PChar(_activityClassName)); jParams[2].l:= env^.NewStringUTF(env, PChar(dataName)); jParams[3].l:= env^.NewStringUTF(env, PChar(dataValue)); jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetContentIntent', '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env,jParams[1].l); env^.DeleteLocalRef(env,jParams[2].l); env^.DeleteLocalRef(env,jParams[3].l); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetIconIdentifier(env: PJNIEnv; _jnotificationmanager: JObject; _iconIdentifier: string); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_iconIdentifier)); jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetIconIdentifier', '(Ljava/lang/String;)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetTitle(env: PJNIEnv; _jnotificationmanager: JObject; _title: string); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_title)); jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetTitle', '(Ljava/lang/String;)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetSubject(env: PJNIEnv; _jnotificationmanager: JObject; _subject: string); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_subject)); jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetSubject', '(Ljava/lang/String;)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetBody(env: PJNIEnv; _jnotificationmanager: JObject; _body: string); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_body)); jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetBody', '(Ljava/lang/String;)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetId(env: PJNIEnv; _jnotificationmanager: JObject; _id: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _id; jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetId', '(I)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_Notify(env: PJNIEnv; _jnotificationmanager: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'Notify', '()V'); env^.CallVoidMethod(env, _jnotificationmanager, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetAutoCancel(env: PJNIEnv; _jnotificationmanager: JObject; _value: boolean); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].z:= JBool(_value); jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetAutoCancel', '(Z)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetPendingFlag(env: PJNIEnv; _jnotificationmanager: JObject; _flag: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _flag; jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetPendingFlag', '(I)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetPriority(env: PJNIEnv; _jnotificationmanager: JObject; _priority: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _priority; jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetPriority', '(I)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; end.
unit OpenAPI.Serializer; interface uses System.SysUtils, System.Generics.Defaults, System.Rtti, System.TypInfo, System.JSON, Neon.Core.Attributes, Neon.Core.Persistence, Neon.Core.Types, Neon.Core.Nullables, OpenAPI.Any; type TOpenAPISerializer = class class function GetNeonConfig: INeonConfiguration; static; end; TNullableStringSerializer = class(TCustomSerializer) protected class function GetTargetInfo: PTypeInfo; override; class function CanHandle(AType: PTypeInfo): Boolean; override; public function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override; function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override; end; TNullableBooleanSerializer = class(TCustomSerializer) protected class function GetTargetInfo: PTypeInfo; override; class function CanHandle(AType: PTypeInfo): Boolean; override; public function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override; function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override; end; TNullableIntegerSerializer = class(TCustomSerializer) protected class function GetTargetInfo: PTypeInfo; override; class function CanHandle(AType: PTypeInfo): Boolean; override; public function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override; function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override; end; TNullableInt64Serializer = class(TCustomSerializer) protected class function GetTargetInfo: PTypeInfo; override; class function CanHandle(AType: PTypeInfo): Boolean; override; public function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override; function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override; end; TNullableDoubleSerializer = class(TCustomSerializer) protected class function GetTargetInfo: PTypeInfo; override; class function CanHandle(AType: PTypeInfo): Boolean; override; public function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override; function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override; end; TNullableTDateTimeSerializer = class(TCustomSerializer) protected class function GetTargetInfo: PTypeInfo; override; class function CanHandle(AType: PTypeInfo): Boolean; override; public function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override; function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override; end; TOpenAPIAnySrializer = class(TCustomSerializer) protected class function GetTargetInfo: PTypeInfo; override; class function CanHandle(AType: PTypeInfo): Boolean; override; public function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override; function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override; end; implementation uses Neon.Core.Utils; { TNullableStringSerializer } class function TNullableStringSerializer.CanHandle(AType: PTypeInfo): Boolean; begin if AType = GetTargetInfo then Result := True else Result := False; end; function TNullableStringSerializer.Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; var LNullValue: NullString; begin LNullValue := AValue.Value; Result := TValue.From<NullString>(LNullValue); end; class function TNullableStringSerializer.GetTargetInfo: PTypeInfo; begin Result := TypeInfo(NullString); end; function TNullableStringSerializer.Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; var LValue: NullString; begin Result := nil; LValue := AValue.AsType<NullString>; if LValue.HasValue then Result := TJSONString.Create(LValue.Value); end; { TNullableBooleanSerializer } class function TNullableBooleanSerializer.CanHandle(AType: PTypeInfo): Boolean; begin if AType = GetTargetInfo then Result := True else Result := False; end; function TNullableBooleanSerializer.Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; var LNullValue: NullBoolean; begin LNullValue := (AValue as TJSONBool).AsBoolean; Result := TValue.From<NullBoolean>(LNullValue); end; class function TNullableBooleanSerializer.GetTargetInfo: PTypeInfo; begin Result := TypeInfo(NullBoolean); end; function TNullableBooleanSerializer.Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; var LValue: NullBoolean; begin Result := nil; LValue := AValue.AsType<NullBoolean>; if LValue.HasValue then Result := TJSONBool.Create(LValue.Value); end; { TNullableIntegerSerializer } class function TNullableIntegerSerializer.CanHandle(AType: PTypeInfo): Boolean; begin if AType = GetTargetInfo then Result := True else Result := False; end; function TNullableIntegerSerializer.Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; var LNullValue: NullInteger; begin LNullValue := (AValue as TJSONNumber).AsInt; Result := TValue.From<NullInteger>(LNullValue); end; class function TNullableIntegerSerializer.GetTargetInfo: PTypeInfo; begin Result := TypeInfo(NullInteger); end; function TNullableIntegerSerializer.Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; var LValue: NullInteger; begin Result := nil; LValue := AValue.AsType<NullInteger>; if LValue.HasValue then Result := TJSONNumber.Create(LValue.Value); end; { TNullableInt64Serializer } class function TNullableInt64Serializer.CanHandle(AType: PTypeInfo): Boolean; begin if AType = GetTargetInfo then Result := True else Result := False; end; function TNullableInt64Serializer.Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; var LNullValue: NullInt64; begin LNullValue := (AValue as TJSONNumber).AsInt64; Result := TValue.From<NullInt64>(LNullValue); end; class function TNullableInt64Serializer.GetTargetInfo: PTypeInfo; begin Result := TypeInfo(NullInt64); end; function TNullableInt64Serializer.Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; var LValue: NullInt64; begin Result := nil; LValue := AValue.AsType<NullInt64>; if LValue.HasValue then Result := TJSONNumber.Create(LValue.Value); end; { TNullableDoubleSerializer } class function TNullableDoubleSerializer.CanHandle(AType: PTypeInfo): Boolean; begin if AType = GetTargetInfo then Result := True else Result := False; end; function TNullableDoubleSerializer.Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; var LNullValue: NullDouble; begin LNullValue := (AValue as TJSONNumber).AsDouble; Result := TValue.From<NullDouble>(LNullValue); end; class function TNullableDoubleSerializer.GetTargetInfo: PTypeInfo; begin Result := TypeInfo(NullDouble); end; function TNullableDoubleSerializer.Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; var LValue: NullDouble; begin Result := nil; LValue := AValue.AsType<NullDouble>; if LValue.HasValue then Result := TJSONNumber.Create(LValue.Value); end; { TNullableTDateTimeSerializer } class function TNullableTDateTimeSerializer.CanHandle(AType: PTypeInfo): Boolean; begin if AType = GetTargetInfo then Result := True else Result := False; end; function TNullableTDateTimeSerializer.Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; var LNullValue: NullDateTime; begin LNullValue := TJSONUtils.JSONToDate(AValue.Value, AContext.GetConfiguration.GetUseUTCDate); Result := TValue.From<NullDateTime>(LNullValue); end; class function TNullableTDateTimeSerializer.GetTargetInfo: PTypeInfo; begin Result := TypeInfo(NullDateTime); end; function TNullableTDateTimeSerializer.Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; var LValue: NullDateTime; begin Result := nil; LValue := AValue.AsType<NullDateTime>; if LValue.HasValue then Result := TJSONString.Create(TJSONUtils.DateToJSON(LValue.Value, AContext.GetConfiguration.GetUseUTCDate)); end; { TOpenAPISerializer } class function TOpenAPISerializer.GetNeonConfig: INeonConfiguration; begin Result := TNeonConfiguration.Create; Result.SetMemberCase(TNeonCase.CamelCase) .SetPrettyPrint(True) .GetSerializers .RegisterSerializer(TNullableStringSerializer) .RegisterSerializer(TNullableBooleanSerializer) .RegisterSerializer(TNullableIntegerSerializer) .RegisterSerializer(TNullableInt64Serializer) .RegisterSerializer(TNullableDoubleSerializer) .RegisterSerializer(TNullableTDateTimeSerializer) .RegisterSerializer(TOpenAPIAnySrializer) ; end; { TOpenAPIAnySrializer } class function TOpenAPIAnySrializer.CanHandle(AType: PTypeInfo): Boolean; begin if AType = GetTargetInfo then Result := True else Result := False; end; function TOpenAPIAnySrializer.Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; begin Result := nil; end; class function TOpenAPIAnySrializer.GetTargetInfo: PTypeInfo; begin Result := TypeInfo(TOpenAPIAny); end; function TOpenAPIAnySrializer.Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; var LValue: TOpenAPIAny; begin LValue := AValue.AsType<TOpenAPIAny>; if not LValue.Value.IsEmpty then Result := AContext.WriteDataMember(LValue.Value) else Result := nil; end; end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Ported to Delphi by Michal Wojcik. // // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved. // Released under the terms of the GNU General Public License version 2 or later. {$H+} unit StandardResultHandler; interface uses StrUtils, SysUtils, StringTokenizer, PrintStream, PageResult, Counts, InputStream, ResultHandler; type //TODO MDM Rename to VerboseResultHandler TStandardResultHandler = class(TInterfacedObject, TResultHandler) private output : TPrintStream; pageCounts : TCounts; function pageDescription(Aresult : TPageResult) : string; public constructor Create(output : TPrintStream); destructor Destroy; override; procedure acceptFinalCount(count : TCounts); procedure acceptResult(result : TPageResult); function getByteCount() : Integer; function getResultStream() : TInputStream; end; implementation { TStandardResultHandler } constructor TStandardResultHandler.Create(output : TPrintStream); begin inherited Create; pageCounts := TCounts.Create; self.output := output; end; destructor TStandardResultHandler.Destroy(); begin inherited Destroy; end; procedure TStandardResultHandler.acceptResult(result : TPageResult); var i : integer; counts : TCounts; begin counts := result.counts(); pageCounts.tallyPageCounts(counts); i := 0; while (i < counts.right) do begin output.print('.'); inc(i); end; if (counts.wrong > 0) or (counts.exceptions > 0) then begin output.println(); if (counts.wrong > 0) then begin output.println(pageDescription(result) + ' has failures'); end; if (counts.exceptions > 0) then begin output.println(pageDescription(result) + ' has errors'); end; end; end; function TStandardResultHandler.pageDescription(Aresult : TPageResult) : string; var description : string; begin description := Aresult.title(); if ('' = description) then begin description := 'The test'; end; result := description; end; procedure TStandardResultHandler.acceptFinalCount(count : TCounts); begin output.println(); output.println('Test Pages: ' + pageCounts.toString); output.println('Assertions: ' + count.toString); end; function TStandardResultHandler.getByteCount() : Integer; begin result := 0; end; function TStandardResultHandler.getResultStream() : TInputStream; begin result := nil; end; end.
unit BaseWinThreadRefObj; interface uses Windows; type (* 用事件(Event)来同步线程是最具弹性的了。一个事件有两种状态: 激发状态和未激发状态。也称有信号状态和无信号状态。事件又分两种类型: 手动重置事件和自­动重置事件。手动重置事件被设置为激发状态后,会唤醒 所有等待的线程,而且一直保持为激发状态,直到程序重新把它设置为未激发 状态。自动重置事件被设置为激发状­态后,会唤醒“一个”等待中的线程, 然后自动恢复为未激发状态。所以用自动重置事件来同步两个线程比较理想 *) PEvent = ^TEvent; TEvent = record Status : Integer; Handle : THandle; end; (* 使用临界区域的第一个忠告就是不要长时间锁住一份资源。这里的长时间是相对的, 视不同程序而定。对一些控制软件来说,可能是数毫秒,但是对另外一些程序来说, 可­以长达数分钟。但进入临界区后必须尽快地离开,释放资源 *) PWinLock = ^TWinLock; TWinLock = record Status : Integer; Handle : TRTLCriticalSection; end; (* 互斥器的功能和临界区域很相似。区别是: Mutex所花费的时间比Critical Section多的多, 但是Mutex是核心对象(Event、Semaphore也是), 可以跨进程使用,而且等待一个被锁住的Mutex可以设定TIMEO­UT, 不会像CriticalSection那样无法得知临界区域的情况,而一直死等 *) PMutex = ^TMutex; TMutex = record Status : Integer; Handle : THandle; end; (* 信号量(Semaphores) 信号量对象对线程的同步方式与前面几种方法不同,信号允许多个线程同时使用共享资源, 这与操作系统中的PV操作相同。它指出了同时访问共享资源的线程最大数目。它允许多个 线程在同一时刻访问同一资源,但是需要限制在同一时刻访问此资源的最大线程数目。 在用CreateSemaphore()创建信号量时即要同时指出允许的最大资源计数和当前可用资源 计数。一般是将当前可用资源计数设置为最大资源计数,每增加一个线程对共享资源的访问, 当前可用资源计数就会减1,只要当前可用资源计数是大于0的,就可以发出信号量信号。 但是当前可用计数减小到0时则说明当前占用资源的线程数已经达到了所允许的最大数目, 不能在允许其他线程的进入,此时的信号量信号将无法发出。线程在处理完共享资源后, 应在离开的同时通过ReleaseSemaphore()函数将当前可用资源计数加1。在任何时候当前 可用资源计数决不可能大于最大资源计数。 信号量是通过计数来对线程访问资源进行控制 的,而实际上信号量确实也被称作Dijkstra计数器 信号量是最具历史的同步机制。信号量是解决producer/consumer问题的关键要素 *) PSemaphore = ^TSemaphore; TSemaphore = record Status : Integer; Handle : THandle; end; function CheckOutWinLock: PWinLock; procedure CheckInWinLock(var AWinLock: PWinLock); procedure InitializeWinLock(AWinLock: PWinLock); procedure FinalizeWinLock(AWinLock: PWinLock); procedure LockWinLock(AWinLock: PWinLock); procedure UnLockWinLock(AWinLock: PWinLock); function CheckOutMutex: PMutex; procedure CheckInMutex(var AMutex: PMutex); procedure InitializeMutex(AMutex: PMutex); procedure FinalizeMutex(AMutex: PMutex); procedure WaitMutex(AMutex: PMutex); function CheckOutEvent: PEvent; procedure CheckInEvent(var AEvent: PEvent); procedure InitializeEvent(AEvent: PEvent); procedure FinalizeEvent(AEvent: PEvent); function CheckOutSemaphore: PSemaphore; procedure CheckInSemaphore(var ASemaphore: PSemaphore); procedure InitializeSemaphore(ASemaphore: PSemaphore); procedure FinalizeSemaphore(ASemaphore: PSemaphore); procedure WaitSemaphore(ASemaphore: PSemaphore); implementation uses BaseMemory; function CheckOutWinLock: PWinLock; begin Result := GetMemory(nil, SizeOf(TWinLock)); if nil <> Result then begin FillChar(Result^, SizeOf(TWinLock), 0); end; end; procedure CheckInWinLock(var AWinLock: PWinLock); begin if nil = AWinLock then exit; FinalizeWinLock(AWinLock); FreeMem(AWinLock); AWinLock := nil; end; procedure InitializeWinLock(AWinLock: PWinLock); begin InitializeCriticalSection(AWinLock.Handle); end; procedure FinalizeWinLock(AWinLock: PWinLock); begin DeleteCriticalSection(AWinLock.Handle); end; procedure LockWinLock(AWinLock: PWinLock); begin EnterCriticalSection(AWinLock.Handle); end; procedure UnLockWinLock(AWinLock: PWinLock); begin LeaveCriticalSection(AWinLock.Handle); end; function CheckOutMutex: PMutex; begin Result := GetMemory(nil, SizeOf(TMutex)); if nil <> Result then begin FillChar(Result^, SizeOf(TMutex), 0); end; end; procedure CheckInMutex(var AMutex: PMutex); begin end; procedure InitializeMutex(AMutex: PMutex); begin AMutex.Handle := Windows.CreateMutexA(nil, False, ''); AMutex.Handle := Windows.OpenMutexA(0, False, ''); end; procedure FinalizeMutex(AMutex: PMutex); begin ReleaseMutex(AMutex.Handle); end; procedure WaitMutex(AMutex: PMutex); begin WaitForSingleObject(AMutex.Handle, INFINITE); //WaitForMultipleObjects(); end; function CheckOutEvent: PEvent; begin Result := GetMemory(nil, SizeOf(TEvent)); if nil <> Result then begin FillChar(Result^, SizeOf(TEvent), 0); end; end; procedure CheckInEvent(var AEvent: PEvent); begin end; procedure InitializeEvent(AEvent: PEvent); begin AEvent.Handle := Windows.CreateEventA(nil, false, false, ''); AEvent.Handle := Windows.OpenEventA(0, false, ''); end; procedure FinalizeEvent(AEvent: PEvent); begin end; function CheckOutSemaphore: PSemaphore; begin Result := GetMemory(nil, SizeOf(TSemaphore)); if nil <> Result then begin FillChar(Result^, SizeOf(TSemaphore), 0); end; end; procedure CheckInSemaphore(var ASemaphore: PSemaphore); begin FinalizeSemaphore(ASemaphore); FreeMem(ASemaphore); ASemaphore := nil; end; procedure InitializeSemaphore(ASemaphore: PSemaphore); begin ASemaphore.Handle := Windows.CreateSemaphore(nil, 0, 0, ''); ASemaphore.Handle := Windows.OpenSemaphore(0, False, ''); end; procedure FinalizeSemaphore(ASemaphore: PSemaphore); begin Windows.ReleaseSemaphore(ASemaphore.Handle, 0, nil); end; procedure WaitSemaphore(ASemaphore: PSemaphore); begin WaitForSingleObject(ASemaphore.Handle, INFINITE); end; end.