text
stringlengths
14
6.51M
unit MedModel; interface uses System.Classes, MedModelConst, Data.SqlExpr; type THL7Segment = class private FMsgText: TStrings; function GetHL7SegmentName: string; published constructor Create(AMsgText: string); overload; destructor Destroy; override; class function IsExistSegment(AMsgText: TStrings; ASegmentType: THL7SegmentType): Boolean; class function CheckMSG(AMsgText: TStrings): Boolean; class procedure GetSegmentMsgText(AMsgText: TStrings; ASegmentType: THL7SegmentType; var AOutStrings: TStrings); class function GetSegmentMsgTextStr(AMsgText: TStrings; ASegmentType: THL7SegmentType): string; class function GetSegmentNameValue(ASegmentType: THL7SegmentType): string; function GetValue(AIdxElement: Integer): string; function ToString: string; override; property MsgText: TStrings read FMsgText; property HL7SegmentName: string read GetHL7SegmentName; end; //Message Header TMSH = class(THL7Segment) private function GetAcceptAcknowledgmentType: string; function GetApplicationAcknowledgmentType: string; function GetCharacterSet: string; function GetContinuationPointer: string; function GetCountryCode: string; function GetDateTimeMsg: TDateTime; function GetEncodingCharacters: string; function GetMessageControlID: string; function GetMessageType: string; function GetPrincipalLangMsg: string; function GetProcessingID: string; function GetReceivingApp: string; function GetReceivingFacility: string; function GetSecurity: string; function GetSendingApp: string; function GetSendingFacility: string; function GetSequenceNumber: string; function GetVersionID: string; function GetAltCharacterSetHandlingScheme: string; function GetMsgProfileId: string; function GetReceivNetworkAddress: string; function GetReceivResponsibleOrg: string; function GetSendNetworkAddress: string; function GetSendResponsibleOrg: string; public function ToString: string; override; property EncodingCharacters: string read GetEncodingCharacters; property SendingApp: string read GetSendingApp; property SendingFacility: string read GetSendingFacility; property ReceivingApp: string read GetReceivingApp; property ReceivingFacility: string read GetReceivingFacility; property DateTimeMsg: TDateTime read GetDateTimeMsg; property Security: string read GetSecurity; property MessageType: string read GetMessageType; property MessageControlID: string read GetMessageControlID; property ProcessingID: string read GetProcessingID; property VersionID: string read GetVersionID; property SequenceNumber: string read GetSequenceNumber; property ContinuationPointer: string read GetContinuationPointer; property AcceptAcknowledgmentType: string read GetAcceptAcknowledgmentType; property ApplicationAcknowledgmentType: string read GetApplicationAcknowledgmentType; property CountryCode: string read GetCountryCode; property CharacterSet: string read GetCharacterSet; property PrincipalLangMsg: string read GetPrincipalLangMsg; property AltCharacterSetHandlingScheme: string read GetAltCharacterSetHandlingScheme; property MsgProfileId: string read GetMsgProfileId; property SendResponsibleOrg: string read GetSendResponsibleOrg; property ReceivResponsibleOrg: string read GetReceivResponsibleOrg; property SendNetworkAddress: string read GetSendNetworkAddress; property ReceivNetworkAddress: string read GetReceivNetworkAddress; end; //Patient Identification TPID = class(THL7Segment) private function GetDTBirth: TDateTime; function GetAddress: string; function GetCountyCode: string; function GetDriverLicNumb: string; function GetGender: string; function GetMaritalStatus: string; function GetMothMaidenName: string; function GetPatientID: Integer; function GetPatientIDAlt: string; function GetPatientIDExt: string; function GetPatientIDInt: string; function GetPatientName: string; function GetPhoneNumbBusiness: string; function GetPhoneNumbHome: string; function GetPrimaryLanguage: string; function GetRace: string; function GetReligion: string; function GetSSNNumb: string; function GetPatientAlias: string; function GetPatientAccountNumber: string; function GetBirthOrder: string; function GetBirthPlace: string; function GetCitizenship: string; function GetEthnicGroup: string; function GetMothersIdentifie: string; function GetMultipleBirthIndicator: string; function GetNationality: string; function GetPatientDeathDateTime: string; function GetPatientDeathIndicator: string; function GetVeteransMilitaryStatus: string; function GetBreedCode: string; function GetIdentityReliabilityCode: string; function GetIdentityUnknownIndicator: string; function GetLastUpdateDateTime: string; function GetLastUpdateFacility: string; function GetProductionClassCode: string; function GetSpeciesCode: string; function GetStrain: string; function GetTribalCitizenshi: string; public function ToString: string; override; property PatientID: Integer read GetPatientID; property PatientIDExt: string read GetPatientIDExt; property PatientIDInt: string read GetPatientIDInt; property PatientIDAlt: string read GetPatientIDAlt; property PatientName: string read GetPatientName; property MothMaidenName: string read GetMothMaidenName; property DTBirth: TDateTime read GetDTBirth; property Gender: string read GetGender; property PatientAlias: string read GetPatientAlias; property Race: string read GetRace; property Address: string read GetAddress; property CountyCode: string read GetCountyCode; property PhoneNumbHome: string read GetPhoneNumbHome; property PhoneNumbBusiness: string read GetPhoneNumbBusiness; property PrimaryLanguage: string read GetPrimaryLanguage; property MaritalStatus: string read GetMaritalStatus; property Religion: string read GetReligion; property PatientAccountNumber: string read GetPatientAccountNumber; property SSNNumb: string read GetSSNNumb; property DriverLicNumb: string read GetDriverLicNumb; property MothersIdentifie: string read GetMothersIdentifie; property EthnicGroup: string read GetEthnicGroup; property BirthPlace: string read GetBirthPlace; property MultipleBirthIndicator: string read GetMultipleBirthIndicator; property BirthOrder: string read GetBirthOrder; property Citizenship: string read GetCitizenship; property VeteransMilitaryStatus: string read GetVeteransMilitaryStatus; property Nationality: string read GetNationality; property PatientDeathDateTime: string read GetPatientDeathDateTime; property PatientDeathIndicator: string read GetPatientDeathIndicator; property IdentityUnknownIndicator: string read GetIdentityUnknownIndicator; property IdentityReliabilityCode: string read GetIdentityReliabilityCode; property LastUpdateDateTime: string read GetLastUpdateDateTime; property LastUpdateFacility: string read GetLastUpdateFacility; property SpeciesCode: string read GetSpeciesCode; property BreedCode: string read GetBreedCode; property Strain: string read GetStrain; property ProductionClassCode: string read GetProductionClassCode; property TribalCitizenshi: string read GetTribalCitizenshi; end; TPatient = class(TPID) private function GetSurname: string; function GetFirstname: string; function GetInitials: string; function GetAddress1: string; function GetAddress2: string; function GetCity: string; function GetPostalCode: string; function GetProvinceCode: string; function GetSEERCountryGeocode: string; function GetFullName: string; public //Name property Surname: string read GetSurname; property Firstname: string read GetFirstname; property Initials: string read GetInitials; property FullName: string read GetFullName; //Address property Address1: string read GetAddress1; property Address2: string read GetAddress2; property City: string read GetCity; property ProvinceCode: string read GetProvinceCode; property PostalCode: string read GetPostalCode; property SEERCountryGeocode: string read GetSEERCountryGeocode; end; //Observation Report TOBR = class(THL7Segment) private function GetAssistantResultInterpreter: string; function GetChargeToPractice: string; function GetCollectionVolume: string; function GetCollectorIdentifier: string; function GetCollectorsComment: string; function GetDangerCode: string; function GetDiagnosticServSectID: string; function GetEscortRequired: string; function GetFillerField1: string; function GetFillerField2: string; function GetFillerOrderNumber: string; function GetNumberOfSampleContainers: Integer; function GetObservationDateTime: TDateTime; function GetObservationEndDateTime: TDateTime; function GetOrderCallbackPhoneNumber: string; function GetOrderingProvider: string; function GetParent: string; function GetParentResult: string; function GetPlacerField1: string; function GetPlacerField2: string; function GetPlacerOrderNumber: string; function GetPlannedPatientTransportComment: string; function GetPrincipalResultInterpreter: string; function GetPriority: string; function GetQuantityOrTiming: string; function GetReasonForStudy: string; function GetRelevantClinicalInfo: string; function GetRequestedDateTime: string; function GetResultCopiesTo: string; function GetResultsRptStatusChngDateTime: string; function GetResultStatus: string; function GetScheduledDateTime: string; function GetSpecimenActionCode: string; function GetSpecimenReceivedDateTime: string; function GetSpecimenSource: string; function GetTechnician: string; function GetTranscriptionist: string; function GetTransportArranged: string; function GetTransportArrangementResponsibility: string; function GetTransportationMode: string; function GetTransportLogisticsOfCollectedSample: string; function GetUniversalServiceID: string; public function ToString: string; override; property PlacerOrderNumber: string read GetPlacerOrderNumber; property FillerOrderNumber: string read GetFillerOrderNumber; property UniversalServiceID: string read GetUniversalServiceID; property Priority: string read GetPriority; property RequestedDateTime: string read GetRequestedDateTime; property ObservationDateTime: TDateTime read GetObservationDateTime; property ObservationEndDateTime: TDateTime read GetObservationEndDateTime; property CollectionVolume: string read GetCollectionVolume; property CollectorIdentifier: string read GetCollectorIdentifier; property SpecimenActionCode: string read GetSpecimenActionCode; property DangerCode: string read GetDangerCode; property RelevantClinicalInfo: string read GetRelevantClinicalInfo; property SpecimenReceivedDateTime: string read GetSpecimenReceivedDateTime; property SpecimenSource: string read GetSpecimenSource; property OrderingProvider: string read GetOrderingProvider; property OrderCallbackPhoneNumber: string read GetOrderCallbackPhoneNumber; property PlacerField1: string read GetPlacerField1; property PlacerField2: string read GetPlacerField2; property FillerField1: string read GetFillerField1; property FillerField2: string read GetFillerField2; property ResultsRptStatusChngDateTime: string read GetResultsRptStatusChngDateTime; property ChargeToPractice: string read GetChargeToPractice; property DiagnosticServSectID: string read GetDiagnosticServSectID; property ResultStatus: string read GetResultStatus; property ParentResult: string read GetParentResult; property QuantityOrTiming: string read GetQuantityOrTiming; property ResultCopiesTo: string read GetResultCopiesTo; property Parent: string read GetParent; property TransportationMode: string read GetTransportationMode; property ReasonForStudy: string read GetReasonForStudy; property PrincipalResultInterpreter: string read GetPrincipalResultInterpreter; property AssistantResultInterpreter: string read GetAssistantResultInterpreter; property Technician: string read GetTechnician; property Transcriptionist: string read GetTranscriptionist; property ScheduledDateTime: string read GetScheduledDateTime; property NumberOfSampleContainers: Integer read GetNumberOfSampleContainers; property TransportLogisticsOfCollectedSample: string read GetTransportLogisticsOfCollectedSample; property CollectorsComment: string read GetCollectorsComment; property TransportArrangementResponsibility: string read GetTransportArrangementResponsibility; property TransportArranged: string read GetTransportArranged; property EscortRequired: string read GetEscortRequired; property PlannedPatientTransportComment: string read GetPlannedPatientTransportComment; end; // TAccessionSpec = class(TOBR) private function GetAccessionNumber: string; function GetNamespaceId: string; function GetSpecimenLabel: string; function GetSurgicalProcedure: string; function GetPriorityId: string; public property AccessionNumber: string read GetAccessionNumber; property NamespaceId: string read GetNamespaceId; property SpecimenLabel: string read GetSpecimenLabel; property SurgicalProcedure: string read GetSurgicalProcedure; property PriorityId: string read GetPriorityId; end; // TOBX = class(THL7Segment) private function GetAbnormalFlags: string; function GetDateLastObsNormalValues: string; function GetDateTimeOfObservation: string; function GetNatureOfAbnormalTest: string; function GetObservationIdentifier: string; function GetObservationMethod: string; function GetObservationSubID: string; function GetObservationValue: string; function GetObservResultStatus: string; function GetProbability: string; function GetProducersID: string; function GetReferencesRange: string; function GetResponsibleObserver: string; function GetUnits: string; function GetUserDefinedAccessChecks: string; function GetValueType: string; function GetOBXNumber: string; public function ToString: string; override; property OBXNumber: string read GetOBXNumber; property ValueType: string read GetValueType; property ObservationIdentifier: string read GetObservationIdentifier; property ObservationSubID: string read GetObservationSubID; property ObservationValue: string read GetObservationValue; property Units: string read GetUnits; property ReferencesRange: string read GetReferencesRange; property AbnormalFlags: string read GetAbnormalFlags; property Probability: string read GetProbability; property NatureOfAbnormalTest: string read GetNatureOfAbnormalTest; property ObservResultStatus: string read GetObservResultStatus; property DateLastObsNormalValues: string read GetDateLastObsNormalValues; property UserDefinedAccessChecks: string read GetUserDefinedAccessChecks; property DateTimeOfObservation: string read GetDateTimeOfObservation; property ProducersID: string read GetProducersID; property ResponsibleObserver: string read GetResponsibleObserver; property ObservationMethod: string read GetObservationMethod; end; TOBXSpec = class(TOBX) private function GetIdentifier: string; function GetTextST: string; function GetComment: string; function GetDiagnosis: string; function GetGrossDescription: string; function GetMicroscopicObserv: string; function GetSpecimenLabel: string; public property Identifier: string read GetIdentifier; property TextST: string read GetTextST; property MicroscopicObserv: string read GetMicroscopicObserv; property Diagnosis: string read GetDiagnosis; property Comment: string read GetComment; property GrossDescription: string read GetGrossDescription; property SpecimenLabel: string read GetSpecimenLabel; end; TSpeciman = class private FGrossDescription: string; FMicroscopicObserv: string; FDiagnosis: string; FId: string; FSpecimenLabel: string; public constructor Create(AId: string); overload; constructor Create(AId, AMicroscopicObserv, ADiagnosis, AGrossDescription, ASpecimenLabel: string); overload; function ToString: string; override; property Id: string read FId write FId; property MicroscopicObserv: string read FMicroscopicObserv write FMicroscopicObserv; property Diagnosis: string read FDiagnosis write FDiagnosis; property GrossDescription: string read FGrossDescription write FGrossDescription; property SpecimenLabel: string read FSpecimenLabel write FSpecimenLabel; end; TPIDList = class(TList); TOBRList = class(TList); TOBXList = class(TList) private function GetTextSTByTypeAndId(AValueType, AIdentifier: string): string; public end; TSpecimanList = class(TList) public function AddSpeciman(AId: string): TSpeciman; function IsExist(AId: string): Boolean; function GetSpecimanById(AId: string): TSpeciman; procedure SaveToDB(ASQLQuery: TSQLQuery; AAccessionNumber: string); procedure Load(var ASQLQuery: TSQLQuery); end; THL7Message = class private FMSH: TMSH; FOBR: TOBR; FPID: TPID; FOBXList: TOBXList; FSpecimanList: TSpecimanList; FPIDList: TPIDList; FOBRList: TOBRList; procedure InitSpecimanList; class function LoadMSHById(ASQLQuery: TSQLQuery): string; class function LoadPIDById(var ASQLQuery: TSQLQuery; AId: Integer): string; class function LoadOBRById(var ASQLQuery: TSQLQuery; AId: Integer): string; function LoadPID(var ASQLQuery: TSQLQuery; var APIDStrings: TStrings): TStrings; procedure LoadOBR(var ASQLQuery: TSQLQuery; var AOBRStrings: TStrings); procedure LoadOBX(var ASQLQuery: TSQLQuery; var AOBXStrings: TStrings); procedure SaveAccession(ASQLQuery: TSQLQuery); procedure SavePatient(ASQLQuery: TSQLQuery); procedure SaveSpecimen(ASQLQuery: TSQLQuery); public constructor Create(AMsg: TStrings); overload; constructor Create(AMsg: string); overload; destructor Destroy; override; function CheckMessage: Boolean; procedure InitMSG(AMsg: TStrings); function ToString: string; override; class function Load(var ASQLQuery: TSQLQuery): THL7Message; procedure SaveToDB(ASQLQuery: TSQLQuery); property MSH: TMSH read FMSH; property PID: TPID read FPID; property OBR: TOBR read FOBR; property PIDList: TPIDList read FPIDList; property OBRList: TOBRList read FOBRList; property OBXList: TOBXList read FOBXList; property SpecimanList: TSpecimanList read FSpecimanList; end; implementation uses System.SysUtils, DateUtils, MedUtils, Data.SqlTimSt; { TPatient } function TPID.GetAddress: string; begin Result := GetValue(Integer(pidePatientAddress)); end; function TPID.GetBirthOrder: string; begin Result := GetValue(Integer(pideBirthOrder)); end; function TPID.GetBirthPlace: string; begin Result := GetValue(Integer(pideBirthPlace)); end; function TPID.GetBreedCode: string; begin Result := GetValue(Integer(pideBreedCode)); end; function TPID.GetCitizenship: string; begin Result := GetValue(Integer(pideCitizenship)); end; function TPID.GetCountyCode: string; begin Result := GetValue(Integer(pideCountyCode)); end; function TPID.GetDriverLicNumb: string; begin Result := GetValue(Integer(pideDriverLicenseNumber)); end; function TPID.GetDTBirth: TDateTime; begin Result := MedDateStrToDate(GetValue(Integer(pideDateBirth))); end; function TPID.GetEthnicGroup: string; begin Result := GetValue(Integer(pideEthnicGroup)); end; function TPID.GetGender: string; begin Result := GetValue(Integer(pideSex)); end; function TPID.GetIdentityReliabilityCode: string; begin Result := GetValue(Integer(pideIdentityReliabilityCode)); end; function TPID.GetIdentityUnknownIndicator: string; begin Result := GetValue(Integer(pideIdentityUnknownIndicator)); end; function TPID.GetLastUpdateDateTime: string; begin Result := GetValue(Integer(pideLastUpdateDateTime)); end; function TPID.GetLastUpdateFacility: string; begin Result := GetValue(Integer(pideLastUpdateFacility)); end; function TPID.GetMaritalStatus: string; begin Result := GetValue(Integer(pideMaritalStatus)); end; function TPID.GetMothersIdentifie: string; begin Result := GetValue(Integer(pideMothersIdentifie)); end; function TPID.GetMothMaidenName: string; begin Result := GetValue(Integer(pideMothMaidenName)); end; function TPID.GetMultipleBirthIndicator: string; begin Result := GetValue(Integer(pideMultipleBirthIndicator)); end; function TPID.GetNationality: string; begin Result := GetValue(Integer(pideNationality)); end; function TPID.GetPatientAccountNumber: string; begin Result := GetValue(Integer(pidePatientAccountNumber)); end; function TPID.GetPatientAlias: string; begin Result := GetValue(Integer(pidePatientAlias)); end; function TPID.GetPatientDeathDateTime: string; begin Result := GetValue(Integer(pidePatientDeathDateTime)); end; function TPID.GetPatientDeathIndicator: string; begin Result := GetValue(Integer(pidePatientDeathIndicator)); end; function TPID.GetPatientID: Integer; begin Result := StrToIntDef(GetValue(Integer(pidePatientID)), 0); end; function TPID.GetPatientIDAlt: string; begin Result := GetValue(Integer(pidePatientIDAlt)); end; function TPID.GetPatientIDExt: string; begin Result := GetValue(Integer(pidePatientIDExt)); end; function TPID.GetPatientIDInt: string; begin Result := GetValue(Integer(pidePatientIDInt)); end; function TPID.GetPatientName: string; begin Result := GetValue(Integer(pidePatientName)); end; function TPID.GetPhoneNumbBusiness: string; begin Result := GetValue(Integer(pidePhoneNumberBusiness)); end; function TPID.GetPhoneNumbHome: string; begin Result := GetValue(Integer(pidePhoneNumberHome)); end; function TPID.GetPrimaryLanguage: string; begin Result := GetValue(Integer(pidePrimaryLanguage)); end; function TPID.GetProductionClassCode: string; begin Result := GetValue(Integer(pideProductionClassCode)); end; function TPID.GetRace: string; begin Result := GetValue(Integer(pideRace)); end; function TPID.GetReligion: string; begin Result := GetValue(Integer(pideReligion)); end; function TPID.GetSpeciesCode: string; begin Result := GetValue(Integer(pideSpeciesCode)); end; function TPID.GetSSNNumb: string; begin Result := GetValue(Integer(pideSSNNumber)); end; function TPID.GetStrain: string; begin Result := GetValue(Integer(pideStrain)); end; function TPID.GetTribalCitizenshi: string; begin Result := GetValue(Integer(pideTribalCitizenshi)); end; function TPID.GetVeteransMilitaryStatus: string; begin Result := GetValue(Integer(pideVeteransMilitaryStatus)); end; function TPID.ToString: string; begin Result := inherited; Result := Result + HL7_SEPARATOR + PatientID.ToString + HL7_SEPARATOR + PatientIDExt + HL7_SEPARATOR + PatientIDInt + HL7_SEPARATOR + PatientIDAlt + HL7_SEPARATOR + PatientName + HL7_SEPARATOR + MothMaidenName + HL7_SEPARATOR + DateToMedDateStr(DTBirth) + HL7_SEPARATOR + Gender + HL7_SEPARATOR + PatientAlias + HL7_SEPARATOR + Race + HL7_SEPARATOR + Address + HL7_SEPARATOR + CountyCode + HL7_SEPARATOR + PhoneNumbHome + HL7_SEPARATOR + PhoneNumbBusiness + HL7_SEPARATOR + PrimaryLanguage + HL7_SEPARATOR + MaritalStatus + HL7_SEPARATOR + Religion + HL7_SEPARATOR + PatientAccountNumber + HL7_SEPARATOR + SSNNumb + HL7_SEPARATOR + DriverLicNumb + HL7_SEPARATOR + MothersIdentifie + HL7_SEPARATOR + EthnicGroup + HL7_SEPARATOR + BirthPlace + HL7_SEPARATOR + MultipleBirthIndicator + HL7_SEPARATOR + BirthOrder + HL7_SEPARATOR + Citizenship + HL7_SEPARATOR + VeteransMilitaryStatus + HL7_SEPARATOR + Nationality + HL7_SEPARATOR + PatientDeathDateTime + HL7_SEPARATOR + PatientDeathIndicator + HL7_SEPARATOR + IdentityUnknownIndicator + HL7_SEPARATOR + IdentityReliabilityCode + HL7_SEPARATOR + LastUpdateDateTime + HL7_SEPARATOR + LastUpdateFacility + HL7_SEPARATOR + SpeciesCode + HL7_SEPARATOR + BreedCode + HL7_SEPARATOR + Strain + HL7_SEPARATOR + ProductionClassCode + HL7_SEPARATOR + TribalCitizenshi; end; { TPatient } function TPatient.GetAddress1: string; begin Result := GetSubElement(Address, HL7_SEPARATOR_COMPONENT, Integer(psaAddress1)); end; function TPatient.GetAddress2: string; begin Result := GetSubElement(Address, HL7_SEPARATOR_COMPONENT, Integer(psaAddress2)); end; function TPatient.GetCity: string; begin Result := GetSubElement(Address, HL7_SEPARATOR_COMPONENT, Integer(psaCity)); end; function TPatient.GetFirstname: string; begin Result := GetSubElement(PatientName, HL7_SEPARATOR_COMPONENT, Integer(psnFirstName)); end; function TPatient.GetFullName: string; begin Result := Trim(Surname + ' ' + Firstname + ' ' + Initials); end; function TPatient.GetInitials: string; begin Result := GetSubElement(PatientName, HL7_SEPARATOR_COMPONENT, Integer(psnInitials)); end; function TPatient.GetPostalCode: string; begin Result := GetSubElement(Address, HL7_SEPARATOR_COMPONENT, Integer(psaPostalCode)); end; function TPatient.GetProvinceCode: string; begin Result := GetSubElement(Address, HL7_SEPARATOR_COMPONENT, Integer(psaProvinceCode)); end; function TPatient.GetSEERCountryGeocode: string; begin Result := GetSubElement(Address, HL7_SEPARATOR_COMPONENT, Integer(psaSEERCountryGeocode)); end; function TPatient.GetSurname: string; begin Result := GetSubElement(PatientName, HL7_SEPARATOR_COMPONENT, Integer(psnSurname)); end; { THL7Segment } class function THL7Segment.CheckMSG(AMsgText: TStrings): Boolean; begin Result := IsExistSegment(AMsgText, hlsMSH) and IsExistSegment(AMsgText, hlsPID) and IsExistSegment(AMsgText, hlsOBR) and IsExistSegment(AMsgText, hlsOBX); end; constructor THL7Segment.Create(AMsgText: string); begin FMsgText := TStringList.Create; FMsgText.StrictDelimiter := True; FMsgText.Delimiter := HL7_SEPARATOR; FMsgText.DelimitedText := AMsgText; end; destructor THL7Segment.Destroy; begin if Assigned(FMsgText) then FMsgText.Free; inherited; end; function THL7Segment.GetHL7SegmentName: string; begin Result := GetValue(0); end; class function THL7Segment.GetSegmentMsgTextStr(AMsgText: TStrings; ASegmentType: THL7SegmentType): string; var I: Integer; begin for I := 0 to AMsgText.Count - 1 do if GetSegmentNameValue(ASegmentType) = AMsgText[I].Substring(0, 3) then begin Result := AMsgText[I]; Break; end; end; class function THL7Segment.GetSegmentNameValue( ASegmentType: THL7SegmentType): string; begin Result := ''; case ASegmentType of hlsNone: Result := HL7_SGM_NONE; hlsMSH: Result := HL7_SGM_MSH; hlsPID: Result := HL7_SGM_PID; hlsOBR: Result := HL7_SGM_OBR; hlsOBX: Result := HL7_SGM_OBX; end; end; class procedure THL7Segment.GetSegmentMsgText(AMsgText: TStrings; ASegmentType: THL7SegmentType; var AOutStrings: TStrings); var I: Integer; begin if Assigned(AMsgText) and Assigned(AOutStrings) then begin for I := 0 to AMsgText.Count - 1 do if GetSegmentNameValue(ASegmentType) = AMsgText[I].Substring(0, 3) then AOutStrings.Add(AMsgText[I]); end; end; function THL7Segment.GetValue(AIdxElement: Integer): string; begin Result := EmptyStr; if MsgText.Count > AIdxElement then Result := MsgText[AIdxElement]; end; class function THL7Segment.IsExistSegment(AMsgText: TStrings; ASegmentType: THL7SegmentType): Boolean; var I: Integer; begin Result := False; if Assigned(AMsgText) then begin for I := 0 to AMsgText.Count - 1 do if GetSegmentNameValue(ASegmentType) = AMsgText[I].Substring(0, 3) then begin Result := True; Break; end; end; end; function THL7Segment.ToString: string; begin Result := HL7SegmentName; end; { THL7Message } constructor THL7Message.Create(AMsg: TStrings); begin InitMSG(AMsg); end; function THL7Message.CheckMessage: Boolean; begin Result := (PID.PatientID > 0) and (PID.PatientIDInt <> EmptyStr);// and // (OBR.FillerOrderNumber <> EmptyStr); end; constructor THL7Message.Create(AMsg: string); var StringList: TStrings; begin StringList := TStringList.Create; try StringList.Text := AMsg; Create(StringList); finally StringList.Free; end; end; destructor THL7Message.Destroy; begin if Assigned(FMSH) then FMSH.Free; if Assigned(FPID) then FPID.Free; if Assigned(FOBR) then FOBR.Free; if Assigned(FPIDList) then FPIDList.Free; if Assigned(FOBRList) then FOBRList.Free; if Assigned(FOBXList) then FOBXList.Free; if Assigned(FSpecimanList) then FSpecimanList.Free; inherited; end; procedure THL7Message.InitMSG(AMsg: TStrings); var I: Integer; TmpStringList: TStrings; begin FMSH := TMSH.Create(THL7Segment.GetSegmentMsgTextStr(AMsg, hlsMSH)); FPID := TPID.Create(THL7Segment.GetSegmentMsgTextStr(AMsg, hlsPID)); FOBR := TOBR.Create(THL7Segment.GetSegmentMsgTextStr(AMsg, hlsOBR)); FPIDList := TPIDList.Create; FOBRList := TOBRList.Create; FOBXList := TOBXList.Create; TmpStringList := TStringList.Create; try //PID TmpStringList.Clear; THL7Segment.GetSegmentMsgText(AMsg, hlsPID, TmpStringList); for I := 0 to TmpStringList.Count - 1 do FPIDList.Add(TPID.Create(TmpStringList[I])); //OBR TmpStringList.Clear; THL7Segment.GetSegmentMsgText(AMsg, hlsOBR, TmpStringList); for I := 0 to TmpStringList.Count - 1 do FOBRList.Add(TOBR.Create(TmpStringList[I])); //OBX TmpStringList.Clear; THL7Segment.GetSegmentMsgText(AMsg, hlsOBX, TmpStringList); for I := 0 to TmpStringList.Count - 1 do FOBXList.Add(TOBX.Create(TmpStringList[I])); finally TmpStringList.Free; end; FSpecimanList := TSpecimanList.Create; InitSpecimanList; end; procedure THL7Message.InitSpecimanList; var Speciman: TSpeciman; OBX: TOBXSpec; I: Integer; J: Integer; begin SpecimanList.Clear; for I := 0 to OBXList.Count - 1 do begin if TOBXSpec(OBXList[I]).ObservationSubID <> EmptyStr then begin if not SpecimanList.IsExist(TOBXSpec(OBXList[I]).ObservationSubID) then Speciman := SpecimanList.AddSpeciman(TOBXSpec(OBXList[I]).ObservationSubID) else Speciman := SpecimanList.GetSpecimanById(TOBXSpec(OBXList[I]).ObservationSubID); //SpecimenLabel for J := 0 to OBXList.Count - 1 do begin OBX := TOBXSpec(OBXList[J]); if (OBX.ObservationSubID = TOBXSpec(OBXList[I]).ObservationSubID) and (OBX.SpecimenLabel <> EmptyStr) then begin Speciman.SpecimenLabel := OBX.SpecimenLabel; Break; end; end; //GrossDescription for J := 0 to OBXList.Count - 1 do begin OBX := TOBXSpec(OBXList[J]); if (OBX.ObservationSubID = TOBXSpec(OBXList[I]).ObservationSubID) and (OBX.GrossDescription <> EmptyStr) then begin Speciman.GrossDescription := OBX.GrossDescription; Break; end; end; //MicroscopicDesc for J := 0 to OBXList.Count - 1 do begin OBX := TOBXSpec(OBXList[J]); if (OBX.ObservationSubID = TOBXSpec(OBXList[I]).ObservationSubID) and (OBX.MicroscopicObserv <> EmptyStr) then begin Speciman.MicroscopicObserv := OBX.MicroscopicObserv; Break; end; end; //Diagnosis for J := 0 to OBXList.Count - 1 do begin OBX := TOBXSpec(OBXList[J]); if (OBX.ObservationSubID = TOBXSpec(OBXList[I]).ObservationSubID) and (OBX.Diagnosis <> EmptyStr) then begin Speciman.Diagnosis := OBX.Diagnosis; Break; end; end; end; end; end; class function THL7Message.Load(var ASQLQuery: TSQLQuery): THL7Message; var StringList: TStrings; I: Integer; begin Result := THL7Message.Create; StringList := TStringList.Create; try //MSH StringList.Add(LoadMSHById(ASQLQuery)); Result.InitMSG(StringList); //PID Result.LoadPID(ASQLQuery, StringList); //OBR Result.LoadOBR(ASQLQuery, StringList); //OBX Result.LoadOBX(ASQLQuery, StringList); Result.InitMSG(StringList); finally StringList.Free; end; end; class function THL7Message.LoadMSHById(ASQLQuery: TSQLQuery): string; begin //SegnentName Result := 'MSH'; //EncodingCharacters Result := Result + HL7_SEPARATOR + '^~\&'; //SendingApp Result := Result + HL7_SEPARATOR + ''; //SendingFacility Result := Result + HL7_SEPARATOR + 'INDEPENDENT LAB SERVICES^33D1234567^CLIA'; //ReceivingApp Result := Result + HL7_SEPARATOR + ''; //ReceivingFacility Result := Result + HL7_SEPARATOR + ''; //DateTimeMsg Result := Result + HL7_SEPARATOR + DateTimeToMedDateTimeStr(Now); //Security Result := Result + HL7_SEPARATOR + ''; //MessageType Result := Result + HL7_SEPARATOR + 'ORU^R01^ORU_R01'; //MessageControlID Result := Result + HL7_SEPARATOR + '2004072813390045'; //ProcessingID Result := Result + HL7_SEPARATOR + 'P'; //VersionID Result := Result + HL7_SEPARATOR + '2.5.1'; //SequenceNumber Result := Result + HL7_SEPARATOR + ''; //ContinuationPointer Result := Result + HL7_SEPARATOR + ''; //AcceptAcknowledgmentType Result := Result + HL7_SEPARATOR + ''; //ApplicationAcknowledgmentType Result := Result + HL7_SEPARATOR + ''; //CountryCode Result := Result + HL7_SEPARATOR + ''; //CharacterSet Result := Result + HL7_SEPARATOR + ''; //PrincipalLangMsg Result := Result + HL7_SEPARATOR + ''; //AltCharacterSetHandlingScheme Result := Result + HL7_SEPARATOR + ''; //MsgProfileId Result := Result + HL7_SEPARATOR + 'VOL_V_30_ORU_R01^NAACCR_CP^2.16.840.1.113883.9.8^ISO'; //SendResponsibleOrg Result := Result + HL7_SEPARATOR + ''; //ReceivResponsibleOrg Result := Result + HL7_SEPARATOR + ''; //SendNetworkAddress Result := Result + HL7_SEPARATOR + ''; //ReceivNetworkAddress Result := Result + HL7_SEPARATOR + ''; end; class function THL7Message.LoadOBRById(var ASQLQuery: TSQLQuery; AId: Integer): string; begin //SegnentName Result := 'OBR'; ASQLQuery.SQL.Text := 'select * from accession a where a.accession_id = ' + IntToStr(AId); try ASQLQuery.Open; if not ASQLQuery.Eof then with ASQLQuery do begin //PlacerOrderNumber Result := Result + HL7_SEPARATOR + '1'; //FillerOrderNumber Result := Result + HL7_SEPARATOR + ''; //UniversalServiceID Result := Result + HL7_SEPARATOR + FieldByName('accession_number').AsString; //Priority Result := Result + HL7_SEPARATOR + ''; //RequestedDateTime Result := Result + HL7_SEPARATOR + ''; //ObservationDateTime Result := Result + HL7_SEPARATOR + ''; //ObservationEndDateTime Result := Result + HL7_SEPARATOR + ''; //CollectionVolume Result := Result + HL7_SEPARATOR + ''; //CollectorIdentifier Result := Result + HL7_SEPARATOR + ''; //SpecimenActionCode Result := Result + HL7_SEPARATOR + ''; //DangerCode Result := Result + HL7_SEPARATOR + ''; //RelevantClinicalInfo Result := Result + HL7_SEPARATOR + ''; //SpecimenReceivedDateTime Result := Result + HL7_SEPARATOR + ''; //SpecimenSource Result := Result + HL7_SEPARATOR + ''; //OrderingProvider Result := Result + HL7_SEPARATOR + ''; //OrderCallbackPhoneNumber Result := Result + HL7_SEPARATOR + ''; //PlacerField1 Result := Result + HL7_SEPARATOR + ''; //PlacerField2 Result := Result + HL7_SEPARATOR + ''; //FillerField1 Result := Result + HL7_SEPARATOR + ''; //FillerField2 Result := Result + HL7_SEPARATOR + ''; //ResultsRptStatusChngDateTime Result := Result + HL7_SEPARATOR + ''; //ChargeToPractice Result := Result + HL7_SEPARATOR + ''; //DiagnosticServSectID Result := Result + HL7_SEPARATOR + ''; //ResultStatus Result := Result + HL7_SEPARATOR + ''; //ParentResult Result := Result + HL7_SEPARATOR + ''; //QuantityOrTiming Result := Result + HL7_SEPARATOR + ''; //ResultCopiesTo Result := Result + HL7_SEPARATOR + ''; //Parent Result := Result + HL7_SEPARATOR + ''; //TransportationMode Result := Result + HL7_SEPARATOR + ''; //ReasonForStudy Result := Result + HL7_SEPARATOR + ''; //PrincipalResultInterpreter Result := Result + HL7_SEPARATOR + ''; //AssistantResultInterpreter Result := Result + HL7_SEPARATOR + ''; //Technician Result := Result + HL7_SEPARATOR + ''; //Transcriptionist Result := Result + HL7_SEPARATOR + ''; //ScheduledDateTime Result := Result + HL7_SEPARATOR + ''; //NumberOfSampleContainers Result := Result + HL7_SEPARATOR + ''; //TransportLogisticsOfCollectedSample Result := Result + HL7_SEPARATOR + ''; //CollectorsComment Result := Result + HL7_SEPARATOR + ''; //TransportArrangementResponsibility Result := Result + HL7_SEPARATOR + ''; //TransportArranged Result := Result + HL7_SEPARATOR + ''; //EscortRequired Result := Result + HL7_SEPARATOR + ''; //PlannedPatientTransportComment Result := Result + HL7_SEPARATOR + ''; end; except end; end; procedure THL7Message.LoadOBR(var ASQLQuery: TSQLQuery; var AOBRStrings: TStrings); var OBRStr: string; begin ASQLQuery.SQL.Text := 'select * from accession a ' + 'order by a.accession_id'; try ASQLQuery.Open; while not ASQLQuery.Eof do with ASQLQuery do begin //SegnentName OBRStr := 'OBR'; //PlacerOrderNumber OBRStr := OBRStr + HL7_SEPARATOR + '1'; //FillerOrderNumber OBRStr := OBRStr + HL7_SEPARATOR + ''; //UniversalServiceID OBRStr := OBRStr + HL7_SEPARATOR + FieldByName('accession_number').AsString; //Priority OBRStr := OBRStr + HL7_SEPARATOR + ''; //RequestedDateTime OBRStr := OBRStr + HL7_SEPARATOR + ''; //ObservationDateTime OBRStr := OBRStr + HL7_SEPARATOR + ''; //ObservationEndDateTime OBRStr := OBRStr + HL7_SEPARATOR + ''; //CollectionVolume OBRStr := OBRStr + HL7_SEPARATOR + ''; //CollectorIdentifier OBRStr := OBRStr + HL7_SEPARATOR + ''; //SpecimenActionCode OBRStr := OBRStr + HL7_SEPARATOR + ''; //DangerCode OBRStr := OBRStr + HL7_SEPARATOR + ''; //RelevantClinicalInfo OBRStr := OBRStr + HL7_SEPARATOR + ''; //SpecimenReceivedDateTime OBRStr := OBRStr + HL7_SEPARATOR + ''; //SpecimenSource OBRStr := OBRStr + HL7_SEPARATOR + ''; //OrderingProvider OBRStr := OBRStr + HL7_SEPARATOR + ''; //OrderCallbackPhoneNumber OBRStr := OBRStr + HL7_SEPARATOR + ''; //PlacerField1 OBRStr := OBRStr + HL7_SEPARATOR + ''; //PlacerField2 OBRStr := OBRStr + HL7_SEPARATOR + ''; //FillerField1 OBRStr := OBRStr + HL7_SEPARATOR + ''; //FillerField2 OBRStr := OBRStr + HL7_SEPARATOR + ''; //ResultsRptStatusChngDateTime OBRStr := OBRStr + HL7_SEPARATOR + ''; //ChargeToPractice OBRStr := OBRStr + HL7_SEPARATOR + ''; //DiagnosticServSectID OBRStr := OBRStr + HL7_SEPARATOR + ''; //ResultStatus OBRStr := OBRStr + HL7_SEPARATOR + ''; //ParentResult OBRStr := OBRStr + HL7_SEPARATOR + ''; //QuantityOrTiming OBRStr := OBRStr + HL7_SEPARATOR + ''; //ResultCopiesTo OBRStr := OBRStr + HL7_SEPARATOR + ''; //Parent OBRStr := OBRStr + HL7_SEPARATOR + ''; //TransportationMode OBRStr := OBRStr + HL7_SEPARATOR + ''; //ReasonForStudy OBRStr := OBRStr + HL7_SEPARATOR + ''; //PrincipalResultInterpreter OBRStr := OBRStr + HL7_SEPARATOR + ''; //AssistantResultInterpreter OBRStr := OBRStr + HL7_SEPARATOR + ''; //Technician OBRStr := OBRStr + HL7_SEPARATOR + ''; //Transcriptionist OBRStr := OBRStr + HL7_SEPARATOR + ''; //ScheduledDateTime OBRStr := OBRStr + HL7_SEPARATOR + ''; //NumberOfSampleContainers OBRStr := OBRStr + HL7_SEPARATOR + ''; //TransportLogisticsOfCollectedSample OBRStr := OBRStr + HL7_SEPARATOR + ''; //CollectorsComment OBRStr := OBRStr + HL7_SEPARATOR + ''; //TransportArrangementResponsibility OBRStr := OBRStr + HL7_SEPARATOR + ''; //TransportArranged OBRStr := OBRStr + HL7_SEPARATOR + ''; //EscortRequired OBRStr := OBRStr + HL7_SEPARATOR + ''; //PlannedPatientTransportComment OBRStr := OBRStr + HL7_SEPARATOR + ''; AOBRStrings.Add(OBRStr); Next; end; except end; end; procedure THL7Message.LoadOBX(var ASQLQuery: TSQLQuery; var AOBXStrings: TStrings); var I: Integer; Speciman: TSpeciman; begin if Assigned(SpecimanList) then SpecimanList.Load(ASQLQuery); //SpecimenLabel for I := 0 to SpecimanList.Count - 1 do begin Speciman := TSpeciman(SpecimanList[I]); if Assigned(Speciman) then if Speciman.SpecimenLabel <> EmptyStr then AOBXStrings.Add(HL7_SGM_OBX + HL7_SEPARATOR + IntToStr(AOBXStrings.Count + 1) + HL7_SEPARATOR + 'TX' + HL7_SEPARATOR + '00000-0' + HL7_SEPARATOR_COMPONENT + OBX_TEXT_ST_SPEC_LABEL + HL7_SEPARATOR_COMPONENT + 'LN' + HL7_SEPARATOR + Speciman.Id + HL7_SEPARATOR + Speciman.SpecimenLabel + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + 'F' ); end; //GrossDescription for I := 0 to SpecimanList.Count - 1 do begin Speciman := TSpeciman(SpecimanList[I]); if Assigned(Speciman) then if Speciman.GrossDescription <> EmptyStr then AOBXStrings.Add(HL7_SGM_OBX + HL7_SEPARATOR + IntToStr(AOBXStrings.Count + 1) + HL7_SEPARATOR + 'TX' + HL7_SEPARATOR + '00000-0' + HL7_SEPARATOR_COMPONENT + OBX_TEXT_ST_GROSS_DESC + HL7_SEPARATOR_COMPONENT + 'LN' + HL7_SEPARATOR + Speciman.Id + HL7_SEPARATOR + Speciman.GrossDescription + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + 'F' ); end; //MicroscopicObserv for I := 0 to SpecimanList.Count - 1 do begin Speciman := TSpeciman(SpecimanList[I]); if Assigned(Speciman) then if Speciman.MicroscopicObserv <> EmptyStr then AOBXStrings.Add(HL7_SGM_OBX + HL7_SEPARATOR + IntToStr(AOBXStrings.Count + 1) + HL7_SEPARATOR + 'TX' + HL7_SEPARATOR + '00000-0' + HL7_SEPARATOR_COMPONENT + OBX_TEXT_ST_MICROSCOPIC_OBSERV + HL7_SEPARATOR_COMPONENT + 'LN' + HL7_SEPARATOR + Speciman.Id + HL7_SEPARATOR + Speciman.MicroscopicObserv + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + 'F' ); end; //Diagnosis for I := 0 to SpecimanList.Count - 1 do begin Speciman := TSpeciman(SpecimanList[I]); if Assigned(Speciman) then if Speciman.Diagnosis <> EmptyStr then AOBXStrings.Add(HL7_SGM_OBX + HL7_SEPARATOR + IntToStr(AOBXStrings.Count + 1) + HL7_SEPARATOR + 'TX' + HL7_SEPARATOR + '00000-0' + HL7_SEPARATOR_COMPONENT + OBX_TEXT_ST_FINAL_DIAGNOSTIC + HL7_SEPARATOR_COMPONENT + 'LN' + HL7_SEPARATOR + Speciman.Id + HL7_SEPARATOR + Speciman.Diagnosis + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + '' + HL7_SEPARATOR + 'F' ); end; end; function THL7Message.LoadPID(var ASQLQuery: TSQLQuery; var APIDStrings: TStrings): TStrings; var PIDStr: string; begin ASQLQuery.SQL.Text := 'select * from patient p ' + 'order by p.patient_id'; try ASQLQuery.Open; while not ASQLQuery.Eof do with ASQLQuery do begin //Segment Name PIDStr := 'PID'; //PatientID PIDStr := PIDStr + HL7_SEPARATOR + IntToStr(FieldByName('patient_id').AsInteger); //PatientIDExt PIDStr := PIDStr + HL7_SEPARATOR + ''; //PatientIDInt PIDStr := PIDStr + HL7_SEPARATOR + FieldByName('medical_record').AsString; //PatientIDAlt PIDStr := PIDStr + HL7_SEPARATOR + ''; //PatientName PIDStr := PIDStr + HL7_SEPARATOR + FieldByName('last_name').AsString; PIDStr := PIDStr + HL7_SEPARATOR_COMPONENT + FieldByName('first_name').AsString; //MothMaidenName PIDStr := PIDStr + HL7_SEPARATOR + ''; //DateBirth PIDStr := PIDStr + HL7_SEPARATOR + DateToMedDateStr(SQLiteDateStrToDate(FieldByName('date_of_birth').AsString)); //Gender PIDStr := PIDStr + HL7_SEPARATOR + FieldByName('gender').AsString; //PatientAlias PIDStr := PIDStr + HL7_SEPARATOR + ''; //Race PIDStr := PIDStr + HL7_SEPARATOR + ''; //Address PIDStr := PIDStr + HL7_SEPARATOR + FieldByName('address').AsString; PIDStr := PIDStr + HL7_SEPARATOR_COMPONENT + ''; PIDStr := PIDStr + HL7_SEPARATOR_COMPONENT + FieldByName('city').AsString; PIDStr := PIDStr + HL7_SEPARATOR_COMPONENT + FieldByName('state_province').AsString; PIDStr := PIDStr + HL7_SEPARATOR_COMPONENT + FieldByName('zip_postal_code').AsString; PIDStr := PIDStr + HL7_SEPARATOR_COMPONENT + ''; //CountyCode PIDStr := PIDStr + HL7_SEPARATOR + FieldByName('country_region').AsString; //PhoneNumbHome PIDStr := PIDStr + HL7_SEPARATOR + FieldByName('home_phone').AsString; //PhoneNumbBusiness PIDStr := PIDStr + HL7_SEPARATOR + FieldByName('business_phone').AsString; //PrimaryLanguage PIDStr := PIDStr + HL7_SEPARATOR + ''; //MaritalStatus PIDStr := PIDStr + HL7_SEPARATOR + ''; //Religion PIDStr := PIDStr + HL7_SEPARATOR + ''; //PatientAccountNumber PIDStr := PIDStr + HL7_SEPARATOR + ''; //SSNNumb PIDStr := PIDStr + HL7_SEPARATOR + ''; //DriverLicNumb PIDStr := PIDStr + HL7_SEPARATOR + ''; //MothersIdentifie PIDStr := PIDStr + HL7_SEPARATOR + ''; //EthnicGroup PIDStr := PIDStr + HL7_SEPARATOR + ''; //BirthPlace PIDStr := PIDStr + HL7_SEPARATOR + ''; //MultipleBirthIndicator PIDStr := PIDStr + HL7_SEPARATOR + ''; //BirthOrder PIDStr := PIDStr + HL7_SEPARATOR + ''; //Citizenship PIDStr := PIDStr + HL7_SEPARATOR + ''; //VeteransMilitaryStatus PIDStr := PIDStr + HL7_SEPARATOR + ''; //Nationality PIDStr := PIDStr + HL7_SEPARATOR + ''; //PatientDeathDateTime PIDStr := PIDStr + HL7_SEPARATOR + ''; //PatientDeathIndicator PIDStr := PIDStr + HL7_SEPARATOR + ''; //End segment PIDStr := PIDStr + HL7_SEPARATOR; APIDStrings.Add(PIDStr); Next; end; except end; end; class function THL7Message.LoadPIDById(var ASQLQuery: TSQLQuery; AId: Integer): string; begin Result := 'PID'; ASQLQuery.SQL.Text := 'select a.accession_id, t.* from accession a ' + 'left join patient t on a.patient_id = t.patient_id ' + 'where a.accession_id = ' + IntToStr(AId); try ASQLQuery.Open; if not ASQLQuery.Eof then with ASQLQuery do begin //PatientID Result := Result + HL7_SEPARATOR + IntToStr(FieldByName('patient_id').AsInteger); //PatientIDExt Result := Result + HL7_SEPARATOR + ''; //PatientIDInt Result := Result + HL7_SEPARATOR + FieldByName('medical_record').AsString; //PatientIDAlt Result := Result + HL7_SEPARATOR + ''; //PatientName Result := Result + HL7_SEPARATOR + FieldByName('last_name').AsString; Result := Result + HL7_SEPARATOR_COMPONENT + FieldByName('first_name').AsString; //MothMaidenName Result := Result + HL7_SEPARATOR + ''; //DateBirth Result := Result + HL7_SEPARATOR + DateToMedDateStr(SQLiteDateStrToDate(FieldByName('date_of_birth').AsString)); //Gender Result := Result + HL7_SEPARATOR + FieldByName('gender').AsString; //PatientAlias Result := Result + HL7_SEPARATOR + ''; //Race Result := Result + HL7_SEPARATOR + ''; //Address Result := Result + HL7_SEPARATOR + FieldByName('address').AsString; Result := Result + HL7_SEPARATOR_COMPONENT + ''; Result := Result + HL7_SEPARATOR_COMPONENT + FieldByName('city').AsString; Result := Result + HL7_SEPARATOR_COMPONENT + FieldByName('state_province').AsString; Result := Result + HL7_SEPARATOR_COMPONENT + FieldByName('zip_postal_code').AsString; Result := Result + HL7_SEPARATOR_COMPONENT + ''; //CountyCode Result := Result + HL7_SEPARATOR + FieldByName('country_region').AsString; //PhoneNumbHome Result := Result + HL7_SEPARATOR + FieldByName('home_phone').AsString; //PhoneNumbBusiness Result := Result + HL7_SEPARATOR + FieldByName('business_phone').AsString; //PrimaryLanguage Result := Result + HL7_SEPARATOR + ''; //MaritalStatus Result := Result + HL7_SEPARATOR + ''; //Religion Result := Result + HL7_SEPARATOR + ''; //PatientAccountNumber Result := Result + HL7_SEPARATOR + ''; //SSNNumb Result := Result + HL7_SEPARATOR + ''; //DriverLicNumb Result := Result + HL7_SEPARATOR + ''; //MothersIdentifie Result := Result + HL7_SEPARATOR + ''; //EthnicGroup Result := Result + HL7_SEPARATOR + ''; //BirthPlace Result := Result + HL7_SEPARATOR + ''; //MultipleBirthIndicator Result := Result + HL7_SEPARATOR + ''; //BirthOrder Result := Result + HL7_SEPARATOR + ''; //Citizenship Result := Result + HL7_SEPARATOR + ''; //VeteransMilitaryStatus Result := Result + HL7_SEPARATOR + ''; //Nationality Result := Result + HL7_SEPARATOR + ''; //PatientDeathDateTime Result := Result + HL7_SEPARATOR + ''; //PatientDeathIndicator Result := Result + HL7_SEPARATOR + ''; //End segment Result := Result + HL7_SEPARATOR; end; except end; end; procedure THL7Message.SaveAccession(ASQLQuery: TSQLQuery); var Accession: TAccessionSpec; SqlStr: string; begin Accession := TAccessionSpec(OBR); with ASQLQuery do begin SqlStr := 'INSERT OR REPLACE INTO accession ' + '(accession_number, ' + ' clinical_information, ' + ' specimen_count, ' + ' patient_id, ' + ' date_obtained) ' + 'VALUES (:accession_number, ' + ':clinical_information, ' + ':specimen_count, ' + ':patient_id, ' + ':date_obtained)'; SQL.Text := SqlStr; ParamByName('accession_number').AsString := Accession.AccessionNumber; ParamByName('clinical_information').AsString := Accession.RelevantClinicalInfo; ParamByName('specimen_count').AsInteger := Accession.NumberOfSampleContainers; ParamByName('patient_id').AsInteger := PID.PatientID; ParamByName('date_obtained').AsString := DateToSQLiteDateStr(Accession.ObservationDateTime); ExecSQL; end; end; procedure THL7Message.SavePatient(ASQLQuery: TSQLQuery); var Patient: TPatient; SqlStr: string; begin Patient := TPatient(PID); if Patient.PatientID > 0 then with ASQLQuery do begin SqlStr := 'INSERT OR REPLACE INTO patient ' + '(patient_id, ' + ' last_name, ' + ' medical_record, ' + ' first_name, ' + ' date_of_birth, ' + ' business_phone, ' + ' home_phone, ' + ' address, ' + ' city, ' + ' state_province, ' + ' zip_postal_code, ' + ' country_region, ' + ' gender, ' + ' marital_status, ' + ' full_name) ' + 'VALUES (:patient_id, ' + ':last_name, ' + ':medical_record, ' + ':first_name, ' + ':date_of_birth, ' + ':business_phone, ' + ':home_phone, ' + ':address, ' + ':city, ' + ':state_province, ' + ':zip_postal_code, ' + ':country_region, ' + ':gender, ' + ':marital_status, ' + ':full_name)'; SQL.Text := SqlStr; ParamByName('patient_id').AsInteger := Patient.PatientID; ParamByName('last_name').AsString := Patient.Surname; ParamByName('medical_record').AsString := Patient.PatientIDInt; ParamByName('first_name').AsString := Patient.Firstname; ParamByName('date_of_birth').AsString := DateToSQLiteDateStr(Patient.DTBirth); ParamByName('business_phone').AsString := Patient.PhoneNumbBusiness; ParamByName('home_phone').AsString := Patient.PhoneNumbHome; ParamByName('address').AsString := Patient.Address1; ParamByName('city').AsString := Patient.City; ParamByName('state_province').AsString := Patient.ProvinceCode; ParamByName('zip_postal_code').AsString := Patient.PostalCode; ParamByName('country_region').AsString := Patient.CountyCode; ParamByName('gender').AsString := Patient.Gender; ParamByName('marital_status').AsString := Patient.MaritalStatus; ParamByName('full_name').AsString := Patient.FullName; ExecSQL; end; end; procedure THL7Message.SaveSpecimen(ASQLQuery: TSQLQuery); begin SpecimanList.SaveToDB(ASQLQuery, TAccessionSpec(OBR).AccessionNumber); end; procedure THL7Message.SaveToDB(ASQLQuery: TSQLQuery); begin if CheckMessage then begin SavePatient(ASQLQuery); SaveAccession(ASQLQuery); SaveSpecimen(ASQLQuery); end; end; function THL7Message.ToString: string; var StringList: TStrings; I: Integer; begin StringList := TStringList.Create; try //MSH StringList.Add(MSH.ToString); //PID for I := 0 to PIDList.Count - 1 do StringList.Add(TPID(PIDList[I]).ToString); //OBR for I := 0 to OBRList.Count - 1 do StringList.Add(TOBR(OBRList[I]).ToString); //OBX for I := 0 to OBXList.Count - 1 do StringList.Add(TOBX(OBXList[I]).ToString); Result := StringList.Text; finally StringList.Free; end; end; { TMSH } function TMSH.GetAcceptAcknowledgmentType: string; begin Result := GetValue(Integer(msheAcceptAcknowledgmentType)); end; function TMSH.GetAltCharacterSetHandlingScheme: string; begin Result := GetValue(Integer(msheAltCharacterSetHandlingScheme)); end; function TMSH.GetApplicationAcknowledgmentType: string; begin Result := GetValue(Integer(msheAcceptAcknowledgmentType)); end; function TMSH.GetCharacterSet: string; begin Result := GetValue(Integer(msheCharacterSet)); end; function TMSH.GetContinuationPointer: string; begin Result := GetValue(Integer(msheContinuationPointer)); end; function TMSH.GetCountryCode: string; begin Result := GetValue(Integer(msheCountryCode)); end; function TMSH.GetDateTimeMsg: TDateTime; begin Result := MedDateTimeStrToDateTime(GetValue(Integer(msheDateTimeMsg))); end; function TMSH.GetEncodingCharacters: string; begin Result := GetValue(Integer(msheEncodingCharacters)); end; function TMSH.GetMessageControlID: string; begin Result := GetValue(Integer(msheMessageControlID)); end; function TMSH.GetMessageType: string; begin Result := GetValue(Integer(msheMessageType)); end; function TMSH.GetMsgProfileId: string; begin Result := GetValue(Integer(msheMsgProfileId)); end; function TMSH.GetPrincipalLangMsg: string; begin Result := GetValue(Integer(mshePrincipalLangMsg)); end; function TMSH.GetProcessingID: string; begin Result := GetValue(Integer(msheProcessingID)); end; function TMSH.GetReceivingApp: string; begin Result := GetValue(Integer(msheReceivingApp)); end; function TMSH.GetReceivingFacility: string; begin Result := GetValue(Integer(msheReceivingFacility)); end; function TMSH.GetReceivNetworkAddress: string; begin Result := GetValue(Integer(msheReceivNetworkAddress)); end; function TMSH.GetReceivResponsibleOrg: string; begin Result := GetValue(Integer(msheReceivResponsibleOrg)); end; function TMSH.GetSecurity: string; begin Result := GetValue(Integer(msheSecurity)); end; function TMSH.GetSendingApp: string; begin Result := GetValue(Integer(msheSendingApp)); end; function TMSH.GetSendingFacility: string; begin Result := GetValue(Integer(msheSendingFacility)); end; function TMSH.GetSendNetworkAddress: string; begin Result := GetValue(Integer(msheSendNetworkAddress)); end; function TMSH.GetSendResponsibleOrg: string; begin Result := GetValue(Integer(msheSendResponsibleOrg)); end; function TMSH.GetSequenceNumber: string; begin Result := GetValue(Integer(msheSequenceNumber)); end; function TMSH.GetVersionID: string; begin Result := GetValue(Integer(msheVersionID)); end; function TMSH.ToString: string; begin Result := inherited; Result := Result + HL7_SEPARATOR + EncodingCharacters + HL7_SEPARATOR + SendingApp + HL7_SEPARATOR + SendingFacility + HL7_SEPARATOR + ReceivingApp + HL7_SEPARATOR + ReceivingFacility + HL7_SEPARATOR + DateTimeToMedDateTimeStr(DateTimeMsg) + HL7_SEPARATOR + Security + HL7_SEPARATOR + MessageType + HL7_SEPARATOR + MessageControlID + HL7_SEPARATOR + ProcessingID + HL7_SEPARATOR + VersionID + HL7_SEPARATOR + SequenceNumber + HL7_SEPARATOR + ContinuationPointer + HL7_SEPARATOR + AcceptAcknowledgmentType + HL7_SEPARATOR + ApplicationAcknowledgmentType + HL7_SEPARATOR + CountryCode + HL7_SEPARATOR + CharacterSet + HL7_SEPARATOR + PrincipalLangMsg + HL7_SEPARATOR + AltCharacterSetHandlingScheme + HL7_SEPARATOR + MsgProfileId + HL7_SEPARATOR + SendResponsibleOrg + HL7_SEPARATOR + ReceivResponsibleOrg + HL7_SEPARATOR + SendNetworkAddress + HL7_SEPARATOR + ReceivNetworkAddress; end; { TOBR } function TOBR.GetAssistantResultInterpreter: string; begin Result := GetValue(Integer(obreAssistantResultInterpreter)); end; function TOBR.GetChargeToPractice: string; begin Result := GetValue(Integer(obreChargeToPractice)); end; function TOBR.GetCollectionVolume: string; begin Result := GetValue(Integer(obreCollectionVolume)); end; function TOBR.GetCollectorIdentifier: string; begin Result := GetValue(Integer(obreCollectorIdentifier)); end; function TOBR.GetCollectorsComment: string; begin Result := GetValue(Integer(obreCollectorsComment)); end; function TOBR.GetDangerCode: string; begin Result := GetValue(Integer(obreDangerCode)); end; function TOBR.GetDiagnosticServSectID: string; begin Result := GetValue(Integer(obreDiagnosticServSectID)); end; function TOBR.GetEscortRequired: string; begin Result := GetValue(Integer(obreEscortRequired)); end; function TOBR.GetFillerField1: string; begin Result := GetValue(Integer(obreFillerField1)); end; function TOBR.GetFillerField2: string; begin Result := GetValue(Integer(obreFillerField2)); end; function TOBR.GetFillerOrderNumber: string; begin Result := GetValue(Integer(obreFillerOrderNumber)); end; function TOBR.GetNumberOfSampleContainers: Integer; begin Result := StrToIntDef(GetValue(Integer(obreNumberOfSampleContainers)), 0); end; function TOBR.GetObservationDateTime: TDateTime; begin Result := MedDateTimeStrToDateTime(GetValue(Integer(obreObservationDateTime))); end; function TOBR.GetObservationEndDateTime: TDateTime; begin Result := MedDateTimeStrToDateTime(GetValue(Integer(obreObservationEndDateTime))); end; function TOBR.GetOrderCallbackPhoneNumber: string; begin Result := GetValue(Integer(obreOrderCallbackPhoneNumber)); end; function TOBR.GetOrderingProvider: string; begin Result := GetValue(Integer(obreOrderingProvider)); end; function TOBR.GetParent: string; begin Result := GetValue(Integer(obreParent)); end; function TOBR.GetParentResult: string; begin Result := GetValue(Integer(obreParentResult)); end; function TOBR.GetPlacerField1: string; begin Result := GetValue(Integer(obrePlacerField1)); end; function TOBR.GetPlacerField2: string; begin Result := GetValue(Integer(obrePlacerField2)); end; function TOBR.GetPlacerOrderNumber: string; begin Result := GetValue(Integer(obrePlacerOrderNumber)); end; function TOBR.GetPlannedPatientTransportComment: string; begin Result := GetValue(Integer(obrePlannedPatientTransportComment)); end; function TOBR.GetPrincipalResultInterpreter: string; begin Result := GetValue(Integer(obrePrincipalResultInterpreter)); end; function TOBR.GetPriority: string; begin Result := GetValue(Integer(obrePriority)); end; function TOBR.GetQuantityOrTiming: string; begin Result := GetValue(Integer(obreQuantityOrTiming)); end; function TOBR.GetReasonForStudy: string; begin Result := GetValue(Integer(obreReasonForStudy)); end; function TOBR.GetRelevantClinicalInfo: string; begin Result := GetValue(Integer(obreRelevantClinicalInfo)); end; function TOBR.GetRequestedDateTime: string; begin Result := GetValue(Integer(obreRequestedDateTime)); end; function TOBR.GetResultCopiesTo: string; begin Result := GetValue(Integer(obreResultCopiesTo)); end; function TOBR.GetResultsRptStatusChngDateTime: string; begin Result := GetValue(Integer(obreResultsRptStatusChngDateTime)); end; function TOBR.GetResultStatus: string; begin Result := GetValue(Integer(obreResultStatus)); end; function TOBR.GetScheduledDateTime: string; begin Result := GetValue(Integer(obreScheduledDateTime)); end; function TOBR.GetSpecimenActionCode: string; begin Result := GetValue(Integer(obreSpecimenActionCode)); end; function TOBR.GetSpecimenReceivedDateTime: string; begin Result := GetValue(Integer(obreSpecimenReceivedDateTime)); end; function TOBR.GetSpecimenSource: string; begin Result := GetValue(Integer(obreSpecimenSource)); end; function TOBR.GetTechnician: string; begin Result := GetValue(Integer(obreTechnician)); end; function TOBR.GetTranscriptionist: string; begin Result := GetValue(Integer(obreTranscriptionist)); end; function TOBR.GetTransportArranged: string; begin Result := GetValue(Integer(obreTransportArranged)); end; function TOBR.GetTransportArrangementResponsibility: string; begin Result := GetValue(Integer(obreTransportArrangementResponsibility)); end; function TOBR.GetTransportationMode: string; begin Result := GetValue(Integer(obreTransportationMode)); end; function TOBR.GetTransportLogisticsOfCollectedSample: string; begin Result := GetValue(Integer(obreTransportLogisticsOfCollectedSample)); end; function TOBR.GetUniversalServiceID: string; begin Result := GetValue(Integer(obreUniversalServiceID)); end; function TOBR.ToString: string; begin Result := inherited; Result := Result + HL7_SEPARATOR + PlacerOrderNumber + HL7_SEPARATOR + FillerOrderNumber + HL7_SEPARATOR + UniversalServiceID + HL7_SEPARATOR + Priority + HL7_SEPARATOR + RequestedDateTime + HL7_SEPARATOR + DateTimeToMedDateTimeStr(ObservationDateTime) + HL7_SEPARATOR + DateTimeToMedDateTimeStr(ObservationEndDateTime) + HL7_SEPARATOR + CollectionVolume + HL7_SEPARATOR + CollectorIdentifier + HL7_SEPARATOR + SpecimenActionCode + HL7_SEPARATOR + DangerCode + HL7_SEPARATOR + RelevantClinicalInfo + HL7_SEPARATOR + SpecimenReceivedDateTime + HL7_SEPARATOR + SpecimenSource + HL7_SEPARATOR + OrderingProvider + HL7_SEPARATOR + OrderCallbackPhoneNumber + HL7_SEPARATOR + PlacerField1 + HL7_SEPARATOR + PlacerField2 + HL7_SEPARATOR + FillerField1 + HL7_SEPARATOR + FillerField2 + HL7_SEPARATOR + ResultsRptStatusChngDateTime + HL7_SEPARATOR + ChargeToPractice + HL7_SEPARATOR + DiagnosticServSectID + HL7_SEPARATOR + ResultStatus + HL7_SEPARATOR + ParentResult + HL7_SEPARATOR + QuantityOrTiming + HL7_SEPARATOR + ResultCopiesTo + HL7_SEPARATOR + Parent + HL7_SEPARATOR + TransportationMode + HL7_SEPARATOR + ReasonForStudy + HL7_SEPARATOR + PrincipalResultInterpreter + HL7_SEPARATOR + AssistantResultInterpreter + HL7_SEPARATOR + Technician + HL7_SEPARATOR + Transcriptionist + HL7_SEPARATOR + ScheduledDateTime + HL7_SEPARATOR + IntToStr(NumberOfSampleContainers) + HL7_SEPARATOR + TransportLogisticsOfCollectedSample + HL7_SEPARATOR + CollectorsComment + HL7_SEPARATOR + TransportArrangementResponsibility + HL7_SEPARATOR + TransportArranged + HL7_SEPARATOR + EscortRequired + HL7_SEPARATOR + PlannedPatientTransportComment + HL7_SEPARATOR; end; { TOBX } function TOBX.GetAbnormalFlags: string; begin Result := GetValue(Integer(obxeAbnormalFlags)); end; function TOBX.GetDateLastObsNormalValues: string; begin Result := GetValue(Integer(obxeDateLastObsNormalValues)); end; function TOBX.GetDateTimeOfObservation: string; begin Result := GetValue(Integer(obxeDateTimeOfObservation)); end; function TOBX.GetNatureOfAbnormalTest: string; begin Result := GetValue(Integer(obxeNatureOfAbnormalTest)); end; function TOBX.GetObservationIdentifier: string; begin Result := GetValue(Integer(obxeObservationIdentifier)); end; function TOBX.GetObservationMethod: string; begin Result := GetValue(Integer(obxeObservationMethod)); end; function TOBX.GetObservationSubID: string; begin Result := GetValue(Integer(obxeObservationSubID)); end; function TOBX.GetObservationValue: string; begin Result := GetValue(Integer(obxeObservationValue)); end; function TOBX.GetObservResultStatus: string; begin Result := GetValue(Integer(obxeObservResultStatus)); end; function TOBX.GetOBXNumber: string; begin Result := GetValue(Integer(obxeOBXNumber)); end; function TOBX.GetProbability: string; begin Result := GetValue(Integer(obxeProbability)); end; function TOBX.GetProducersID: string; begin Result := GetValue(Integer(obxeProducersID)); end; function TOBX.GetReferencesRange: string; begin Result := GetValue(Integer(obxeReferencesRange)); end; function TOBX.GetResponsibleObserver: string; begin Result := GetValue(Integer(obxeResponsibleObserver)); end; function TOBX.GetUnits: string; begin Result := GetValue(Integer(obxeUnits)); end; function TOBX.GetUserDefinedAccessChecks: string; begin Result := GetValue(Integer(obxeUserDefinedAccessChecks)); end; function TOBX.GetValueType: string; begin Result := GetValue(Integer(obxeValueType)); end; function TOBX.ToString: string; begin Result := inherited; Result := Result + HL7_SEPARATOR + OBXNumber + HL7_SEPARATOR + ValueType + HL7_SEPARATOR + ObservationIdentifier + HL7_SEPARATOR + ObservationSubID + HL7_SEPARATOR + ObservationValue + HL7_SEPARATOR + Units + HL7_SEPARATOR + ReferencesRange + HL7_SEPARATOR + AbnormalFlags + HL7_SEPARATOR + Probability + HL7_SEPARATOR + NatureOfAbnormalTest + HL7_SEPARATOR + ObservResultStatus + HL7_SEPARATOR + DateLastObsNormalValues + HL7_SEPARATOR + UserDefinedAccessChecks + HL7_SEPARATOR + DateTimeOfObservation + HL7_SEPARATOR + ProducersID + HL7_SEPARATOR + ResponsibleObserver + HL7_SEPARATOR + ObservationMethod + HL7_SEPARATOR; end; { TAccession } function TAccessionSpec.GetAccessionNumber: string; begin Result := GetValue(Integer(obreUniversalServiceID)); end; function TAccessionSpec.GetNamespaceId: string; begin Result := GetSubElement(FillerOrderNumber, HL7_SEPARATOR_COMPONENT, Integer(afnNamespaceId)); end; function TAccessionSpec.GetPriorityId: string; begin Result := GetSubElement(Priority, HL7_SEPARATOR_COMPONENT, 0); end; function TAccessionSpec.GetSpecimenLabel: string; begin Result := GetSubElement(SpecimenSource, HL7_SEPARATOR_COMPONENT, Integer(sssAdditives)); end; function TAccessionSpec.GetSurgicalProcedure: string; begin Result := GetSubElement(SpecimenSource, HL7_SEPARATOR_COMPONENT, Integer(sssFreeText)); end; { TOBXList } function TOBXList.GetTextSTByTypeAndId(AValueType, AIdentifier: string): string; var I: Integer; OBX: TOBXSpec; begin for I := 0 to Count - 1 do begin OBX := TOBXSpec(Items[I]); if Assigned(OBX) then if OBX.ValueType = AValueType then if OBX.Identifier = AIdentifier then begin Result := OBX.TextST; Break; end; end; end; { TOBXSpec } function TOBXSpec.GetComment: string; begin if TextST = OBX_TEXT_ST_SPEC_LABEL then Result := GetSubElement(ObservationIdentifier, HL7_SEPARATOR_COMPONENT, Integer(ssoTextST)); end; function TOBXSpec.GetDiagnosis: string; begin Result := ''; if TextST = OBX_TEXT_ST_FINAL_DIAGNOSTIC then Result := GetValue(Integer(obxeObservationValue)); end; function TOBXSpec.GetGrossDescription: string; begin Result := ''; if TextST = OBX_TEXT_ST_GROSS_DESC then Result := GetValue(Integer(obxeObservationValue)); end; function TOBXSpec.GetIdentifier: string; begin Result := GetSubElement(ObservationIdentifier, HL7_SEPARATOR_COMPONENT, Integer(ssoIdentifierST)); end; function TOBXSpec.GetMicroscopicObserv: string; begin Result := ''; if TextST = OBX_TEXT_ST_MICROSCOPIC_OBSERV then Result := GetValue(Integer(obxeObservationValue)); end; function TOBXSpec.GetSpecimenLabel: string; begin Result := ''; if TextST = OBX_TEXT_ST_SPEC_LABEL then Result := GetValue(Integer(obxeObservationValue)); end; function TOBXSpec.GetTextST: string; begin Result := GetSubElement(ObservationIdentifier, HL7_SEPARATOR_COMPONENT, Integer(ssoTextST)); end; { TSpeciman } constructor TSpeciman.Create(AId: string); begin FId := AId; end; constructor TSpeciman.Create(AId, AMicroscopicObserv, ADiagnosis, AGrossDescription, ASpecimenLabel: string); begin FId := AId; FMicroscopicObserv := AMicroscopicObserv; FDiagnosis := ADiagnosis; FGrossDescription := AGrossDescription; FSpecimenLabel := ASpecimenLabel; end; function TSpeciman.ToString: string; begin // Result := HL7_SGM_OBX + HL7_SEPARATOR + // Id + HL7_SEPARATOR + // 'TX' + HL7_SEPARATOR + // // ObservationSubID + HL7_SEPARATOR + // ObservationValue + HL7_SEPARATOR + // Units + HL7_SEPARATOR + // ReferencesRange + HL7_SEPARATOR + // AbnormalFlags + HL7_SEPARATOR + // Probability + HL7_SEPARATOR + // NatureOfAbnormalTest + HL7_SEPARATOR + // ObservResultStatus + HL7_SEPARATOR + // DateLastObsNormalValues + HL7_SEPARATOR + // UserDefinedAccessChecks + HL7_SEPARATOR + // DateTimeOfObservation + HL7_SEPARATOR + // ProducersID + HL7_SEPARATOR + // ResponsibleObserver + HL7_SEPARATOR + // ObservationMethod + HL7_SEPARATOR; end; { TSpecimanList } function TSpecimanList.AddSpeciman(AId: string): TSpeciman; begin Add(TSpeciman.Create(AId)); Result := TSpeciman(Items[Count - 1]); end; function TSpecimanList.GetSpecimanById(AId: string): TSpeciman; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do if TSpeciman(Items[I]).Id = AId then begin Result := TSpeciman(Items[I]); Break; end; end; function TSpecimanList.IsExist(AId: string): Boolean; var I: Integer; begin Result := False; for I := 0 to Count - 1 do if TSpeciman(Items[I]).Id = AId then begin Result := True; Break; end; end; procedure TSpecimanList.Load(var ASQLQuery: TSQLQuery); begin ASQLQuery.SQL.Text := 'select * from specimen s ' + 'order by s.specimen_id '; // ASQLQuery.SQL.Text := // 'select a.accession_id, a.accession_number, t.* from accession a ' + // 'left join specimen t on a.accession_number = t.accession_number ' + // 'where a.accession_id = ' + IntToStr(AId); try ASQLQuery.Open; while not ASQLQuery.Eof do with ASQLQuery do begin Add(TSpeciman.Create( IntToStr(Count + 1), FieldByName('microscopic_description').AsString, FieldByName('diagnosis').AsString, FieldByName('gross_description').AsString, FieldByName('specimen_label').AsString)); Next; end; except end; end; procedure TSpecimanList.SaveToDB(ASQLQuery: TSQLQuery; AAccessionNumber: string); var SqlStr: string; I: Integer; Speciman: TSpeciman; begin for I := 0 to Count - 1 do with ASQLQuery do begin Speciman := TSpeciman(Items[I]); SqlStr := 'INSERT OR REPLACE INTO specimen ' + '(accession_number, ' + ' specimen_label, ' + ' microscopic_description, ' + ' gross_description, ' + ' diagnosis) ' + 'VALUES (:accession_number, ' + ':specimen_label, ' + ':microscopic_description, ' + ':gross_description, ' + ':diagnosis)'; SQL.Text := SqlStr; ParamByName('accession_number').AsString := AAccessionNumber; ParamByName('specimen_label').AsString := Speciman.SpecimenLabel; ParamByName('microscopic_description').AsString := Speciman.MicroscopicObserv; ParamByName('gross_description').AsString := Speciman.GrossDescription; ParamByName('diagnosis').AsString := Speciman.Diagnosis; ExecSQL; end; end; end.
PROGRAM Stat(INPUT, OUTPUT); CONST Error = -1; EndString = -2; FUNCTION CharToInt(VAR Ch: CHAR): INTEGER; BEGIN {CharToInt} IF ('0' <= Ch) AND (Ch <= '9') THEN BEGIN IF Ch = '0' THEN CharToInt := 0 ELSE IF Ch = '1' THEN CharToInt := 1 ELSE IF Ch = '2' THEN CharToInt := 2 ELSE IF Ch = '3' THEN CharToInt := 3 ELSE IF Ch = '4' THEN CharToInt := 4 ELSE IF Ch = '5' THEN CharToInt := 5 ELSE IF Ch = '6' THEN CharToInt := 6 ELSE IF Ch = '7' THEN CharToInt := 7 ELSE IF Ch = '8' THEN CharToInt := 8 ELSE IF Ch = '9' THEN CharToInt := 9 END ELSE CharToInt := EndString END; {CharToInt} FUNCTION ReadDigit(VAR F: TEXT): INTEGER; VAR Ch: CHAR; BEGIN {ReadDigit} ReadDigit := Error; IF NOT(EOLN(F)) THEN BEGIN READ(F, Ch); ReadDigit := CharToInt(Ch) END ELSE ReadDigit := EndString END; {ReadDigit} FUNCTION ReadNumber(VAR F: TEXT): INTEGER; {Преобразует строку цифр из файла, завершающуюся нецифровым символом, в соответствующее целочисленное значение N, и возвращает N} VAR Mult, Digit: INTEGER; BEGIN {ReadNumber} IF NOT(EOLN(F)) THEN BEGIN Mult := 0; Digit := ReadDigit(F); IF Digit = Error THEN Mult := Error; IF Digit = EndString THEN Mult := EndString; WHILE (Digit <> Error) AND (Digit <> EndString) DO IF (Mult <= (MAXINT DIV 10)) AND (Digit <> EndString) THEN BEGIN Mult := Mult * 10 + Digit; Digit := ReadDigit(F) END ELSE BEGIN IF (Digit <> EndString) THEN Mult := Error; Digit := Error END; ReadNumber := Mult END ELSE ReadNumber := Error END; {ReadNumber} PROCEDURE ValueNumbers(VAR F: TEXT); VAR Max, Min, AverageInt, AverageFloat, NumberOfNumber, Sum: INTEGER; BEGIN Max := 0; Min := MAXINT; Sum := 0; AverageInt := 0; AverageFloat := 0; NumberOfNumber := 0; WHILE NOT(EOLN(F)) DO BEGIN Sum := Sum + ReadNumber(F); END; END; BEGIN {SumValues} ValueNumbers(INPUT); END. {SumValues}
unit TextEditor.CompletionProposal.Colors; interface uses System.Classes, System.UITypes; type TTextEditorCompletionProposalColors = class(TPersistent) strict private FBackground: TColor; FForeground: TColor; FSelectedBackground: TColor; FSelectedText: TColor; public constructor Create; procedure Assign(ASource: TPersistent); override; published property Background: TColor read FBackground write FBackground default TColors.SysWindow; property Foreground: TColor read FForeground write FForeground default TColors.SysWindowText; property SelectedBackground: TColor read FSelectedBackground write FSelectedBackground default TColors.SysHighlight; property SelectedText: TColor read FSelectedText write FSelectedText default TColors.SysHighlightText; end; implementation constructor TTextEditorCompletionProposalColors.Create; begin inherited; FBackground := TColors.SysWindow; FForeground := TColors.SysWindowText; FSelectedBackground := TColors.SysHighlight; FSelectedText := TColors.SysHighlightText; end; procedure TTextEditorCompletionProposalColors.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorCompletionProposalColors) then with ASource as TTextEditorCompletionProposalColors do begin Self.FBackground := FBackground; Self.FForeground := FForeground; Self.FSelectedBackground := FSelectedBackground; Self.FSelectedText := FSelectedText; end else inherited Assign(ASource); end; end.
unit Core.ResourceStrings; interface resourcestring {$REGION 'Core.Exceptions'} SGameOver = 'The current game is over. Please start a new game.'; SGameNotStarted = 'The game has not started. Please start a new game.'; SInvalidPins = 'Invalid Pins. The maximum allowed pins per frame is %d'; SGameObjectWithValueNotFound = 'Game object %s with value %s not found'; {$ENDREGION} implementation end.
unit Relatorio_NovaImpressao; interface uses Windows, SysUtils, Messages, Classes, Graphics, Controls, StdCtrls, ExtCtrls, Forms, QuickRpt, QRPrntr, QRCtrls, DB, DBClient, QRPDFFilt, CJVQRBarCode; type TTipoBand = (tHeaderUnico, tHeaderPagina, tDetalhe, tSubDetalhe, tRodape); TRelatorioNovaImpressao = class(TQuickRep) QRPDFFilter1: TQRPDFFilter; CabecalhoGeral: TQRBand; Principal: TQRBand; FilhoPrincipal: TQRChildBand; Detalhe01: TQRSubDetail; Rodape01: TQRBand; Cabecalho02: TQRBand; Detalhe02: TQRSubDetail; Rodape02: TQRBand; Cabecalho03: TQRBand; Detalhe03: TQRSubDetail; Rodape03: TQRBand; Cabecalho01: TQRBand; procedure QRBandCabecalhoGeralBeforePrint(Sender: TQRCustomBand; var PrintBand: Boolean); private procedure ConfigurarCampoLabel(var Componente: TQRCustomLabel; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer; NomeBand: String); procedure AdicionarCampoLabel(Texto: String; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer; NomeBand: String); procedure AdicionarCampoDBLabel(Field: String; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer; NomeBand: String); function GetParent(NomeComponente: String): TWinControl; procedure RedimensionarParent(Componente: TWinControl); procedure AdicionarBand(Nome: String; TipoBand: TTipoBand); public Constructor Create(AOwner: TComponent); override; procedure MontarRelatorio(); procedure Preview(); end; implementation {$R *.DFM} { TRelatorioNovaImpressao } Constructor TRelatorioNovaImpressao.Create(AOwner: TComponent); var I: Integer; begin inherited; for I := 0 to ComponentCount - 1 do if (TComponent(Components[I]).ClassType = TQRBand) or (TComponent(Components[I]).ClassType = TQRSubDetail) or (TComponent(Components[I]).ClassType = TQRChildBand) then begin TQRCustomBand(Components[I]).Visible := False; TQRCustomBand(Components[I]).Height := 0; TQRCustomBand(Components[I]).TransparentBand := False; end; end; procedure TRelatorioNovaImpressao.Preview; var I: Integer; begin for I := 0 to ComponentCount - 1 do if (Components[I].ClassType = TQRSubDetail) then TQRSubDetail(Components[I]).PrintIfEmpty := False; Self.PrevInitialZoom := qrZoom100; Self.PreviewInitialState := wsMaximized; Self.PrevShowThumbs := False; Self.PrevShowSearch := False; Self.PreviewModal; end; procedure TRelatorioNovaImpressao.ConfigurarCampoLabel(var Componente: TQRCustomLabel; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer; NomeBand: String); begin Componente.Parent := GetParent(NomeBand); Componente.Left := Coluna; Componente.Top := Linha; Componente.Font.Size := TamanhoFonte; Componente.Width := TamanhoMaxTexto; Componente.AutoSize := False; if (TamanhoMaxTexto = 0) then Componente.AutoSize := True; RedimensionarParent(Componente); end; procedure TRelatorioNovaImpressao.AdicionarCampoLabel(Texto: String; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer; NomeBand: String); var Componente: TQRCustomLabel; begin Componente := TQRLabel.Create(Self); TQRLabel(Componente).Transparent := True; TQRLabel(Componente).Caption := Texto; ConfigurarCampoLabel(Componente, Linha, Coluna, TamanhoMaxTexto, TamanhoFonte, NomeBand); end; procedure TRelatorioNovaImpressao.AdicionarCampoDBLabel(Field: String; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer; NomeBand: String); var Componente: TQRCustomLabel; Parent: TComponent; begin Componente := TQRDBText.Create(Self); TQRDBText(Componente).Transparent := True; Parent := GetParent(NomeBand); if (Parent <> nil) then begin if (Parent.ClassType = TQRSubDetail) then TQRDBText(Componente).DataSet := TQRSubDetail(Parent).DataSet else if (Parent.ClassType = TQRBand) or (Parent.ClassType = TQRChildBand) then TQRDBText(Componente).DataSet := Self.DataSet; end; TQRDBText(Componente).DataField := Field; ConfigurarCampoLabel(Componente, Linha, Coluna, TamanhoMaxTexto, TamanhoFonte, NomeBand); end; procedure TRelatorioNovaImpressao.AdicionarBand(Nome: String; TipoBand: TTipoBand); var ABand: TComponent; begin case TipoBand of tHeaderUnico: ABand := TComponent.Create(Self); tHeaderPagina: ABand := TComponent.Create(Self); tDetalhe: ABand := TComponent.Create(Self); tSubDetalhe: ABand := TComponent.Create(Self); tRodape: ABand := TComponent.Create(Self); end; end; function TRelatorioNovaImpressao.GetParent(NomeComponente: String): TWinControl; begin Result := TWinControl(FindComponent(NomeComponente)); end; procedure TRelatorioNovaImpressao.RedimensionarParent(Componente: TWinControl); var TamanhoOcupadoComponente: Integer; begin TamanhoOcupadoComponente := Componente.Top + Componente.Height; if (Componente.Parent <> nil) then // evitar exception de parent inexistente if (Componente.Parent.Height < TamanhoOcupadoComponente) then Componente.Parent.Height := TamanhoOcupadoComponente; end; procedure TRelatorioNovaImpressao.QRBandCabecalhoGeralBeforePrint(Sender: TQRCustomBand; var PrintBand: Boolean); begin // PrintBand := (Self.PageNumber > 1); end; procedure TRelatorioNovaImpressao.MontarRelatorio(); const CabecalhoGeral = 'CabecalhoGeral'; BaseRelatorio = 'Principal'; Cabecalho01 = 'Cabecalho01'; Cabecalho02 = 'Cabecalho02'; Cabecalho03 = 'Cabecalho03'; Detalhe01 = 'Detalhe01'; Detalhe02 = 'Detalhe02'; Detalhe03 = 'Detalhe03'; Rodape01 = 'Rodape01'; Rodape02 = 'Rodape02'; Rodape03 = 'Rodape03'; RodapeGeral = 'QRBandRodape'; begin AdicionarCampoLabel('----------', 1, 1, 0, 12, 'FilhoPrincipal'); AdicionarCampoLabel('Total Itens: ' + IntToStr(Self.DataSet.RecordCount), 1, 300, 0, 12, CabecalhoGeral); AdicionarCampoLabel('texto fixo em toda pagina ', 1, 100, 0, 12, CabecalhoGeral); AdicionarCampoLabel('texto fixo em todo rodape ', 1, 100, 0, 12, RodapeGeral); AdicionarCampoLabel('texto corpo', 1, 300, 0, 12, BaseRelatorio); AdicionarCampoLabel('texto corpo 2', 30, 300, 0, 12, BaseRelatorio); AdicionarCampoDBLabel('numero', 1, 50, 50, 12, BaseRelatorio); AdicionarCampoDBLabel('emissao', 1, 150, 0, 12, BaseRelatorio); AdicionarCampoLabel('numero-->', 1, 50, 0, 10, Cabecalho01); AdicionarCampoDBLabel('numero', 1, 50, 0, 10, Detalhe01); AdicionarCampoDBLabel('produto', 1, 200, 0, 10, Detalhe01); AdicionarCampoLabel('texto fixo itens', 10, 300, 0, 10, Detalhe01); AdicionarCampoLabel('numero<--', 1, 50, 0, 10, Rodape01); AdicionarCampoLabel('ordem-->', 1, 50, 0, 10, Cabecalho02); AdicionarCampoDBLabel('numero', 1, 1, 0, 10, Detalhe02); AdicionarCampoDBLabel('ordem', 1, 50, 0, 10, Detalhe02); AdicionarCampoDBLabel('VCTO', 1, 100, 0, 10, Detalhe02); AdicionarCampoDBLabel('valor', 1, 250, 0, 10, Detalhe02); AdicionarCampoLabel('texto fixo ordem', 1, 400, 0, 10, Detalhe02); AdicionarCampoLabel('ordem<--', 1, 50, 0, 10, Rodape02); AdicionarCampoLabel('bloqueio-->', 1, 50, 0, 10, Cabecalho03); AdicionarCampoDBLabel('pedido', 1, 1, 0, 10, Detalhe03); AdicionarCampoDBLabel('motivo', 1, 50, 0, 10, Detalhe03); AdicionarCampoDBLabel('autorizado', 1, 100, 0, 10, Detalhe03); AdicionarCampoLabel('texto fixo bloqueio', 1, 400, 0, 10, Detalhe03); AdicionarCampoLabel('bloqueio<--', 1, 50, 0, 10, Rodape03); end; end.
unit DocSqlManager; interface uses SysUtils, Classes, rtcFunction, rtcDataCli, rtcCliModule, rtcInfo, rtcConn, rtcHttpCli, rtcLog, rtcDB, DB, MemTableDataEh,MemTableEh, variants, DataDriverEh, vkvariable, Dialogs, uLog, System.Generics.Collections, System.Contnrs; type // TOnFillFieldNameList = procedure(Sender:TObject); TAdditionalSqlManager = class private FTableName: String; FFieldList: TStringList; FObjectList: TObjectList; public constructor Create; destructor Destroy;override; property TableName: String read FTableName write FTableName; property FieldList: TStringList read FFieldList; property ObjectList:TObjectList read FObjectList; end; TDocSqlManager = class(TObject) private FTableName: String; FKeyFields: String; FKeyFieldsList: TStringList; FGenId: String; FSelectSQL: TStringList; FUpdateSQL: TStringList; FInsertSQL: TStringList; FDeleteSQL: TStringList; FLockSQL: tStringList; FDocVariableList: TVkVariableCollection; FFieldNameList: TStringList; FOnFillFieldNameList: TNotifyEvent; FAdditionalList: TList<TAdditionalSqlManager>; procedure SetTableName(const Value: String); function GetKeyFieldsList: TStringList; protected procedure FillFieldNameList; virtual; public constructor Create; destructor Destroy;override; procedure CalcVariablesOnDs(DataSet: TDataSet; AVarList: TVkVariableCollection); function GetKeyValues(ADataSet: TDataSet): Variant;overload; function GetKeyValues(AVarList: TVkVariableCollection): Variant;overload; // procedure GenerateDinamicSQLInsert; // procedure GenerateDinamicSQLUpdate(var bChanged: Boolean); // procedure GenerateDinamicSQLDelete; // procedure GenerateDinamicSQLLock; function GetWhereOnKeyFields:String; procedure InitCommonParams(const ATableName:String ='';const AKeyFields:String =''; const AGenId : String = ''); procedure SaveVariablesInDataSet(ADataSet: TDataSet; AVarList: TVkVariableCollection); procedure UpdateVariablesOnDeltaDs(DataSet: TDataSet; AVarList: TVkVariableCollection); function IndexOfInAdditionalFields(const AName:String):Integer; property AdditionalList: TList<TAdditionalSqlManager> read FAdditionalList; property DocVariableList: TVkVariableCollection read FDocVariableList; property TableName: String read FTableName write SetTableName; property GenId: String read FGenId write FGenId; property SelectSQL: TStringList read FSelectSQL; property UpdateSQL: TStringList read FUpdateSQL; property InsertSQL: TStringList read FInsertSQL; property DeleteSQL: TStringList read FDeleteSQL; property LockSQL: TStringList read FLockSQL; property KeyFields:String read FKeyFields; property KeyFieldsList: TStringList read GetKeyFieldsList; property OnFillFieldNameList: TNotifyEvent read FOnFillFieldNameList write FOnFillFieldNameList; property FieldNameList: TStringList read FFieldNameList; end; implementation { TDocSqlManager } procedure TDocSqlManager.CalcVariablesOnDs(DataSet: TDataSet; AVarList: TVkVariableCollection); var i: Integer; ind: Integer; begin with DataSet do begin for I := 0 to FieldCount - 1 do begin ind := AVarList.IndexOf(Fields[i].FieldName) ; if ind >-1 then begin case Fields[i].DataType of ftFMTBcd: AVarList[Fields[i].FieldName].InitValue := Fields[i].AsFloat; ftBcd: AVarList[Fields[i].FieldName].InitValue := Fields[i].AsLargeInt; ftBlob: AVarList[Fields[i].FieldName].InitValue := Fields[i].AsString; else try AVarList.Items[ind].InitValue := Fields[i].Value; TLogWriter.Log(Fields[i].FieldName+' = '+ Fields[i].AsString); except TLogWriter.Log(Fields[i].FieldName+' = '+ Fields[i].AsString); ShowMessage((' error in InitVariable i = '+IntToStr(i))); Raise; end; end; end; end; end; end; constructor TDocSqlManager.Create; begin FSelectSQL := TStringList.Create; FUpdateSQL := TStringList.Create; FInsertSQL := TStringList.Create; FDeleteSQL := TStringList.Create; FLockSQL := TStringList.Create; FFieldnameList := TStringList.Create; FDocVariableList:= TVkVariableCollection.Create(nil); FKeyFieldsList := TStringList.Create; FAdditionalList := TList<TAdditionalSqlManager>.Create; end; destructor TDocSqlManager.Destroy; begin FSelectSQL.Free; FUpdateSQL.Free; FInsertSQL.Free; FDeleteSQL.Free; FLockSQL.Free; FDocVariableList.Free; FKeyFieldsList.Free; FFieldnameList.Free; FAdditionalList.Free; inherited; end; procedure TDocSqlManager.FillFieldNameList; begin if Assigned(FOnFillFieldNameList) then FOnFillFieldNameList(Self) else raise Exception.Create('Error - OnFillFieldNameList - is not defined'); end; { procedure TDocSqlManager.GenerateDinamicSQlDelete; begin FDeleteSQL.Clear; FDeleteSQL.Add(' DELETE FROM '+FTableName); FDeleteSQL.Add(GetWhereOnKeyFields); end; procedure TDocSqlManager.GenerateDinamicSQLInsert; var i: Integer; bFirst: Boolean; begin with FInsertSQL do begin Clear; Add(' INSERT INTO '+FTableName); Add('('); bFirst := true; for I := 0 to FDocVariableList.Count-1 do begin if (FFieldNameList.IndexOf(FDocVariableList.Items[i].Name)>-1) and (IndexOfInAdditionalFields(FDocVariableList.Items[i].Name)=-1) then begin if not bFirst then Add(','); Add(FDocVariableList.Items[i].Name); bFirst := False; // if i<FDocVariableList.Count-1 then // Add(','); end; end; Add(')'); Add(' VALUES ('); bFirst := True; for I := 0 to FDocVariableList.Count-1 do begin if (FFieldNameList.IndexOf(FDocVariableList.Items[i].Name)>-1) and (IndexOfInAdditionalFields(FDocVariableList.Items[i].Name)=-1) then begin if not bFirst then Add(','); Add(':'+FDocVariableList.Items[i].name); bFirst := False; end; end; Add(')'); end; end; procedure TDocSqlManager.GenerateDinamicSQLLock; begin with FLockSQL do begin Clear; Add(' SELECT * FROM '+FTablename); Add(GetWhereOnKeyFields); Add(' WITH LOCK '); end; end; procedure TDocSqlManager.GenerateDinamicSQlUpdate; var i: Integer; _UpdateList: TStringList; bFirst: Boolean; begin _UpdateList := TStringList.Create; bFirst := True; try FDocVariableList.GetChangedList(_UpdateList); bChanged := False; //_UpdateList.Count > 0; with FUpdateSQL do begin Clear; Add(' UPDATE '+FTableName); Add(' SET'); for I := 0 to _UpdateList.Count-1 do begin if (FFieldNameList.IndexOf(_UpdateList[i])>-1) and (IndexOfInAdditionalFields(_UpdateList[i])=-1) then begin if not bFirst then Add(',') else begin bFirst := False; bChanged := True; end; if FDocVariableList.VarByName(_UpdateList[i]).IsDelta then Add(_UpdateList[i]+' = '+_UpdateList[i]+'+:'+_UpdateList[i]) else Add(_UpdateList[i]+' = :'+_UpdateList[i]); end; end; Add(GetWhereOnKeyFields); end; finally FreeandNil(_UpdateList); end; end; *} function TDocSqlManager.GetKeyFieldsList: TStringList; begin FKeyFieldsList.Clear; FKeyFieldsList.Delimiter := ';'; FKeyFieldsList.DelimitedText := FKeyFields; Result := FKeyFieldsList; end; function TDocSqlManager.GetKeyValues(AVarList: TVkVariableCollection): Variant; var sList: TStringList; i: Integer; begin if AVarList.Count=0 then begin Result := null; Exit; end; sList := TStringList.Create; try sList.Delimiter := ';'; sList.DelimitedText := FKeyFields; if sList.Count = 0 then Result := null else if sList.Count = 1 then Result := AVarList.VarByName(sList[0]).Value else begin Result := VarArrayCreate([0, sList.Count-1], varvariant); for i := 0 to sList.Count-1 do Result[i] := AVarList.VarByName(sList[i ]).Value; end; finally sList.Free; end; end; function TDocSqlManager.GetKeyValues(ADataSet: TDataSet): Variant; var sList: TStringList; i: Integer; begin if ADataSet.isEmpty then begin Result := null; Exit; end; sList := TStringList.Create; try sList.Delimiter := ';'; sList.DelimitedText := FKeyFields; if sList.Count = 0 then Result := null else if sList.Count = 1 then Result := ADataSet.FieldByName(sList[0]).Value else begin Result := VarArrayCreate([0, sList.Count-1], varvariant); for i := 0 to sList.Count-1 do Result[i] := ADataSet.FieldByName(sList[i ]).Value; end; finally sList.Free; end; end; function TDocSqlManager.GetWhereOnKeyFields: String; var _List: TStringList; i: Integer; begin _List := TStringList.Create; try _List.Delimiter := ';'; _List.DelimitedText := FKeyFields; if _List.Count = 0 then Result := '' else if _List.Count = 1 then Result := ' WHERE '+_List[0]+' = :' +_List[0] else begin Result := ' WHERE '; for i := 0 to _List.Count-1 do begin Result := Result + _List[i]+' = :'+ _List[i]; if i< _List.Count-1 then Result := Result + ' AND '; end; end; finally _List.Free; end; end; function TDocSqlManager.IndexOfInAdditionalFields(const AName: String): Integer; var _Item: TAdditionalSqlManager; begin Result := -1; for _Item in AdditionalList do begin Result := _Item.FieldList.IndexOf(AName); if Result> -1 then Break; end; end; procedure TDocSqlManager.InitCommonParams(const ATableName, AKeyFields, AGenId: String); begin if ATableName<>'' then FTableName := UpperCase(ATableName); if AKeyFields<>'' then FKeyFields := UpperCase(AKeyFields); if AGenId<>'' then FGenId := UpperCase(AGenId); FillFieldNameList; { GenerateDinamicSQLInsert; GenerateDinamicSQLUpdate; GenerateDinamicSQLDelete; GenerateDinamicSQLLock; } end; procedure TDocSqlManager.SaveVariablesInDataSet(ADataSet: TDataSet; AVarList: TVkVariableCollection); var i: Integer; _Field: TField; _ReadOnly: Boolean; begin for I := 0 to AVarList.Count-1 do begin _Field := ADataSet.FindField(AVarList.Items[i].Name); if Assigned(_Field) then begin _ReadOnly := _Field.ReadOnly; try if _ReadOnly then _Field.ReadOnly := False; if AVarList.Items[i].Value = unassigned then _Field.Value := null else _Field.Value := AVarList.Items[i].Value; finally _Field.ReadOnly := _ReadOnly; end; end; end; end; procedure TDocSqlManager.SetTableName(const Value: String); begin FTableName := UpperCase(Value); FillFieldNameList; end; procedure TDocSqlManager.UpdateVariablesOnDeltaDs(DataSet: TDataSet; AVarList: TVkVariableCollection); var i: Integer; ind: Integer; begin with DataSet do begin for I := 0 to FieldCount - 1 do begin if Fields[i].NewValue<> Unassigned then begin ind := AVarList.IndexOf(Fields[i].FieldName) ; if ind>-1 then try AVarList.Items[ind].Value := Fields[i].Value; except ShowMessage('Name '+Fields[i].FieldName+', Index - '+IntToStr(ind)); Raise; end; end; end; end; end; { TAdditionalSqlManager } constructor TAdditionalSqlManager.Create; begin FFieldList := TStringList.Create; FObjectList := TObjectList.Create; FObjectList.OwnsObjects := true; end; destructor TAdditionalSqlManager.Destroy; begin FFieldList.Free; FObjectList.Free; inherited; end; end.
unit TestIntervalParameter; interface uses Parameter, Fluid, BaseObjects, Classes; type TTestIntervalParameter = class(TParameter) private FFluidType: TFluidType; protected procedure AssignTo(Dest: TPersistent); override; public property FluidType: TFluidType read FFluidType write FFluidType; function List(AListOption: TListOption = loBrief): string; override; constructor Create(ACollection: TIDObjects); override; end; TTestIntervalParameters = class(TParameters) private function GetItems(Index: integer): TTestIntervalParameter; public procedure Delete(Index: integer); override; function Remove(AObject: TObject): Integer; override; property Items[Index: integer]: TTestIntervalParameter read GetItems; constructor Create; override; end; implementation uses Facade, TestIntervalParameterDataPoster; { TTestIntervalParameter } procedure TTestIntervalParameter.AssignTo(Dest: TPersistent); begin inherited; (Dest as TTestIntervalParameter).FluidType := FluidType; end; constructor TTestIntervalParameter.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Параметр испытания'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TTestIntervalParameterDataPoster]; end; function TTestIntervalParameter.List(AListOption: TListOption): string; begin Result := inherited List; { if Assigned(FluidType) then Result := Result + '(' + FluidType.List(loBrief) + ')';} end; { TTestIntervalParameters } constructor TTestIntervalParameters.Create; begin inherited; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TTestIntervalParameterDataPoster]; FObjectClass := TTestIntervalParameter; end; function TTestIntervalParameters.GetItems( Index: integer): TTestIntervalParameter; begin Result := inherited Items[Index] as TTestIntervalParameter; end; procedure TTestIntervalParameters.Delete(Index: integer); begin if Items[Index].RefCount = 0 then inherited; end; function TTestIntervalParameters.Remove(AObject: TObject): Integer; begin Result := -1; if (AObject as TParameter).RefCount = 0 then Result := inherited Remove(AObject); end; end.
unit uUtilFncs; interface uses Classes, windows, sysutils, Printers, DateUtils; function GetComputerName: string; function GetBuildInfo(exe: string): string; function PrinterExists: boolean; function SenhaDoDia(senha: string): boolean; function SysWinDir: string; function GetFileList(FDirectory, Filter: TFileName; ShowFolder: boolean) : TStringList; function SerialHD(FDrive: String): String; function ForceForegroundWindow(hwnd: THandle): boolean; implementation function GetComputerName: string; var buffer: array [0 .. MAX_COMPUTERNAME_LENGTH + 1] of Char; Size: Cardinal; begin Size := MAX_COMPUTERNAME_LENGTH + 1; windows.GetComputerName(@buffer, Size); Result := StrPas(buffer); end; function GetBuildInfo(exe: string): string; var VerInfoSize: DWORD; VerInfo: Pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; V1, V2, V3, V4: Word; Prog: string; begin Prog := exe; VerInfoSize := GetFileVersionInfoSize(PChar(Prog), Dummy); GetMem(VerInfo, VerInfoSize); GetFileVersionInfo(PChar(Prog), 0, VerInfoSize, VerInfo); VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize); with VerValue^ do begin V1 := dwFileVersionMS shr 16; V2 := dwFileVersionMS and $FFFF; V3 := dwFileVersionLS shr 16; V4 := dwFileVersionLS and $FFFF; end; FreeMem(VerInfo, VerInfoSize); Result := Copy(IntToStr(100 + V1), 3, 2) + Copy(IntToStr(100 + V2), 3, 2) + Copy(IntToStr(100 + V3), 3, 2) + Copy(IntToStr(100 + V4), 3, 2); end; function PrinterExists: boolean; begin Result := Printer.Printers.Count > 0; end; function SenhaDoDia(senha: string): boolean; var senhaDia: Word; begin senhaDia := (DayOf(now) + MonthOf(now) + YearOf(now)) * DayOfWeek(now); Result := senhaDia.ToString = senha; end; function SysWinDir: string; begin Result := 'C:\Windows\'; end; function GetFileList(FDirectory, Filter: TFileName; ShowFolder: boolean) : TStringList; { Cria um stringList com todos os arquivos de um diretório } var ARec: TSearchRec; Res: Integer; begin if FDirectory[Length(FDirectory)] <> '\' then begin FDirectory := FDirectory + '\'; end; Result := TStringList.Create; try Res := FindFirst(FDirectory + Filter, faAnyFile or faArchive, ARec); while Res = 0 do begin if ((ARec.Attr and faArchive) = faAnyFile) or ((ARec.Attr and faArchive) = faArchive) then begin if ShowFolder then begin Result.Add(FDirectory + ARec.Name); end else begin Result.Add(ARec.Name); end end; Res := FindNext(ARec); end; FindClose(ARec); except Result.Free; end; end; function SerialHD(FDrive: String): String; Var Serial: DWORD; DirLen, Flags: DWORD; DLabel: Array [0 .. 11] of Char; begin Try GetVolumeInformation(PChar(FDrive + ':\'), DLabel, 12, @Serial, DirLen, Flags, nil, 0); Result := IntToHex(Serial, 8); Except Result := ''; end; end; function ForceForegroundWindow(hwnd: THandle): boolean; const SPI_GETFOREGROUNDLOCKTIMEOUT = $2000; SPI_SETFOREGROUNDLOCKTIMEOUT = $2001; var ForegroundThreadID: DWORD; ThisThreadID: DWORD; timeout: DWORD; begin if IsIconic(hwnd) then ShowWindow(hwnd, SW_RESTORE); if GetForegroundWindow = hwnd then Result := true else begin // Windows 98/2000 doesn´t want to foreground a window when some other // window has keyboard focus if ((Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion > 4)) or ((Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and ((Win32MajorVersion > 4) or ((Win32MajorVersion = 4) and (Win32MinorVersion > 0)))) then begin // Code from Karl E. Peterson, www.mvps.org/vb/sample.htm // Converted to Delphi by Ray Lischner // Published in The Delphi Magazine 55, page 16 Result := false; ForegroundThreadID := GetWindowThreadProcessID(GetForegroundWindow, nil); ThisThreadID := GetWindowThreadProcessID(hwnd, nil); if AttachThreadInput(ThisThreadID, ForegroundThreadID, true) then begin BringWindowToTop(hwnd); // IE 5.5 related hack SetForegroundWindow(hwnd); AttachThreadInput(ThisThreadID, ForegroundThreadID, false); Result := (GetForegroundWindow = hwnd); end; if not Result then begin // Code by Daniel P. Stasinski SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, @timeout, 0); SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, TObject(0), SPIF_SENDCHANGE); BringWindowToTop(hwnd); // IE 5.5 related hack SetForegroundWindow(hwnd); SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, TObject(timeout), SPIF_SENDCHANGE); end; end else begin BringWindowToTop(hwnd); // IE 5.5 related hack SetForegroundWindow(hwnd); end; Result := (GetForegroundWindow = hwnd); end; end; end.
unit CommonfrmInstallOnUSBDrive; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, SDUForms, ComCtrls, OTFEFreeOTFE_InstructionRichEdit; type TfrmInstallOnUSBDrive = class(TSDUForm) pbOK: TButton; pbCancel: TButton; edPath: TEdit; cbDrive: TComboBox; Label1: TLabel; Label2: TLabel; ckSetupAutoplay: TCheckBox; pbBrowse: TButton; pbRefreshDrives: TButton; ckHideAutorunInf: TCheckBox; reInstructCopyToUSBDrive: TOTFEFreeOTFE_InstructionRichEdit; procedure FormShow(Sender: TObject); procedure pbBrowseClick(Sender: TObject); procedure edPathChange(Sender: TObject); procedure pbRefreshDrivesClick(Sender: TObject); procedure pbOKClick(Sender: TObject); private procedure EnableDisableControls(); function GetInstallDrive(): char; function GetInstallFullPath(): string; function GetInstallRelativePath(): string; function InstallOnUSBDrive(): boolean; function CreateAutorunInfFile(): boolean; public procedure PopulateUSBDrives(); end; implementation {$R *.dfm} uses {$WARN UNIT_PLATFORM OFF} FileCtrl, {$WARN UNIT_PLATFORM ON} SDUDialogs, SDUi18n, SDUGeneral; {$IFDEF _NEVER_DEFINED} // This is just a dummy const to fool dxGetText when extracting message // information // This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to // picks up SDUGeneral.SDUCRLF const SDUCRLF = ''#13#10; {$ENDIF} procedure TfrmInstallOnUSBDrive.FormShow(Sender: TObject); begin self.Caption := SDUParamSubstitute( _('Copy %1 to USB Drive'), [Application.title] ); reInstructCopyToUSBDrive.Text := SDUParamSubstitute( _('This function provides an easy means of copying %1 to a USB drive, and configuring it to launch automatically when the USB drive is plugged in.'+SDUCRLF+ SDUCRLF+ 'Please select the USB drive, and location on it, where you would like %1 to be copied to:'), [Application.Title] ); ckSetupAutoplay.Caption := SDUParamSubstitute( _('&Setup autorun.inf to launch %1 when drive inserted'), [Application.Title] ); // Replace any " " with "_", otherwise autorun.inf won't be able to launch // the executable edPath.text := '\'+StringReplace(Application.Title, ' ', '_', [rfReplaceAll]); ckSetupAutoplay.checked := TRUE; PopulateUSBDrives(); EnableDisableControls(); end; procedure TfrmInstallOnUSBDrive.pbBrowseClick(Sender: TObject); var newPath: string; rootPath: string; begin rootPath := GetInstallDrive()+':\'; if SelectDirectory( SDUParamSubstitute(_('Select location to copy %1 to'), [Application.Title]), rootPath, newPath {$IFDEF VER185} , // Comma from previous line [sdNewUI, sdNewFolder] {$ENDIF} ) then begin // 3 and -2 in order to strip off the "<driveletter>:" edPath.text := Copy(newPath, 3, (length(newPath)-2)); end; end; procedure TfrmInstallOnUSBDrive.pbOKClick(Sender: TObject); begin if InstallOnUSBDrive() then begin SDUMessageDlg(SDUParamSubstitute( _('%1 copy complete.'), [Application.Title] ), mtInformation); ModalResult := mrOK; end; end; function TfrmInstallOnUSBDrive.InstallOnUSBDrive(): boolean; var allOK: boolean; destPath: string; srcPath: string; copyOK: boolean; begin allOK := TRUE; destPath := GetInstallFullPath(); srcPath := ExcludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))); // Check that if user wants to create an autorun.inf file, they don't have // any spaces in teh install path if allOK then begin if ckSetupAutoplay.checked then begin if (Pos(' ', GetInstallRelativePath()) > 0) then begin allOK := (SDUMessageDlg( SDUParamSubstitute( _('The path specified has spaces in it.'+SDUCRLF+ SDUCRLF+ 'Because of this, Windows will be able to display the %1 icon for the drive, but not launch %1 automatically when the drive is inserted.'+SDUCRLF+ SDUCRLF+ 'Do you wish to continue?'), [Application.Title] ), mtWarning, [mbYes, mbNo], 0 ) = mrYes); end; end; end; if allOK then begin // Sanity check - user trying to install into root dir? // Note: GetInstallRelativePath() will return '\', at a minimum if (length(GetInstallRelativePath()) <= 1) then begin allOK := (SDUMessageDlg( SDUParamSubstitute( _('You have opted to copy %1 to the root directory of your USB drive, and not a subdirectory.'), [Application.title] )+SDUCRLF+ SDUCRLF+ _('Are you sure you wish to do this?'), mtWarning, [mbYes, mbNo], 0 ) = mrYes); end; end; // Copy FreeOTFE software to drive if allOK then begin // Disable the form, so the user mess with it while files are being copied SDUEnableControl(self, FALSE); // CopyFile(...), but using Windows API to display "flying files" dialog // while copying // Note: This force-creates the destPath directory copyOK := SDUFileCopy(srcPath+'\*', destPath); if not(copyOK) then begin SDUMessageDlg( SDUParamSubstitute(_('Unable to copy %1 to:'+SDUCRLF+ SDUCRLF+ '%2'), [Application.Title, destPath]), mtError ); allOK := FALSE; end; // Reenable the form SDUEnableControl(self, TRUE); // SDUEnableControl(...) resets various display properties on the // instructions control; reset them here reInstructCopyToUSBDrive.ResetDisplay(); EnableDisableControls(); end; // Create autorun.inf file, if needed if allOK then begin if ckSetupAutoplay.checked then begin if not(CreateAutorunInfFile()) then begin SDUMessageDlg( SDUParamSubstitute( _('%1 was successfully copied over, but an autoplay (autorun.inf) file could not be created.'), [Application.title] ), mtWarning ); // We take this as a success - the autorun.inf is pretty minor allOK := TRUE; end; end; end; Result := allOK; end; function TfrmInstallOnUSBDrive.CreateAutorunInfFile(): boolean; var autorunContent: TStringList; allOK: boolean; partPath: string; srcExeFilename: string; autorunFilename: string; begin allOK := FALSE; autorunContent := TStringList.Create(); try partPath := GetInstallRelativePath(); srcExeFilename := ExtractFileName(ParamStr(0)); // Strip off any prefixing "\" if (length(partPath) > 0) then begin if (partPath[1] = '\') then begin partPath := Copy(partPath, 2, (length(partPath)-1)); end; end; autorunContent.Add('[autorun]'); autorunContent.Add('icon='+partPath+'\'+srcExeFilename); autorunContent.Add('open='+partPath+'\'+srcExeFilename); autorunContent.Add('action='+SDUParamSubstitute(_('Launch %1'), [Application.Title])); autorunContent.Add('shell\launch\='+SDUParamSubstitute(_('Launch %1'), [Application.Title])); autorunContent.Add('shell\launch\command='+partPath+'\'+srcExeFilename); autorunFilename := GetInstallDrive()+':\autorun.inf'; try // Try to delete any existing autorun.inf file if FileExists(autorunFilename) then begin DeleteFile(autorunFilename); end; autorunContent.SaveToFile(autorunFilename); if ckHideAutorunInf.checked then begin SetFileAttributes(PChar(autorunFilename), FILE_ATTRIBUTE_HIDDEN); end; allOK := TRUE; except on E:Exception do begin // Nothing - just swallow exception end; end; finally autorunContent.Free(); end; Result := allOK; end; procedure TfrmInstallOnUSBDrive.pbRefreshDrivesClick(Sender: TObject); begin PopulateUSBDrives(); end; procedure TfrmInstallOnUSBDrive.PopulateUSBDrives(); begin SDUPopulateRemovableDrives(cbDrive); // Select first drive, if any available cbDrive.ItemIndex := -1; if (cbDrive.items.count > 0) then begin cbDrive.ItemIndex := 0; end; end; procedure TfrmInstallOnUSBDrive.edPathChange(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmInstallOnUSBDrive.EnableDisableControls(); begin SDUEnableControl(cbDrive, (cbDrive.Items.count > 1)); SDUEnableControl(ckHideAutorunInf, ckSetupAutoplay.checked); SDUEnableControl( pbOK, ( (cbDrive.ItemIndex >= 0) and (Pos(':', edPath.text) = 0) // No ":" allowed in path ) ); end; function TfrmInstallOnUSBDrive.GetInstallDrive(): char; var retval: char; begin retval := #0; if (cbDrive.ItemIndex >= 0) then begin // Only the 1st char of the drive... retval := cbDrive.Items[cbDrive.ItemIndex][1]; end; Result := retval; end; function TfrmInstallOnUSBDrive.GetInstallFullPath(): string; begin Result := GetInstallDrive() + ':' + GetInstallRelativePath(); end; function TfrmInstallOnUSBDrive.GetInstallRelativePath(): string; var retval: string; begin retval := trim(edPath.text); if (Pos('\', retval) <> 1) then begin retval := '\'+retval; end; Result := retval; end; END.
program PilhaDePratos; type rPrato = record Material: String; Cor: String; end; rPilha = record Itens: array[0..4] of rPrato; Topo: Integer; end; var PilhaDePratos: rPilha; lSair: Boolean; nOpcao: Integer; procedure MontarMenu; begin clrscr; writeln('1 - Empilhar'); writeln('2 - Desempilhar'); writeln('3 - Mostrar pilha'); writeln('4 - Limpar pilha'); writeln('0 - Sair'); write('Escolha uma opção: '); readln(nOpcao); end; procedure LimparPilha; begin //Apenas marca o topo com -1, indicando que //Não tem nenhuma posição válida. PilhaDePratos.Topo := -1; end; procedure EmpilharPrato; var nNovoTopo: Integer; begin clrscr; //Verifica se não está cheia. //Se o topo for igual a última posição //do vetor, quer dizer que está cheia. if PilhaDePratos.Topo = 4 then writeln('Erro: A pilha já está cheia!') else begin //Se não está cheia então adiciona o prato. //Aumenta o topo da pilha em 1 Inc(PilhaDePratos.Topo); nNovoTopo := PilhaDePratos.Topo; //Armazena os dados do novo prato no topo da pilha write('Material: '); readln(PilhaDePratos.Itens[nNovoTopo].Material); write('Cor: '); readln(PilhaDePratos.Itens[nNovoTopo].Cor); writeln('Prato empilhado com sucesso!'); end; readkey; end; procedure Desempilhar; begin clrscr; //Verifica se a pilha não está vazia. //Se estiver da mensagem de erro. if PilhaDePratos.Topo = -1 then writeln('Erro: A pilha está vazia') else begin //Se não está vazia, apenas diminui o //topo da pilha, fazendo com que aquele //prato não seja mais considerado PilhaDePratos.Topo := PilhaDePratos.Topo - 1; writeln('Prato desempilhado'); end; readkey; end; procedure ExibirPilha; var i: Integer; begin clrscr; writeln('Pilha de pratos:'); for i := PilhaDePratos.Topo downto 0 do begin writeln(i,' - Material: ', PilhaDePratos.Itens[i].Material, ' - Cor: ', PilhaDePratos.Itens[i].Cor); end; readkey; end; begin LimparPilha; lSair := False; while not lSair do begin MontarMenu; case nOpcao of 1: EmpilharPrato; 2: Desempilhar; 3: ExibirPilha; 4: LimparPilha; else lSair := True; end; end; end.
unit CatTime; { Catarinka - Useful time-related functions Copyright (c) 2003-2017 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details } interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} System.SysUtils, Vcl.Controls; {$ELSE} SysUtils, Controls; {$ENDIF} function CalcAge(const StartDate, Date: TDate): integer; function DateTimeToUnix(const Date: TDateTime): Longint; function DescribeDateDiff(const t, d: string): string; function DescribePassedTime(const starttime: TDateTime): string; function DescribeTimeDiff(const t: string): string; function DiffDate(const day1, day2: TDateTime): integer; function GetDayOfWeekAsNumber: integer; function GetDayOfWeekAsText: string; function IsValidDate(const S: string;const format:string='mm/dd/yyyy';const sep:Char='/'): boolean; function UnixToDateTime(const sec: Longint): TDateTime; implementation const UnixStartDate: TDateTime = 25569.0; // 01/01/1970 function CalcAge(const StartDate, Date: TDate): integer; var d, m, y: Word; ds, ms, ys: Word; age: integer; begin Result := 0; if not(Date > StartDate) then Exit; DecodeDate(Date, y, m, d); DecodeDate(StartDate, ys, ms, ds); age := y - ys; if m > ms then Result := age else begin if m < ms then Result := age - 1 else begin if d >= ds then Result := age else Result := age - 1 end end; end; function DateTimeToUnix(const Date: TDateTime): Longint; begin Result := Round((Date - UnixStartDate) * 86400); end; function DescribeDateDiff(const t, d: string): string; var dif: integer; d1, d2: TDate; begin d1 := Date; d2 := strtodate(d); dif := trunc(d1) - trunc(d2); if dif = 1 then Result := t + ' Yesterday' else Result := t + ' ' + d; end; function DescribePassedTime(const starttime: TDateTime): string; const timeformat = 'hh:nn:ss'; // 24h dateformat = 'ddd, dd mmm yyyy'; var Date, time: string; begin Date := FormatDateTime(dateformat, starttime); time := FormatDateTime(timeformat, starttime); if FormatDateTime(dateformat, now) = Date then Result := DescribeTimeDiff(time) else Result := DescribeDateDiff(time, datetostr(starttime)); end; function DescribeTimeDiff(const t: string): string; function TimeExt(n: string; s: string; p: string): string; begin if n = '1' then Result := n + ' ' + s else Result := n + ' ' + p; end; var h, m, s: string; t1, t2, ft: ttime; const zero = '0'; begin t2 := now; t1 := strtotime(t); ft := t2 - t1; h := FormatDateTime('h', ft); m := FormatDateTime('n', ft); s := FormatDateTime('s', ft); if h <> zero then begin Result := 'about ' + TimeExt(h, 'hour ago', 'hours ago'); end else begin if m <> zero then begin Result := TimeExt(m, 'minute ago', 'minutes ago'); end else begin if s <> zero then Result := TimeExt(s, 'second ago', 'seconds ago'); end; end; end; function DiffDate(const day1, day2: TDateTime): integer; var diff: double; begin diff := day2 - day1; Result := Round(diff); end; function GetDayOfWeekAsNumber: integer; var d: TDateTime; begin d := now; Result := DayOfWeek(d); end; function GetDayOfWeekAsText: string; var d: TDateTime; begin d := now; case DayOfWeek(d) of 1: Result := 'Sunday'; 2: Result := 'Monday'; 3: Result := 'Tuesday'; 4: Result := 'Wednesday'; 5: Result := 'Thursday'; 6: Result := 'Friday'; 7: Result := 'Saturday'; end; end; function IsValidDate(const S: string;const format:string='mm/dd/yyyy';const sep:Char='/'): boolean; var dt: TDateTime; fs: TFormatSettings; begin fs.ShortDateFormat := format; fs.DateSeparator := sep; if TryStrToDate(s, dt, fs) then result:=true else result:=false; end; function UnixToDateTime(const sec: Longint): TDateTime; begin Result := (sec / 86400) + UnixStartDate; end; // ------------------------------------------------------------------------// end.
{******************************************************************************* Title: T2Ti ERP Description: Biblioteca de funções. The MIT License Copyright: Copyright (C) 2020 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (T2Ti.COM) @version 3.0 *******************************************************************************} unit Biblioteca; interface uses Messages, SysUtils, StrUtils, Classes, Controls, Forms, Windows, IdHashMessageDigest, Constantes, Math, IdGlobal, TlHelp32, EncdDecd, // criptografia DCPbase64, DCPrijndael, // email IniFiles, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdBaseComponent, IdMessage, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdAttachmentFile, IdText; function Modulo11(Numero: String): String; Function ValidaCNPJ(xCNPJ: String): Boolean; Function ValidaCPF(xCPF: String): Boolean; Function ValidaEstado(Dado: string): Boolean; Function MixCase(InString: String): String; Function Hora_Seg(Horas: string): LongInt; Function Seg_Hora(Seg: LongInt): string; Function Minuscula(InString: String): String; Function StrZero(Num: Real; Zeros, Deci: integer): string; function MD5File(const fileName: string): string; function MD5FileGed(const pArquivo: TStringStream): string; function MD5String(const texto: string): string; Function TruncaValor(Value: Extended; Casas: integer): Extended; Function ArredondaTruncaValor(Operacao: String; Value: Extended; Casas: integer): Extended; function UltimoDiaMes(Mdt: TDateTime): String; overload; function UltimoDiaMes(pMes: String): String; overload; function FormataFloat(Tipo: String; Valor: Extended): string; // Tipo => 'Q'=Quantidade | 'V'=Valor procedure Split(const Delimiter: Char; Input: string; const Strings: TStrings); function CriaGuidStr: string; function CaminhoApp: string; function TextoParaData(pData: string): TDate; function DataParaTexto(pData: TDate): string; function DateToSQL(pDate: TDateTime; pComAspas: Boolean = True; pComHoras: Boolean = True): string; function DatesToSQL(pDataInicial, pDataFinal: TDateTime; pCondicao: string; pIncluirHora: Boolean): string; function UFToInt(pUF: String): Integer; function IntToUF(pUF: Integer): String; function VerificaInteiro(Value: String): Boolean; function FileSize(FileName: string): Int64; function Codifica(Action, Src: String): String; function PeriodoAnterior(pMesAno: String): String; function PeriodoPosterior(pMesAno: String): String; function RetiraMascara(Texto:String): String; function PegarPlanoPdv(DescricaoProduto: string): string; function PegarModuloFiscalPdv(DescricaoProduto: string): string; function ExecAndWait(ExeNameAndParams: string; ncmdShow: Integer = SW_SHOWNORMAL): Integer; function KillTask(ExeFileName: string): Integer; procedure DecodeFileBase64(const base64: AnsiString; const FileName: string); function EnviarEmail(AAssunto: string; ADestino: string; ACorpo: string): Boolean; function CifrarDCPCrypt(Valor: AnsiString): string; function DecifrarDCPCrypt(Valor: AnsiString): string; var InString: String; implementation function CifrarDCPCrypt(Valor: AnsiString): string; var Cipher: TDCP_rijndael; Data, Key, IV: AnsiString; begin key := TConstantes.CHAVE; iv := TConstantes.VETOR; Data := Valor; Cipher := TDCP_rijndael.Create(nil); try Cipher.Init(key[1], 256, @IV[1]); Cipher.EncryptCTR(Data[1], Data[1], Length(Data)); finally Cipher.Free; end; Result := DCPBase64.Base64EncodeStr(Data); end; function DecifrarDCPCrypt(Valor: AnsiString): string; var Cipher: TDCP_rijndael; Data, Key, IV: AnsiString; begin key := TConstantes.CHAVE; iv := TConstantes.VETOR; Data := DCPBase64.Base64DecodeStr(Valor); Cipher := TDCP_rijndael.Create(nil); try Cipher.Init(key[1], 256, @IV[1]); Cipher.DecryptCTR(Data[1], Data[1], Length(Data)); finally Cipher.Free; end; Result := Data; end; function EnviarEmail(AAssunto: string; ADestino: string; ACorpo: string): Boolean; // Fonte: http://portal.tdevrocks.com.br/2017/05/05/tutorial-como-enviar-e-mail-pelo-gmail-com-delphi-10/ var IniFile : TIniFile; sFrom : String; sBccList : String; sHost : String; iPort : Integer; sUserName : String; sPassword : String; idMsg : TIdMessage; IdText : TIdText; idSMTP : TIdSMTP; IdSSLIOHandlerSocket : TIdSSLIOHandlerSocketOpenSSL; Corpo: TStringList; begin try try //Criação e leitura do arquivo INI com as configurações IniFile := TIniFile.Create('c:\t2ti\ini\config-email.ini'); sFrom := IniFile.ReadString('Email', 'From', sFrom); sBccList := IniFile.ReadString('Email', 'BccList', sBccList); sHost := IniFile.ReadString('Email', 'Host', sHost); iPort := IniFile.ReadInteger('Email', 'Port', iPort); sUserName := IniFile.ReadString('Email', 'UserName', sUserName); sPassword := IniFile.ReadString('Email', 'Password', sPassword); //Configura os parâmetros necessários para SSL IdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create; IdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23; IdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient; //Variável referente a mensagem idMsg := TIdMessage.Create; idMsg.CharSet := 'utf-8'; idMsg.Encoding := meMIME; idMsg.From.Name := 'T2Ti.COM'; idMsg.From.Address := sFrom; idMsg.Priority := mpNormal; idMsg.Subject := AAssunto; //Destinatário(s) idMsg.Recipients.Add; idMsg.Recipients.EMailAddresses := ADestino; // idMsg.CCList.EMailAddresses := 'PARA@DOMINIO.COM.BR'; // idMsg.BccList.EMailAddresses := sBccList; // idMsg.BccList.EMailAddresses := 'PARA@DOMINIO.COM.BR'; //Cópia Oculta //Corpo idText := TIdText.Create(idMsg.MessageParts); idText.Body.Add(ACorpo); idText.ContentType := 'text/html; text/plain; charset=iso-8859-1'; //Prepara o Servidor IdSMTP := TIdSMTP.Create; IdSMTP.IOHandler := IdSSLIOHandlerSocket; IdSMTP.UseTLS := utUseImplicitTLS; IdSMTP.AuthType := satDefault; IdSMTP.Host := sHost; IdSMTP.AuthType := satDefault; IdSMTP.Port := iPort; IdSMTP.Username := sUserName; IdSMTP.Password := sPassword; //Conecta e Autentica IdSMTP.Connect; IdSMTP.Authenticate; // if AAnexo &lt;&gt; EmptyStr then // if FileExists(AAnexo) then // TIdAttachmentFile.Create(idMsg.MessageParts, AAnexo); //Se a conexão foi bem sucedida, envia a mensagem if IdSMTP.Connected then begin IdSMTP.Send(idMsg); end; //Depois de tudo pronto, desconecta do servidor SMTP if IdSMTP.Connected then IdSMTP.Disconnect; Result := True; finally IniFile.Free; UnLoadOpenSSLLibrary; FreeAndNil(idMsg); FreeAndNil(IdSSLIOHandlerSocket); FreeAndNil(idSMTP); end; except on e:Exception do begin Result := False; end; end; end; function Modulo11(Numero: String): String; var i, k: integer; Soma: integer; Digito: integer; begin Result := ''; Try Soma := 0; k := 2; for i := Length(Numero) downto 1 do begin Soma := Soma + (StrToInt(Numero[i]) * k); inc(k); if k > 9 then k := 2; end; Digito := 11 - Soma mod 11; if Digito >= 10 then Digito := 0; Result := Result + Chr(Digito + Ord('0')); except Result := 'X'; end; end; { Valida o CNPJ digitado } function ValidaCNPJ(xCNPJ: String): Boolean; Var d1, d4, xx, nCount, fator, resto, digito1, digito2: integer; Check: String; begin d1 := 0; d4 := 0; xx := 1; for nCount := 1 to Length(xCNPJ) - 2 do begin if Pos(Copy(xCNPJ, nCount, 1), '/-.') = 0 then begin if xx < 5 then begin fator := 6 - xx; end else begin fator := 14 - xx; end; d1 := d1 + StrToInt(Copy(xCNPJ, nCount, 1)) * fator; if xx < 6 then begin fator := 7 - xx; end else begin fator := 15 - xx; end; d4 := d4 + StrToInt(Copy(xCNPJ, nCount, 1)) * fator; xx := xx + 1; end; end; resto := (d1 mod 11); if resto < 2 then begin digito1 := 0; end else begin digito1 := 11 - resto; end; d4 := d4 + 2 * digito1; resto := (d4 mod 11); if resto < 2 then begin digito2 := 0; end else begin digito2 := 11 - resto; end; Check := IntToStr(digito1) + IntToStr(digito2); if Check <> Copy(xCNPJ, succ(Length(xCNPJ) - 2), 2) then begin Result := False; end else begin Result := True; end; end; { Valida o CPF digitado } function ValidaCPF(xCPF: String): Boolean; Var d1, d4, xx, nCount, resto, digito1, digito2: integer; Check: String; Begin d1 := 0; d4 := 0; xx := 1; for nCount := 1 to Length(xCPF) - 2 do begin if Pos(Copy(xCPF, nCount, 1), '/-.') = 0 then begin d1 := d1 + (11 - xx) * StrToInt(Copy(xCPF, nCount, 1)); d4 := d4 + (12 - xx) * StrToInt(Copy(xCPF, nCount, 1)); xx := xx + 1; end; end; resto := (d1 mod 11); if resto < 2 then begin digito1 := 0; end else begin digito1 := 11 - resto; end; d4 := d4 + 2 * digito1; resto := (d4 mod 11); if resto < 2 then begin digito2 := 0; end else begin digito2 := 11 - resto; end; Check := IntToStr(digito1) + IntToStr(digito2); if Check <> Copy(xCPF, succ(Length(xCPF) - 2), 2) then begin Result := False; end else begin Result := True; end; end; { Valida a UF digitada } function ValidaEstado(Dado: string): Boolean; const Estados = 'SPMGRJRSSCPRESDFMTMSGOTOBASEALPBPEMARNCEPIPAAMAPFNACRRRO'; var Posicao: integer; begin Result := True; if Dado <> '' then begin Posicao := Pos(UpperCase(Dado), Estados); if (Posicao = 0) or ((Posicao mod 2) = 0) then begin Result := False; end; end; end; { Corrige a string que contenha caracteres maiusculos inseridos no meio dela para tudo minusculo e com a primeira letra maiuscula } Function MixCase(InString: String): String; Var i: integer; Begin Result := LowerCase(InString); Result[1] := UpCase(Result[1]); For i := 1 To Length(InString) - 1 Do Begin If (Result[i] = ' ') Or (Result[i] = '''') Or (Result[i] = '"') Or (Result[i] = '-') Or (Result[i] = '.') Or (Result[i] = '(') Then Result[i + 1] := UpCase(Result[i + 1]); if Result[i] = 'Ç' then Result[i] := 'ç'; if Result[i] = 'Ã' then Result[i] := 'ã'; if Result[i] = 'Á' then Result[i] := 'á'; if Result[i] = 'É' then Result[i] := 'é'; if Result[i] = 'Í' then Result[i] := 'í'; if Result[i] = 'Õ' then Result[i] := 'õ'; if Result[i] = 'Ó' then Result[i] := 'ó'; if Result[i] = 'Ú' then Result[i] := 'ú'; if Result[i] = 'Â' then Result[i] := 'â'; if Result[i] = 'Ê' then Result[i] := 'ê'; if Result[i] = 'Ô' then Result[i] := 'ô'; End; End; { Converte de hora para segundos } function Hora_Seg(Horas: string): LongInt; Var Hor, Min, Seg: LongInt; begin Horas[Pos(':', Horas)] := '['; Horas[Pos(':', Horas)] := ']'; Hor := StrToInt(Copy(Horas, 1, Pos('[', Horas) - 1)); Min := StrToInt(Copy(Horas, Pos('[', Horas) + 1, (Pos(']', Horas) - Pos('[', Horas) - 1))); if Pos(':', Horas) > 0 then Seg := StrToInt(Copy(Horas, Pos(']', Horas) + 1, (Pos(':', Horas) - Pos(']', Horas) - 1))) else Seg := StrToInt(Copy(Horas, Pos(']', Horas) + 1, 2)); Result := Seg + (Hor * 3600) + (Min * 60); end; { Converte de segundos para hora } function Seg_Hora(Seg: LongInt): string; Var Hora, Min: LongInt; Tmp: Double; begin Tmp := Seg / 3600; Hora := Round(Int(Tmp)); Seg := Round(Seg - (Hora * 3600)); Tmp := Seg / 60; Min := Round(Int(Tmp)); Seg := Round(Seg - (Min * 60)); Result := StrZero(Hora, 2, 0) + ':' + StrZero(Min, 2, 0) + ':' + StrZero(Seg, 2, 0); end; { converte tudo para minuscula } Function Minuscula(InString: String): String; Var i: integer; Begin Result := LowerCase(InString); For i := 1 To Length(InString) - 1 Do Begin If (Result[i] = ' ') Or (Result[i] = '''') Or (Result[i] = '"') Or (Result[i] = '-') Or (Result[i] = '.') Or (Result[i] = '(') Then Result[i] := UpCase(Result[i]); if Result[i] = 'Ç' then Result[i] := 'ç'; if Result[i] = 'Ã' then Result[i] := 'ã'; if Result[i] = 'Á' then Result[i] := 'á'; if Result[i] = 'É' then Result[i] := 'é'; if Result[i] = 'Í' then Result[i] := 'í'; if Result[i] = 'Õ' then Result[i] := 'õ'; if Result[i] = 'Ó' then Result[i] := 'ó'; if Result[i] = 'Ú' then Result[i] := 'ú'; if Result[i] = 'Â' then Result[i] := 'â'; if Result[i] = 'Ê' then Result[i] := 'ê'; if Result[i] = 'Ô' then Result[i] := 'ô'; End; End; function StrZero(Num: Real; Zeros, Deci: integer): string; var Tam, Z: integer; Res, Zer: string; begin {$WARNINGS OFF} Str(Num: Zeros: Deci, Res); Res := Trim(Res); Tam := Length(Res); Zer := ''; for Z := 01 to (Zeros - Tam) do Zer := Zer + '0'; Result := Zer + Res; {$WARNINGS ON} end; function MD5File(const fileName: string): string; var idmd5: TIdHashMessageDigest5; fs: TFileStream; begin idmd5 := TIdHashMessageDigest5.Create; fs := TFileStream.Create(fileName, fmOpenRead OR fmShareDenyWrite); try Result := idmd5.HashStreamAsHex(fs); finally fs.Free; idmd5.Free; end; end; function MD5FileGed(const pArquivo: TStringStream): string; var idmd5: TIdHashMessageDigest5; begin idmd5 := TIdHashMessageDigest5.Create; try Result := idmd5.HashBytesAsHex(TIdBytes(pArquivo.Bytes)); finally idmd5.Free; end; end; function MD5String(const texto: string): string; var idmd5: TIdHashMessageDigest5; begin idmd5 := TIdHashMessageDigest5.Create; try Result := LowerCase(idmd5.HashStringAsHex(texto)); finally idmd5.Free; end; end; Function TruncaValor(Value: Extended; Casas: integer): Extended; Var sValor: String; nPos: integer; begin // Transforma o valor em string sValor := FloatToStr(Value); // Verifica se possui ponto decimal nPos := Pos(FormatSettings.DecimalSeparator, sValor); If (nPos > 0) Then begin sValor := Copy(sValor, 1, nPos + Casas); End; Result := StrToFloat(sValor); end; Function ArredondaTruncaValor(Operacao: String; Value: Extended; Casas: integer): Extended; Var sValor: String; nPos: integer; begin if Operacao = 'A' then Result := SimpleRoundTo(Value, Casas * -1) else begin // Transforma o valor em string sValor := FloatToStr(Value); // Verifica se possui ponto decimal nPos := Pos(FormatSettings.DecimalSeparator, sValor); If (nPos > 0) Then begin sValor := Copy(sValor, 1, nPos + Casas); End; Result := StrToFloat(sValor); end; end; function UltimoDiaMes(Mdt: TDateTime): String; var ano, mes, dia: word; mDtTemp: TDateTime; begin Decodedate(Mdt, ano, mes, dia); mDtTemp := (Mdt - dia) + 33; Decodedate(mDtTemp, ano, mes, dia); mDtTemp := mDtTemp - dia; Decodedate(mDtTemp, ano, mes, dia); Result := IntToStr(dia) end; function UltimoDiaMes(pMes: String): String; var ano, mes, dia: word; mDtTemp: TDateTime; Mdt: TDateTime; begin Mdt := StrToDateTime('01/' + pMes + '/' + FormatDateTime('YYYY', Now)); Decodedate(Mdt, ano, mes, dia); mDtTemp := (Mdt - dia) + 33; Decodedate(mDtTemp, ano, mes, dia); mDtTemp := mDtTemp - dia; Decodedate(mDtTemp, ano, mes, dia); Result := IntToStr(dia) end; function FormataFloat(Tipo: String; Valor: Extended): string; // Tipo => 'Q'=Quantidade | 'V'=Valor var i: integer; Mascara: String; begin Mascara := '0.'; if Tipo = 'Q' then begin for i := 1 to Constantes.TConstantes.DECIMAIS_QUANTIDADE do Mascara := Mascara + '0'; end else if Tipo = 'V' then begin for i := 1 to Constantes.TConstantes.DECIMAIS_VALOR do Mascara := Mascara + '0'; end; Result := FormatFloat(Mascara, Valor); end; procedure Split(const Delimiter: Char; Input: string; const Strings: TStrings); begin Assert(Assigned(Strings)); Strings.Clear; Strings.Delimiter := Delimiter; Strings.DelimitedText := Input; end; function CriaGuidStr: string; var Guid: TGUID; begin CreateGUID(Guid); Result := GUIDToString(Guid); end; function CaminhoApp: string; begin Result := ExtractFileDir(GetCurrentDir); end; function TextoParaData(pData: string): TDate; var dia, mes, ano: integer; begin if (pData <> '') AND (pData <> '0000-00-00') then begin dia := StrToInt(Copy(pData, 9, 2)); mes := StrToInt(Copy(pData, 6, 2)); ano := StrToInt(Copy(pData, 1, 4)); Result := EncodeDate(ano, mes, dia); end else begin Result := 0; end; end; function DataParaTexto(pData: TDate): string; begin if pData > 0 then Result := FormatDateTime('YYYY-MM-DD', pData) else Result := '0000-00-00'; end; function DateToSQL(pDate: TDateTime; pComAspas: Boolean = True; pComHoras: Boolean = True): string; var ano, mes, dia, Hora, Minuto, Segundo, MileSegundo: word; begin Decodedate(pDate, ano, mes, dia); Result := IntToStr(ano) + '-' + IntToStr(mes) + '-' + IntToStr(dia); DecodeTime(pDate, Hora, Minuto, Segundo, MileSegundo); if ((Hora + Minuto + Segundo) > 0) and (pComHoras) then begin Result := Result + ' ' + IntToStr(Hora) + ':' + IntToStr(Minuto) + ':' + IntToStr(Segundo); end; if pComAspas then begin Result := QuotedStr(Result); end; end; function DatesToSQL(pDataInicial, pDataFinal: TDateTime; pCondicao: string; pIncluirHora: Boolean): string; begin if (pDataInicial > 0) and (pDataFinal > 0) then begin if pIncluirHora then begin Result := pCondicao + ' BETWEEN ' + QuotedStr(DateToSQL(pDataInicial, False, False) + ' 00:00:00') + ' AND ' + QuotedStr(DateToSQL(pDataFinal, False, False) + ' 23:59:59'); end else begin Result := pCondicao + ' BETWEEN ' + DateToSQL(pDataInicial, True, False) + ' AND ' + DateToSQL(pDataFinal, True, False); end; end else if (pDataInicial > 0) and (pDataFinal = 0) then Result := pCondicao + ' >= ' + DateToSQL(pDataInicial, True, False) else if (pDataInicial = 0) and (pDataFinal > 0) then begin if pIncluirHora then begin Result := pCondicao + ' <= ' + QuotedStr(DateToSQL(pDataFinal, False, False) + ' 23:59:59'); end else begin Result := pCondicao + ' <= ' + DateToSQL(pDataFinal, True, False); end; end else Result := ''; end; // função auxiliar para converte UF do cliente para codigo function UFToInt(pUF: String): integer; begin Result := 0; if pUF = 'RO' then Result := 11; if pUF = 'AC' then Result := 12; if pUF = 'AM' then Result := 13; if pUF = 'RR' then Result := 14; if pUF = 'PA' then Result := 15; if pUF = 'AP' then Result := 16; if pUF = 'TO' then Result := 17; if pUF = 'MA' then Result := 21; if pUF = 'PI' then Result := 22; if pUF = 'CE' then Result := 23; if pUF = 'RN' then Result := 24; if pUF = 'PB' then Result := 25; if pUF = 'PE' then Result := 26; if pUF = 'AL' then Result := 27; if pUF = 'SE' then Result := 28; if pUF = 'BA' then Result := 29; if pUF = 'MG' then Result := 31; if pUF = 'ES' then Result := 32; if pUF = 'RJ' then Result := 33; if pUF = 'SP' then Result := 35; if pUF = 'PR' then Result := 41; if pUF = 'SC' then Result := 42; if pUF = 'RS' then Result := 43; if pUF = 'MS' then Result := 50; if pUF = 'MT' then Result := 51; if pUF = 'GO' then Result := 52; if pUF = 'DF' then Result := 53; end; // função auxiliar para converte Codigo UF do cliente para UF function IntToUF(pUF: integer): String; begin Result := ''; if pUF = 11 then Result := 'RO'; if pUF = 12 then Result := 'AC'; if pUF = 13 then Result := 'AM'; if pUF = 14 then Result := 'RR'; if pUF = 15 then Result := 'PA'; if pUF = 16 then Result := 'AP'; if pUF = 17 then Result := 'TO'; if pUF = 21 then Result := 'MA'; if pUF = 22 then Result := 'PI'; if pUF = 23 then Result := 'CE'; if pUF = 24 then Result := 'RN'; if pUF = 25 then Result := 'PB'; if pUF = 26 then Result := 'PE'; if pUF = 27 then Result := 'AL'; if pUF = 28 then Result := 'SE'; if pUF = 29 then Result := 'BA'; if pUF = 31 then Result := 'MG'; if pUF = 32 then Result := 'ES'; if pUF = 33 then Result := 'RJ'; if pUF = 35 then Result := 'SP'; if pUF = 41 then Result := 'PR'; if pUF = 42 then Result := 'SC'; if pUF = 43 then Result := 'RS'; if pUF = 50 then Result := 'MS'; if pUF = 51 then Result := 'MT'; if pUF = 52 then Result := 'GO'; if pUF = 53 then Result := 'DF'; end; function VerificaInteiro(Value: String): Boolean; var i: integer; begin Result := False; for i := 0 to 9 do begin if Pos(IntToStr(i), Value) <> 0 then begin Result := True; exit; end; end; end; function FileSize(FileName: string): Int64; var SearchRec: TSearchRec; begin if FindFirst(FileName, faAnyFile, SearchRec) = 0 then // se achou o arquivo // SearchRec.Size funciona legal para arquivos menores que 2GB Result := Int64(SearchRec.FindData.nFileSizeHigh) shl Int64(32) + // calcula o tamanho Int64(SearchRec.FindData.nFileSizeLow) else Result := 0; // FindClose(SearchRec); // fecha end; function Codifica(Action, Src: String): String; Label Fim; //Função para criptografar e descriptografar string's var KeyLen : Integer; KeyPos : Integer; OffSet : Integer; Dest, Key : String; SrcPos : Integer; SrcAsc : Integer; TmpSrcAsc : Integer; Range : Integer; begin try if (Src = '') Then begin Result:= ''; Goto Fim; end; Key := 'YUQL23KL23DF90WI5E1JAS467NMCXXL6JAOAUWWMCL0AOMM4A4VZYW9KHJUI2347EJHJKDF3424SKL K3LAKDJSL9RTIKJ'; Dest := ''; KeyLen := Length(Key); KeyPos := 0; SrcPos := 0; SrcAsc := 0; Range := 256; if (Action = UpperCase('C')) then begin Randomize; OffSet := Random(Range); Dest := Format('%1.2x',[OffSet]); for SrcPos := 1 to Length(Src) do begin Application.ProcessMessages; SrcAsc := (Ord(Src[SrcPos]) + OffSet) Mod 255; if KeyPos < KeyLen then KeyPos := KeyPos + 1 else KeyPos := 1; SrcAsc := SrcAsc Xor Ord(Key[KeyPos]); Dest := Dest + Format('%1.2x',[SrcAsc]); OffSet := SrcAsc; end; end Else if (Action = UpperCase('D')) then begin OffSet := StrToInt('$'+ copy(Src,1,2)); SrcPos := 3; repeat SrcAsc := StrToInt('$'+ copy(Src,SrcPos,2)); if (KeyPos < KeyLen) Then KeyPos := KeyPos + 1 else KeyPos := 1; TmpSrcAsc := SrcAsc Xor Ord(Key[KeyPos]); if TmpSrcAsc <= OffSet then TmpSrcAsc := 255 + TmpSrcAsc - OffSet else TmpSrcAsc := TmpSrcAsc - OffSet; Dest := Dest + Chr(TmpSrcAsc); OffSet := SrcAsc; SrcPos := SrcPos + 2; until (SrcPos >= Length(Src)); end; Result:= Dest; Fim: Except Result:= '1'; end; end; function PeriodoAnterior(pMesAno: String): String; var Mes, Ano: Integer; begin Mes := StrToInt(Copy(pMesAno, 1, 2)); Ano := StrToInt(Copy(pMesAno, 4, 4)); if Mes = 1 then begin Mes := 12; Ano := Ano - 1; Result := IntToStr(Mes) + '/' + IntToStr(Ano); end else Result := StringOfChar('0', 2 - Length(IntToStr(Mes - 1))) + IntToStr(Mes - 1) + '/' + IntToStr(Ano); end; function PeriodoPosterior(pMesAno: String): String; var Mes, Ano: Integer; begin Mes := StrToInt(Copy(pMesAno, 1, 2)); Ano := StrToInt(Copy(pMesAno, 4, 4)); if Mes = 12 then begin Mes := 1; Ano := Ano + 1; Result := IntToStr(Mes) + '/' + IntToStr(Ano); end else Result := StringOfChar('0', 2 - Length(IntToStr(Mes + 1))) + IntToStr(Mes + 1) + '/' + IntToStr(Ano); end; function RetiraMascara(Texto: String): String; begin Result := Texto; Result := StringReplace(Result,'*','',[rfReplaceAll]); Result := StringReplace(Result,'.','',[rfReplaceAll]); Result := StringReplace(Result,'-','',[rfReplaceAll]); Result := StringReplace(Result,'/','',[rfReplaceAll]); Result := StringReplace(Result,'\','',[rfReplaceAll]); end; function PegarPlanoPdv(DescricaoProduto: string): string; begin if ContainsText(DescricaoProduto, 'Mensal') then Result := 'M' else if ContainsText(DescricaoProduto, 'Semestral') then Result := 'S' else if ContainsText(DescricaoProduto, 'Anual') then Result := 'A'; end; function PegarModuloFiscalPdv(DescricaoProduto: string): string; begin if ContainsText(DescricaoProduto, 'NFC') then Result := 'NFC' else if ContainsText(DescricaoProduto, 'SAT') then Result := 'SAT' else if ContainsText(DescricaoProduto, 'MFE') then Result := 'MFE'; end; function ExecAndWait(ExeNameAndParams: string; ncmdShow: Integer = SW_SHOWNORMAL): Integer; var StartupInfo: TStartupInfo; ProcessInformation: TProcessInformation; Res: Bool; lpExitCode: DWORD; begin with StartupInfo do //you can play with this structure begin cb := SizeOf(TStartupInfo); lpReserved := nil; lpDesktop := nil; lpTitle := nil; dwFlags := STARTF_USESHOWWINDOW; wShowWindow := ncmdShow; cbReserved2 := 0; lpReserved2 := nil; end; Res := CreateProcess(nil, PChar(ExeNameAndParams), nil, nil, True, CREATE_DEFAULT_ERROR_MODE or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInformation); while True do begin GetExitCodeProcess(ProcessInformation.hProcess, lpExitCode); if lpExitCode <> STILL_ACTIVE then Break; Application.ProcessMessages; end; Result := Integer(lpExitCode); end; function KillTask(ExeFileName: string): Integer; const PROCESS_TERMINATE = $0001; var ContinueLoop: BOOL; FSnapshotHandle: THandle; FProcessEntry32: TProcessEntry32; begin Result := 0; FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); FProcessEntry32.dwSize := SizeOf(FProcessEntry32); ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32); while Integer(ContinueLoop) <> 0 do begin if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName))) then Result := Integer(TerminateProcess( OpenProcess(PROCESS_TERMINATE, BOOL(0), FProcessEntry32.th32ProcessID), 0)); ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32); end; CloseHandle(FSnapshotHandle); end; procedure DecodeFileBase64(const base64: AnsiString; const FileName: string); var stream: TBytesStream; begin stream := TBytesStream.Create(DecodeBase64(base64)); try stream.SaveToFile(Filename); finally stream.Free; end; end; end.{******************************************************************************* Title: T2Ti ERP Description: Biblioteca de funções. The MIT License Copyright: Copyright (C) 2020 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (T2Ti.COM) @version 3.0 *******************************************************************************} unit Biblioteca; interface uses Messages, SysUtils, StrUtils, Classes, Controls, Forms, Windows, IdHashMessageDigest, Constantes, Math, IdGlobal, TlHelp32, EncdDecd, // email IniFiles, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdBaseComponent, IdMessage, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdAttachmentFile, IdText; function Modulo11(Numero: String): String; Function ValidaCNPJ(xCNPJ: String): Boolean; Function ValidaCPF(xCPF: String): Boolean; Function ValidaEstado(Dado: string): Boolean; Function MixCase(InString: String): String; Function Hora_Seg(Horas: string): LongInt; Function Seg_Hora(Seg: LongInt): string; Function Minuscula(InString: String): String; Function StrZero(Num: Real; Zeros, Deci: integer): string; function MD5File(const fileName: string): string; function MD5FileGed(const pArquivo: TStringStream): string; function MD5String(const texto: string): string; Function TruncaValor(Value: Extended; Casas: integer): Extended; Function ArredondaTruncaValor(Operacao: String; Value: Extended; Casas: integer): Extended; function UltimoDiaMes(Mdt: TDateTime): String; overload; function UltimoDiaMes(pMes: String): String; overload; function FormataFloat(Tipo: String; Valor: Extended): string; // Tipo => 'Q'=Quantidade | 'V'=Valor procedure Split(const Delimiter: Char; Input: string; const Strings: TStrings); function CriaGuidStr: string; function CaminhoApp: string; function TextoParaData(pData: string): TDate; function DataParaTexto(pData: TDate): string; function DateToSQL(pDate: TDateTime; pComAspas: Boolean = True; pComHoras: Boolean = True): string; function DatesToSQL(pDataInicial, pDataFinal: TDateTime; pCondicao: string; pIncluirHora: Boolean): string; function UFToInt(pUF: String): Integer; function IntToUF(pUF: Integer): String; function VerificaInteiro(Value: String): Boolean; function FileSize(FileName: string): Int64; function Codifica(Action, Src: String): String; function PeriodoAnterior(pMesAno: String): String; function PeriodoPosterior(pMesAno: String): String; function RetiraMascara(Texto:String): String; function PegarPlanoPdv(DescricaoProduto: string): string; function PegarModuloFiscalPdv(DescricaoProduto: string): string; function ExecAndWait(ExeNameAndParams: string; ncmdShow: Integer = SW_SHOWNORMAL): Integer; function KillTask(ExeFileName: string): Integer; procedure DecodeFileBase64(const base64: AnsiString; const FileName: string); function EnviarEmail(AAssunto: string; ADestino: string; ACorpo: string): Boolean; var InString: String; implementation function EnviarEmail(AAssunto: string; ADestino: string; ACorpo: string): Boolean; var IniFile : TIniFile; sFrom : String; sBccList : String; sHost : String; iPort : Integer; sUserName : String; sPassword : String; idMsg : TIdMessage; IdText : TIdText; idSMTP : TIdSMTP; IdSSLIOHandlerSocket : TIdSSLIOHandlerSocketOpenSSL; Corpo: TStringList; begin try try //Criação e leitura do arquivo INI com as configurações IniFile := TIniFile.Create('c:\t2ti\config-email.ini'); sFrom := IniFile.ReadString('Email', 'From', sFrom); sBccList := IniFile.ReadString('Email', 'BccList', sBccList); sHost := IniFile.ReadString('Email', 'Host', sHost); iPort := IniFile.ReadInteger('Email', 'Port', iPort); sUserName := IniFile.ReadString('Email', 'UserName', sUserName); sPassword := IniFile.ReadString('Email', 'Password', sPassword); //Configura os parâmetros necessários para SSL IdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create; IdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23; IdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient; //Variável referente a mensagem idMsg := TIdMessage.Create; idMsg.CharSet := 'utf-8'; idMsg.Encoding := meMIME; idMsg.From.Name := 'T2Ti.COM'; idMsg.From.Address := sFrom; idMsg.Priority := mpNormal; idMsg.Subject := AAssunto; //Destinatário(s) idMsg.Recipients.Add; idMsg.Recipients.EMailAddresses := ADestino; // idMsg.CCList.EMailAddresses := 'PARA@DOMINIO.COM.BR'; // idMsg.BccList.EMailAddresses := sBccList; // idMsg.BccList.EMailAddresses := 'PARA@DOMINIO.COM.BR'; //Cópia Oculta //Corpo idText := TIdText.Create(idMsg.MessageParts); idText.Body.Add(ACorpo); idText.ContentType := 'text/html; text/plain; charset=iso-8859-1'; //Prepara o Servidor IdSMTP := TIdSMTP.Create; IdSMTP.IOHandler := IdSSLIOHandlerSocket; IdSMTP.UseTLS := utUseImplicitTLS; IdSMTP.AuthType := satDefault; IdSMTP.Host := sHost; IdSMTP.AuthType := satDefault; IdSMTP.Port := iPort; IdSMTP.Username := sUserName; IdSMTP.Password := sPassword; //Conecta e Autentica IdSMTP.Connect; IdSMTP.Authenticate; // if AAnexo &lt;&gt; EmptyStr then // if FileExists(AAnexo) then // TIdAttachmentFile.Create(idMsg.MessageParts, AAnexo); //Se a conexão foi bem sucedida, envia a mensagem if IdSMTP.Connected then begin IdSMTP.Send(idMsg); end; //Depois de tudo pronto, desconecta do servidor SMTP if IdSMTP.Connected then IdSMTP.Disconnect; Result := True; finally IniFile.Free; UnLoadOpenSSLLibrary; FreeAndNil(idMsg); FreeAndNil(IdSSLIOHandlerSocket); FreeAndNil(idSMTP); end; except on e:Exception do begin Result := False; end; end; end; function Modulo11(Numero: String): String; var i, k: integer; Soma: integer; Digito: integer; begin Result := ''; Try Soma := 0; k := 2; for i := Length(Numero) downto 1 do begin Soma := Soma + (StrToInt(Numero[i]) * k); inc(k); if k > 9 then k := 2; end; Digito := 11 - Soma mod 11; if Digito >= 10 then Digito := 0; Result := Result + Chr(Digito + Ord('0')); except Result := 'X'; end; end; { Valida o CNPJ digitado } function ValidaCNPJ(xCNPJ: String): Boolean; Var d1, d4, xx, nCount, fator, resto, digito1, digito2: integer; Check: String; begin d1 := 0; d4 := 0; xx := 1; for nCount := 1 to Length(xCNPJ) - 2 do begin if Pos(Copy(xCNPJ, nCount, 1), '/-.') = 0 then begin if xx < 5 then begin fator := 6 - xx; end else begin fator := 14 - xx; end; d1 := d1 + StrToInt(Copy(xCNPJ, nCount, 1)) * fator; if xx < 6 then begin fator := 7 - xx; end else begin fator := 15 - xx; end; d4 := d4 + StrToInt(Copy(xCNPJ, nCount, 1)) * fator; xx := xx + 1; end; end; resto := (d1 mod 11); if resto < 2 then begin digito1 := 0; end else begin digito1 := 11 - resto; end; d4 := d4 + 2 * digito1; resto := (d4 mod 11); if resto < 2 then begin digito2 := 0; end else begin digito2 := 11 - resto; end; Check := IntToStr(digito1) + IntToStr(digito2); if Check <> Copy(xCNPJ, succ(Length(xCNPJ) - 2), 2) then begin Result := False; end else begin Result := True; end; end; { Valida o CPF digitado } function ValidaCPF(xCPF: String): Boolean; Var d1, d4, xx, nCount, resto, digito1, digito2: integer; Check: String; Begin d1 := 0; d4 := 0; xx := 1; for nCount := 1 to Length(xCPF) - 2 do begin if Pos(Copy(xCPF, nCount, 1), '/-.') = 0 then begin d1 := d1 + (11 - xx) * StrToInt(Copy(xCPF, nCount, 1)); d4 := d4 + (12 - xx) * StrToInt(Copy(xCPF, nCount, 1)); xx := xx + 1; end; end; resto := (d1 mod 11); if resto < 2 then begin digito1 := 0; end else begin digito1 := 11 - resto; end; d4 := d4 + 2 * digito1; resto := (d4 mod 11); if resto < 2 then begin digito2 := 0; end else begin digito2 := 11 - resto; end; Check := IntToStr(digito1) + IntToStr(digito2); if Check <> Copy(xCPF, succ(Length(xCPF) - 2), 2) then begin Result := False; end else begin Result := True; end; end; { Valida a UF digitada } function ValidaEstado(Dado: string): Boolean; const Estados = 'SPMGRJRSSCPRESDFMTMSGOTOBASEALPBPEMARNCEPIPAAMAPFNACRRRO'; var Posicao: integer; begin Result := True; if Dado <> '' then begin Posicao := Pos(UpperCase(Dado), Estados); if (Posicao = 0) or ((Posicao mod 2) = 0) then begin Result := False; end; end; end; { Corrige a string que contenha caracteres maiusculos inseridos no meio dela para tudo minusculo e com a primeira letra maiuscula } Function MixCase(InString: String): String; Var i: integer; Begin Result := LowerCase(InString); Result[1] := UpCase(Result[1]); For i := 1 To Length(InString) - 1 Do Begin If (Result[i] = ' ') Or (Result[i] = '''') Or (Result[i] = '"') Or (Result[i] = '-') Or (Result[i] = '.') Or (Result[i] = '(') Then Result[i + 1] := UpCase(Result[i + 1]); if Result[i] = 'Ç' then Result[i] := 'ç'; if Result[i] = 'Ã' then Result[i] := 'ã'; if Result[i] = 'Á' then Result[i] := 'á'; if Result[i] = 'É' then Result[i] := 'é'; if Result[i] = 'Í' then Result[i] := 'í'; if Result[i] = 'Õ' then Result[i] := 'õ'; if Result[i] = 'Ó' then Result[i] := 'ó'; if Result[i] = 'Ú' then Result[i] := 'ú'; if Result[i] = 'Â' then Result[i] := 'â'; if Result[i] = 'Ê' then Result[i] := 'ê'; if Result[i] = 'Ô' then Result[i] := 'ô'; End; End; { Converte de hora para segundos } function Hora_Seg(Horas: string): LongInt; Var Hor, Min, Seg: LongInt; begin Horas[Pos(':', Horas)] := '['; Horas[Pos(':', Horas)] := ']'; Hor := StrToInt(Copy(Horas, 1, Pos('[', Horas) - 1)); Min := StrToInt(Copy(Horas, Pos('[', Horas) + 1, (Pos(']', Horas) - Pos('[', Horas) - 1))); if Pos(':', Horas) > 0 then Seg := StrToInt(Copy(Horas, Pos(']', Horas) + 1, (Pos(':', Horas) - Pos(']', Horas) - 1))) else Seg := StrToInt(Copy(Horas, Pos(']', Horas) + 1, 2)); Result := Seg + (Hor * 3600) + (Min * 60); end; { Converte de segundos para hora } function Seg_Hora(Seg: LongInt): string; Var Hora, Min: LongInt; Tmp: Double; begin Tmp := Seg / 3600; Hora := Round(Int(Tmp)); Seg := Round(Seg - (Hora * 3600)); Tmp := Seg / 60; Min := Round(Int(Tmp)); Seg := Round(Seg - (Min * 60)); Result := StrZero(Hora, 2, 0) + ':' + StrZero(Min, 2, 0) + ':' + StrZero(Seg, 2, 0); end; { converte tudo para minuscula } Function Minuscula(InString: String): String; Var i: integer; Begin Result := LowerCase(InString); For i := 1 To Length(InString) - 1 Do Begin If (Result[i] = ' ') Or (Result[i] = '''') Or (Result[i] = '"') Or (Result[i] = '-') Or (Result[i] = '.') Or (Result[i] = '(') Then Result[i] := UpCase(Result[i]); if Result[i] = 'Ç' then Result[i] := 'ç'; if Result[i] = 'Ã' then Result[i] := 'ã'; if Result[i] = 'Á' then Result[i] := 'á'; if Result[i] = 'É' then Result[i] := 'é'; if Result[i] = 'Í' then Result[i] := 'í'; if Result[i] = 'Õ' then Result[i] := 'õ'; if Result[i] = 'Ó' then Result[i] := 'ó'; if Result[i] = 'Ú' then Result[i] := 'ú'; if Result[i] = 'Â' then Result[i] := 'â'; if Result[i] = 'Ê' then Result[i] := 'ê'; if Result[i] = 'Ô' then Result[i] := 'ô'; End; End; function StrZero(Num: Real; Zeros, Deci: integer): string; var Tam, Z: integer; Res, Zer: string; begin {$WARNINGS OFF} Str(Num: Zeros: Deci, Res); Res := Trim(Res); Tam := Length(Res); Zer := ''; for Z := 01 to (Zeros - Tam) do Zer := Zer + '0'; Result := Zer + Res; {$WARNINGS ON} end; function MD5File(const fileName: string): string; var idmd5: TIdHashMessageDigest5; fs: TFileStream; begin idmd5 := TIdHashMessageDigest5.Create; fs := TFileStream.Create(fileName, fmOpenRead OR fmShareDenyWrite); try Result := idmd5.HashStreamAsHex(fs); finally fs.Free; idmd5.Free; end; end; function MD5FileGed(const pArquivo: TStringStream): string; var idmd5: TIdHashMessageDigest5; begin idmd5 := TIdHashMessageDigest5.Create; try Result := idmd5.HashBytesAsHex(TIdBytes(pArquivo.Bytes)); finally idmd5.Free; end; end; function MD5String(const texto: string): string; var idmd5: TIdHashMessageDigest5; begin idmd5 := TIdHashMessageDigest5.Create; try Result := LowerCase(idmd5.HashStringAsHex(texto)); finally idmd5.Free; end; end; Function TruncaValor(Value: Extended; Casas: integer): Extended; Var sValor: String; nPos: integer; begin // Transforma o valor em string sValor := FloatToStr(Value); // Verifica se possui ponto decimal nPos := Pos(FormatSettings.DecimalSeparator, sValor); If (nPos > 0) Then begin sValor := Copy(sValor, 1, nPos + Casas); End; Result := StrToFloat(sValor); end; Function ArredondaTruncaValor(Operacao: String; Value: Extended; Casas: integer): Extended; Var sValor: String; nPos: integer; begin if Operacao = 'A' then Result := SimpleRoundTo(Value, Casas * -1) else begin // Transforma o valor em string sValor := FloatToStr(Value); // Verifica se possui ponto decimal nPos := Pos(FormatSettings.DecimalSeparator, sValor); If (nPos > 0) Then begin sValor := Copy(sValor, 1, nPos + Casas); End; Result := StrToFloat(sValor); end; end; function UltimoDiaMes(Mdt: TDateTime): String; var ano, mes, dia: word; mDtTemp: TDateTime; begin Decodedate(Mdt, ano, mes, dia); mDtTemp := (Mdt - dia) + 33; Decodedate(mDtTemp, ano, mes, dia); mDtTemp := mDtTemp - dia; Decodedate(mDtTemp, ano, mes, dia); Result := IntToStr(dia) end; function UltimoDiaMes(pMes: String): String; var ano, mes, dia: word; mDtTemp: TDateTime; Mdt: TDateTime; begin Mdt := StrToDateTime('01/' + pMes + '/' + FormatDateTime('YYYY', Now)); Decodedate(Mdt, ano, mes, dia); mDtTemp := (Mdt - dia) + 33; Decodedate(mDtTemp, ano, mes, dia); mDtTemp := mDtTemp - dia; Decodedate(mDtTemp, ano, mes, dia); Result := IntToStr(dia) end; function FormataFloat(Tipo: String; Valor: Extended): string; // Tipo => 'Q'=Quantidade | 'V'=Valor var i: integer; Mascara: String; begin Mascara := '0.'; if Tipo = 'Q' then begin for i := 1 to Constantes.TConstantes.DECIMAIS_QUANTIDADE do Mascara := Mascara + '0'; end else if Tipo = 'V' then begin for i := 1 to Constantes.TConstantes.DECIMAIS_VALOR do Mascara := Mascara + '0'; end; Result := FormatFloat(Mascara, Valor); end; procedure Split(const Delimiter: Char; Input: string; const Strings: TStrings); begin Assert(Assigned(Strings)); Strings.Clear; Strings.Delimiter := Delimiter; Strings.DelimitedText := Input; end; function CriaGuidStr: string; var Guid: TGUID; begin CreateGUID(Guid); Result := GUIDToString(Guid); end; function CaminhoApp: string; begin Result := ExtractFileDir(GetCurrentDir); end; function TextoParaData(pData: string): TDate; var dia, mes, ano: integer; begin if (pData <> '') AND (pData <> '0000-00-00') then begin dia := StrToInt(Copy(pData, 9, 2)); mes := StrToInt(Copy(pData, 6, 2)); ano := StrToInt(Copy(pData, 1, 4)); Result := EncodeDate(ano, mes, dia); end else begin Result := 0; end; end; function DataParaTexto(pData: TDate): string; begin if pData > 0 then Result := FormatDateTime('YYYY-MM-DD', pData) else Result := '0000-00-00'; end; function DateToSQL(pDate: TDateTime; pComAspas: Boolean = True; pComHoras: Boolean = True): string; var ano, mes, dia, Hora, Minuto, Segundo, MileSegundo: word; begin Decodedate(pDate, ano, mes, dia); Result := IntToStr(ano) + '-' + IntToStr(mes) + '-' + IntToStr(dia); DecodeTime(pDate, Hora, Minuto, Segundo, MileSegundo); if ((Hora + Minuto + Segundo) > 0) and (pComHoras) then begin Result := Result + ' ' + IntToStr(Hora) + ':' + IntToStr(Minuto) + ':' + IntToStr(Segundo); end; if pComAspas then begin Result := QuotedStr(Result); end; end; function DatesToSQL(pDataInicial, pDataFinal: TDateTime; pCondicao: string; pIncluirHora: Boolean): string; begin if (pDataInicial > 0) and (pDataFinal > 0) then begin if pIncluirHora then begin Result := pCondicao + ' BETWEEN ' + QuotedStr(DateToSQL(pDataInicial, False, False) + ' 00:00:00') + ' AND ' + QuotedStr(DateToSQL(pDataFinal, False, False) + ' 23:59:59'); end else begin Result := pCondicao + ' BETWEEN ' + DateToSQL(pDataInicial, True, False) + ' AND ' + DateToSQL(pDataFinal, True, False); end; end else if (pDataInicial > 0) and (pDataFinal = 0) then Result := pCondicao + ' >= ' + DateToSQL(pDataInicial, True, False) else if (pDataInicial = 0) and (pDataFinal > 0) then begin if pIncluirHora then begin Result := pCondicao + ' <= ' + QuotedStr(DateToSQL(pDataFinal, False, False) + ' 23:59:59'); end else begin Result := pCondicao + ' <= ' + DateToSQL(pDataFinal, True, False); end; end else Result := ''; end; // função auxiliar para converte UF do cliente para codigo function UFToInt(pUF: String): integer; begin Result := 0; if pUF = 'RO' then Result := 11; if pUF = 'AC' then Result := 12; if pUF = 'AM' then Result := 13; if pUF = 'RR' then Result := 14; if pUF = 'PA' then Result := 15; if pUF = 'AP' then Result := 16; if pUF = 'TO' then Result := 17; if pUF = 'MA' then Result := 21; if pUF = 'PI' then Result := 22; if pUF = 'CE' then Result := 23; if pUF = 'RN' then Result := 24; if pUF = 'PB' then Result := 25; if pUF = 'PE' then Result := 26; if pUF = 'AL' then Result := 27; if pUF = 'SE' then Result := 28; if pUF = 'BA' then Result := 29; if pUF = 'MG' then Result := 31; if pUF = 'ES' then Result := 32; if pUF = 'RJ' then Result := 33; if pUF = 'SP' then Result := 35; if pUF = 'PR' then Result := 41; if pUF = 'SC' then Result := 42; if pUF = 'RS' then Result := 43; if pUF = 'MS' then Result := 50; if pUF = 'MT' then Result := 51; if pUF = 'GO' then Result := 52; if pUF = 'DF' then Result := 53; end; // função auxiliar para converte Codigo UF do cliente para UF function IntToUF(pUF: integer): String; begin Result := ''; if pUF = 11 then Result := 'RO'; if pUF = 12 then Result := 'AC'; if pUF = 13 then Result := 'AM'; if pUF = 14 then Result := 'RR'; if pUF = 15 then Result := 'PA'; if pUF = 16 then Result := 'AP'; if pUF = 17 then Result := 'TO'; if pUF = 21 then Result := 'MA'; if pUF = 22 then Result := 'PI'; if pUF = 23 then Result := 'CE'; if pUF = 24 then Result := 'RN'; if pUF = 25 then Result := 'PB'; if pUF = 26 then Result := 'PE'; if pUF = 27 then Result := 'AL'; if pUF = 28 then Result := 'SE'; if pUF = 29 then Result := 'BA'; if pUF = 31 then Result := 'MG'; if pUF = 32 then Result := 'ES'; if pUF = 33 then Result := 'RJ'; if pUF = 35 then Result := 'SP'; if pUF = 41 then Result := 'PR'; if pUF = 42 then Result := 'SC'; if pUF = 43 then Result := 'RS'; if pUF = 50 then Result := 'MS'; if pUF = 51 then Result := 'MT'; if pUF = 52 then Result := 'GO'; if pUF = 53 then Result := 'DF'; end; function VerificaInteiro(Value: String): Boolean; var i: integer; begin Result := False; for i := 0 to 9 do begin if Pos(IntToStr(i), Value) <> 0 then begin Result := True; exit; end; end; end; function FileSize(FileName: string): Int64; var SearchRec: TSearchRec; begin if FindFirst(FileName, faAnyFile, SearchRec) = 0 then // se achou o arquivo // SearchRec.Size funciona legal para arquivos menores que 2GB Result := Int64(SearchRec.FindData.nFileSizeHigh) shl Int64(32) + // calcula o tamanho Int64(SearchRec.FindData.nFileSizeLow) else Result := 0; // FindClose(SearchRec); // fecha end; function Codifica(Action, Src: String): String; Label Fim; //Função para criptografar e descriptografar string's var KeyLen : Integer; KeyPos : Integer; OffSet : Integer; Dest, Key : String; SrcPos : Integer; SrcAsc : Integer; TmpSrcAsc : Integer; Range : Integer; begin try if (Src = '') Then begin Result:= ''; Goto Fim; end; Key := 'YUQL23KL23DF90WI5E1JAS467NMCXXL6JAOAUWWMCL0AOMM4A4VZYW9KHJUI2347EJHJKDF3424SKL K3LAKDJSL9RTIKJ'; Dest := ''; KeyLen := Length(Key); KeyPos := 0; SrcPos := 0; SrcAsc := 0; Range := 256; if (Action = UpperCase('C')) then begin Randomize; OffSet := Random(Range); Dest := Format('%1.2x',[OffSet]); for SrcPos := 1 to Length(Src) do begin Application.ProcessMessages; SrcAsc := (Ord(Src[SrcPos]) + OffSet) Mod 255; if KeyPos < KeyLen then KeyPos := KeyPos + 1 else KeyPos := 1; SrcAsc := SrcAsc Xor Ord(Key[KeyPos]); Dest := Dest + Format('%1.2x',[SrcAsc]); OffSet := SrcAsc; end; end Else if (Action = UpperCase('D')) then begin OffSet := StrToInt('$'+ copy(Src,1,2)); SrcPos := 3; repeat SrcAsc := StrToInt('$'+ copy(Src,SrcPos,2)); if (KeyPos < KeyLen) Then KeyPos := KeyPos + 1 else KeyPos := 1; TmpSrcAsc := SrcAsc Xor Ord(Key[KeyPos]); if TmpSrcAsc <= OffSet then TmpSrcAsc := 255 + TmpSrcAsc - OffSet else TmpSrcAsc := TmpSrcAsc - OffSet; Dest := Dest + Chr(TmpSrcAsc); OffSet := SrcAsc; SrcPos := SrcPos + 2; until (SrcPos >= Length(Src)); end; Result:= Dest; Fim: Except Result:= '1'; end; end; function PeriodoAnterior(pMesAno: String): String; var Mes, Ano: Integer; begin Mes := StrToInt(Copy(pMesAno, 1, 2)); Ano := StrToInt(Copy(pMesAno, 4, 4)); if Mes = 1 then begin Mes := 12; Ano := Ano - 1; Result := IntToStr(Mes) + '/' + IntToStr(Ano); end else Result := StringOfChar('0', 2 - Length(IntToStr(Mes - 1))) + IntToStr(Mes - 1) + '/' + IntToStr(Ano); end; function PeriodoPosterior(pMesAno: String): String; var Mes, Ano: Integer; begin Mes := StrToInt(Copy(pMesAno, 1, 2)); Ano := StrToInt(Copy(pMesAno, 4, 4)); if Mes = 12 then begin Mes := 1; Ano := Ano + 1; Result := IntToStr(Mes) + '/' + IntToStr(Ano); end else Result := StringOfChar('0', 2 - Length(IntToStr(Mes + 1))) + IntToStr(Mes + 1) + '/' + IntToStr(Ano); end; function RetiraMascara(Texto: String): String; begin Result := Texto; Result := StringReplace(Result,'*','',[rfReplaceAll]); Result := StringReplace(Result,'.','',[rfReplaceAll]); Result := StringReplace(Result,'-','',[rfReplaceAll]); Result := StringReplace(Result,'/','',[rfReplaceAll]); Result := StringReplace(Result,'\','',[rfReplaceAll]); end; function PegarPlanoPdv(DescricaoProduto: string): string; begin if ContainsText(DescricaoProduto, 'Mensal') then Result := 'M' else if ContainsText(DescricaoProduto, 'Semestral') then Result := 'S' else if ContainsText(DescricaoProduto, 'Anual') then Result := 'A'; end; function PegarModuloFiscalPdv(DescricaoProduto: string): string; begin if ContainsText(DescricaoProduto, 'NFC') then Result := 'NFC' else if ContainsText(DescricaoProduto, 'SAT') then Result := 'SAT' else if ContainsText(DescricaoProduto, 'MFE') then Result := 'MFE'; end; function ExecAndWait(ExeNameAndParams: string; ncmdShow: Integer = SW_SHOWNORMAL): Integer; var StartupInfo: TStartupInfo; ProcessInformation: TProcessInformation; Res: Bool; lpExitCode: DWORD; begin with StartupInfo do //you can play with this structure begin cb := SizeOf(TStartupInfo); lpReserved := nil; lpDesktop := nil; lpTitle := nil; dwFlags := STARTF_USESHOWWINDOW; wShowWindow := ncmdShow; cbReserved2 := 0; lpReserved2 := nil; end; Res := CreateProcess(nil, PChar(ExeNameAndParams), nil, nil, True, CREATE_DEFAULT_ERROR_MODE or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInformation); while True do begin GetExitCodeProcess(ProcessInformation.hProcess, lpExitCode); if lpExitCode <> STILL_ACTIVE then Break; Application.ProcessMessages; end; Result := Integer(lpExitCode); end; function KillTask(ExeFileName: string): Integer; const PROCESS_TERMINATE = $0001; var ContinueLoop: BOOL; FSnapshotHandle: THandle; FProcessEntry32: TProcessEntry32; begin Result := 0; FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); FProcessEntry32.dwSize := SizeOf(FProcessEntry32); ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32); while Integer(ContinueLoop) <> 0 do begin if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName))) then Result := Integer(TerminateProcess( OpenProcess(PROCESS_TERMINATE, BOOL(0), FProcessEntry32.th32ProcessID), 0)); ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32); end; CloseHandle(FSnapshotHandle); end; procedure DecodeFileBase64(const base64: AnsiString; const FileName: string); var stream: TBytesStream; begin stream := TBytesStream.Create(DecodeBase64(base64)); try stream.SaveToFile(Filename); finally stream.Free; end; end; end.
unit PasPlayerListProcessor; interface uses PasRequestProcessor, IdCustomHTTPServer, System.SysUtils, System.Classes; type TPlayerListProcessor = class(TRequestProcessor) protected function innerRequested(requestUri: string; requestAction: string) : Boolean; override; function onGet(requestInfo: TIdHTTPRequestInfo; responseInfo: TIdHTTPResponseInfo): Boolean; override; end; implementation uses PasMessagerHelper, PasLibVlcPlayerUnit, PasLibVlcClassUnit, System.JSON, PasLibVlcUserData, PasLibVlcUnit; function TPlayerListProcessor.innerRequested(requestUri: string; requestAction: string): Boolean; begin Result := 'showList'.Equals(requestAction); end; function TPlayerListProcessor.onGet(requestInfo: TIdHTTPRequestInfo; responseInfo: TIdHTTPResponseInfo): Boolean; var playerList: TPasLibVlcMediaList; media: TPasLibVlcMedia; userData: TLibVlcUserData; returnValue: Cardinal; step: Integer; jsonResult: TJSONArray; jsonElement: TJSONObject; begin returnValue := TMessagerHelper.sendMessage(FM_LIST, 0); if returnValue > 0 then begin playerList := Pointer(returnValue); jsonResult := TJSONArray.Create; jsonElement := TJSONObject.Create; for step := 0 to playerList.Count - 1 do begin media := playerList.GetMedia(step); userData := media.GetUserData; jsonElement.AddPair('id', TJSONNumber.Create(step)); jsonElement.AddPair('title', userData.Title); jsonElement.AddPair('playstatus', TJSONNumber.Create(userData.PlayStatus)); jsonResult.AddElement(jsonElement); media.Free; end; responseInfo.ContentText := jsonResult.ToJSON; jsonElement.Free; jsonResult.Free; end; responseInfo.ContentType := 'application/json'; responseInfo.CharSet := 'utf-8'; end; end.
unit VirtualQueryExCache; { Caching system that could be useful in some slow lookup/emulation situations For windows there's no good way to 'cache' the VQE call, but on linux where normally the full /proc/pid/map file is parsed for every call this can speed things up considerably } {$mode objfpc}{$H+} interface uses {$ifdef JNI} Classes, SysUtils, ctypes,syncobjs, newkernelhandler, unixporthelper; {$else} {$ifdef darwin} macport, {$endif} {$ifdef windows} jwawindows, windows, {$endif} Classes, SysUtils, newkernelhandler, math; {$endif} type TVirtualQueryExCache=class private lastAccessed: integer; fhandle: THandle; regions: TList; //list of sorted TMEMORYBASICINFORMATION entries public function getRegion(BaseAddress: ptruint; out mbi: TMEMORYBASICINFORMATION): boolean; procedure AddRegion(mbi: TMemoryBasicInformation); constructor create(phandle: THandle); destructor destroy; override; property Handle: THandle read fHandle; end; implementation destructor TVirtualQueryExCache.destroy; begin if regions<>nil then freeandnil(regions); inherited destroy; end; constructor TVirtualQueryExCache.create(phandle: THandle); begin fhandle:=phandle; lastAccessed:=-1; regions:=tlist.create; end; function TVirtualQueryExCache.getRegion(BaseAddress: ptruint; out mbi: TMEMORYBASICINFORMATION): boolean; var i: integer; //usually vqe accesses are sequential so check the next one fist (if there is one) begin result:=false; if regions.count>0 then begin for i:=lastAccessed+1 to regions.count-1 do begin if BaseAddress<ptruint(PMEMORYBASICINFORMATION(regions[i])^.BaseAddress) then break; if BaseAddress>=ptruint(PMEMORYBASICINFORMATION(regions[i])^.BaseAddress) then begin if baseaddress<ptruint(PMEMORYBASICINFORMATION(regions[i])^.BaseAddress)+PMEMORYBASICINFORMATION(regions[i])^.RegionSize then begin mbi:=PMEMORYBASICINFORMATION(regions[i])^; mbi.BaseAddress:=pointer(ptruint(baseaddress) and qword($fffffffffffff000)); result:=true; lastAccessed:=i; exit; end; end; end; if lastAccessed<>-1 then begin for i:=lastAccessed downto 0 do begin if BaseAddress>ptruint(PMEMORYBASICINFORMATION(regions[i])^.BaseAddress)+PMEMORYBASICINFORMATION(regions[i])^.RegionSize then break; //won't be found if BaseAddress>=ptruint(PMEMORYBASICINFORMATION(regions[i])^.BaseAddress) then begin if baseaddress<ptruint(PMEMORYBASICINFORMATION(regions[i])^.BaseAddress)+PMEMORYBASICINFORMATION(regions[i])^.RegionSize then begin mbi:=PMEMORYBASICINFORMATION(regions[i])^; mbi.BaseAddress:=pointer(ptruint(baseaddress) and qword($fffffffffffff000)); result:=true; lastAccessed:=i; exit; end; end; end; end; //fallback... find the closest region (should not happen when properly implemented) for i:=regions.count-1 downto 0 do begin if baseaddress>ptruint(PMEMORYBASICINFORMATION(regions[i])^.BaseAddress) then begin mbi:=PMEMORYBASICINFORMATION(regions[i])^; if baseaddress>ptruint(mbi.BaseAddress)+mbi.RegionSize then begin //overshot it. That means it's not in the list if i=regions.count-1 then //the last item in the list was too small. Mark it as the end exit; mbi.BaseAddress:=pointer(ptruint(baseaddress) and qword($fffffffffffff000)); if i>0 then mbi.AllocationBase:=pointer(ptruint(PMEMORYBASICINFORMATION(regions[i-1])^.BaseAddress)+PMEMORYBASICINFORMATION(regions[i-1])^.RegionSize) else mbi.AllocationBase:=nil; if i<regions.count-1 then begin mbi.RegionSize:=ptruint(PMEMORYBASICINFORMATION(regions[i])^.BaseAddress)-ptruint(mbi.BaseAddress); result:=true; end; exit; end else begin mbi.BaseAddress:=pointer(ptruint(baseaddress) and qword($fffffffffffff000)); result:=true; lastAccessed:=i; exit; end; end; end; end; end; procedure TVirtualQueryExCache.AddRegion(mbi: TMemoryBasicInformation); var p: PMEMORYBASICINFORMATION; i: integer; begin getmem(p, sizeof(TMemoryBasicInformation)); p^:=mbi; if (regions.Count>0) and (ptruint(PMEMORYBASICINFORMATION(regions[regions.count-1])^.BaseAddress)>ptruint(mbi.BaseAddress)) then begin //this should never happen // freemem(p); raise exception.create('AddRegion called with an region bigger than the previously added region'); //but just in case add some support for i:=0 to regions.count-1 do if ptruint(PMEMORYBASICINFORMATION(regions[regions.count-1])^.BaseAddress)>ptruint(mbi.BaseAddress) then begin regions.Insert(i,p); exit; end; end else regions.add(p); end; end.
{********************************************************} { } { Zeos Database Objects } { DB2 Query and Table components } { } { Copyright (c) 1999-2001 Sergey Seroukhov } { Copyright (c) 1999-2002 Zeos Development Group } { } {********************************************************} unit ZDb2SqlQuery; interface {$R *.dcr} uses SysUtils, Windows, Db, Classes, ZDirSql, ZDirDb2Sql, DbCommon, ZDb2SqlCon, ZDb2SqlTr, ZToken, ZLibDb2Sql, ZSqlExtra, ZQuery, ZSqlTypes, ZSqlItems, ZSqlBuffer; {$INCLUDE ..\Zeos.inc} type TZDb2SqlOption = (doStoreResult); TZDb2SqlOptions = set of TZDb2SqlOption; { Direct Oracle8 dataset with descendant of TZDataSet } TZCustomDb2SqlDataset = class(TZDataSet) private FExtraOptions: TZDb2SqlOptions; FUseConnect: TDirDb2SqlConnect; FUseTransact: TDirDb2SqlTransact; procedure SetDatabase(Value: TZDb2SqlDatabase); procedure SetTransact(Value: TZDb2SqlTransact); function GetDatabase: TZDb2SqlDatabase; function GetTransact: TZDb2SqlTransact; protected { Overriding ZDataset methods } procedure QueryRecord; override; function GetIdentityField(Table: string): Integer; procedure UpdateAfterPost(OldData, NewData: PRecordData); override; procedure UpdateAfterInit(RecordData: PRecordData); override; {$IFDEF WITH_IPROVIDER} { IProvider support } function PSInTransaction: Boolean; override; function PSExecuteStatement(const ASql: string; AParams: TParams; ResultSet: Pointer): Integer; override; procedure PSSetCommandText(const CommandText: string); override; {$ENDIF} procedure InternalClose; override; procedure CreateConnections; override; public constructor Create(AOwner: TComponent); override; procedure AddTableFields(Table: string; SqlFields: TSqlFields); override; procedure AddTableIndices(Table: string; SqlFields: TSqlFields; SqlIndices: TSqlIndices); override; function FieldValueToSql(Value: string; FieldDesc: PFieldDesc): string; override; published // property ExtraOptions: TZDb2SqlOptions read FExtraOptions write FExtraOptions; property Database: TZDb2SqlDatabase read GetDatabase write SetDatabase; property Transaction: TZDb2SqlTransact read GetTransact write SetTransact; end; { Direct Db2Sql query with descendant of TDataSet } TZDb2SqlQuery = class(TZCustomDb2SqlDataset) public property MacroCount; property ParamCount; published property MacroChar; property Macros; property MacroCheck; property Params; property ParamCheck; property DataSource; property Sql; property RequestLive; property Database; property Transaction; property Active; end; { Direct Db2Sql query with descendant of TDataSet } TZDb2SqlTable = class(TZCustomDb2SqlDataset) public constructor Create(AOwner: TComponent); override; published property TableName; property ReadOnly default False; property DefaultIndex default True; property Database; property Transaction; property Active; end; implementation uses ZExtra, ZDBaseConst, ZBlobStream, Math; {********** TZCustomDb2SqlDataset implementation **********} { Class constructor } constructor TZCustomDb2SqlDataset.Create(AOwner: TComponent); begin inherited Create(AOwner); Query := TDirDb2SqlQuery.Create(nil, nil); DatabaseType := dtDb2; FExtraOptions := [{doStoreResult}]; FUseConnect := TDirDb2SqlConnect.Create; FUseTransact := TDirDb2SqlTransact.Create(FUseConnect); end; { Set connect to database component } procedure TZCustomDb2SqlDataset.SetDatabase(Value: TZDb2SqlDatabase); begin inherited SetDatabase(Value); end; { Set connect to transact-server component } procedure TZCustomDb2SqlDataset.SetTransact(Value: TZDb2SqlTransact); begin inherited SetTransact(Value); end; { Get connect to database component } function TZCustomDb2SqlDataset.GetDatabase: TZDb2SqlDatabase; begin Result := TZDb2SqlDatabase(DatabaseObj); end; { Get connect to transact-server component } function TZCustomDb2SqlDataset.GetTransact: TZDb2SqlTransact; begin Result := TZDb2SqlTransact(TransactObj); end; { Read query from server to internal buffer } procedure TZCustomDb2SqlDataset.QueryRecord; var I, Count: Integer; RecordData: PRecordData; FieldDesc: PFieldDesc; TempLong: LongInt; TempDate: PSQL_DATE_STRUCT; TempTime: PSQL_TIME_STRUCT; TempDateTime: PSQL_TIMESTAMP_STRUCT; TempTime1: TDateTime; TimeStamp: TTimeStamp; BlobPtr: PRecordBlob; // Status: Integer; Cancel: Boolean; begin Count := SqlBuffer.Count; while not Query.EOF and (Count = SqlBuffer.Count) do begin { Go to the record } if SqlBuffer.FillCount > 0 then Query.Next; { Invoke OnProgress event } if Assigned(OnProgress) then begin Cancel := False; OnProgress(Self, psRunning, ppFetching, Query.RecNo+1, MaxIntValue([Query.RecNo+1, Query.RecordCount]), Cancel); if Cancel then Query.Close; end; if Query.EOF then Break; { Getting record } RecordData := SqlBuffer.Add; for I := 0 to SqlBuffer.SqlFields.Count - 1 do begin FieldDesc := SqlBuffer.SqlFields[I]; if FieldDesc.FieldNo < 0 then Continue; if Query.FieldIsNull(FieldDesc.FieldNo) and not (FieldDesc.FieldType in [ftBlob, ftMemo]) then Continue; case FieldDesc.FieldType of ftString: begin SqlBuffer.SetFieldDataLen(FieldDesc, Query.FieldBuffer(FieldDesc.FieldNo), RecordData, Query.FieldSize(FieldDesc.FieldNo)); end; ftInteger, ftFloat {$IFNDEF VER100}, ftLargeInt {$ENDIF}: SqlBuffer.SetFieldData(FieldDesc, Query.FieldBuffer(FieldDesc.FieldNo), RecordData); ftDateTime: begin TempDateTime := PSQL_TIMESTAMP_STRUCT(Query.FieldBuffer(FieldDesc.FieldNo)); TimeStamp := DateTimeToTimeStamp(EncodeDate(TempDateTime.year, TempDateTime.month, TempDateTime.day) + EncodeTime( TempDateTime.hour, TempDateTime.minute, TempDateTime.second, 0)); TempTime1 := TimeStampToMSecs(TimeStamp); SqlBuffer.SetFieldData(FieldDesc, @TempTime1, RecordData); end; ftDate: begin TempDate := PSQL_DATE_STRUCT(Query.FieldBuffer(FieldDesc.FieldNo)); TempLong := DateTimeToTimeStamp(EncodeDate(TempDate.year, TempDate.month, TempDate.day)).Date; SqlBuffer.SetFieldData(FieldDesc, @TempLong, RecordData); end; ftTime: begin TempTime := PSQL_TIME_STRUCT(Query.FieldBuffer(FieldDesc.FieldNo)); TempLong := DateTimeToTimeStamp(EncodeTime(TempTime.hour, TempTime.minute, TempTime.second, 0)).Time; SqlBuffer.SetFieldData(FieldDesc, @TempLong, RecordData); end; ftMemo, ftBlob: begin { Process blob and memo fields } BlobPtr := PRecordBlob(@RecordData.Bytes[FieldDesc.Offset+1]); if (Query.FieldType(FieldDesc.FieldNo) <> SQL_LONGVARCHAR) and (Query.FieldType(FieldDesc.FieldNo) <> SQL_WLONGVARCHAR) then begin BlobPtr.Handle.Ptr := 0; BlobPtr.Handle.PtrEx := TDirDb2SqlQuery(Query).FieldTypeCode( FieldDesc.FieldNo) + 1000; BlobPtr.Size := 0; BlobPtr.Data := nil; BlobPtr.BlobType := btExternal; if not Query.FieldIsNull(FieldDesc.FieldNo) then begin RecordData.Bytes[FieldDesc.Offset] := 0; BlobPtr.Handle.Ptr := PInteger(Query.FieldBuffer(FieldDesc.FieldNo))^; end; end else begin BlobPtr.BlobType := btInternal; { Fill not null fields } if not Query.FieldIsNull(FieldDesc.FieldNo) then begin RecordData.Bytes[FieldDesc.Offset] := 0; BlobPtr.Size := Query.FieldSize(FieldDesc.FieldNo); BlobPtr.Data := AllocMem(BlobPtr.Size); System.Move(PChar(ConvertFromSqlEnc(Query.Field(FieldDesc.FieldNo)))^, BlobPtr.Data^, BlobPtr.Size) end { Fill null fields } else begin BlobPtr.Size := 0; BlobPtr.Data := nil; end; end; end; else DatabaseError(SUnknownType + FieldDesc.Alias); end; end; { Filter received record } SqlBuffer.FilterItem(SqlBuffer.Count-1); end; end; { Internal close query } procedure TZCustomDb2SqlDataset.InternalClose; begin inherited InternalClose; { Close lowerlevel connect to database } FUseTransact.Close; FUseConnect.Disconnect; end; {************** Sql-queries processing ******************} { Fill collection with fields } procedure TZCustomDb2SqlDataset.AddTableFields(Table: string; SqlFields: TSqlFields); var Size: Integer; Decimals: Integer; FieldType: TFieldType; Query: TDirDb2SqlQuery; Default: string; BlobType: TBlobType; AutoType: TAutoType; begin Query := TDirDb2SqlQuery(Transaction.QueryHandle); Query.ShowColumns(Table, ''); while not Query.EOF do begin { Evalute field parameters } Size := StrToIntDef(Query.Field(3), 0); Decimals := StrToIntDef(Query.Field(6), 0); FieldType := Db2SqlToDelphiType(Query.Field(2), Size, Decimals, BlobType); if FieldType <> ftString then Size := 0; Default := Query.Field(5); if Query.Field(7) = 'Y' then AutoType := atIdentity else if Trim(Query.Field(8)) <> '' then AutoType := atGenerated else AutoType := atNone; { Put new field description } SqlFields.Add(Table, Query.Field(1), '', Query.Field(2), FieldType, Size, Decimals, AutoType, Query.Field(4) = 'Y', False, Default, BlobType); Query.Next; end; Query.Close; end; { Fill collection with indices } procedure TZCustomDb2SqlDataset.AddTableIndices(Table: string; SqlFields: TSqlFields; SqlIndices: TSqlIndices); var KeyType: TKeyType; SortType: TSortType; Query: TDirDb2SqlQuery; begin Query := TDirDb2SqlQuery(TransactObj.QueryHandle); Query.ShowIndexes(Table); while not Query.EOF do begin { Define a key type } if Query.Field(2) = 'P' then KeyType := ktPrimary else if Query.Field(2) = 'U' then KeyType := ktUnique else KeyType := ktIndex; { Define a sorting mode } if Query.Field(3) = 'D' then SortType := stDescending else SortType := stAscending; { Put new index description } SqlIndices.AddIndex(Query.Field(0), Table, Query.Field(4), KeyType, SortType); Query.Next; end; Query.Close; end; { Convert field value to sql value } function TZCustomDb2SqlDataset.FieldValueToSql(Value: string; FieldDesc: PFieldDesc): string; begin Result := inherited FieldValueToSql(Value, FieldDesc); if FieldDesc.FieldType = ftDateTime then Result := 'TIMESTAMP(' + Result + ')' else if FieldDesc.FieldType = ftDate then Result := 'DATE(' + Result + ')' else if FieldDesc.FieldType = ftTime then Result := 'TIME(' + Result + ')'; end; { Get identity field of table } function TZCustomDb2SqlDataset.GetIdentityField(Table: string): Integer; var I: Integer; FieldDesc: PFieldDesc; begin Result := -1; for I := 0 to SqlBuffer.SqlFields.Count-1 do begin FieldDesc := SqlBuffer.SqlFields[I]; if (FieldDesc.AutoType = atIdentity) and StrCaseCmp(FieldDesc.Table, Table) then begin Result := I; Exit; end; end; end; { Update record after post updates } procedure TZCustomDb2SqlDataset.UpdateAfterPost(OldData, NewData: PRecordData); var Index: Integer; FieldDesc: PFieldDesc; begin { Apply identity fields } Index := GetIdentityField(SqlParser.Tables[0]); if (OldData.RecordType = ztInserted) and (Index >= 0) then begin FieldDesc := SqlBuffer.SqlFields[Index]; if SqlBuffer.GetFieldNull(FieldDesc, NewData) then SqlBuffer.SetField(FieldDesc, EvaluteDef('IDENTITY_VAL_LOCAL()'), NewData); end; inherited UpdateAfterPost(OldData, NewData); end; { Update record after initialization } procedure TZCustomDb2SqlDataset.UpdateAfterInit(RecordData: PRecordData); var I: Integer; FieldDesc: PFieldDesc; RecordBlob: PRecordBlob; begin inherited UpdateAfterInit(RecordData); { Correct blobs description } for I := 0 to SqlBuffer.SqlFields.Count-1 do begin FieldDesc := SqlBuffer.SqlFields[I]; if FieldDesc.FieldType in [ftBlob, ftMemo, ftGraphic, ftFmtMemo] then begin RecordBlob := PRecordBlob(@RecordData.Bytes[FieldDesc.Offset+1]); RecordBlob.BlobType := btExternal; RecordBlob.Handle.PtrEx := TDirDb2SqlQuery(Query).FieldTypeCode( FieldDesc.FieldNo) + 1000; end; end; end; { Create demanded connections } procedure TZCustomDb2SqlDataset.CreateConnections; begin { Check database and transaction object } if not Assigned(DatabaseObj) then DatabaseError(SConnectNotDefined); if not Assigned(TransactObj) then DatabaseError(STransactNotDefined); { Connect to transact-server } TransactObj.Connect; if not TransactObj.Connected then DatabaseError(SConnectTransactError); { Define database connect by open mode } if doStoreResult in FExtraOptions then begin Query.Connect := DatabaseObj.Handle; Query.Transact := TransactObj.Handle; // FetchAll := True; end else begin { Attach to database } FUseConnect.HostName := DatabaseObj.Handle.HostName; FUseConnect.Port := DatabaseObj.Handle.Port; FUseConnect.Database := DatabaseObj.Handle.Database; FUseConnect.Login := DatabaseObj.Handle.Login; FUseConnect.Passwd := DatabaseObj.Handle.Passwd; FUseConnect.Connect; if not FUseConnect.Active then DatabaseError(SConnectError); { Attach to database } FUseTransact.TransIsolation := TDirDb2SqlTransact(TransactObj.Handle).TransIsolation; FUseTransact.TransactSafe := TransactObj.Handle.TransactSafe; FUseTransact.Open; if not FUseTransact.Active then DatabaseError(SConnectError); { Assign new connect } Query.Connect := FUseConnect; Query.Transact := FUseTransact; // FetchAll := False; end; end; {$IFDEF WITH_IPROVIDER} { IProvider support } { Is in transaction } function TZCustomDb2SqlDataset.PSInTransaction: Boolean; begin Result := True; end; { Execute an sql statement } function TZCustomDb2SqlDataset.PSExecuteStatement(const ASql: string; AParams: TParams; ResultSet: Pointer): Integer; begin if Assigned(ResultSet) then begin TDataSet(ResultSet^) := TZDb2SqlQuery.Create(nil); with TZDb2SqlQuery(ResultSet^) do begin Sql.Text := ASql; Params.Assign(AParams); Open; Result := RowsAffected; end; end else Result := TransactObj.ExecSql(ASql); end; { Set command query } procedure TZCustomDb2SqlDataset.PSSetCommandText(const CommandText: string); begin Close; if Self is TZDb2SqlQuery then TZDb2SqlQuery(Self).Sql.Text := CommandText else if Self is TZDb2SqlTable then TZDb2SqlQuery(Self).TableName := CommandText; end; {$ENDIF} { TZDb2SqlTable } constructor TZDb2SqlTable.Create(AOwner: TComponent); begin inherited Create(AOwner); DefaultIndex := True; ReadOnly := False; end; end.
unit uUsuario; interface uses Classes, SysUtils, Variants; type TUsuario = class private Idusuario: Integer; Usuario: String; Login: String; Senha: String; Idacesso: Integer; Acesso: String; Ativo: Integer; Uscadast: String; Dtcadast: TDateTime; Usmodifi: String; Dtmodifi: TDateTime; public procedure setIdusuario(Value: Integer); procedure setUsuario(Value: String); procedure setLogin(Value: String); procedure setSenha(Value: String); procedure setIdacesso(Value: Integer); procedure setAcesso(Value: String); procedure setAtivo(Value: Integer); procedure setUscadast(Value: String); procedure setDtcadast(Value: TDateTime); procedure setUsmodifi(Value: String); procedure setDtmodifi(Value: TDateTime); function getIdusuario: Integer; function getUsuario: String; function getLogin: String; function getSenha: String; function getIdacesso: Integer; function getAcesso: String; function getAtivo: Integer; function getUscadast: String; function getDtcadast: TDateTime; function getUsmodifi: String; function getDtmodifi: TDateTime; // property Idusuario: Integer read getIdusuario write setIdusuario; // property Usuario: String read getUsuario write setUsuario; // property Login: String read getLogin write setLogin; // property Senha: String read getSenha write setSenha; // property Idacesso: Integer read getIdacesso write setIdacesso; // property Acesso: String read getAcesso write setAcesso; // property Ativo: Integer read getAtivo write setAtivo; // property Uscadast: String read getUscadast write setUscadast; // property Dtcadast: TDateTime read getDtcadast write setDtcadast; // property Usmodifi: String read getUsmodifi write setUsmodifi; // property Dtmodifi: TDateTime read getDtmodifi write setDtmodifi; procedure setLogado(Value: TStringList); end; implementation { TUsuario } { get } function TUsuario.getIdusuario: Integer; begin Result := Idusuario; end; function TUsuario.getUsuario: String; begin Result := Usuario; end; function TUsuario.getLogin: String; begin Result := Login; end; function TUsuario.getSenha: String; begin Result := Senha; end; function TUsuario.getIdacesso: Integer; begin Result := Idacesso; end; function TUsuario.getAcesso: String; begin Result := Acesso; end; function TUsuario.getAtivo: Integer; begin Result := Ativo; end; function TUsuario.getUscadast: String; begin Result := Uscadast; end; function TUsuario.getDtcadast: TDateTime; begin Result := Dtcadast; end; function TUsuario.getUsmodifi: String; begin Result := Usmodifi; end; function TUsuario.getDtmodifi: TDateTime; begin Result := Dtmodifi; end; { set } procedure TUsuario.setIdusuario(Value: Integer); begin Idusuario := Value; end; procedure TUsuario.setUsuario(Value: String); begin Usuario := Value; end; procedure TUsuario.setLogin(Value: String); begin Login := Value; end; procedure TUsuario.setSenha(Value: String); begin Senha := Value; end; procedure TUsuario.setIdacesso(Value: Integer); begin Idacesso := Value; end; procedure TUsuario.setAcesso(Value: String); begin Acesso := Value; end; procedure TUsuario.setAtivo(Value: Integer); begin Ativo := Value; end; procedure TUsuario.setUscadast(Value: String); begin Uscadast := Value; end; procedure TUsuario.setDtcadast(Value: TDateTime); begin Dtcadast := Value; end; procedure TUsuario.setUsmodifi(Value: String); begin Usmodifi := Value; end; procedure TUsuario.setDtmodifi(Value: TDateTime); begin Dtmodifi := Value; end; procedure TUsuario.setLogado(Value: TStringList); begin if Value.Count > 0 then begin setIdusuario(StrToInt(Value[0])); //idusuario setUsuario(Value[1]); //usuario setLogin(Value[2]); //login setSenha(Value[3]); //senha setIdacesso(StrToInt(Value[4])); //idacesso setAcesso(Value[5]); //acesso setAtivo(StrToInt(Value[6])); //ativo setUscadast(Value[7]); //uscadast if Value[8] <> null then setDtcadast(StrToDateTime(Value[8])); //dtcadast setUsmodifi(Value[9]); //usmodifi if Value[10] <> null then setDtmodifi(StrToDateTime(Value[10])); //dtmodifi end else begin end; end; end.
unit Model.Entregadores; interface type TEntregadores = class private FCadastro: Integer; FEntregador: Integer; FFantasia: String; FAgente: Integer; FData: TDate; FChave: String; FGrupo: Integer; FVerba: Double; FExecutor: String; FManutencao: TDateTime; public property Cadastro: Integer read FCadastro write FCadastro; property Entregador: Integer read FEntregador write FEntregador; property Fantasia: String read FFantasia write FFantasia; property Agente: Integer read FAgente write FAgente; property Data: TDate read FData write FData; property Chave: String read FChave write FChave; property Grupo: Integer read FGrupo write FGrupo; property Verba: Double read FVerba write FVerba; property Executor: String read FExecutor write FExecutor; property Manutencao: TDateTime read FManutencao write FManutencao; constructor Create; overload; constructor Create(pFCadastro: Integer; pFEntregador: Integer; pFFantasia: String; pFAgente: Integer; pFData: TDate; pFChave: String; pFGrupo: Integer; pFVerba: Double; pFExecutor: String; pFManutencao: TDateTime); overload; end; implementation { TEntregadores } constructor TEntregadores.Create; begin inherited Create; end; constructor TEntregadores.Create(pFCadastro, pFEntregador: Integer; pFFantasia: String; pFAgente: Integer; pFData: TDate; pFChave: String; pFGrupo: Integer; pFVerba: Double; pFExecutor: String; pFManutencao: TDateTime); begin FCadastro := pFCadastro; FEntregador := pFEntregador; FFantasia := pFFantasia; FAgente := pFAgente; FData := pFData; FChave := pFChave; FGrupo := pFGrupo; FVerba := pFVerba; FExecutor := pFExecutor; FManutencao := pFManutencao; end; end.
object DmConsulta: TDmConsulta OldCreateOrder = False Height = 428 Width = 579 object QryCltaJogador: TFDQuery Connection = DataModuleConexao.FDConnection1 SQL.Strings = ( 'SELECT jogador.jog_numero,' ' jogador.pai_codigo,' ' pais.pai_nome,' ' jogador.clb_codigo,' ' clube.clb_nome,' ' jogador.jog_nome,' ' jogador.jog_posicao,' ' jogador.jog_idade,' ' jogador.jog_lado,' ' jogador.jog_titular,' ' jogador.jog_caracteristica' 'FROM jogador' 'INNER JOIN pais ON (jogador.pai_codigo = pais.pai_codigo)' 'INNER JOIN clube ON (jogador.clb_codigo = clube.clb_codigo)') Left = 48 Top = 40 object QryCltaJogadorJOG_NUMERO: TIntegerField FieldName = 'JOG_NUMERO' Origin = 'JOG_NUMERO' ProviderFlags = [pfInUpdate, pfInWhere, pfInKey] Required = True end object QryCltaJogadorPAI_CODIGO: TIntegerField FieldName = 'PAI_CODIGO' Origin = 'PAI_CODIGO' Required = True end object QryCltaJogadorPAI_NOME: TStringField AutoGenerateValue = arDefault FieldName = 'PAI_NOME' Origin = 'PAI_NOME' ProviderFlags = [] ReadOnly = True Size = 60 end object QryCltaJogadorCLB_CODIGO: TIntegerField FieldName = 'CLB_CODIGO' Origin = 'CLB_CODIGO' ProviderFlags = [pfInUpdate, pfInWhere, pfInKey] Required = True end object QryCltaJogadorCLB_NOME: TStringField AutoGenerateValue = arDefault FieldName = 'CLB_NOME' Origin = 'CLB_NOME' ProviderFlags = [] ReadOnly = True Size = 60 end object QryCltaJogadorJOG_NOME: TStringField FieldName = 'JOG_NOME' Origin = 'JOG_NOME' Required = True Size = 60 end object QryCltaJogadorJOG_POSICAO: TStringField FieldName = 'JOG_POSICAO' Origin = 'JOG_POSICAO' Required = True Size = 30 end object QryCltaJogadorJOG_IDADE: TIntegerField FieldName = 'JOG_IDADE' Origin = 'JOG_IDADE' Required = True end object QryCltaJogadorJOG_LADO: TStringField FieldName = 'JOG_LADO' Origin = 'JOG_LADO' Required = True FixedChar = True Size = 1 end object QryCltaJogadorJOG_TITULAR: TStringField FieldName = 'JOG_TITULAR' Origin = 'JOG_TITULAR' Required = True FixedChar = True Size = 1 end object QryCltaJogadorJOG_CARACTERISTICA: TStringField FieldName = 'JOG_CARACTERISTICA' Origin = 'JOG_CARACTERISTICA' Size = 100 end end object QryCltaTecnico: TFDQuery Connection = DataModuleConexao.FDConnection1 SQL.Strings = ( 'SELECT tecnico.tec_codigo,' ' tecnico.tec_nome,' #9' pais.pai_nome ' 'FROM tecnico' 'INNER JOIN pais ON (tecnico.pai_codigo = pais.pai_codigo)') Left = 144 Top = 40 object QryCltaTecnicoTEC_CODIGO: TIntegerField FieldName = 'TEC_CODIGO' Origin = 'TEC_CODIGO' ProviderFlags = [pfInUpdate, pfInWhere, pfInKey] Required = True end object QryCltaTecnicoTEC_NOME: TStringField FieldName = 'TEC_NOME' Origin = 'TEC_NOME' Required = True Size = 60 end object QryCltaTecnicoPAI_NOME: TStringField AutoGenerateValue = arDefault FieldName = 'PAI_NOME' Origin = 'PAI_NOME' ProviderFlags = [] ReadOnly = True Size = 60 end end object QryCltaClube: TFDQuery Connection = DataModuleConexao.FDConnection1 SQL.Strings = ( 'SELECT clube.clb_codigo,' ' clube.clb_nome,' ' clube.clb_estadio,' ' clube.clb_dtfundacao,' ' tatica.tat_esquema,' ' tecnico.tec_nome,' ' pais.pai_nome'#9' ' 'FROM clube' 'INNER JOIN tatica ON (clube.tat_codigo = tatica.tat_codigo)' 'INNER JOIN tecnico ON (clube.tec_codigo = tecnico.tec_codigo)' 'INNER JOIN pais ON (clube.pai_codigo = pais.pai_codigo)') Left = 240 Top = 40 object QryCltaClubeCLB_CODIGO: TIntegerField FieldName = 'CLB_CODIGO' Origin = 'CLB_CODIGO' ProviderFlags = [pfInUpdate, pfInWhere, pfInKey] Required = True end object QryCltaClubeCLB_NOME: TStringField FieldName = 'CLB_NOME' Origin = 'CLB_NOME' Required = True Size = 60 end object QryCltaClubeCLB_ESTADIO: TStringField FieldName = 'CLB_ESTADIO' Origin = 'CLB_ESTADIO' Size = 60 end object QryCltaClubeCLB_DTFUNDACAO: TDateField FieldName = 'CLB_DTFUNDACAO' Origin = 'CLB_DTFUNDACAO' end object QryCltaClubeTAT_ESQUEMA: TStringField AutoGenerateValue = arDefault FieldName = 'TAT_ESQUEMA' Origin = 'TAT_ESQUEMA' ProviderFlags = [] ReadOnly = True Size = 5 end object QryCltaClubeTEC_NOME: TStringField AutoGenerateValue = arDefault FieldName = 'TEC_NOME' Origin = 'TEC_NOME' ProviderFlags = [] ReadOnly = True Size = 60 end object QryCltaClubePAI_NOME: TStringField AutoGenerateValue = arDefault FieldName = 'PAI_NOME' Origin = 'PAI_NOME' ProviderFlags = [] ReadOnly = True Size = 60 end end object QryCltaTatica: TFDQuery Connection = DataModuleConexao.FDConnection1 SQL.Strings = ( 'SELECT tatica.tat_codigo,' #9' tatica.tat_descricao,' ' tatica.tat_esquema'#9' ' 'FROM tatica') Left = 352 Top = 40 object QryCltaTaticaTAT_CODIGO: TIntegerField FieldName = 'TAT_CODIGO' Origin = 'TAT_CODIGO' ProviderFlags = [pfInUpdate, pfInWhere, pfInKey] Required = True end object QryCltaTaticaTAT_DESCRICAO: TStringField FieldName = 'TAT_DESCRICAO' Origin = 'TAT_DESCRICAO' Required = True Size = 60 end object QryCltaTaticaTAT_ESQUEMA: TStringField FieldName = 'TAT_ESQUEMA' Origin = 'TAT_ESQUEMA' Required = True Size = 5 end end object QryCltaPais: TFDQuery Connection = DataModuleConexao.FDConnection1 SQL.Strings = ( 'SELECT pais.pai_codigo,' #9' pais.pai_nome ' 'FROM pais') Left = 456 Top = 40 object QryCltaPaisPAI_CODIGO: TIntegerField FieldName = 'PAI_CODIGO' Origin = 'PAI_CODIGO' ProviderFlags = [pfInUpdate, pfInWhere, pfInKey] Required = True end object QryCltaPaisPAI_NOME: TStringField FieldName = 'PAI_NOME' Origin = 'PAI_NOME' Required = True Size = 60 end end end
PROGRAM Encryption(INPUT, OUTPUT); {Переводит символы из INPUT в код согласно Chiper и печатает новые символы в OUTPUT} CONST MaxLen = 20; ErrorSymbol = '&'; TYPE Str = ARRAY [1 .. MaxLen] OF ' ' .. 'Z'; Chiper = ARRAY [' ' .. 'Z'] OF CHAR; VAR Msg: Str; Code: Chiper; I: 0 .. MaxLen; StrLen: 0 .. MaxLen; ValidCharSet: SET OF CHAR; //симол, у которого есть шифр PROCEDURE Initialize(VAR Code: Chiper); {Присвоить Code шифр замены} VAR ChiperFile: TEXT; Symbol, ChiperSymbol: CHAR; BEGIN {Initialize} ASSIGN(ChiperFile, 'ChiperFile.txt'); //файл формата 'Символ''Шифр' RESET(ChiperFile); WHILE NOT EOF(ChiperFile) DO BEGIN IF NOT EOLN(ChiperFile) THEN READ(ChiperFile, Symbol); //Читать символ IF NOT EOLN(ChiperFile) THEN READ(ChiperFile, ChiperSymbol); //Читать шифр ELSE ChiperSymbol = ErrorSymbol Code[Symbol] := ChiperSymbol; ValidCharSet := ValidCharSet + [Symbol]; READLN(ChiperFile) END END; {Initialize} PROCEDURE Encode(VAR S: Str; StrLen: INTEGER); {Выводит символы из Code, соответствующие символам из S} VAR Index: 1 .. MaxLen; BEGIN {Encode} FOR Index := 1 TO StrLen DO IF S[Index] IN ValidCharSet THEN WRITE(Code[S[Index]]) ELSE WRITE(S[Index]); WRITELN END; {Encode} BEGIN {Encryption} {Инициализировать Code} Initialize(Code); WHILE NOT EOF DO BEGIN {читать строку в Msg и распечатать ее} I := 0; WHILE NOT EOLN AND (I < MaxLen) DO BEGIN I := I + 1; READ(Msg[I]); WRITE(Msg[I]) END; READLN; WRITELN; StrLen := I; {распечатать кодированное сообщение} Encode(Msg, StrLen) END END. {Encryption}
{ Quicksort Pascal from RosettaCode.org } var X: array [0..99] of integer; procedure quicksort ( left, right : integer ); var i, j, tmp, pivot : integer; begin i := left; j := right; pivot := X[ (left + right) shr 1]; repeat while pivot > X[i] do inc(i); while pivot < X[j] do dec(j); if i <= j then begin tmp := X[i]; X[i] := X[j]; X[j] := tmp; dec(j); inc(i); end; until i > j; if left < j then quicksort(left, j); if i < right then quicksort(i, right); end; procedure print_array ( a : array of integer ); var array_length, i : integer; begin array_length := length(a); for i := 1 to array_length do write(a[i], ', '); writeln; end; procedure random_populate; var array_length, i, min, max : integer; begin randomize; min := 1; max := 1000; array_length := length(X); (* oops, global variable *) for i := 1 to array_length do X[i] := min + random(10000) mod max + 1; end; begin writeln('-- the randomized array is:'); random_populate; print_array(X); writeln('-- running quicksort & printing again'); quicksort(0, 50); print_array(X); end.
unit TeraWMSToolsDefs; {$writeableconst on} {$i ..\..\..\..\DebugConsts.inc} interface uses TeraWMSTools, capabilities_1_1_1, SysUtils, Classes, Contnrs, HTTPProd; type TServiceAlias = class Path : string; ExpandedPath : string; Description : string; DescriptionURL : string; end; TCapabilitiesProcessor = procedure(c : IXMLWMT_MS_CapabilitiesType); TWMSDispatcher = class; TDispatchRequest = procedure(var RequestInfo : TRequestInfo; Request : string) of object; TWMSGetCapabilitiesDispatcher = class function BuildCapabilities(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : WideString; virtual; function GetCapabilities(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : WideString; virtual; abstract; end; TWMSGetCapabilitiesModifier = class(TWMSGetCapabilitiesDispatcher) CapabilitiesProcessor : TCapabilitiesProcessor; function GetCapabilities(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : WideString; override; end; TWMSGetCapabilitiesFileReader = class(TWMSGetCapabilitiesDispatcher) function CapabilitiesFileName(Request: TRequestInfo) : string; virtual; abstract; function GetCapabilities(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : WideString; override; end; TGetMapDispatcher = class function GetMap(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : TStream; virtual; end; TWMSDispatcher = class private fParamNames : string; fRequestType : TRequestType; _PageProducer : TPageProducer; _ERRORMESSAGES : string; fPathInfo : string; fDescription : string; fCaption : string; fRelativeLink : string; fDescriptionFileName : string; fGetCapabilitiesDispatcher : TWMSGetCapabilitiesDispatcher; fGetMapDispatcher : TGetMapDispatcher; fOtherRequestDispatcher : TDispatchRequest; fDesciptionHTMLTagEvent : THTMLTagEvent; function GetPageProducer : TPageProducer; procedure DefaultPageProducerHTMLTag(Sender: TObject; Tag: TTag; const TagString: String; TagParams: TStrings; var ReplaceText: String); procedure SetParamNames(v : string); function GetDescription : string; procedure SetPathInfo(v : string); protected _Request : TRequestInfo; public property DesciptionHTMLTagEvent : THTMLTagEvent read fDesciptionHTMLTagEvent write fDesciptionHTMLTagEvent; property ParamNames : string read fParamNames write SetParamNames; property RelativeLink : string read fRelativeLink write fRelativeLink; property Description : string read GetDescription write fDescription; property Caption : string read fCaption write fCaption; property PathInfo : string read fPathInfo write SetPathInfo; property DescriptionFileName : string read fDescriptionFileName write fDescriptionFileName; property PageProducer : TPageProducer read GetPageProducer; property RequestType : TRequestType read fRequestType; property GetCapabilitiesDispatcher : TWMSGetCapabilitiesDispatcher read fGetCapabilitiesDispatcher write fGetCapabilitiesDispatcher; property GetMapDispatcher : TGetMapDispatcher read fGetMapDispatcher write fGetMapDispatcher; property OtherRequestDispatcher : TDispatchRequest read fOtherRequestDispatcher write fOtherRequestDispatcher; function KnowParam(ParamID : string) : boolean; constructor Create(aParamNames : string = ''); destructor Destroy; override; procedure DispatchRequest(var RequestInfo : TRequestInfo); virtual; procedure AddParamName(ParamName : string); procedure AddDataDirSupportParamName; end; TWMSDispatchers = class(TObjectList) private _DefaultDispatcher : TWMSDispatcher; function GetItem(i : integer) : TWMSDispatcher; procedure __DispatchRequestOld(RequestInfo : TRequestInfo); public property Item[i : integer] : TWMSDispatcher read GetItem; default; procedure DispatchRequest(RequestInfo : TRequestInfo); function Add : TWMSDispatcher; end; function ValueOfName(Request: TRequestInfo; aName : string) : string; overload; function IndexOfName(Request: TRequestInfo; aName : string) : integer; function BuildErrorStream(Request: TRequestInfo; Format : string; msg : string = '') : TStream; function ServiceAliases : TStrings; procedure CapabilitiesProcessor_RemoveUnknownFormats(c : IXMLWMT_MS_CapabilitiesType); far; const INFOPAGETEMPLATE_FILENAME = 'TeraWMSServices_InfoPageTemplate.htm'; SOURCEWMS_ID = 'SOURCEWMS'; PARAMNAMES_DELIMETER = ';'; function WMSDispatchers : TWMSDispatchers; implementation uses RegisterHandlers, WMSAggregationTools, WMSRasterProcessorDispatcher, XLSTransformationDispatcher, WMSGeoReference, WMSLayerMergeDispatcher, WMSMaskDefs, ShareTools, DataDirSupport, WebShare, Console, Graphics, Registry, Windows, ComObj, XMLIntf, StrUtils; const TERASTUDIO_KEY = 'SOFTWARE\GEOS_ACR\TERASTUDIO\'; IIS_TERA_PATH = 'IIS_TERA_PATH'; IIS_WEB_URL = 'IIS_WEB_URL'; _RegistryKeyFound : boolean = false; __ScriptURL : string = ''; __ServiceAliases : TStringList = nil; function TeraIISPath : string; const FirstRun : boolean = true; _Result : string = ''; var r : TRegistry; begin Result := ''; if FirstRun then begin r := TRegistry.Create; try r.RootKey := HKEY_LOCAL_MACHINE; _RegistryKeyFound := r.OpenKeyReadOnly(TERASTUDIO_KEY); if _RegistryKeyFound then Result := r.ReadString(IIS_TERA_PATH); _Result := Result; FirstRun := false; finally r.CloseKey; r.Free; end; end else Result := _Result; end; function TeraWebUrl : string; const FirstRun : boolean = true; _Result : string = ''; var r : TRegistry; begin Result := ''; if FirstRun then begin r := TRegistry.Create; try r.RootKey := HKEY_LOCAL_MACHINE; _RegistryKeyFound := r.OpenKeyReadOnly(TERASTUDIO_KEY); if _RegistryKeyFound then Result := r.ReadString(IIS_WEB_URL); _Result := Result; FirstRun := false; finally r.CloseKey; r.Free; end; end else Result := _Result; end; procedure CapabilitiesProcessor_RemoveUnknownFormats(c : IXMLWMT_MS_CapabilitiesType); far; var i : integer; begin for i := c.Capability.Request.GetMap.Format.Count - 1 downto 0 do if StrToStringIndex(c.Capability.Request.GetMap.Format[i], IMAGEFORMATCAPTIONS) = -1 then c.Capability.Request.GetMap.Format.Delete(i); end; function BuildErrorStream(Request: TRequestInfo; Format : string; msg : string = '') : TStream; var bmp : Graphics.TBitmap; i, y, dy : integer; begin Console.DisplayErrorMsg('Building an error graphic...'); Result := TMemoryStream.Create; bmp := BuildResponseBitmap(Request); try if Msg <> '' then begin bmp.TransparentColor := clWhite; bmp.Transparent := true; bmp.TransparentMode := tmAuto; bmp.Canvas.Brush.Color := clRed; bmp.Canvas.Font.Color := clBlack; bmp.Canvas.Font.Style := [fsBold]; bmp.Canvas.TextOut(bmp.Width - 5 - bmp.Canvas.TextWidth(Msg), bmp.Height - 5 - bmp.Canvas.TextHeight(Msg), Msg); dy := bmp.Canvas.TextHeight('X'); y := dy; if Console.ErrorsStrings <> nil then begin for i := 0 to Console.ErrorsStrings.Count - 1 do begin bmp.Canvas.TextOut(5, y, Console.ErrorsStrings.Strings[i]); y := y + dy; end; end; for i := 0 to Request.QueryFields.Count - 1 do begin bmp.Canvas.TextOut(5, y, Request.QueryFields[i]); y := y + dy; end; end; if Format = '' then Format := RequestToFormatStr(Request); Result.Free; Result := BMPtoWMSStream(bmp, Format); Result.Position := 0; finally bmp.Free; end; end; function IndexOfName(Request: TRequestInfo; aName : string) : integer; var i : integer; begin aName := UpperCase(aName); Result := -1; for i := 0 to Request.QueryFields.Count - 1 do if UpperCase(Request.QueryFields.Names[i]) = aName then begin Result := i; Exit; end; end; function ValueOfName(Request: TRequestInfo; aName : string) : string; overload; var i : integer; begin aName := UpperCase(aName); Result := ''; for i := 0 to Request.QueryFields.Count - 1 do if UpperCase(Request.QueryFields.Names[i]) = aName then begin Result := Request.QueryFields.ValueFromIndex[i]; Exit; end; end; // ************************************************************** // WMSDispatchers // ************************************************************** const __WMSDispatchers : TWMSDispatchers = nil; function WMSDispatchers : TWMSDispatchers; begin if __WMSDispatchers = nil then begin __WMSDispatchers := TWMSDispatchers.Create; with __WMSDispatchers.Add do begin Caption := 'Informace o službách'; DescriptionFileName := INFOPAGETEMPLATE_FILENAME; DesciptionHTMLTagEvent := DefaultPageProducerHTMLTag; end; end; Result := __WMSDispatchers; end; // ************************************************************** // TWMSGetCapabilitiesFileReader // ************************************************************** function TWMSGetCapabilitiesFileReader.GetCapabilities(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : WideString; begin Result := FileToStr(CapabilitiesFileName(RequestInfo)); RequestInfo.Handled := true; end; // ************************************************************** // TWMSGetCapabilitiesDispatcher // ************************************************************** function TWMSGetCapabilitiesDispatcher.BuildCapabilities; begin Result := GetCapabilities(Parent, RequestInfo); end; // ************************************************************** // TWMSDispatcher // ************************************************************** constructor TWMSDispatcher.Create; begin inherited Create; _PageProducer := nil; fPathInfo := ''; fRelativeLink :=''; fGetCapabilitiesDispatcher := nil; fOtherRequestDispatcher := nil; ParamNames := aParamNames; fDescriptionFileName := ''; end; procedure TWMSDispatcher.AddDataDirSupportParamName; begin DataDirSupport.AddDataDirSupportToParamNames(Self); end; procedure TWMSDispatcher.AddParamName(ParamName : string); begin if ParamName = '' then Exit; if ParamNames <> '' then ParamNames := ParamNames + PARAMNAMES_DELIMETER; ParamNames := ParamNames + ParamName; end; function TWMSDispatcher.GetDescription : string; var s : string; begin if DescriptionFileName = '' then Result := fDescription else begin GetPageProducer.HTMLFile := ExtractFilePath(ParamStr(0)) + '\WMSDesktop\' + DescriptionFileName; s := _PageProducer.Content; { s := FileToStr(ExtractFilePath(ParamStr(0)) + '\WMSDesktop\' + DescriptionFileName); } GetAndDeleteStrItem(s, '<body>'); // vymazeme vsechno pred body vcetne body Result := GetAndDeleteStrItem(s, '</body>'); // ziskame vsechno pred </body> end; end; procedure TWMSDispatcher.SetPathInfo(v : string); begin if (v <> '') and (v[1] = '/') then System.Delete(v, 1, 1); fPathInfo := v; end; procedure TWMSDispatcher.SetParamNames(v : string); begin fParamNames := UpperCase(v); end; function TWMSDispatcher.KnowParam(ParamID : string) : boolean; begin ParamID := UpperCase(ParamID) + ';'; Result := Pos(UpperCase(ParamID) + ';', ParamNames) > 0; end; destructor TWMSDispatcher.Destroy; begin _PageProducer.Free; fGetCapabilitiesDispatcher.Free; inherited; end; function TWMSDispatcher.GetPageProducer : TPageProducer; begin if _PageProducer = nil then begin _PageProducer := TPageProducer.Create(nil); _PageProducer.HTMLFile := BaseDataDir + DescriptionFileName; _PageProducer.OnHTMLTag := DesciptionHTMLTagEvent; { _PageProducer.HTMLFile := BaseDataDir + INFOPAGETEMPLATE_FILENAME; _PageProducer.OnHTMLTag := DefaultPageProducerHTMLTag; } end; Result := _PageProducer; end; procedure TWMSDispatcher.DefaultPageProducerHTMLTag(Sender: TObject; Tag: TTag; const TagString: String; TagParams: TStrings; var ReplaceText: String); var s : string; procedure AddNodeValue(Id, Value : string); begin if Value <> '' then s := s + Id + '=' + Value + '<br>'; end; var UpperS, PredA, PoA : string; d : TWMSDispatcher; i : integer; begin UpperS := UpperCase(TagString); if UpperS = 'SERVERBASEURL' then begin ReplaceText := _Request.WebServerHTTP; Exit; end; if UpperS = 'TERAWMSSERVER_CSS' then begin ReplaceText := '<style>' + FileToStr(BaseDataDir + 'TeraWMSServer.css') + '</style>'; Exit; end; if UpperS = 'TERAWEBURL' then begin ReplaceText := TeraWebUrl; Exit; end; if UpperS = 'REQUESTTOTABLE' then begin ReplaceText := _Request.RequestToTable; Exit; end; if UpperS = 'CONSOLELINES' then begin ReplaceText := ConsoleStringsToHTML(0, true, false); Exit; end; if UpperS = 'SERVICESLIST' then begin ReplaceText := '<table><tr><th>Path</th><th>Název</th><th>Popis</th></tr>'; for i := 0 to WMSDispatchers.Count - 1 do with WMSDispatchers[i] do begin if WMSDispatchers[i].RelativeLink = '' then begin PredA := ''; PoA := ''; end else begin PredA := '<a href="' + __ScriptURL + WMSDispatchers[i].RelativeLink + '">'; PoA := '</a>'; end; ReplaceText := Format('%s<tr><td>%s/%s%s</td><td>%s</td><td>%s</td></tr>', [ReplaceText, PredA, PathInfo, PoA, Caption, Description]); end; ReplaceText := ReplaceText + '</table>'; Exit; end; if UpperS = 'SERVICESTABS_LI' then begin s := ''; for i := 0 to WMSDispatchers.Count - 1 do if WMSDispatchers[i].PathInfo <> '' then begin s := s + Format('<li><a href="#servicetabs_%d">%s</a></li>', [i, WMSDispatchers[i].PathInfo]); end; ReplaceText := s; Exit; end; if UpperS = 'SERVICESTABS_DIVS' then begin s := ''; for i := 0 to WMSDispatchers.Count - 1 do if WMSDispatchers[i].PathInfo <> '' then begin d := WMSDispatchers[i]; s := s + Format('<div id="servicetabs_%d">', [i]); if d.Caption <> '' then s := s + '<h1>Služba ' + d.Caption + '</h1>'; if d.Description <> '' then s := s + '<p>' + d.Description + '<br>'; AddNodeValue('ParamNames', d.ParamNames); AddNodeValue('RelativeLink', d.RelativeLink); AddNodeValue('PathInfo', d.PathInfo); s := s + '</div>'; end; ReplaceText := s; Exit; end; if UpperS = 'ERRORMESSAGES' then begin ReplaceText := _ERRORMESSAGES; Exit; end; if UpperS = 'SERVICEALIASESLIST' then begin s := ''; for i := 0 to ServiceAliases.Count - 1 do begin s := Format('%s<p><a href="%s">%s</a>', [s, ServiceAliases.ValueFromIndex[i], ServiceAliases.Names[i]]); end; ReplaceText := s; Exit; end; end; procedure TWMSDispatcher.DispatchRequest(var RequestInfo : TRequestInfo); var s : TStream; sRequest : string; i, ErrorCount : integer; begin RequestInfo.Handled := false; if Console.ErrorsStrings <> nil then ErrorCount := Console.ErrorsStrings.Count; sRequest := RequestInfo.QueryFields.Values['REQUEST']; Console.DisplayWarningMsg('WMS parametr REQUEST je prázdný'); _Request := RequestInfo; __ScriptURL := RequestInfo.WebRequestToScriptURL; fRequestType := TRequestType(SafeStrToStringIndex(UpperCase(sRequest), RequestTypeCaptions)); case RequestType of rt_None: if Assigned(OtherRequestDispatcher) then begin OtherRequestDispatcher(RequestInfo, sRequest); end; rt_RebuildCapabilities, rt_BuildCapabilities: if Assigned(GetCapabilitiesDispatcher) then begin RequestInfo.Content := GetCapabilitiesDispatcher.BuildCapabilities(Self, RequestInfo); RequestInfo.ContentType := 'text/xml'; end; rt_GetCapabilities: if Assigned(GetCapabilitiesDispatcher) then begin RequestInfo.Content := GetCapabilitiesDispatcher.GetCapabilities(Self, RequestInfo); Console.DisplayDebugMsg('After GetCapabilitiesDispatcher.GetCapabilities'); RequestInfo.ContentType := 'text/xml'; end; rt_GetMap: if Assigned(GetMapDispatcher) then begin RequestInfo.ContentType := TeraWMSTools.qStr(RequestInfo.QueryFields, 'FORMAT', 'image/jpeg'); s := GetMapDispatcher.GetMap(Self, RequestInfo); s.Position := 0; RequestInfo.ContentStream := s; Console.DisplayDebugMsg('%d %d bytes', [Integer(RequestInfo.Handled), s.Size]); end; else Console.DisplayErrorMsg('Neznámy požadavek WMS ' + sRequest); end; if not RequestInfo.Handled then begin Console.DisplayDebugMsg('Not Handled : ' + RequestInfo.Content); if RequestInfo.Content <> '' then _ERRORMESSAGES := 'Errors: "' + RequestInfo.Content + '"<br><br>' else if PathInfo = '' then _ERRORMESSAGES := '' else _ERRORMESSAGES := '<br><br>Error:Nenalezen ovladač požadavku...<br><br>'; if (Console.ErrorsStrings <> nil) and (Console.ErrorsStrings.Count > ErrorCount) then begin for i := ErrorCount to Console.ErrorsStrings.Count - 1 do _ERRORMESSAGES := _ERRORMESSAGES + '<br>' + Console.ErrorsStrings[i]; end; RequestInfo.ContentType := 'text/html'; RequestInfo.Content := PageProducer.Content; RequestInfo.Handled := true; end; end; // ************************************************************** // TWMSDispatchers // ************************************************************** function TWMSDispatchers.GetItem(i : integer) : TWMSDispatcher; begin Result := pointer(Items[i]); end; function TWMSDispatchers.Add : TWMSDispatcher; begin Result := TWMSDispatcher.Create; inherited Add(Result); end; procedure TWMSDispatchers.DispatchRequest(RequestInfo : TRequestInfo); const PathDelimeter = '/'; var i : integer; ds : TWMSDispatcher; PathInfo, s : string; begin DefConsole.OpenSection('Dispatching request'); try DataDirSupport.ProcessRequest(RequestInfo.QueryFields); Console.DisplayDebugMsg('Searching for dispatcher'); PathInfo := UpperCase(RequestInfo.PathInfo); Console.DisplayMsg('PathInfo=' + PathInfo); for i := 0 to Count - 1 do begin ds := Item[i]; if ds.PathInfo = '' then _DefaultDispatcher := Item[i] else if AnsiStartsText(PathDelimeter + UpperCase(ds.PathInfo), PathInfo) then begin Console.DisplayMsg('Found handler:' + ds.Caption); ds.DispatchRequest(RequestInfo); Break; end; ds := nil; end; Console.DisplayDebugMsg('Dispatcher not found...'); if not RequestInfo.Handled and (_DefaultDispatcher <> nil) then _DefaultDispatcher.DispatchRequest(RequestInfo); finally if ds = nil then s := 'unassigned' else s := ds.Caption; DefConsole.CloseSection(Format('Handler:%s, Handled:%s, Content type:%s', [s, booltostr(RequestInfo.Handled), RequestInfo.ContentType])); end; end; procedure TWMSDispatchers.__DispatchRequestOld(RequestInfo : TRequestInfo); const PathDelimeter = '/'; var i : integer; ds : TWMSDispatcher; PathInfo, s : string; begin DefConsole.OpenSection('Dispatching request'); try DataDirSupport.ProcessRequest(RequestInfo.QueryFields); Console.DisplayDebugMsg('Searching for dispatcher'); PathInfo := RequestInfo.PathInfo; if PathInfo <> '' then begin i := 2; while (i < Length(PathInfo)) and (PathInfo[i] <> PathDelimeter) do Inc(i); if i < Length(PathInfo) then PathInfo := Copy(PathInfo, i, Length(PathInfo)); end; PathInfo := UpperCase(PathInfo); Console.DisplayMsg('PathInfo=' + PathInfo); for i := 0 to Count - 1 do begin ds := Item[i]; if ds.PathInfo = '' then _DefaultDispatcher := Item[i]; if AnsiEndsText(PathInfo, PathDelimeter + ds.PathInfo) then begin //if (UpperCase(PathDelimeter + ds.PathInfo) = PathInfo) then begin Console.DisplayMsg('Found handler:' + ds.Caption); ds.DispatchRequest(RequestInfo); Break; end; ds := nil; end; Console.DisplayDebugMsg('Dispatcher not found...'); if not RequestInfo.Handled and (_DefaultDispatcher <> nil) then _DefaultDispatcher.DispatchRequest(RequestInfo); finally if ds = nil then s := 'unassigned' else s := ds.Caption; DefConsole.CloseSection(Format('Handler:%s, Handled:%s, Content type:%s', [s, booltostr(RequestInfo.Handled), RequestInfo.ContentType])); end; end; // ************************************************************** // TWMSGetCapabilitiesModifier // ************************************************************** function TWMSGetCapabilitiesModifier.GetCapabilities(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : WideString; var c : IXMLWMT_MS_CapabilitiesType; SelfURL, SourceWMS : string; begin SourceWMS := RequestInfo.QueryFields.Values[SOURCEWMS_ID]; if SourceWMS = '' then Result := '<xml>Nenalezen parametr ' + SourceWMS + '</xml>' else begin SourceWMS := FormatGetCapabilitiesRequest(SourceWMS); Console.DisplayDebugMsg('Loading capabilities from ' + SourceWMS); c := SafeLoadCapabilities(SourceWMS); try SelfURL := RequestInfo.WebRequestToURL; SelfURL := DeleteGetCapabilitiesTokens(SelfURL); Console.DisplayDebugMsg('1' + SelfURL); AssignOnlineResource(c, SelfURL); Console.DisplayDebugMsg('1'); { c.Capability.Request.GetMap.Format.Clear; c.Capability.Request.GetMap.Format.Add(IMAGEFORMATCAPTIONS[wms_JPEG]); } if Assigned(CapabilitiesProcessor) then CapabilitiesProcessor(c); Result := c.xml; RequestInfo.Handled := true; finally c := nil; end; end; Console.DisplayDebugMsg('Leaving TWMSGetCapabilitiesModifier.GetCapabilities...'); end; // ************************************************************** // TGetMapDispatcher // ************************************************************** function TGetMapDispatcher.GetMap(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : TStream; begin Result := BuildErrorStream(RequestInfo, ''); RequestInfo.Handled := true; end; function ServiceAliases : TStrings; begin if __ServiceAliases = nil then begin __ServiceAliases := TStringList.Create; __ServiceAliases.LoadFromFile(ExtractFilePath(ParamStr(0)) + '\WMSDesktop\ServiceAliases.txt'); end; Result := __ServiceAliases; end; initialization finalization __ServiceAliases.Free; __WMSDispatchers.Free; end.
unit Model.Compromisso; interface uses System.SysUtils, Model.Categoria, Services.ComplexTypes; type TCompromissoModel = class private FValor: Currency; FDescricao: String; FCodigo: Integer; FID: TGUID; FCategoria: TCategoriaModel; FTipo: TTipoCompromisso; FData: TDateTime; FRealizado: Boolean; procedure SetCategoria(const Value: TCategoriaModel); procedure SetCodigo(const Value: Integer); procedure SetData(const Value: TDateTime); procedure SetDescricao(const Value: String); procedure SetID(const Value: TGUID); procedure SetTipo(const Value: TTipoCompromisso); procedure SetValor(const Value: Currency); procedure SetRealizado(const Value: Boolean); public constructor Create; destructor Destroy; override; property ID : TGUID read FID write SetID; property Codigo : Integer read FCodigo write SetCodigo; property Tipo : TTipoCompromisso read FTipo write SetTipo; property Descricao : String read FDescricao write SetDescricao; property Data : TDateTime read FData write SetData; property Valor : Currency read FValor write SetValor; property Categoria : TCategoriaModel read FCategoria write SetCategoria; property Realizado : Boolean read FRealizado write SetRealizado; procedure Assign(Source : TCompromissoModel); function ToString : String; override; class function New : TCompromissoModel; end; implementation { TCompromissoModel } class function TCompromissoModel.New: TCompromissoModel; begin Result := Self.Create; end; procedure TCompromissoModel.Assign(Source: TCompromissoModel); begin if Assigned(Source) then begin FID := Source.ID; FCodigo := Source.Codigo; FDescricao := Source.Descricao; FValor := Source.Valor; FData := Source.Data; FTipo := Source.Tipo; FCategoria.Assign(Source.Categoria); end; end; constructor TCompromissoModel.Create; begin FID := TGUID.Empty; FCodigo := 0; FDescricao := EmptyStr; FData := Date; FValor := 0.0; FCategoria := TCategoriaModel.Create; FRealizado := False; FTipo := TTipoCompromisso.tipoCompromissoAReceber; end; destructor TCompromissoModel.Destroy; begin FCategoria.DisposeOf; inherited; end; procedure TCompromissoModel.SetCategoria(const Value: TCategoriaModel); begin FCategoria := Value; end; procedure TCompromissoModel.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TCompromissoModel.SetData(const Value: TDateTime); begin FData := Value; end; procedure TCompromissoModel.SetDescricao(const Value: String); begin FDescricao := Value.Trim; end; procedure TCompromissoModel.SetID(const Value: TGUID); begin FID := Value; end; procedure TCompromissoModel.SetRealizado(const Value: Boolean); begin FRealizado := Value; end; procedure TCompromissoModel.SetTipo(const Value: TTipoCompromisso); begin FTipo := Value; end; procedure TCompromissoModel.SetValor(const Value: Currency); begin FValor := Value; end; function TCompromissoModel.ToString: String; begin Result := FID.ToString; end; end.
{ MIT License Copyright (c) 2022 Viacheslav Komenda Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } {$A-} unit help; interface type PHelpTopic = ^THelpTopic; THelpTopic = record name : array[1..12] of char; recno : word; ofs : byte; lvl : byte; end; PHelpTopicList = ^THelpTopicList; THelpTopicList = record topic : THelpTopic; htext : pchar; hlen : word; next : PHelpTopicList; end; function from_file(fname : string):PHelpTopicList; function from_memory(p : pointer):PHelpTopicList; function find(root : PHelpTopicList; topic_name : string):PHelpTopicList; procedure free(hlp : PHelpTopicList); procedure compile(ifname, ofname : string); implementation uses system2; type PHelpIntTopic = ^THelpIntTopic; THelpIntTopic = record name : string; ofs : longint; lvl : byte; next : PHelpIntTopic; end; function is_digit(c : char):boolean; begin is_digit := c in ['0'..'9']; end; procedure compile(ifname, ofname : string); var ifile : bfile; ofile : bfile; s : string; tcount : word; root, last, cur : PHelpIntTopic; ofs : longint; topic : THelpTopic; i, l : integer; begin tcount := 0; root := nil; last := nil; ofs := 0; assign(ifile, ifname); reset(ifile); if ifile.ioresult <> 0 then exit; while not eof(ifile) do begin readln(ifile, s); l := length(s); if length(s)>4 then begin if (s[1] = '/') and (s[2] = '/') and (s[3] = '/') and is_digit(s[4]) then begin getmem(cur, sizeof(THelpIntTopic)); cur^.lvl := ord(s[4]) - ord('0'); cur^.name := copy(s, 5, length(s)-4); cur^.ofs := ofs + length(s); cur^.next := nil; if root = nil then root := cur; if last <> nil then last^.next := cur; last := cur; inc(tcount); end; end; inc(ofs, length(s) + 2); end; inc(tcount); while ((tcount * sizeof(THelpTopic)) and $7f) <> 0 do begin inc(tcount); end; assign(ofile, ofname); rewrite(ofile); ofs := sizeof(THelpTopic) * tcount; cur := root; while cur <> nil do begin inc(cur^.ofs, ofs); topic.recno := cur^.ofs shr 7; topic.ofs := cur^.ofs and $7f; topic.lvl := cur^.lvl; fillchar(topic.name, 12, ' '); l := length(cur^.name); if l > 12 then l := 12; for i:=1 to l do topic.name[i] := upcase(cur^.name[i]); blockwrite(ofile, topic, sizeof(THelpTopic)); dec(tcount); cur := cur^.next; end; topic.recno := 0; topic.ofs := 0; topic.lvl := 0; fillchar(topic.name, 12, ' '); topic.name[1] := '$'; while tcount <> 0 do begin blockwrite(ofile, topic, sizeof(THelpTopic)); dec(tcount); end; seek(ifile, 0); blockcopy(ifile, ofile, filesize(ifile)); l := 128 - (filepos(ofile) and $7f); fillchar(s[1], l, #$1a); s[0] := chr(l); blockwrite(ofile, s[1], l); close(ifile); close(ofile); while root <> nil do begin cur := root; root := root^.next; freemem(cur, sizeof(THelpIntTopic)); end; end; function find(root : PHelpTopicList; topic_name : string) : PHelpTopicList; var name : array[1..12] of char; i, l : integer; found : boolean; r : PHelpTopicList; begin fillchar(name, 12, ' '); l := length(topic_name); if l > 12 then l := 12; for i:=1 to l do name[i] := upcase(topic_name[i]); r := root; found := false; while (not found) and (r <> nil) do begin found := true; i := 1; while i <= 12 do begin if name[i] <> r^.topic.name[i] then begin found := false; break; end; inc(i); end; if found then begin find := r; exit; end; r := r^.next; end; find := nil; end; function from_file(fname : string) : PHelpTopicList; var f : bfile; r, l, c : PHelpTopicList; nt, fs : longint; begin r := nil; c := nil; l := nil; assign(f, fname); reset(f); while true do begin getmem(c, sizeof(THelpTopicList)); blockread(f, c^.topic, sizeof(THelpTopic)); c^.next := nil; c^.htext := nil; c^.hlen := 0; if r = nil then r := c; if l <> nil then l^.next := c; if (c^.topic.recno = 0) and (c^.topic.ofs = 0) and (c^.topic.ofs = 0) then break; l := c; end; fs := filesize(f); c := r; while c <> nil do begin if (c^.topic.recno = 0) and (c^.topic.ofs = 0) and (c^.topic.ofs = 0) then break; if (c^.next^.topic.recno = 0) and (c^.next^.topic.ofs = 0) and (c^.next^.topic.ofs = 0) then nt := fs else nt := (c^.next^.topic.recno shl 7) + c^.next^.topic.ofs; c^.hlen := nt - ((c^.topic.recno shl 7) + c^.topic.ofs) + 1; getmem(c^.htext, c^.hlen); seek(f, (c^.topic.recno shl 7) + c^.topic.ofs); blockread(f, c^.htext^, c^.hlen - 1); c^.htext[c^.hlen - 1] := #0; c := c^.next; end; close(f); from_file := r; end; function from_memory(p : pointer) : PHelpTopicList; var rp, ep : pchar; r, l, c : PHelpTopicList; nt, fs : longint; begin r := nil; c := nil; l := nil; rp := p; while true do begin getmem(c, sizeof(THelpTopicList)); move(rp^, c^.topic, sizeof(THelpTopic)); inc(rp, sizeof(THelpTopic)); c^.next := nil; c^.htext := nil; c^.hlen := 0; if r = nil then r := c; if l <> nil then l^.next := c; if (c^.topic.recno = 0) and (c^.topic.ofs = 0) and (c^.topic.ofs = 0) then break; l := c; end; ep := rp; while ep^ <> #$1a do inc(ep); rp := p; fs := ep - rp; c := r; while c <> nil do begin if (c^.topic.recno = 0) and (c^.topic.ofs = 0) and (c^.topic.ofs = 0) then break; if (c^.next^.topic.recno = 0) and (c^.next^.topic.ofs = 0) and (c^.next^.topic.ofs = 0) then nt := fs else nt := (c^.next^.topic.recno shl 7) + c^.next^.topic.ofs; c^.hlen := nt - ((c^.topic.recno shl 7) + c^.topic.ofs) + 1; getmem(c^.htext, c^.hlen); move(rp[(c^.topic.recno shl 7) + c^.topic.ofs], c^.htext[0], c^.hlen - 1); c^.htext[c^.hlen - 1] := #0; c := c^.next; end; from_memory := r; end; procedure free(hlp : PHelpTopicList); var h : PHelpTopicList; begin while hlp <> nil do begin h := hlp; hlp := hlp^.next; if h^.htext <> nil then freemem(h^.htext, h^.hlen); freemem(h, sizeof(THelpTopicList)); end; end; end.
Unit VeHinh; INTERFACE TYPE Location = OBJECT X,Y : Integer; Constructor Init(InitX,InitY : Integer); Function GetX : Integer; Function GetY : Integer; End; Pointptr = ^Point; Point = OBJECT(Location) Visible : Boolean; Constructor Init(InitX,InitY : Integer); Destructor Done; Virtual; Procedure Show; Virtual; Procedure Hide; Virtual; Function IsVisible : Boolean; Procedure MoveTo(NewX,NewY :Integer); Procedure Drag(DragBy : Integer); Virtual; End; CirclePtr =^Circle; Circle = OBJECT(Point) Radius : Integer; Constructor Init(InitX,InitY,InitRadius : Integer); Procedure Show; Virtual; Procedure Hide; Virtual; procedure Expand(ExpandBy : Integer); Virtual; Procedure ConStract(ConstractBy : Integer); Virtual; End; IMPLEMENTATION Uses Graph, Crt; {CAI DAT LOCATION} {-----------------------------------} Constructor Location.Init; Begin X := InitX; Y := InitY; End; {-----------------------------------} Function Location.GetX; Begin GetX := X; End; {-----------------------------------} Function Location.GetY; Begin GetY := Y; End; {-----------------------------------} {CAI DAT POINT} {-----------------------------------} Constructor Point.Init; Begin Location.Init(initX,InitY); Visible := False; End; {-----------------------------------} Destructor Point.Done; Begin Hide; End; {-----------------------------------} Procedure Point.Show; Begin Visible := True; PutPixel(X,Y,GetColor); End; {-----------------------------------} Procedure Point.Hide; Begin Visible := False; PutPixel(X,Y,GetBkColor); End; {-----------------------------------} Function Point.IsVisible; Begin IsVisible := Visible; End; {-----------------------------------} Procedure Point.MoveTo; Begin Hide; X := NewX; Y := NewY; Show; End; {-----------------------------------} Function GetDelta(Var DeltaX,DeltaY : Integer): Boolean; Var KeyChar : Char; Quit : Boolean; Result : Boolean; Begin DeltaX := 0; DeltaY := 0;Result := True; Repeat KeyChar := ReadKey; Quit := True; If KeyChar = #0 then KeyChar := ReadKey; Case KeyChar Of #72 : DeltaY := -1; { Mui ten len} #80 : DeltaY := 1; { Mui ten xuong } #75 : DeltaX :=-1; {Mui ten trai } #77 : DeltaX := 1; { Mui ten phai } #27 : Result := False {Phim Esc } Else Quit := False; End; Until Quit; GetDelta :=Result; End; {-----------------------------------} Procedure Point.Drag; Var DeltaX,DeltaY : Integer; FigureX,FigureY : Integer; Begin Show; FigureX := GetX; FigureY := GetY; While GetDelta(DeltaX,DeltaY) Do Begin Inc(FigureX,DeltaX*DragBy); Inc(FigureY,DeltaY*DragBy); MoveTo(FigureX,FigureY); End; End; {-----------------------------------} { CAI DAT CIRCLE} {-----------------------------------} Constructor Circle.Init; Begin Point.Init(InitX,InitY); Radius := InitRadius; End; {-----------------------------------} Procedure Circle.Show; Begin Visible := True; Graph.Circle(X,Y,Radius); End; {-----------------------------------} Procedure Circle.Hide; Var TempColor : Word; Begin TempColor := Graph.GetColor; Graph.SetColor(GetBkColor); Visible := False; Graph.Circle(X,Y,Radius); Graph.SetColor(TempColor); End; {-----------------------------------} Procedure Circle.Expand; Begin Hide; Inc(Radius, ExpandBy); If Radius < 0 Then Radius := 0; Show; End; {-----------------------------------} Procedure Circle.Constract; Begin Expand(-ConstractBy); End; END.
unit tpCritSect; (* Permission is hereby granted, on 24-June-2017, free of charge, to any person obtaining a copy of this file (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Author of original version of TtpCriticalSection: Michael Ax Copyright transferred to HREF Tools Corp. on 2-May-2000. For background, see Richter's book and the win32 help files. *) interface {$I hrefdefines.inc} { Master copy of hrefdefines.inc is versioned on Source Forge in the ZaphodsMap project: https://sourceforge.net/p/zaphodsmap/code/HEAD/tree/trunk/ZaphodsMap/Source/hrefdefines.inc } uses {$IFDEF MSWINDOWS}Windows,{$ENDIF} Classes, SysUtils; type TtpCriticalSection = class(TObject) private fCSect: TRTLCriticalSection; // see also TCriticalSection in System.SyncObjs in Delphi 10.2 Tokyo fOnExecute: TNotifyEvent; protected procedure DoExecute; virtual; public constructor Create; destructor Destroy; override; // procedure Lock; procedure UnLock; // procedure Synchronize(Method: TThreadMethod); // procedure Execute; property OnExecute: TNotifyEvent read fOnExecute write fOnExecute; property CSect: TRTLCriticalSection read fCSect; end; implementation constructor TtpCriticalSection.Create; begin inherited Create; Windows.InitializeCriticalSection(fCSect); end; destructor TtpCriticalSection.Destroy; begin {$IFDEF MSWINDOWS} DeleteCriticalSection(fCSect); {$ENDIF} inherited Destroy; end; // procedure TtpCriticalSection.Lock; begin {$IFNDEF LINUX} EnterCriticalSection(fCSect); {$ENDIF} end; procedure TtpCriticalSection.UnLock; begin {$IFNDEF LINUX} LeaveCriticalSection(fCSect); {$ENDIF} end; procedure TtpCriticalSection.Synchronize(Method: TThreadMethod); begin Lock; try Method; finally UnLock; end; end; procedure TtpCriticalSection.Execute; begin Lock; try DoExecute; finally UnLock; end; end; procedure TtpCriticalSection.DoExecute; begin if assigned(fOnExecute) then fOnExecute(self); end; end.
unit JvLogClasses; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} SysUtils, Contnrs; type TJvLogEventSeverity = (lesError, lesWarning, lesInformation); TJvLogRecord = class(TObject) public Time: string; Title: string; Description: string; Severity : TJvLogEventSeverity; function GetOutputString: string; end; TJvLogRecordList = class(TObjectList) private function GetItem(Index: Integer): TJvLogRecord; procedure SetItem(Index: Integer; const ALogRecord: TJvLogRecord); public property Items[Index: Integer]: TJvLogRecord read GetItem write SetItem; default; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvLogClasses.pas $'; Revision: '$Revision: 12991 $'; Date: '$Date: 2011-02-26 09:25:34 +0100 (sam. 26 févr. 2011) $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} function GetSeverityString( const Severity : TJvLogEventSeverity) : string; function GetSeverityFromString( const SeverityString : string) : TJvLogEventSeverity; implementation resourcestring STR_SEVERITY_INFORMATION = 'Information'; STR_SEVERITY_WARNING = 'Warning'; STR_SEVERITY_ERROR = 'Error'; function GetSeverityString( const Severity : TJvLogEventSeverity) : string; begin case Severity of lesError: result := STR_SEVERITY_ERROR; lesWarning: result := STR_SEVERITY_WARNING; lesInformation: result := STR_SEVERITY_INFORMATION; end; end; function GetSeverityFromString( const SeverityString : string) : TJvLogEventSeverity; begin if SeverityString = STR_SEVERITY_ERROR then Result := lesError else if SeverityString = STR_SEVERITY_WARNING then Result := lesWarning else Result := lesInformation; end; // === { TJvLogRecord } ======================================= function TJvLogRecord.GetOutputString: string; begin Result := '[' + Time + ']' + GetSeverityString( Severity) + '>' + StringReplace(Title, '>', '>>', [rfReplaceAll]) + '>' + Description + sLineBreak; end; // === { TJvLogRecordList } =================================== function TJvLogRecordList.GetItem(Index: Integer): TJvLogRecord; begin Result := TJvLogRecord(inherited Items[Index]); end; procedure TJvLogRecordList.SetItem(Index: Integer; const ALogRecord: TJvLogRecord); begin inherited Items[Index] := ALogRecord; end; end.
unit uLibResize; interface uses Windows, SysUtils, Classes, Graphics, Math, JPEG, GR32, GIFImage, PNGImage, GR32_Resamplers; type TImageType = (itUnknown, itBMP, itGIF, itJPG, itPNG); TImageInfo = record ImgType: TImageType; Width: Cardinal; Height: Cardinal; end; function GetImageInfo(const AFilename: String): TImageInfo; overload; function GetImageInfo(const AStream: TStream): TImageInfo; overload; function ResizeImage(const ASource, ADest: String; const AWidth, AHeight: Integer; const ABackColor: TColor; const AType: TImageType = itUnknown): Boolean; overload; function ResizeImage(const ASource, ADest: TStream; const AWidth, AHeight: Integer; const ABackColor: TColor; const AType: TImageType = itUnknown): Boolean; overload; implementation type TGetDimensions = procedure(const ASource: TStream; var AImageInfo: TImageInfo); TCardinal = record case Byte of 0: (Value: Cardinal); 1: (Byte1, Byte2, Byte3, Byte4: Byte); end; TWord = record case Byte of 0: (Value: Word); 1: (Byte1, Byte2: Byte); end; TPNGIHDRChunk = packed record Width: Cardinal; Height: Cardinal; Bitdepth: Byte; Colortype: Byte; Compression: Byte; Filter: Byte; Interlace: Byte; end; TGIFHeader = packed record Signature: array[0..2] of Char; Version: array[0..2] of Char; Width: Word; Height: Word; end; TJPGChunk = record ID: Word; Length: Word; end; TJPGHeader = packed record Reserved: Byte; Height: Word; Width: Word; end; const SIG_BMP: array[0..1] of Char = ('B', 'M'); SIG_GIF: array[0..2] of Char = ('G', 'I', 'F'); SIG_JPG: array[0..2] of Char = (#255, #216, #255); SIG_PNG: array[0..7] of Char = (#137, #80, #78, #71, #13, #10, #26, #10); function SwapBytes(const ASource: Cardinal): Cardinal; overload; var mwSource: TCardinal; mwDest: TCardinal; begin mwSource.Value := ASource; mwDest.Byte1 := mwSource.Byte4; mwDest.Byte2 := mwSource.Byte3; mwDest.Byte3 := mwSource.Byte2; mwDest.Byte4 := mwSource.Byte1; Result := mwDest.Value; end; function SwapBytes(const ASource: Word): Word; overload; var mwSource: TWord; mwDest: TWord; begin mwSource.Value := ASource; mwDest.Byte1 := mwSource.Byte2; mwDest.Byte2 := mwSource.Byte1; Result := mwDest.Value; end; procedure GetBMPDimensions(const ASource: TStream; var AImageInfo: TImageInfo); var bmpFileHeader: TBitmapFileHeader; bmpInfoHeader: TBitmapInfoHeader; begin FillChar(bmpFileHeader, SizeOf(TBitmapFileHeader), #0); FillChar(bmpInfoHeader, SizeOf(TBitmapInfoHeader), #0); ASource.Read(bmpFileHeader, SizeOf(TBitmapFileHeader)); ASource.Read(bmpInfoHeader, SizeOf(TBitmapInfoHeader)); AImageInfo.Width := bmpInfoHeader.biWidth; AImageInfo.Height := bmpInfoHeader.biHeight; end; procedure GetGIFDimensions(const ASource: TStream; var AImageInfo: TImageInfo); var gifHeader: TGIFHeader; begin FillChar(gifHeader, SizeOf(TGIFHeader), #0); ASource.Read(gifHeader, SizeOf(TGIFHeader)); AImageInfo.Width := gifHeader.Width; AImageInfo.Height := gifHeader.Height; end; procedure GetJPGDimensions(const ASource: TStream; var AImageInfo: TImageInfo); var cSig: array[0..1] of Char; jpgChunk: TJPGChunk; jpgHeader: TJPGHeader; iSize: Integer; iRead: Integer; begin FillChar(cSig, SizeOf(cSig), #0); ASource.Read(cSig, SizeOf(cSig)); iSize := SizeOf(TJPGChunk); repeat FillChar(jpgChunk, iSize, #0); iRead := ASource.Read(jpgChunk, iSize); if iRead <> iSize then Break; if jpgChunk.ID = $C0FF then begin ASource.Read(jpgHeader, SizeOf(TJPGHeader)); AImageInfo.Width := SwapBytes(jpgHeader.Width); AImageInfo.Height := SwapBytes(jpgHeader.Height); Break; end else ASource.Position := ASource.Position + (SwapBytes(jpgChunk.Length) - 2); until False; end; procedure GetPNGDimensions(const ASource: TStream; var AImageInfo: TImageInfo); var cSig: array[0..7] of Char; cChunkLen: Cardinal; cChunkType: array[0..3] of Char; ihdrData: TPNGIHDRChunk; begin FillChar(cSig, SizeOf(cSig), #0); FillChar(cChunkType, SizeOf(cChunkType), #0); ASource.Read(cSig, SizeOf(cSig)); cChunkLen := 0; ASource.Read(cChunkLen, SizeOf(Cardinal)); cChunkLen := SwapBytes(cChunkLen); if cChunkLen = SizeOf(TPNGIHDRChunk) then begin ASource.Read(cChunkType, SizeOf(cChunkType)); if AnsiUpperCase(cChunkType) = 'IHDR' then begin FillChar(ihdrData, SizeOf(TPNGIHDRChunk), #0); ASource.Read(ihdrData, SizeOf(TPNGIHDRChunk)); AImageInfo.Width := SwapBytes(ihdrData.Width); AImageInfo.Height := SwapBytes(ihdrData.Height); end; end; end; function GetImageInfo(const AFilename: String): TImageInfo; var fsImage: TFileStream; begin fsImage := TFileStream.Create(AFilename, fmOpenRead or fmShareDenyWrite); try Result := GetImageInfo(fsImage); finally FreeAndNil(fsImage); end; end; function GetImageInfo(const AStream: TStream): TImageInfo; var iPos: Integer; cBuffer: array[0..2] of Char; cPNGBuffer: array[0..4] of Char; GetDimensions: TGetDimensions; begin GetDimensions := nil; Result.ImgType := itUnknown; Result.Width := 0; Result.Height := 0; FillChar(cBuffer, SizeOf(cBuffer), #0); FillChar(cPNGBuffer, SizeOf(cPNGBuffer), #0); iPos := AStream.Position; AStream.Read(cBuffer, SizeOf(cBuffer)); if cBuffer = SIG_GIF then begin Result.ImgType := itGIF; GetDimensions := GetGIFDimensions; end else if cBuffer = SIG_JPG then begin Result.ImgType := itJPG; GetDimensions := GetJPGDimensions; end else if cBuffer = Copy(SIG_PNG, 1, 3) then begin AStream.Read(cPNGBuffer, SizeOf(cPNGBuffer)); if cPNGBuffer = Copy(SIG_PNG, 4, 5) then begin Result.ImgType := itPNG; GetDimensions := GetPNGDimensions; end; end else if Copy(cBuffer, 1, 2) = SIG_BMP then begin Result.ImgType := itBMP; GetDimensions := GetBMPDimensions; end; AStream.Position := iPos; if Assigned(GetDimensions) then begin GetDimensions(AStream, Result); AStream.Position := iPos; end; end; procedure GIFToBMP(const ASource: TStream; const ADest: TBitmap); var imgSource: TGIFImage; begin imgSource := TGIFImage.Create(); try imgSource.LoadFromStream(ASource); ADest.Assign(imgSource); finally FreeAndNil(imgSource); end; end; procedure JPGToBMP(const ASource: TStream; const ADest: TBitmap); var imgSource: TJPEGImage; begin imgSource := TJPEGImage.Create(); try imgSource.LoadFromStream(ASource); ADest.Assign(imgSource); finally FreeAndNil(imgSource); end; end; procedure PNGToBMP(const ASource: TStream; const ADest: TBitmap); var imgSource: TPNGImage; begin imgSource := TPNGImage.Create(); try imgSource.LoadFromStream(ASource); ADest.Assign(imgSource); finally FreeAndNil(imgSource); end; end; function ResizeImage(const ASource, ADest: String; const AWidth, AHeight: Integer; const ABackColor: TColor; const AType: TImageType = itUnknown): Boolean; var fsSource: TFileStream; fsDest: TFileStream; begin Result := False; fsSource := TFileStream.Create(ASource, fmOpenRead or fmShareDenyWrite); try fsDest := TFileStream.Create(ADest, fmCreate or fmShareExclusive); try Result := not Result; //hide compiler hint Result := ResizeImage(fsSource, fsDest, AWidth, AHeight, ABackColor, AType); finally FreeAndNil(fsDest); end; finally FreeAndNil(fsSource); end; end; function ResizeImage(const ASource, ADest: TStream; const AWidth, AHeight: Integer; const ABackColor: TColor; const AType: TImageType = itUnknown): Boolean; var itImage: TImageType; ifImage: TImageInfo; bmpTemp: TBitmap; bmpSource: TBitmap32; bmpResized: TBitmap32; cBackColor: TColor32; rSource: TRect; rDest: TRect; dWFactor: Double; dHFactor: Double; dFactor: Double; iSrcWidth: Integer; iSrcHeight: Integer; iWidth: Integer; iHeight: Integer; jpgTemp: TJPEGImage; begin Result := False; itImage := AType; if itImage = itUnknown then begin ifImage := GetImageInfo(ASource); itImage := ifImage.ImgType; if itImage = itUnknown then Exit; end; bmpTemp := TBitmap.Create(); try case itImage of itBMP: bmpTemp.LoadFromStream(ASource); itGIF: GIFToBMP(ASource, bmpTemp); itJPG: JPGToBMP(ASource, bmpTemp); itPNG: PNGToBMP(ASource, bmpTemp); end; bmpSource := TBitmap32.Create(); bmpResized := TBitmap32.Create(); try cBackColor := Color32(ABackColor); bmpSource.Assign(bmpTemp); bmpResized.Width := AWidth; bmpResized.Height := AHeight; bmpResized.Clear(cBackColor); iSrcWidth := bmpSource.Width; iSrcHeight := bmpSource.Height; iWidth := iSrcWidth; iHeight := iSrcHeight; with rSource do begin Left := 0; Top := 0; Right := iSrcWidth; Bottom := iSrcHeight; end; if (iWidth > AWidth) or (iHeight > AHeight) then begin dWFactor := AWidth / iWidth; dHFactor := AHeight / iHeight; if (dWFactor > dHFactor) then dFactor := dHFactor else dFactor := dWFactor; iWidth := Floor(iWidth * dFactor); iHeight := Floor(iHeight * dFactor); end; with rDest do begin Left := Floor((AWidth - iWidth) / 2); Top := Floor((AHeight - iHeight) / 2); Right := Left + iWidth; Bottom := Top + iHeight; end; bmpSource.Resampler := TKernelResampler.Create; TKernelResampler(bmpSource.Resampler).Kernel := TLanczosKernel.Create; bmpSource.DrawMode := dmOpaque; bmpResized.Draw(rDest, rSource, bmpSource); bmpTemp.Assign(bmpResized); jpgTemp := TJPEGImage.Create(); jpgTemp.CompressionQuality := 80; try jpgTemp.Assign(bmpTemp); jpgTemp.SaveToStream(ADest); Result := True; finally FreeAndNil(jpgTemp); end; finally FreeAndNil(bmpResized); FreeAndNil(bmpSource); end; finally FreeAndNil(bmpTemp); end; end; end.
{------------------------------------ 功能说明:模块安装接口 创建日期:2011/04/19 作者:wei 版权:wei -------------------------------------} unit ModuleInstallerIntf; {$weakpackageunit on} interface type IModuleInstaller = interface ['{97E777E9-0541-47DD-BCD3-4DB2BCB3145D}'] procedure InstallModule(const ModuleFile: String); procedure UninstallModule(const ModuleFile: string); end; implementation end.
{******************************************************************************} { CnPack For Delphi/C++Builder } { 中国人自己的开放源码第三方开发包 } { (C)Copyright 2001-2006 CnPack 开发组 } { ------------------------------------ } { } { 本开发包是开源的自由软件,您可以遵照 CnPack 的发布协议来修 } { 改和重新发布这一程序。 } { } { 发布这一开发包的目的是希望它有用,但没有任何担保。甚至没有 } { 适合特定目的而隐含的担保。更详细的情况请参阅 CnPack 发布协议。 } { } { 您应该已经和开发包一起收到一份 CnPack 发布协议的副本。如果 } { 还没有,可访问我们的网站: } { } { 网站地址:http://www.cnpack.org } { 电子邮件:master@cnpack.org } { } {******************************************************************************} unit ZhConsts; {* |<PRE> ================================================================================ * 软件名称:开发包基础库 * 单元名称:公共资源字符串定义单元 * 单元作者:CnPack开发组 * 备 注: * 开发平台:PWin98SE + Delphi 5.0 * 兼容测试:PWin9X/2000/XP + Delphi 5/6 * 本 地 化:该单元中的字符串均符合本地化处理方式 * 单元标识:$Id: CnConsts.pas,v 1.11 2006/09/23 17:27:03 passion Exp $ * 修改记录: * 2004.09.18 V1.2 * 新增CnMemProf的字符串定义 * 2002.04.18 V1.1 * 新增部分字符串定义 * 2002.04.08 V1.0 * 创建单元 ================================================================================ |</PRE>} interface uses Windows; //{$I CnPack.inc} //============================================================================== // 不需要本地化的字符串 //============================================================================== resourcestring // 注册表路径 SCnPackRegPath = '\Software\CnPack'; // 辅助工具路径 SCnPackToolRegPath = 'CnTools'; //============================================================================== // 需要本地化的字符串 //============================================================================== var // 公共信息 {$IFDEF GB2312} SCnInformation: string = '提示'; SCnWarning: string = '警告'; SCnError: string = '错误'; SCnEnabled: string = '有效'; SCnDisabled: string = '禁用'; SCnMsgDlgOK: string = '确认(&O)'; SCnMsgDlgCancel: string = '取消(&C)'; {$ELSE} SCnInformation: string = 'Information'; SCnWarning: string = 'Warning'; SCnError: string = 'Error'; SCnEnabled: string = 'Enabled'; SCnDisabled: string = 'Disabled'; SCnMsgDlgOK: string = '&OK'; SCnMsgDlgCancel: string = '&Cancel'; {$ENDIF} const // 开发包信息 SCnPackAbout = 'CnPack'; SCnPackVer = 'Ver 0.0.8.0'; SCnPackStr = SCnPackAbout + ' ' + SCnPackVer; SCnPackUrl = 'http://www.cnpack.org'; SCnPackBbsUrl = 'http://bbs.cnpack.org'; SCnPackNewsUrl = 'news://news.cnpack.org'; SCnPackEmail = 'master@cnpack.org'; SCnPackBugEmail = 'bugs@cnpack.org'; SCnPackSuggestionsEmail = 'suggestions@cnpack.org'; SCnPackDonationUrl = 'http://www.cnpack.org/foundation.php'; SCnPackDonationUrlSF = 'http://sourceforge.net/donate/index.php?group_id=110999'; {$IFDEF GB2312} SCnPackGroup = 'CnPack 开发组'; {$ELSE} SCnPackGroup = 'CnPack Team'; {$ENDIF} SCnPackCopyright = '(C)Copyright 2001-2006 ' + SCnPackGroup; // CnPropEditors {$IFDEF GB2312} SCopyrightFmtStr = SCnPackStr + #13#10#13#10 + '组件名称: %s' + #13#10 + '组件作者: %s(%s)' + #13#10 + '组件说明: %s' + #13#10#13#10 + '下载网站: ' + SCnPackUrl + #13#10 + '技术支持: ' + SCnPackEmail + #13#10#13#10 + SCnPackCopyright; {$ELSE} SCopyrightFmtStr = SCnPackStr + #13#10#13#10 + 'Component Name: %s' + #13#10 + 'Author: %s(%s)' + #13#10 + 'Comment: %s' + #13#10 + 'HomePage: ' + SCnPackUrl + #13#10 + 'Email: ' + SCnPackEmail + #13#10#13#10 + SCnPackCopyright; {$ENDIF} resourcestring // 组件安装面板名 SCnNonVisualPalette = 'CnPack Tools'; SCnGraphicPalette = 'CnPack VCL'; SCnNetPalette = 'CnPack Net'; SCnDatabasePalette = 'CnPack DB'; SCnReportPalette = 'CnPack Report'; // 开发组成员信息请在后面添加,注意本地化处理 var {$IFDEF GB2312} SCnPack_Zjy: string = '周劲羽'; SCnPack_Shenloqi: string = '沈龙强(Chinbo)'; SCnPack_xiaolv: string = '吕宏庆'; SCnPack_Flier: string = 'Flier Lu'; SCnPack_LiuXiao: string = '刘啸(Passion)'; SCnPack_PanYing: string = '潘鹰(Pan Ying)'; SCnPack_Hubdog: string = '陈省(Hubdog)'; SCnPack_Wyb_star: string = '王玉宝'; SCnPack_Licwing: string = '朱磊(Licwing Zue)'; SCnPack_Alan: string = '张伟(Alan)'; SCnPack_Aimingoo: string = '周爱民(Aimingoo)'; SCnPack_QSoft: string = '何清(QSoft)'; SCnPack_Hospitality: string = '张炅轩(Hospitality)'; SCnPack_SQuall: string = '刘玺(SQUALL)'; SCnPack_Hhha: string = 'Hhha'; SCnPack_Beta: string = '熊恒(beta)'; SCnPack_Leeon: string = '李柯(Leeon)'; SCnPack_SuperYoyoNc: string = '许子健'; SCnPack_JohnsonZhong: string = 'Johnson Zhong'; SCnPack_DragonPC: string = 'Dragon P.C.'; SCnPack_Kendling: string = '小冬(Kending)'; SCnPack_ccrun: string = 'ccRun(老妖)'; {$ELSE} SCnPack_Zjy: string = 'Zhou JingYu'; SCnPack_Shenloqi: string = 'Chinbo'; SCnPack_xiaolv: string = 'xiaolv'; SCnPack_Flier: string = 'Flier Lu'; SCnPack_LiuXiao: string = 'Liu Xiao'; SCnPack_PanYing: string = 'Pan Ying'; SCnPack_Hubdog: string = 'Hubdog'; SCnPack_Wyb_star: string = 'wyb_star'; SCnPack_Licwing: string = 'Licwing zue'; SCnPack_Alan: string = 'Alan'; SCnPack_Aimingoo: string = 'Aimingoo'; SCnPack_QSoft: string = 'QSoft'; SCnPack_Hospitality: string = 'ZhangJiongXuan (Hospitality)'; SCnPack_SQuall: string = 'SQUALL'; SCnPack_Hhha: string = 'Hhha'; SCnPack_Beta: string = 'beta'; SCnPack_Leeon: string = 'Leeon'; SCnPack_SuperYoyoNc: string = 'SuperYoyoNC'; SCnPack_JohnsonZhong: string = 'Johnson Zhong'; SCnPack_DragonPC: string = 'Dragon P.C.'; SCnPack_Kendling: string = 'Kending'; SCnPack_ccrun: string = 'ccrun'; {$ENDIF} // CnCommon {$IFDEF GB2312} SUnknowError: string = '未知错误'; SErrorCode: string = '错误代码:'; {$ELSE} SUnknowError: string = 'Unknow error'; SErrorCode: string = 'Error code:'; {$ENDIF} const SCnPack_ZjyEmail = 'zjy@cnpack.org'; SCnPack_ShenloqiEmail = 'Shenloqi@hotmail.com'; SCnPack_xiaolvEmail = 'xiaolv888@etang.com'; SCnPack_FlierEmail = 'flier_lu@sina.com'; SCnPack_LiuXiaoEmail = 'passion@cnpack.org'; SCnPack_PanYingEmail = 'panying@sina.com'; SCnPack_HubdogEmail = 'hubdog@263.net'; SCnPack_Wyb_starMail = 'wyb_star@sina.com'; SCnPack_LicwingEmail = 'licwing@chinasystemsn.com'; SCnPack_AlanEmail = 'BeyondStudio@163.com'; SCnPack_AimingooEmail = 'aim@263.net'; SCnPack_QSoftEmail = 'hq.com@263.net'; SCnPack_HospitalityEmail = 'Hospitality_ZJX@msn.com'; SCnPack_SQuallEmail = 'squall_sa@163.com'; SCnPack_HhhaEmail = 'Hhha@eyou.com'; SCnPack_BetaEmail = 'beta@01cn.net'; SCnPack_LeeonEmail = 'real-like@163.com'; SCnPack_SuperYoyoNcEmail = 'superyoyonc@sohu.com'; SCnPack_JohnsonZhongEmail = 'zhongs@tom.com'; SCnPack_DragonPCEmail = 'dragonpc@21cn.com'; SCnPack_KendlingEmail = 'kendling@21cn.com'; SCnPack_ccRunEmail = 'info@ccrun.com'; // CnMemProf {$IFDEF GB2312} SCnPackMemMgr = '内存管理监视器'; SMemLeakDlgReport = '出现 %d 处内存漏洞[替换内存管理器之前已分配 %d 处]。'; SMemMgrODSReport = '获取 = %d,释放 = %d,重分配 = %d'; SMemMgrOverflow = '内存管理监视器指针列表溢出,请增大列表项数!'; SMemMgrRunTime = '%d 小时 %d 分 %d 秒。'; SOldAllocMemCount = '替换内存管理器前已分配 %d 处内存。'; SAppRunTime = '程序运行时间: '; SMemSpaceCanUse = '可用地址空间: %d 千字节'; SUncommittedSpace = '未提交部分: %d 千字节'; SCommittedSpace = '已提交部分: %d 千字节'; SFreeSpace = '空闲部分: %d 千字节'; SAllocatedSpace = '已分配部分: %d 千字节'; SAllocatedSpacePercent = '地址空间载入: %d%%'; SFreeSmallSpace = '全部小空闲内存块: %d 千字节'; SFreeBigSpace = '全部大空闲内存块: %d 千字节'; SUnusedSpace = '其它未用内存块: %d 千字节'; SOverheadSpace = '内存管理器消耗: %d 千字节'; SObjectCountInMemory = '内存对象数目: '; SNoMemLeak = '没有内存泄漏。'; SNoName = '(未命名)'; SNotAnObject = '不是对象'; SByte = '字节'; SCommaString = ','; SPeriodString = '。'; {$ELSE} SCnPackMemMgr = 'CnMemProf'; SMemLeakDlgReport = 'Found %d memory leaks. [There are %d allocated before replace memory manager.]'; SMemMgrODSReport = 'Get = %d Free = %d Realloc = %d'; SMemMgrOverflow = 'Memory Manager''s list capability overflow, Please enlarge it!'; SMemMgrRunTime = '%d hour(s) %d minute(s) %d second(s)。'; SOldAllocMemCount = 'There are %d allocated before replace memory manager.'; SAppRunTime = 'Application total run time: '; SMemSpaceCanUse = 'HeapStatus.TotalAddrSpace: %d KB'; SUncommittedSpace = 'HeapStatus.TotalUncommitted: %d KB'; SCommittedSpace = 'HeapStatus.TotalCommitted: %d KB'; SFreeSpace = 'HeapStatus.TotalFree: %d KB'; SAllocatedSpace = 'HeapStatus.TotalAllocated: %d KB'; SAllocatedSpacePercent = 'TotalAllocated div TotalAddrSpace: %d%%'; SFreeSmallSpace = 'HeapStatus.FreeSmall: %d KB'; SFreeBigSpace = 'HeapStatus.FreeBig: %d KB'; SUnusedSpace = 'HeapStatus.Unused: %d KB'; SOverheadSpace = 'HeapStatus.Overhead: %d KB'; SObjectCountInMemory = 'Objects count in memory: '; SNoMemLeak = ' No memory leak.'; SNoName = '(no name)'; SNotAnObject = ' Not an object'; SByte = 'Byte'; SCommaString = ','; SPeriodString = '.'; {$ENDIF GB2312} implementation end.
unit NLDMailOut; // Dany Rosseel { History of this unit 28-10-2003: * Initial version 20-03-2005: * Converted the "SendMail" procedures into functions. They return True (success) or false (failiure) 20-04-2005: * Small correction in "SendMail", made "word" variable an "integer". } {$WARN SYMBOL_PLATFORM OFF} {$WARN UNIT_PLATFORM OFF} interface uses Classes, IdSMTP; procedure SetMailOutParams(Host, Port: string; Auth: TAuthenticationType; Id, Pw: string); procedure SetMailOutAddresses(From, Answer: string); function SendMail(Subject, Towards: string; Body: TStrings; CC: string = ''; BCC: string = ''; Attachments: TStrings = nil): Boolean; overload; function SendMail(Subject, Towards: string; Body: string; CC: string = ''; BCC: string = ''; Attachments: TStrings = nil): Boolean; overload; function SendMail(Subject: string; Towards: Tstrings; Body: TStrings; CC: string = ''; BCC: string = ''; Attachments: TStrings = nil): Boolean; overload; function SendMail(Subject: string; Towards: Tstrings; Body: string; CC: string = ''; BCC: string = ''; Attachments: TStrings = nil): Boolean; overload; implementation uses SysUtils, IdMessage, NLDSMTPSetup, NLDRcsStrings; var SMTPHost: string; SMTPPort: string; SMTPAuth: TAuthenticationType; SMTPId: string; SMTPPw: string; SMTPFrom: string; SMTPAnswer: string; ParamsInitialized: Boolean; MailAddressesInitialized: Boolean; procedure SetMailOutParams(Host, Port: string; Auth: TAuthenticationType; Id, Pw: string); begin SMTPHost := Host; SMTPPort := Port; SMTPAuth := Auth; SMTPId := Id; SMTPPw := Pw; ParamsInitialized := True; // do not reload then any more end; procedure SetMailOutAddresses(From, Answer: string); begin SMTPFrom := From; SMTPAnswer := Answer; MailAddressesInitialized := True; // do not reload them any more end; procedure InitParams; begin if not ParamsInitialized then GetSmtpValues(SMTPHost, SMTPPort, SMTPAuth, SMTPId, SMTPPw); end; procedure InitAddresses; begin if not MailAddressesInitialized then GetEmailAddresses(SMTPFrom, SMTPAnswer); end; function SendMail(Subject, Towards: string; Body: TStrings; CC: string = ''; BCC: string = ''; Attachments: TStrings = nil): Boolean; var Mess: TIdMessage; IdSMTP1: TIdSMTP; I: Integer; begin Result := false; InitParams; { get SMTP settings } InitAddresses; { get own addresses } IdSMTP1 := TIdSMTP.Create(nil); try IdSMTP1.host := SMTPHost; IdSMTP1.port := strtoint(SMTPPort); IdSMTP1.AuthenticationType := SMTPAuth; IdSMTP1.Username := SMTPId; IdSMTP1.Password := SMTPPw; IdSMTP1.MailAgent := 'Microsoft Outlook Express 6.00.2720.3000'; IdSMTP1.ReadTimeout := 60000; Mess := TIdMessage.Create(nil); try Mess.Encoding := meMIME; Mess.AttachmentEncoding := 'MIME'; Mess.ContentType := 'text/plain'; Mess.Charset := 'iso-8859-1'; Mess.ContentTransferEncoding := '7bit'; Mess.Subject := Subject; Mess.Recipients.Emailaddresses := Towards; // comma separated addresses Mess.CCList.EMailAddresses := CC; // comma separated addresses Mess.BCCList.EMailAddresses := BCC; // comma separated addresses Mess.from.Address := SMTPFrom; Mess.ReplyTo.Emailaddresses := SMTPAnswer; // comma separated addresses Mess.Body.Assign(Body); if Assigned(Attachments) then begin for I := 0 to Attachments.Count - 1 do begin if FileExists(Attachments[I]) then TIdAttachment.Create(Mess.MessageParts, Attachments[I]); end; end; try IdSMTP1.Connect; try IdSMTP1.Send(Mess); Result := true; // success finally IdSMTP1.Disconnect; end; except on Exception do; // failiure end; finally Mess.Free; end; finally IdSMTP1.Free; end; end; function SendMail(Subject, Towards: string; Body: string; CC: string = ''; BCC: string = ''; Attachments: TStrings = nil): Boolean; var Bdy: TStrings; begin Bdy := TStringList.Create; try Bdy.Add(Body); Result := Sendmail(Subject, Towards, Bdy, CC, BCC, Attachments); finally Bdy.Free; end; end; function SendMail(Subject: string; Towards: Tstrings; Body: TStrings; CC: string = ''; BCC: string = ''; Attachments: TStrings = nil): Boolean; var I: Integer; begin // trim the mail address list for I := Towards.Count - 1 downto 0 do begin Towards[I] := trim(Towards[I]); if Towards[I] = '' then Towards.Delete(I); end; // send the mail Result := SendMail(Subject, TStringsToString(Towards), Body, CC, BCC, Attachments); end; function SendMail(Subject: string; Towards: Tstrings; Body: string; CC: string = ''; BCC: string = ''; Attachments: TStrings = nil): Boolean; var I: Integer; begin // trim the mail address list for I := Towards.Count - 1 downto 0 do begin Towards[I] := trim(Towards[I]); if Towards[I] = '' then Towards.Delete(I); end; // send the mail Result := SendMail(Subject, TStringsToString(Towards), Body, CC, BCC, Attachments); end; begin ParamsInitialized := False; MailAddressesInitialized := false; end.
unit retrydlg; (* Permission is hereby granted, on 6-May-2003, free of charge, to any person obtaining a copy of this file (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *) // Author of original version of this file: Michael Ax interface uses Classes, SysUtils, ExtCtrls, Forms, Dialogs, Controls, UcTypes, retry, errormsg; type TRetryDialog = class(TRetry) private fErrorDialog: TErrorDialog; {can use a linked in error dialog before ours but after event} protected procedure DoOnException(Sender:TObject;E:Exception;var Action:TExceptionReAction); override; public published property ErrorDialog: TErrorDialog read fErrorDialog write fErrorDialog; end; implementation procedure TRetryDialog.DoOnException(Sender:TObject;E:Exception;var Action:TExceptionReAction); begin inherited DoOnException(Sender,E,Action); if fErrorDialog<>nil then {call fancier error proc} with fErrorDialog do begin CanRetry:=True; CanIgnore:=Self.CanIgnore; RetryException(Sender,E,Action); end; end; end.
unit diagram; {$mode objfpc}{$H+}{$COperators on} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,math,FPimage,IntfGraphics, LCLType,LCLProc,LCLIntf; type TAxis=class; TValueTranslateEvent=procedure (sender: TAxis; i: float; var translated: string) of object; { TLegend } //a*x^3+b*x^2+c*x+d TDiagramSplinePiece = record a,b,c,d: float; end; TLegend=class(TPersistent) private Fauto: boolean; FColor: TColor; FHeight: longint; Fvisible: boolean; FWidth: longint; FModifiedEvent: TNotifyEvent; procedure doModified; procedure Setauto(const AValue: boolean); procedure SetColor(const AValue: TColor); procedure SetHeight(const AValue: longint); procedure Setvisible(const AValue: boolean); procedure SetWidth(const AValue: longint); published property visible: boolean read Fvisible write Setvisible ; property Width:longint read FWidth write SetWidth ; property Height: longint read FHeight write SetHeight; //** Background color property Color:TColor read FColor write SetColor; //** Determines if the size is automatically calculated property auto: boolean read Fauto write Setauto ; end; { TAxis } TRangePolicy = (rpAuto, rpApplication); TAxis=class(TPersistent) private FGridLinePen: TPen; FLinePen: TPen; Fmax: float; Fmin: float; FModifiedEvent: TNotifyEvent; FrangePolicy: TRangePolicy; Fresolution: float; FShowText: boolean; FvalueTranslate: TValueTranslateEvent; FVisible: boolean; procedure doModified(sender:tobject); procedure SetGridLinePen(const AValue: TPen); procedure SetLinePen(const AValue: TPen); procedure Setmax(const AValue: float); procedure Setmin(const AValue: float); procedure SetrangePolicy(const AValue: TRangePolicy); procedure Setresolution(const AValue: float); procedure SetShowText(const AValue: boolean); procedure SetvalueTranslate(const AValue: TValueTranslateEvent); procedure SetVisible(const AValue: boolean); protected function doTranslate(const i:float): string; public constructor create(); destructor destroy();override; //title: string; function translate(const i:float): string;inline; //**choose a usable resolution for a given range/output //**this procedure tries to keep rmin+n*resolution in output coordinates constant procedure rangeChanged(const rmin,rmax:float; realSize: longint); published //**Pen used to draw grids line perpendicular to the axis property gridLinePen: TPen read FGridLinePen write SetGridLinePen; //**Color of the axis property linePen: TPen read FLinePen write SetLinePen; property min: float read Fmin write Setmin; property max: float read Fmax write Setmax; property resolution: float read Fresolution write Setresolution; property rangePolicy: TRangePolicy read FrangePolicy write SetrangePolicy; //**Function/Event to allow customizaiton of the axis labels property valueTranslate: TValueTranslateEvent read FvalueTranslate write SetvalueTranslate; property Visible:boolean read FVisible write SetVisible; //property ShowText:boolean read FShowText write SetShowText; end; TDataPoint=record x,y:float; end; const DiagramEpsilon=1e-15; type TModelFlag=(mfEditable); TModelFlags=set of TModelFlag; TModelRowFlag=(rfFullX, rfFullY); //**< full flags draw lines across the plot TModelRowFlags=set of TModelRowFlag; //**lsDefault=lsNone in drawer setting, otherwise (in model settings) it means "use drawer setting" //**lsNone=no lines, lsLinear=the points are connected with straight lines //**lsCubicSpline=the points are connected with a normal cubic spline (needing O(n) additional memory) //**lsLocalCubicSpline=the points are connected with a pseudo cubic spline (needing no additional memory, but looks not so nicely) TLineStyle=(lsDefault, lsNone, lsLinear, lsCubicSpline, lsLocalCubicSpline); TPointStyle = (psDefault, psNone, psPixel, psCircle, psRectangle, psPlus, psCross); TDiagramFillStyle = (fsNone, fsLastOverFirst, fsMinOverMax); //**<controls if the space under a line is filled. fsLastOverFirst fills one row after one, fsMinOverMax draw each x-position separately TFillGradientFlags = set of (fgGradientX, fgGradientY); //**< controls the color gradient for filling. Notice that fgGradientY is much slower since it switch to single pixel drawing (but fgGradientX makes no difference) { TAbstractDiagramModel } {** This is the abstract model class which stores the data to be shown If you want full customization you can use it as base class, but in most cases a TDiagramDataListModel is easier } TAbstractDiagramModel = class(TPersistent) private FOnModified: TNotifyEvent; FSplines: array of array of TDiagramSplinePiece; //**stores a spline interpolation of the data (only if necessary) FmodifiedSinceSplineCalc: longint; //0: not modified, 1: modified since calculateSplines(<>lsCubicSpline), 2: modified since calculateSplines(lsCubicSpline) FDestroyEvents,fmodifiedEvents: TMethodList; procedure calculateSplines(defaultLineStyle: TLineStyle); //**< calculates the splines if needed (O(n) memory) procedure SetOnModified(const AValue: TNotifyEvent); protected procedure doModified(row:longint=-1); //**<Call when ever the model data has been changed (give row=-1 if all rows are modified) (it especially important with cubic splines, because they aren't calculated if doModified isn't called) public constructor create; destructor destroy;override; //**This returns the number of data rows (override if you use more than 1) function dataRows: longint; virtual; //**This returns the title of every data row for the legend function dataTitle(i:longint):string; virtual; //**This setups the canvas (override it to set the color, set pen and brush to the same) procedure setupCanvasForData(i:longint; c: TCanvas); virtual; //**Returns the count of data points in a given row function dataPoints(i:longint):longint; virtual;abstract; //**This returns the actual data (you must override it), j from 0 to dataPoints(i)-1, the must be in sorted order (x[i]<x[i+1]) procedure data(i,j:longint; out x,y:float); virtual;abstract; //**Set the data point and returns the new index (default does nothing and returns j) (if you override it, keep in mind that data must return its values in a sorted order) function setData(i,j:longint; const x,y:float):integer;virtual; //**Add a data point and returns the new index (default does nothing and returns -1) (if you override it, keep in mind that data must return its values in a sorted order) function addData(i:longint; const x,y:float):integer;virtual; //**removes a certain data point (default does nothing) procedure removeData(i,j:longint);virtual; //**returns the minimum x (default first data point, O(1)) function minX(i:longint):float; virtual; //**returns the maximum x (default last data point, O(1)) function maxX(i:longint):float; virtual; //**returns the minimum value (default scans all values, O(n)) function minY(i:longint):float; virtual; //**returns the maximum value (default scans all values, O(n)) function maxY(i:longint):float; virtual; function getFlags: TModelFlags; virtual;//**<returns model flags (e.g. editable) function getRowFlags(i:longint): TModelRowFlags; virtual; //**<returns flags for a given row function getRowLineStyle(i:longint):TLineStyle; virtual; //**<overrides drawer line style function getRowPointStyle(i:longint):TPointStyle; virtual; //**<overrides drawer line style //**Searchs the point in row i at position x,y with xtolerance, ytolerance //**If y is NaN, only the x position is used //**If ytolerance is NaN, the x tolerance is used for it //**If the point isn't found, it returns -1 //**The default implementation checks all points TODO: implement binary search function find(i:longint; const x:float; const y:float; const xtolerance:float=DiagramEpsilon; const ytolerance:float=NaN):longint;virtual; //**like find but set the position to the correct values (default calls find) function findAndGet(i:longint; var x:float; var y:float; const xtolerance:float=DiagramEpsilon; const ytolerance:float=NaN):longint;virtual; //**like find but searchs in all rows and returns the correct one (default calls find) function findWithRow(out i:longint; const x:float; const y:float; const xtolerance:float=DiagramEpsilon; const ytolerance:float=NaN):longint;virtual; //**like findRow but set the position to the correct values (default calls findAndGet) function findWithRowAndGet(out i:longint; var x:float; var y:float; const xtolerance:float=DiagramEpsilon; const ytolerance:float=NaN):longint;virtual; function dataX(i,j:longint):float; //**<returns x of point i,j, calls data function dataY(i,j:longint):float; //**<returns y of point i,j, calls data function minX:float; function maxX:float; function minY:float; function maxY:float; //**this returns the position of the interpolation line (linear/cubic) in data coordinates function lineApproximationAtX(const defaultLineStyle:TLineStyle; i:longint; const x: float): float; //**finds a line like find. (since the line is 1-dimensional the x coordinate is not sufficient and has to be exact) function findLineApproximation(const defaultLineStyle:TLineStyle; const x,y:float; const ytolerance: float=DiagramEpsilon): longint; procedure addModifiedHandler(event: TNotifyEvent); procedure removeModifiedHandler(event: TNotifyEvent); procedure addDestroyHandler(event: TNotifyEvent); procedure removeDestroyHandler(event: TNotifyEvent); property OnModified:TNotifyEvent read FOnModified write SetOnModified; end; { TDiagramDrawer } TClipValues = set of (cvX, cvY); //**This class draws the data model into a TBitmap TDiagramDrawer = class(TPersistent) private FAutoSetRangeX: boolean; FAutoSetRangeY: boolean; FBackColor: TColor; FClipValues: TClipValues; FDataBackColor: TColor; FFillGradient: TFillGradientFlags; FLayoutModified: Boolean; FLineStyle: TLineStyle; FModifiedEvent: TNotifyEvent; FFillStyle: TDiagramFillStyle; Flegend: TLegend; FModel: TAbstractDiagramModel; FModelModified: boolean; //don't use fmodel.modified => problem with multiple views (but drawer:1<->1:view) FModelOwnership: boolean; FPointSize: longint; FPointStyle: TPointStyle; FRangeMaxX: float; FRangeMaxY: float; FRangeMinX: float; FRangeMinY: float; fvalueAreaX,FValueAreaY,FValueAreaWidth,FValueAreaHeight,FValueAreaRight,FValueAreaBottom: longint; FDiagram: TBitmap; FLAxis,FYMAxis,FRAxis, FTAxis,FXMAxis,FBAxis: TAxis; procedure doModified; procedure SetAutoSetRangeX(const AValue: boolean); procedure SetAutoSetRangeY(const AValue: boolean); procedure SetBackColor(const AValue: TColor); procedure SetClipValues(const AValue: TClipValues); procedure SetDataBackColor(const AValue: TColor); procedure SetFillGradient(const AValue: TFillGradientFlags); procedure SetFillStyle(const AValue: TDiagramFillStyle); procedure SetLineStyle(const AValue: TLineStyle); procedure SetModel(AValue: TAbstractDiagramModel);overload; procedure SetPointSize(const AValue: longint); procedure SetPointStyle(const AValue: TPointStyle); procedure SetRangeMaxX(const AValue: float); procedure SetRangeMaxY(const AValue: float); procedure SetRangeMinX(const AValue: float); procedure SetRangeMinY(const AValue: float); public constructor create; function update(): TBitmap; //**<Redraws the bitmap and returns it (and updates the Diagram property) destructor destroy;override; //**Sets the model to be drawn, if takeOwnership is true, then the model is freed automatically by the drawer, otherwise you have to free it yourself procedure SetModel(amodel: TAbstractDiagramModel; takeOwnership: boolean);overload; function posToDataX(x: longint): float; //**<Translate a pixel position in the bitmap to the coordinates used by the model function posToDataY(y: longint): float; //**<Translate a pixel position in the bitmap to the coordinates used by the model function dataToPosX(const x: float): integer; //**<Translate model coordinates to the corresponding pixel in the bitmap (rounds) function dataToPosY(const y: float): integer; //**<Translate model coordinates to the corresponding pixel in the bitmap (rounds) function pixelSizeX: float; //**< Returns the width of one output pixel in data coordinates function pixelSizeY: float; //**< Returns the height of one output pixel in data coordinates property Diagram: TBitmap read FDiagram; //**<Last drawn bitmap property valueAreaX: longint read fvalueAreaX; property ValueAreaY: longint read fvalueAreaY; property ValueAreaWidth: longint read FValueAreaWidth; property ValueAreaHeight: longint read FValueAreaHeight; property ValueAreaRight: longint read FValueAreaRight; property ValueAreaBottom: longint read FValueAreaBottom; published property RangeMinX: float read FRangeMinX write SetRangeMinX; property RangeMaxX: float read FRangeMaxX write SetRangeMaxX; property RangeMinY: float read FRangeMinY write SetRangeMinY; property RangeMaxY: float read FRangeMaxY write SetRangeMaxY; property AutoSetRangeX: boolean read FAutoSetRangeX write SetAutoSetRangeX; property AutoSetRangeY: boolean read FAutoSetRangeY write SetAutoSetRangeY; property legend:TLegend read Flegend; //**< Class for legend settings property LeftAxis: TAxis read FLAxis; //**< Axis left from the value area property RightAxis: TAxis read FRAxis; //**< Axis right to the value area property TopAxis: TAxis read FTAxis; //**< Axis over the value area property BottomAxis: TAxis read FBAxis; //**< Axis below the value area property HorzMidAxis: TAxis read FXMAxis; //**< Axis from the left to the right side in the vertical mid of the value area (like the x-axis in an plot) property VertMidAxis: TAxis read FYMAxis; //**< Axis from the top to the bottom side in the horizontal mid of the value area (like the x-axis in an plot) property LineStyle: TLineStyle read FLineStyle write SetLineStyle; //**< Line style used to draw the lines (can be overridden by the model) property PointStyle: TPointStyle read FPointStyle write SetPointStyle; //**< Point style used to draw points (can be overridden by the model) property PointSize: longint read FPointSize write SetPointSize; property FillGradient: TFillGradientFlags read FFillGradient write SetFillGradient ; property FillStyle: TDiagramFillStyle read FFillStyle write SetFillStyle; property Model: TAbstractDiagramModel read FModel write SetModel; property BackColor: TColor read FBackColor write SetBackColor; //**<Background color around the value area property DataBackColor: TColor read FDataBackColor write SetDataBackColor; //**<Background color of the value area property ClipValues: TClipValues read FClipValues write SetClipValues; end; { TDiagramView } TDiagramPointMovement=(pmSimple, pmAffectNeighbours); TDiagramEditAction=(eaMovePoints, eaAddPoints, eaDeletePoints); TDiagramEditActions=set of TDiagramEditAction; //**This class shows a model and allows the user to interact with it TDiagramView = class (TCustomControl) private FAllowedEditActions: TDiagramEditActions; FPointMovement: TDiagramPointMovement; FSelRow,FSelPoint:longint; FSelPointMoving: boolean; FHighlightPoint: TDataPoint; FDrawer: TDiagramDrawer; FModel: TAbstractDiagramModel; procedure modelChanged(sender:Tobject); procedure modelDestroyed(sender:Tobject); procedure layoutChanged(sender:Tobject); procedure DoOnResize;override; procedure SetAllowedEditActions(const AValue: TDiagramEditActions); procedure SetModel(const AValue: TAbstractDiagramModel); procedure SetPointMovement(const AValue: TDiagramPointMovement); public constructor create(aowner:TComponent);override; destructor destroy;override; //**Sets the model, if takeOwnership is true, the model will automatically be freed if the view is freed procedure SetModel(amodel: TAbstractDiagramModel; takeOwnership: boolean=false); procedure paint;override; procedure MouseDown(Button: TMouseButton; Shift:TShiftState; X,Y:Integer); override; procedure MouseMove(Shift: TShiftState; X,Y: Integer);override; procedure MouseUp(Button: TMouseButton; Shift:TShiftState; X,Y:Integer); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure DoExit; override; published //**Drawer drawing the diagram, use it to read/set everything relating to the visual output property Drawer: TDiagramDrawer read FDrawer; //**Specifies how points are moved property PointMovement: TDiagramPointMovement read FPointMovement write SetPointMovement; //**Controls how the model can be modified property AllowedEditActions: TDiagramEditActions read FAllowedEditActions write SetAllowedEditActions; //**The model assigned to this view property Model: TAbstractDiagramModel read FModel write SetModel; property OnAlignInsertBefore; property OnAlignPosition; property OnDockDrop; property OnDockOver; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnUnDock; property OnUTF8KeyPress; property OnConstrainedResize; property OnContextPopup; property OnDblClick; property OnTripleClick; property OnQuadClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseEnter; property OnMouseLeave; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnStartDock; property OnStartDrag; end; { TDataList } TDataList=class(TPersistent) private FLineStyle: TLineStyle; FPointStyle: TPointStyle; FRowNumber: longint; FColor: TColor; FFlags: TModelRowFlags; Ftitle: string; procedure DoModified; procedure SetColor(const AValue: TColor); procedure SetFlags(const AValue: TModelRowFlags); procedure SetLineStyle(const AValue: TLineStyle); procedure SetPointStyle(const AValue: TPointStyle); procedure SetTitle(const AValue: string); protected maxX,minX,maxY,minY:float; owner: TAbstractDiagramModel; points: array of TDataPoint; pointCount: longint; //lastRead: longint; //**<last point returned by nextX (needed for O(1) index lookup) procedure rescanYBorder; function resortPoint(i:longint):integer; public constructor create(aowner:TAbstractDiagramModel; aRowNumber: longint; acolor: TColor); procedure assign(list:TDataList); //**<assign another list, including colors, etc. (only the owner is excluded) procedure assign(list:TPersistent);override; //function getPoint(x:longint): longint; procedure clear(keepMemory: boolean=false); //**<removes all points, if keepMemory is true, the memory of the points is not freed function count:longint; //**adds a point at position (x,y) in the sorted list, removing duplicates on same x. (possible moving all existing points => O(1) if called in right order, O(n) if the inserted point belongs to the beginnning). //**It does use an intelligent growth strategy (size *2 if < 512, size+=512 otherwise, starting at 8) function addPoint(x,y:float):longint; overload; //**adds a point at position (x+1,y) in the sorted list. (possible moving all existing points). //**It does use an intelligent growth strategy function addPoint(y:float):longint; overload; //**sets the point j to the position x,y; reorders point if necessary (possible moving the point j to another index) (can change minY, maxY) function setPoint(j:longint; const x,y:float):integer; //**removes point j procedure removePoint(j:longint); //xxreads the points from a string by calling sscanf multiple times //procedure scanFStr(const s,format:string); procedure point(i:longint; out x,y: float); //**<returns the data at position i published property Color:TColor read FColor write SetColor; property Title:string read Ftitle write Settitle; property Flags:TModelRowFlags read FFlags write SetFlags; property LineStyle: TLineStyle read FLineStyle write SetLineStyle; property PointStyle: TPointStyle read FPointStyle write SetPointStyle; end; { TDiagramDataListModel } TDiagramDataListModel = class (TAbstractDiagramModel) private FFlags: TModelFlags; FLists: TFPList; function getDataList(i:Integer): TDataList; procedure SetFlags(const AValue: TModelFlags); public constructor create; destructor destroy;override; //**delete all lists procedure deleteLists;virtual; //**Set the count of data lists procedure setDataRows(c:longint); procedure deleteDataRow(i: longint); function addDataList:TDataList; //**This returns the number of data lists function dataRows: longint; override; //**This returns the title of every data list for the legend function dataTitle(i:longint):string; override; //**This set the color to the data list color procedure setupCanvasForData(i:longint; c: TCanvas); override; //**This returns the number of data points in a given lists function dataPoints(i:longint): longint; override; //**This returns the actual data (amortized O(1) if called in correct order) procedure data(i,j:longint; out x,y:float); override; //**Set the data point (only accept changes if flags contains mfEditable, use lists[i].setPoint in other cases) function setData(i,j:longint; const x,y:float):integer;override; //**Add a data point to an existing row and returns the new index (only accept changes if flags contains mfEditable, use lists[i].addPoint in other cases) function addData(i:longint; const x,y:float):integer;override; //**removes the data point (only accept changes if flags contains mfEditable, use lists[i].removePoint in other cases) procedure removeData(i,j:longint);override; //**returns the minimum x function minX(i:longint):float; override;overload; //**returns the maximum x function maxX(i:longint):float; override;overload; //**returns the minimum value (O(1)) function minY(i:longint):float; override;overload; //**returns the maximum value (O(1)) function maxY(i:longint):float; override;overload; function GetFlags: TModelFlags;override; function getRowFlags(i:longint): TModelRowFlags; override; function getRowLineStyle(i:longint):TLineStyle; override; function getRowPointStyle(i:longint):TPointStyle; override; property lists[i:Integer]: TDataList read getDataList; default; published property Flags: TModelFlags read GetFlags write SetFlags; end; { TDiagramFixedWidthCircularDataListModel } //**this is a special model you probably don't need //**It is like a TDiagramDataListModel but ensures that the last and first point always have //**the same y-position if modified by the user and that he can't modify their x-position //**(the application interface with lists[i] can modify everything) TDiagramFixedWidthCircularDataListModel = class (TDiagramDataListModel) function setData(i,j:longint; const x,y:float):integer;override; function addData(i:longint; const x,y:float):integer;override; procedure removeData(i,j:longint);override; end; { TDiagramModelMerger } //**This model merges several models together, so they can be drawn at the same time //**It can also hide certain rows TDiagramModelMerger = class(TAbstractDiagramModel) private FBaseModel: integer; FHideCertainRows: boolean; FRowVisible: array of boolean; fmodels: TFPList; ownerShipModels: TFPList; function GetModel(i: longint): TAbstractDiagramModel; function rowToRealRow(i:longint; out m, r: longint):boolean; function GetRowVisible(i: integer): boolean; procedure SetBaseModel(const AValue: integer); procedure SetHideCertainRows(const AValue: boolean); procedure SetModel(i: longint; const AValue: TAbstractDiagramModel); procedure SetRowVisible(i: integer; const AValue: boolean); procedure subModelModified(sender: TObject); procedure subModelDestroyed(sender: TObject); public //**adds a model to the model list (if takeOwnership is true, this model is automatically freed in the destructor) procedure addModel(model: TAbstractDiagramModel; takeOwnership: boolean=false); //**removes an model from the list and adds a new one at this position (or at the end if oldModel don't exist) procedure replaceModel(oldModel, newModel: TAbstractDiagramModel; takeOwnership: boolean=false); //**removes a certain model (and frees it, if takeOwnership was true) procedure removeModel(model:TAbstractDiagramModel); //**removes all models (and frees them, if takeOwnership was true) procedure removeAllModels(); //**Deletes a model procedure deleteModel(i:longint); //**Sets a model procedure SetModel(i: longint; const AValue: TAbstractDiagramModel; takeOwnerShip: boolean=false); property Models[i:longint]: TAbstractDiagramModel read GetModel write SetModel; constructor create; constructor create(model: TAbstractDiagramModel; takeOwnership: boolean=false); constructor create(model1, model2: TAbstractDiagramModel; takeOwnership1:boolean=false; takeOwnership2: boolean=false); destructor destroy;override; //overriden model functions function dataRows: longint; override; function dataTitle(i:longint):string; override; procedure setupCanvasForData(i:longint; c: TCanvas); override; function dataPoints(i:longint):longint; override; procedure data(i,j:longint; out x,y:float); override; function setData(i,j:longint; const x,y:float):integer;override; function addData(i:longint; const x,y:float):integer;override; procedure removeData(i,j:longint);override; function minX(i:longint):float; override; function maxX(i:longint):float; override; function minY(i:longint):float; override; function maxY(i:longint):float; override; function getFlags: TModelFlags; override;//**<returns model flags (e.g. editable) function getRowFlags(i:longint): TModelRowFlags; override; //**<returns flags for a given row function getRowLineStyle(i:longint):TLineStyle; override; //**<overrides drawer line style function getRowPointStyle(i:longint):TPointStyle; override; //**<overrides drawer line style //**This controls if there are invisible rows. Set it to false to make all rows visible property HideCertainRows: boolean read FHideCertainRows write SetHideCertainRows; //**If RowVisibleAt[i] is false, the row with number i is hidden //**Notice that this don't track rows, e.g. if you have one hidden row and remove this one, the row with its number (= the next row, after the deleted one) will be hidden //**Setting it to false for one (existing) index, sets HideCertainRows to true //**And hidden rows seems to be completely removed from this model, so if row 0 is hidden, data(0,...) returns the data for row 1 (of course only if row 1 isn't hidden) (the sub models this model is based on aren't effected at all) property RowVisibleAt[i:integer]: boolean read GetRowVisible write SetRowVisible; //**Model used for row independent properies (e.g. model flags) property BaseModel: integer read FBaseModel write SetBaseModel; end; implementation { Math helper functions } const PInfinity=Infinity; MInfinity=NegInfinity; function calcSpline(const spline:TDiagramSplinePiece; const x:float):float; begin //result:=a*x*x*x+b*x*x+c*x+d; with spline do result:=((a*x+b)*x+c)*x+d; end; procedure updateSpline3P(var spline: TDiagramSplinePiece; const x1,y1,x2,y2,x3,y3: float); //P(x1) = y1, P(x2) = y2, P(x3) = y3 //P'(x1) = P0'(x1) var od1, fr: float; begin with spline do begin od1:= (3*a*x1+2*b)*x1+c; //P0'(ox) = 3*a*x*x+2*b*x+c { SOLVE([a·x1^3 + b·x1*x1 + c·x1 + d = y1, a·x2^3 + b·x2^2 + c·x2 + d = y2, 3·a·x1·x1 + 2·b·ox + c = od1, a·x3^3 + b·x3^2 + c·x3 + d = y3], [b, a, c, d]) } fr:=((x1*x1-2*x1*x3+x3*x3)*(x1*x1-2*x1*x2+x2*x2)*(x2-x3)); if abs(fr)<DiagramEpsilon then exit; fr:=1/fr; //TODO: optimize/make human readable a:=fr*(od1*(x1*x1-x1*(x2+x3)+x2*x3)*(x2-x3)+x1*x1*(y2-y3)-2*x1*(x2*(y1-y3)+x3*(y2-y1))+x2*x2*(y1-y3)+x3*x3*(y2-y1)); b:=-fr*(od1*(x1*x1*x1-x1*(x2*x2+x2*x3+x3*x3)+x2*x3*(x2+x3))*(x2-x3)+2*x1*x1*x1*(y2-y3)-3*x1*x1*(x2*(y1-y3)+x3*(y2-y1))+x2*x2*x2*(y1-y3)+x3*x3*x3*(y2-y1)); c:=fr*(od1*(x2-x3)*(x1*x1*x1*(x2+x3)-x1*x1*(x2*x2+x2*x3+x3*x3)+x2*x2*x3*x3)+x1*(x1*x1*x1*(y2-y3)-3*x1*(x2*x2*(y1-y3)+x3*x3*(y2-y1))+2*(x2*x2*x2*(y1-y3)+x3*x3*x3*(y2-y1)))); d:=-fr*(od1*x1*x2*x3*(x1*x1-x1*(x2+x3)+x2*x3)*(x2-x3)+x1*x1*x1*x1*(x3*y2-x2*y3)+2*x1*x1*x1*(x2*x2*y3-x3*x3*y2)-x1*x1*(x2*x2*x2*y3+3*x2*x2*x3*y1-3*x2*x3*x3*y1-x3*x3*x3*y2)+2*x1*x2*x3*y1*(x2+x3)*(x2-x3)-x2*x2*x3*x3*y1*(x2-x3)); (* For smooth second derivate, ignoring third point: { SOLVE([a·x1^3 + b·x1*x1 + c·x1 + d = y1, a·x2^3 + b·x2^2 + c·x2 + d = y2, 3·a·x1·x1 + 2·b·x1 + c = od1, 6*a*x1+2*b=od2], [b, a, c, d]) } { fr:=((x1*x1-2*x1*x3+x3*x3)*(x1*x1-2*x1*x2+x2*x2)*(x2-x3)); if abs(fr)<DiagramEpsilon then exit; fr:=1/fr;} //TODO: optimize a := - 0.5*(2*od1*(x1 - x2) - od2*(x1*x1 - 2*x1*x2 + x2*x2) - 2*(y1 - y2))/(x1*x1*x1 - 3*x1*x1*x2 + 3*x1*x2*x2 - x2*x2*x2); b := 0.5*(6*od1*x1*(x1 - x2) - od2*(2*x1*x1*x1 - 3*x1*x1*x2 + x2*x2*x2) + 6*x1*(y2 - y1))/(x1*x1*x1 - 3*x1*x1*x2 + 3*x1*x2*x2 - x2*x2*x2); c := 0.5*(x1*(od2*(x1*x1*x1 - 3*x1*x2*x2 + 2*x2*x2*x2) + 6*x1*(y1 - y2)) - 2*od1*(2*x1*x1*x1 - 3*x1*x2*x2 + x2*x2*x2))/(x1*x1*x1 - 3*x1*x1*x2 + 3*x1*x2*x2 - x2*x2*x2); d := 0.5*(2*od1*x1*x2*(2*x1*x1 - 3*x1*x2 + x2*x2) - od2*x1*x1*x2*(x1*x1 - 2*x1*x2 + x2*x2) + 2*(x1*x1*x1*y2 - 3*x1*x1*x2*y1 + 3*x1*x2*x2*y1 - x2*x2*x2*y1))/(x1*x1*x1 - 3*x1*x1*x2 + 3*x1*x2*x2 - x2*x2*x2);*) end; end; //faster than byte versions procedure RedGreenBlue(rgb: TColor; out Red, Green, Blue: integer); begin Red := rgb and $000000ff; Green := (rgb shr 8) and $000000ff; Blue := (rgb shr 16) and $000000ff; end; function RGBToColor(R, G, B: integer): TColor; begin Result := (B shl 16) or (G shl 8) or R; end; { Axis } procedure TAxis.doModified(sender:tobject); begin if assigned(FModifiedEvent) then FModifiedEvent(self); end; procedure TAxis.SetGridLinePen(const AValue: TPen); begin if FGridLinePen=AValue then exit; FGridLinePen.Assign(AValue); domodified(self); end; procedure TAxis.SetLinePen(const AValue: TPen); begin if FLinePen=AValue then exit; FLinePen.Assign(AValue); domodified(self); end; procedure TAxis.Setmax(const AValue: float); begin if Fmax=AValue then exit; Fmax:=AValue; doModified(self); end; procedure TAxis.Setmin(const AValue: float); begin if Fmin=AValue then exit; Fmin:=AValue; doModified(self); end; procedure TAxis.SetrangePolicy(const AValue: TRangePolicy); begin if FrangePolicy=AValue then exit; FrangePolicy:=AValue; doModified(self); end; procedure TAxis.Setresolution(const AValue: float); begin if AValue<=0 then exit; if Fresolution=AValue then exit; Fresolution:=AValue; doModified(self); end; procedure TAxis.SetShowText(const AValue: boolean); begin if FShowText=AValue then exit; FShowText:=AValue; doModified(self); end; procedure TAxis.SetvalueTranslate(const AValue: TValueTranslateEvent); begin if FvalueTranslate=AValue then exit; FvalueTranslate:=AValue; doModified(self); end; procedure TAxis.SetVisible(const AValue: boolean); begin if FVisible=AValue then exit; FVisible:=AValue; doModified(self); end; function TAxis.doTranslate(const i:float): string; begin if frac(i)<1e-16 then result:=inttostr(round(i)) else if resolution>1 then result:=inttostr(round(i)) else result:=format('%.2g',[i]); if assigned(valueTranslate) then valueTranslate(self,i,result); end; constructor TAxis.create(); begin FGridLinePen:=TPen.Create; FLinePen:=TPen.Create; FGridLinePen.OnChange:=@doModified; FLinePen.OnChange:=@doModified; end; destructor TAxis.destroy(); begin inherited destroy(); end; function TAxis.translate(const i: float): string;inline; begin result:=doTranslate(i); end; procedure TAxis.rangeChanged(const rmin,rmax:float; realSize: longint); begin {if max-min<imageSize then begin case imageSize div (max-min) of 0..9: resolution:=10; else resolution:=1; end; end else begin case (max-min) div imageSize of 0..9: resolution:=1; 10..99: resolution:=10; 100..999: resolution:=100; 1000..9999: resolution:=1000; end; end;} //Count of intervals: (max-min) / resolution //Size " " : imageSize / Count if IsInfinite(rmin) or IsInfinite(rmax) or IsNan(rmin) or IsNan(rmax) or (realSize=0) then begin resolution:=NaN; exit; end; min:=rmin; max:=rmax; if abs(max-min)<1e-16 then resolution:=1 else if realSize / (max-min)>20 then resolution:=1 else if realSize / (max-min)>0 then resolution:=(max-min)*30 / realSize else resolution:=(max-min)*30 / realSize; end; procedure TDataList.point(i: longint; out x, y: float); begin if (i<0) or (i>=pointCount) then begin x:=nan; y:=nan; exit; end; x:=points[i].x; y:=points[i].y; end; procedure TDataList.Settitle(const AValue: string); begin if Ftitle=AValue then exit; Ftitle:=AValue; doModified; end; procedure TDataList.DoModified; begin if Assigned(owner) then owner.doModified(FRowNumber); end; procedure TDataList.SetColor(const AValue: TColor); begin if FColor=AValue then exit; FColor:=AValue; doModified; end; procedure TDataList.SetFlags(const AValue: TModelRowFlags); begin if FFlags=AValue then exit; FFlags:=AValue; DoModified; end; procedure TDataList.SetLineStyle(const AValue: TLineStyle); begin if FLineStyle=AValue then exit; FLineStyle:=AValue; DoModified; end; procedure TDataList.SetPointStyle(const AValue: TPointStyle); begin if FPointStyle=AValue then exit; FPointStyle:=AValue; DoModified; end; procedure TDataList.rescanYBorder; var i:longint; begin maxY:=MInfinity; minY:=PInfinity; for i:=0 to pointCount-1 do begin if points[i].y<minY then minY:=points[i].y; if points[i].y>maxY then maxY:=points[i].y; end; end; function TDataList.resortPoint(i: longint):integer; var temp:TDataPoint; begin if i>=pointCount then exit; //check left side while (i>=1) and (points[i-1].x>points[i].x) do begin temp:=points[i]; points[i]:=points[i-1]; points[i-1]:=temp; i-=1; end; //check right side while (i<pointCount-1) and (points[i].x>points[i+1].x) do begin temp:=points[i]; points[i]:=points[i+1]; points[i+1]:=temp; i+=1; end; result:=i; minX:=points[0].x; maxX:=points[pointCount-1].x; end; constructor TDataList.create(aowner: TAbstractDiagramModel; aRowNumber: longint;acolor: TColor); begin FRowNumber:=aRowNumber; owner:=aowner; fcolor:=acolor; maxX:=MInfinity; minX:=PInfinity; maxY:=MInfinity; minY:=PInfinity; ftitle:='data row'; end; procedure TDataList.assign(list: TDataList); begin color:=list.color; title:=list.title; points:=list.points; Setlength(points,length(points));//copy pointCount:=list.pointCount; MaxX:=list.maxX; minX:=list.minX; maxY:=list.maxY; minY:=list.minY; if assigned(owner) then owner.doModified(FRowNumber); end; procedure TDataList.assign(list: TPersistent); begin if list is tdatalist then assign(TDataList(list)) else inherited assign(list); end; procedure TDataList.clear(keepMemory: boolean=false); begin if not keepMemory then setlength(points,0); pointCount:=0; maxX:=MInfinity; minX:=PInfinity; maxY:=MInfinity; minY:=PInfinity; if assigned(owner) then owner.doModified(FRowNumber); end; function TDataList.count: longint; begin result:=pointCount; end; function TDataList.addPoint(x,y:float):longint; var i:integer; begin if x<minX then minX:=x; if x>maxX then maxX:=x; if y<minY then minY:=y; if y>maxY then maxY:=y; if pointCount=0 then begin setlength(points,8); pointCount:=1; points[0].x:=x; points[0].y:=y; if assigned(owner) then owner.doModified(FRowNumber); exit(0); end; if pointCount=length(points) then begin //resize if pointCount<512 then setlength(points,length(points)*2) else setlength(points,length(points)+512); end; if (points[pointCount-1].x>=x) then begin i:=0; while i<pointCount do begin if points[i].x=x then begin if points[i].y<>y then begin points[i].y:=y; //this could break the minY/maxY if assigned(owner) then owner.doModified(FRowNumber); end; exit(i); end else if points[i].x>x then break; inc(i); end; Move(points[i],points[i+1],sizeof(points[0])*(pointCount-i)); inc(pointCount); end else begin i:=pointCount; inc(pointCount); end; points[i].x:=x; points[i].y:=y; if assigned(owner) then owner.doModified(FRowNumber); result:=i; end; function TDataList.addPoint(y:float):longint; begin if pointCount=0 then result:=addPoint(0,y) else result:=addPoint(points[pointCount-1].x+1,y); end; function TDataList.setPoint(j: longint; const x, y: float):integer; var wasBorder:boolean; begin if (j<0) then exit; if (j>=pointCount) then begin addPoint(x,y); exit; end; wasBorder:=(points[j].y<=minY) or (points[j].y>=maxY); points[j].x:=x; points[j].y:=y; if wasBorder then rescanYBorder; result:=resortPoint(j); if assigned(owner) then owner.doModified(FRowNumber); end; procedure TDataList.removePoint(j: longint); var wasBorder:boolean; begin if (j<0) or (j>=pointCount) then exit; if j=pointCount-1 then begin pointCount-=1; if pointCount>0 then begin maxX:=points[pointCount-1].x; if (maxY<=points[j].y) or (minY>=points[j].y) then rescanYBorder; end; if assigned(owner) then owner.doModified(FRowNumber); exit; end; wasBorder:=(points[j].y<=minY) or (points[j].y>=maxY); move(points[j+1],points[j],sizeof(points[j])*(pointCount-j-1)); pointCount-=1; if j=0 then minX:=points[0].x; if wasBorder then rescanYBorder; if assigned(owner) then owner.doModified(FRowNumber); end; { procedure TDataList.scanFStr(const s, format: string); var c:string; len: integer; x,y:float; begin clear(); c:=s; while true do begin len:=SScanf(c,format,[@x,@y]); if len=0 end; } //================================================================================== procedure TDiagramDrawer.SetModel(AValue: TAbstractDiagramModel); begin SetModel(AValue,false); end; procedure TDiagramDrawer.SetPointSize(const AValue: longint); begin if FPointSize=AValue then exit; FPointSize:=AValue; doModified; end; procedure TDiagramDrawer.SetPointStyle(const AValue: TPointStyle); begin if FPointStyle=AValue then exit; FPointStyle:=AValue; doModified; end; procedure TDiagramDrawer.SetRangeMaxX(const AValue: float); begin if FRangeMaxX=AValue then exit; FRangeMaxX:=AValue; doModified; end; procedure TDiagramDrawer.SetRangeMaxY(const AValue: float); begin if FRangeMaxY=AValue then exit; FRangeMaxY:=AValue; doModified; end; procedure TDiagramDrawer.SetRangeMinX(const AValue: float); begin if FRangeMinX=AValue then exit; FRangeMinX:=AValue; doModified; end; procedure TDiagramDrawer.SetRangeMinY(const AValue: float); begin if FRangeMinY=AValue then exit; FRangeMinY:=AValue; doModified; end; procedure TDiagramDrawer.doModified; begin FLayoutModified:=true; if Assigned(FModifiedEvent) then FModifiedEvent(self); end; procedure TDiagramDrawer.SetAutoSetRangeX(const AValue: boolean); begin if FAutoSetRangeX=AValue then exit; FAutoSetRangeX:=AValue; if assigned(fmodel) then fmodelModified:=true; //cause full update doModified; end; procedure TDiagramDrawer.SetAutoSetRangeY(const AValue: boolean); begin if FAutoSetRangeY=AValue then exit; FAutoSetRangeY:=AValue; if assigned(fmodel) then fmodelModified:=true; //cause full update doModified; end; procedure TDiagramDrawer.SetBackColor(const AValue: TColor); begin if FBackColor=AValue then exit; FBackColor:=AValue; doModified; end; procedure TDiagramDrawer.SetClipValues(const AValue: TClipValues); begin if FClipValues=AValue then exit; FClipValues:=AValue; doModified; end; procedure TDiagramDrawer.SetDataBackColor(const AValue: TColor); begin if FDataBackColor=AValue then exit; FDataBackColor:=AValue; doModified; end; procedure TDiagramDrawer.SetFillGradient(const AValue: TFillGradientFlags); begin if FFillGradient=AValue then exit; FFillGradient:=AValue; doModified; end; procedure TDiagramDrawer.SetFillStyle(const AValue: TDiagramFillStyle); begin if FFillStyle=AValue then exit; FFillStyle:=AValue; doModified; end; procedure TDiagramDrawer.SetLineStyle(const AValue: TLineStyle); begin if FLineStyle=AValue then exit; FLineStyle:=AValue; if assigned(FModel) then FModel.calculateSplines(LineStyle); doModified; end; constructor TDiagramDrawer.create; begin FLAxis:=TAxis.Create; FBAxis:=TAxis.Create; FLAxis.rangePolicy:=rpAuto; FBAxis.rangePolicy:=rpAuto; FBAxis.gridLinePen.Style:=psClear; FLAxis.gridLinePen.Color:=clGray; FBAxis.gridLinepen.Color:=clGray; FLAxis.linePen.Color:=clBlack; FBAxis.linepen.Color:=clBlack; FLAxis.Visible:=true; FBAxis.Visible:=true; FRAxis:=TAxis.create; FRAxis.gridLinePen.Style:=psClear; FRAxis.Visible:=false; FTAxis:=TAxis.create; FTAxis.gridLinePen.Style:=psClear; FTAxis.Visible:=false; FXMAxis:=TAxis.create; FXMAxis.gridLinePen.Style:=psClear; FXMAxis.Visible:=false; FYMAxis:=TAxis.create; FYMAxis.gridLinePen.Style:=psClear; FYMAxis.Visible:=false; FDiagram:=TBitmap.Create; FDiagram.width:=300; FDiagram.height:=300; fbackColor:=clBtnFace; fdataBackColor:=clSilver; flegend:=TLegend.Create; flegend.auto:=true; flegend.visible:=true; flegend.color:=clBtnFace; fLineStyle:=lsLinear; FPointSize:=3; fRangeMinX:=0; fRangeMaxX:=100; fRangeMinY:=0; fRangeMaxY:=100; FAutoSetRangeX:=true; FAutoSetRangeY:=true; fvalueAreaX:=0; FValueAreaY:=0; FValueAreaWidth:=fdiagram.width; FValueAreaRight:=fdiagram.width; FValueAreaHeight:=fdiagram.height; FValueAreaBottom:=fdiagram.height; FFillGradient:=[fgGradientX]; end; destructor TDiagramDrawer.destroy; begin FRAxis.free; FTAxis.free; FXMAxis.free; FYMAxis.free; FLAxis.free; FBAxis.free; FDiagram.free; legend.free; SetModel(nil); inherited; end; procedure TDiagramDrawer.SetModel(amodel: TAbstractDiagramModel; takeOwnership: boolean); begin if assigned(FModel) and FModelOwnership then FreeAndNil(FModel); FModel:=amodel; FModelOwnership:=takeOwnership; end; function TDiagramDrawer.update(): TBitmap; const AXIS_SIZE=20; AXIS_DASH_SIZE=2; var xstart,ystart,xfactor,yfactor,xend,yend: float; //copied ranges textHeightC:longint; RealValueRect: TRect; function translateX(const x:float):longint;inline; begin result:=FValueAreaX+round((x-xstart)*xfactor); end; function translateXBack(const x:longint):float;inline; begin result:=(x-FValueAreaX)/xfactor+xstart; end; function translateY(const y:float):longint;inline; begin result:=FValueAreaBottom-round((y-ystart)*yfactor); end; procedure translate(const x,y:float; out px,py:longint);inline; begin px:=FValueAreaX+round((x-xstart)*xfactor); py:=FValueAreaBottom-round((y-ystart)*yfactor); end; procedure getRPos(const i,j:longint; out px,py:longint);inline; var x,y:float; begin FModel.data(i,j,x,y); translate(x,y,px,py); end; var canvas: TCanvas; procedure drawLinearLines(id:longint); var i,x,y:longint; begin getRPos(id,0,x,y); canvas.MoveTo(x,y); for i:=1 to fModel.dataPoints(id)-1 do begin getRPos(id,i,x,y); canvas.LineTo(x,y); if x>RealValueRect.Right then break; end; end; procedure drawCubicSpline(id:longint); var i,x,y,xmax:longint; fx,lx,nx: float; begin //see also calculateSplines, here the splines map P [x1-x1, x2-x1] |-> [y1, y2] if (length(fmodel.FSplines) <= id) or (length(fmodel.FSplines[id])<fmodel.dataPoints(id)) then exit; //wtf getRPos(id,0,x,y); canvas.MoveTo(x,y); i:=0; lx:=FModel.dataX(id,0); if FModel.dataPoints(id)>1 then nx:=FModel.dataX(id,1) else nx:=lx+10; x:=translateX(FModel.minX(id)); if x<RealValueRect.Left then x:=RealValueRect.Left; xmax:=translateX(FModel.maxX(id)); if xmax>RealValueRect.Right then xmax:=RealValueRect.Right; for x:=x to xmax do begin fx:=translateXBack(x); if fx>=nx then begin while fx>=nx do begin i+=1; if i>=FModel.dataPoints(id)-1 then exit; lx:=nx; nx:=FModel.dataX(id,i+1); end; if i>=FModel.dataPoints(id)-1 then break; end; canvas.LineTo(x,translateY(calcSpline(fmodel.FSplines[id,i],fx-lx))); end; end; procedure drawCubicSpline3P(id:longint); var i,x,x1,y1:longint; fx0,fy0,fx1,fy1,fx2,fy2: float; spline: TDiagramSplinePiece; begin FillChar(spline, sizeof(spline), 0); //see also lineYatX, here the splines map P [x1, x2] |-> [y1, y2] FModel.data(id,0,fx1,fy1); translate(fx1,fy1,x1,y1); canvas.MoveTo(x1,y1); FModel.data(id,1,fx2,fy2); updateSpline3P(spline,fx1-2*(fx2-fx1),fy1,fx1,fy1,fx2,fy2); for i:=1 to fModel.dataPoints(id)-1 do begin //next point fx0:=fx1;fy0:=fy1; fx1:=fx2;fy1:=fy2; FModel.data(id,i,fx2,fy2); updateSpline3P(spline,fx0,fy0,fx1,fy1,fx2,fy2); //draw spline x:=translateX(fx0); if x>RealValueRect.Right then exit; for x:=x to translateX(fx1) do canvas.LineTo(x,translateY(calcSpline(spline,translateXBack(x)))); //canvas.LineTo(ox+x,translateY(calcSpline(spline,x/dw))); end; //last point with connection to virtual point far right updateSpline3P(spline,fx1,fy1,fx2,fy2,fx2+2*(fx2-fx1),fy2); //draw spline for x:=translateX(fx1) to translateX(fx2) do canvas.LineTo(x,translateY(calcSpline(spline,translateXBack(x)))); end; procedure drawPoints(id: longint); var i:longint; x,y: longint; ps:TPointStyle; begin ps:=FModel.getRowPointStyle(id); if ps=psDefault then ps:=PointStyle; for i:=0 to fModel.dataPoints(id)-1 do begin getRPos(id,i,x,y); if rfFullX in FModel.getRowFlags(id) then canvas.Line(fvalueAreaX,y,FValueAreaRight,y); if rfFullY in FModel.getRowFlags(id) then canvas.Line(x,fvalueAreaY,x,FValueAreaBottom); case ps of psPixel: Canvas.Pixels[x,y]:=canvas.Pen.Color; psCircle: canvas.EllipseC(x,y,pointSize,pointSize); psRectangle: canvas.Rectangle(x-PointSize,y-PointSize,x+pointSize,y+pointSize); psPlus: begin canvas.Line(x-PointSize,y,x+PointSize+1,y); canvas.Line(x,y-PointSize,x,y+PointSize+1); end; psCross: begin canvas.Line(x-PointSize,y-PointSize,x+PointSize+1,y+PointSize+1); canvas.Line(x+PointSize,y-PointSize,x-PointSize-1,y+PointSize+1); end; end; if x>RealValueRect.Right then exit; end; end; //----------------------------filling drawing---------------------------- function scaleXGC(color,xpos,xmid:integer): integer;inline; //color gradient X begin result:=color-abs(color*2*(xpos-xmid)div (3*xmid)); end; function scaleYGC(color,ypos,yvalue:integer): integer;inline;//color gradient Y begin result:=(color-color div 4)*(FValueAreaBottom-ypos)div (FValueAreaBottom-yvalue)+color div 4; end; procedure assignLazImageAndFree(lazImage: TLazIntfImage); var bitmap,tempmaskbitmap: HBITMAP; begin lazImage.CreateBitmaps(bitmap,tempmaskbitmap,true); result.Handle:=bitmap; result.canvas.clipping:=FClipValues<>[]; if result.canvas.clipping then begin result.canvas.ClipRect:=RealValueRect; IntersectClipRect(result.canvas.Handle,RealValueRect.Left,RealValueRect.top,RealValueRect.Right,RealValueRect.Bottom); end; lazImage.Free; end; //TODO: filling to zero line instead of bottom //TODO: not always clip procedure drawFillingLastOverFirst(); var i,x,xmax,xmid,y,yi: LongInt; startColor: TColor; RStart, GStart, BStart: integer; tempLazImage:TLazIntfImage; begin if fgGradientY in FFillGradient then begin //canvas.gradientfill is too slow since the rect change on every x tempLazImage:=TLazIntfImage.Create(0,0); tempLazImage.LoadFromBitmap(result.Handle,0); end; for i:=0 to FModel.dataRows-1 do begin if fModel.dataPoints(i)=0 then continue; if FModel.getRowLineStyle(i)=lsNone then continue; if (LineStyle=lsNone) and (FModel.getRowLineStyle(i)=lsDefault) then continue; FModel.setupCanvasForData(i,canvas); startColor:=canvas.pen.color; if FFillGradient<>[] then begin RedGreenBlue(startColor,RStart,GStart,BStart); if fgGradientY in FFillGradient then begin //use fp color RStart:=RStart + RStart shl 8; GStart:=GStart + GStart shl 8; BStart:=BStart + BStart shl 8; end; end; xmax:=translateX(FModel.maxX(i)); if xmax>FValueAreaRight then xmax:=FValueAreaRight; x:=translateX(FModel.minX(i)); if x<fvalueAreaX then x:=fvalueAreaX; xmid:=(x+xmax) div 2; for x:=x to xmax do begin y:=translateY(fmodel.lineApproximationAtX(LineStyle,i,translateXBack(x))); if fgGradientY in FFillGradient then begin if y<RealValueRect.top then y:=RealValueRect.Top; if fgGradientX in FFillGradient then begin for yi:=y to FValueAreaBottom-1 do tempLazImage[x,yi]:=FPColor(scaleYGC(scaleXGC(RStart,x,xmid),yi,y), scaleYGC(scaleXGC(GStart,x,xmid),yi,y), scaleYGC(scaleXGC(BStart,x,xmid),yi,y)); end else for yi:=y to FValueAreaBottom-1 do tempLazImage[x,yi]:=FPColor(scaleYGC(RStart,yi,y),scaleYGC(GStart,yi,y),scaleYGC(BStart,yi,y)); end else begin if fgGradientX in FFillGradient then canvas.pen.color:=RGBToColor(scaleXGC(RStart,x,xmid),scaleXGC(GStart,x,xmid),scaleXGC(BStart,x,xmid)); canvas.Line(x,y,x,FValueAreaBottom); end; end; end; if fgGradientY in FFillGradient then assignLazImageAndFree(tempLazImage); end; procedure drawFillingMinOverMax(); var i,j,r,k,x,temp,y,yi: LongInt; fx:float; tempY:array of longint = nil; tempYMap:array of longint = nil; tempMaxX:array of longint = nil; tempMinX:array of longint = nil; xmid: array of longint = nil; //needed for gradient RStart: array of longint = nil; //needed for gradient GStart: array of longint = nil; //needed for gradient BStart: array of longint = nil; //needed for gradient tempLazImage:TLazIntfImage; begin if fgGradientY in FFillGradient then begin //canvas.gradientfill is too slow since the rect change on every x tempLazImage:=TLazIntfImage.Create(0,0); tempLazImage.LoadFromBitmap(result.Handle,0); end; setlength(tempY, fmodel.dataRows+1); setlength(tempYMap, fmodel.dataRows+1); setlength(tempMinX, fmodel.dataRows); setlength(tempMaxX, fmodel.dataRows); if FFillGradient<>[] then begin setlength(xmid, fmodel.dataRows); setlength(RStart, fmodel.dataRows); setlength(GStart, fmodel.dataRows); setlength(BStart, fmodel.dataRows); end; for i:=0 to FModel.dataRows-1 do begin if fModel.dataPoints(i)=0 then continue; tempMinX[i]:=translateX(fmodel.minX(i)); tempMaxX[i]:=translateX(fmodel.maxX(i)); FModel.setupCanvasForData(i,canvas); if FFillGradient<>[] then begin xmid[i]:=(tempMinX[i] + tempMaxX[i]) div 2; RedGreenBlue(canvas.pen.color,RStart[i],GStart[i],BStart[i]); if fgGradientY in FFillGradient then begin //use fp color RStart[i]:=RStart[i] + RStart[i] shl 8; GStart[i]:=GStart[i] + GStart[i] shl 8; BStart[i]:=BStart[i] + BStart[i] shl 8; end; end; end; for x:=fvalueAreaX to FValueAreaRight do begin j:=0; fx:=translateXBack(x); for i:=0 to FModel.dataRows do begin if fModel.dataPoints(i)=0 then continue; if FModel.getRowLineStyle(i)=lsNone then continue; if (LineStyle=lsNone) and (FModel.getRowLineStyle(i)=lsDefault) then continue; if (x < tempMinX[i]) or (x>tempMaxX[i]) then continue; tempY[j]:=translateY(fmodel.lineApproximationAtX(LineStyle,i,fx)); tempYMap[j]:=i; k:=j; while (k >0) and (tempY[k-1]>tempY[k]) do begin temp:=tempY[k-1];tempY[k-1]:=tempY[k];tempY[k]:=temp; temp:=tempYMap[k-1];tempYMap[k-1]:=tempYMap[k];tempYMap[k]:=temp; k-=1; end; j+=1; end; if j=0 then continue; {if tempY[j-1]<FValueAreaBottom then }tempY[j]:=FValueAreaBottom; canvas.MoveTo(x,tempY[0]); for i:=0 to j-1 do begin r:=tempYMap[i]; if fgGradientY in FFillGradient then begin y:=tempY[i]; if y<RealValueRect.Top then y:=RealValueRect.Top; if fgGradientX in FFillGradient then begin for yi:=y to tempY[i+1]-1 do tempLazImage[x,yi]:=FPColor(scaleYGC(scaleXGC(RStart[r],x,xmid[r]),yi,y), scaleYGC(scaleXGC(GStart[r],x,xmid[r]),yi,y), scaleYGC(scaleXGC(BStart[r],x,xmid[r]),yi,y)); end else for yi:=y to tempY[i+1]-1 do tempLazImage[x,yi]:=FPColor(scaleYGC(RStart[r],yi,y),scaleYGC(GStart[r],yi,y),scaleYGC(BStart[r],yi,y)); end else begin if fgGradientX in FFillGradient then canvas.pen.color:=RGBToColor(scaleXGC(RStart[r],x,xmid[r]),scaleXGC(GStart[r],x,xmid[r]),scaleXGC(BStart[r],x,xmid[r])) else FModel.setupCanvasForData(r,canvas); canvas.LineTo(x,tempY[i+1]); end; end; end; if fgGradientY in FFillGradient then assignLazImageAndFree(tempLazImage); end; //----------------------------Axis drawing---------------------------- procedure drawHorzAxis(axis: TAxis; posY: longint; textOverAxis: boolean); var p,res: float; caption, captionOld: string; pos:longint; begin captionOld:=''; canvas.pen:=axis.linePen; canvas.MoveTo(FValueAreaX,posY); canvas.LineTo(FValueAreaRight,posY); res:=axis.resolution; if IsNan(res) or IsInfinite(res)or(res<=0) then res:=round((xend-xstart) / 10); p:=xstart; while p<=xend do begin caption:=axis.doTranslate(p); if caption<>captionOld then begin captionOld:=caption; pos:=FValueAreaX+round((p-xstart)*xfactor); if axis.gridLinePen.Style<>psClear then begin canvas.pen:=axis.gridLinePen; canvas.MoveTo(pos,FValueAreaY); canvas.LineTo(pos,FValueAreaBottom); canvas.pen:=axis.linePen; end; canvas.MoveTo(pos,posY-AXIS_DASH_SIZE); canvas.LineTo(pos,posY+AXIS_DASH_SIZE+1); if textOverAxis then canvas.TextOut(pos-canvas.textwidth(caption) div 2,posY-AXIS_DASH_SIZE-textHeightC-2,caption) else canvas.TextOut(pos-canvas.textwidth(caption) div 2,posY+AXIS_DASH_SIZE+2,caption); end; p+=res; end; end; procedure drawVertAxis(axis: TAxis; posX: longint; textLeftFromAxis: boolean); var p,res: float; caption, captionOld: string; pos:longint; begin captionOld:=''; canvas.pen:=axis.linePen; canvas.MoveTo(posX,FValueAreaY); canvas.LineTo(posX,FValueAreaBottom); res:=axis.resolution; if IsNan(res) or IsInfinite(res)or(res<=0) then res:=round((yend-ystart) / 10); p:=ystart; while p<=yend do begin caption:=axis.doTranslate(p); if caption<>captionOld then begin captionOld:=caption; pos:=FValueAreaBottom-round((p-ystart)*yfactor); if axis.gridLinePen.Style<>psClear then begin canvas.pen:=axis.gridLinePen; canvas.MoveTo(fvalueAreaX,pos); canvas.LineTo(FValueAreaRight,pos); canvas.pen:=axis.linePen; end; canvas.MoveTo(posX-AXIS_DASH_SIZE,pos); canvas.LineTo(posX+AXIS_DASH_SIZE+1,pos); if textLeftFromAxis then canvas.TextOut(posX-AXIS_DASH_SIZE-2-canvas.textwidth(caption),pos-textHeightC div 2,caption) else canvas.TextOut(posX+AXIS_DASH_SIZE+2,pos-textHeightC div 2,caption); end; p+=res; end; end; function getVertAxisWidth(axis:TAxis): longint; var p,res: float; caption, captionOld: string; newWidth: LongInt; begin captionOld:=''; result:=0; res:=axis.resolution; if IsNan(res) or IsInfinite(res)or(res<=0) then res:=round((yend-ystart) / 10); p:=ystart; while p<=yend do begin caption:=axis.doTranslate(p); if caption<>captionOld then begin captionOld:=caption; newWidth := canvas.textwidth(caption); if newWidth > result then result := newWidth; end; p+=res; end; end; var i,j,pos,legendX:longint; usedLineStyle: TLineStyle; range: Float; begin result:=Diagram; canvas:=result.canvas; if Diagram.Height=0 then exit; if not assigned(FMOdel) then exit; textHeightC:=result.Canvas.TextHeight(',gqpHTMIT'); //setup legend if legend.auto then begin legend.width:=0; for i:=0 to FModel.dataRows-1 do begin j:=result.Canvas.TextWidth(FModel.dataTitle(i)); if j>legend.width then legend.width:=j; end; legend.width:=legend.width+20; legend.height:=(textHeightC+5)*FModel.dataRows()+5; end; //setup output height FValueAreaY:=3; if FTAxis.Visible then FValueAreaY+=AXIS_SIZE; FValueAreaBottom:=result.Height-3; if FBAxis.Visible then FValueAreaBottom-=AXIS_SIZE; if (FLAxis.Visible or FRAxis.Visible) and not (FTAxis.Visible) then //don't truncate last text line FValueAreaY+=textHeightC div 2; if (FLAxis.Visible or FRAxis.Visible) and not (FBAxis.Visible) then FValueAreaBottom-=textHeightC div 2; FValueAreaHeight:=FValueAreaBottom-FValueAreaY; if FValueAreaHeight<=0 then exit; if cvY in FClipValues then begin RealValueRect.Top:=fvalueAreaY; RealValueRect.Bottom:=FValueAreaBottom; end else begin RealValueRect.Top:=0; RealValueRect.Bottom:=result.Height; end; //setup ranges (vertical) if fmodel.dataRows>0 then begin if FAutoSetRangeY then begin FRangeMinY:=fmodel.minY; if IsInfinite(FRangeMinY) or IsNan(FRangeMinY) then FRangeMinY:=0; FRangeMaxY:=fmodel.maxY; if IsInfinite(FRangeMaxY) or IsNan(FRangeMaxY) or (FRangeMaxY<=FRangeMinY) then FRangeMaxY:=FRangeMinY+5; end; if FLAxis.rangePolicy=rpAuto then FLAxis.rangeChanged(FRangeMinY,FRangeMaxY,FValueAreaHeight); if FYMAxis.rangePolicy=rpAuto then FYMAxis.rangeChanged(FRangeMinY,FRangeMaxY,FValueAreaHeight); if FRAxis.rangePolicy=rpAuto then FRAxis.rangeChanged(FRangeMinY,FRangeMaxY,FValueAreaHeight); end; ystart:=RangeMinY; yend:=RangeMaxY; range := yend-ystart; if IsZero(range) then exit; yfactor:=FValueAreaHeight / range; //setup output width FValueAreaX:=3; if FLAxis.Visible then FValueAreaX+=3+getVertAxisWidth(FLAxis); FValueAreaRight:=result.Width-3; if legend.visible then FValueAreaRight-=3+legend.width; if FRAxis.Visible then FValueAreaRight-=AXIS_SIZE; FValueAreaWidth:=FValueAreaRight- FValueAreaX; if FValueAreaWidth<=0 then exit; if cvX in FClipValues then begin RealValueRect.Left:=fvalueAreaX; RealValueRect.Right:=FValueAreaRight; end else begin RealValueRect.Left:=0; RealValueRect.Right:=result.width; end; //setup ranges (horizontal) if fmodel.dataRows>0 then begin if FAutoSetRangeX then begin FRangeMinX:=fmodel.minX; if IsInfinite(FRangeMinX) or IsNan(FRangeMinX) then FRangeMinX:=0; FRangeMaxX:=fmodel.maxX; if IsInfinite(FRangeMaxX) or IsNan(FRangeMaxX) or (FRangeMaxX<=FRangeMinX) then FRangeMaxX:=FRangeMinX+5; end; if FTAxis.rangePolicy=rpAuto then FTAxis.rangeChanged(FRangeMinX,FRangeMaxX,FValueAreaWidth); if FXMAxis.rangePolicy=rpAuto then FXMAxis.rangeChanged(FRangeMinX,FRangeMaxX,FValueAreaWidth); if FBAxis.rangePolicy=rpAuto then FBAxis.rangeChanged(FRangeMinX,FRangeMaxX,FValueAreaWidth); end; xstart:=RangeMinX; xend:=RangeMaxX; range := xend-xstart; if IsZero(range) then exit; xfactor:=FValueAreaWidth / range; with result.Canvas do begin Clipping:=false; SelectClipRGN(canvas.Handle,0); brush.style:=bsSolid; brush.color:=backColor; FillRect(0,0,result.Width,result.Height); brush.color:=dataBackColor;//eaX+FValueAreaWidth,FValueAreaY+FValueAreaHeight); brush.style:=bsSolid; brush.color:=dataBackColor; FillRect(FValueAreaX,FValueAreaY,FValueAreaX+FValueAreaWidth,FValueAreaY+FValueAreaHeight); brush.style:=bsClear; //Draw axis if FLAxis.Visible then drawVertAxis(FLAxis,fvalueAreaX,true); if FRAxis.Visible then drawVertAxis(FRAxis,FValueAreaRight,false); if FYMAxis.Visible then drawVertAxis(FYMAxis,fvalueAreaX+FValueAreaWidth div 2,false); if FTAxis.Visible then drawHorzAxis(FTAxis,fvalueAreaY,true); if FBAxis.Visible then drawHorzAxis(FBAxis,FValueAreaBottom,false); if FXMAxis.Visible then drawHorzAxis(FXMAxis,fvalueAreaY+FValueAreaHeight div 2,false); //activate clipping ClipRect:=RealValueRect; Clipping:=FClipValues<>[]; if Clipping then begin IntersectClipRect(canvas.Handle,RealValueRect.Left,RealValueRect.top,RealValueRect.Right,RealValueRect.Bottom); end; //Calculate Spline if FModel.FmodifiedSinceSplineCalc<>0 then fmodel.calculateSplines(LineStyle); //fill values case FillStyle of fsLastOverFirst: drawFillingLastOverFirst(); fsMinOverMax: drawFillingMinOverMax(); end; //draw lines + points for i:=0 to FModel.dataRows-1 do begin if fModel.dataPoints(i)=0 then continue; FModel.setupCanvasForData(i,canvas); if fModel.dataPoints(i)>1 then begin usedLineStyle:=FModel.getRowLineStyle(i); if usedLineStyle=lsDefault then usedLineStyle:=LineStyle; case usedLineStyle of lsLinear: drawLinearLines(i); lsCubicSpline: drawCubicSpline(i); lsLocalCubicSpline: drawCubicSpline3P(i); end; end; if PointStyle<>psNone then drawPoints(i); end; //draw legend if legend.visible then begin if Clipping then begin SelectClipRGN(canvas.handle,0); Clipping:=false; end; brush.style:=bsSolid; brush.Color:=legend.color; pen.color:=clBlack; legendX:=result.Width-legend.Width-3; Rectangle(legendX,(result.Height -legend.height) div 2, legendX+legend.width,(result.Height + legend.height) div 2); pos:=(result.Height -legend.height) div 2+5; for i:=0 to FModel.dataRows-1 do begin brush.style:=bsSolid; fmodel.setupCanvasForData(i,Result.Canvas); Rectangle(legendX+5,pos,legendX+10,pos+TextHeightC); brush.style:=bsClear; TextOut(legendX+15,pos,fmodel.dataTitle(i)); inc(pos,TextHeightC+5); end; end; end; //xaxis.min:=xaxisOldMin; Result:=result; end; function TDiagramDrawer.posToDataX(x: longint): float; begin //umgekehrt: (i-XAxis.min)*FValueAreaWidth div (XAxis.max-XAxis.min)+FValueAreaX if FValueAreaWidth=0 then exit(0); result:=(x-FValueAreaX)*(FRangeMaxX-FRangeMinX) / FValueAreaWidth + FRangeMinX; end; function TDiagramDrawer.posToDataY(y: longint): float; begin if FValueAreaHeight=0 then exit(0); result:=(FValueAreaBottom- y)*(RangeMaxY-RangeMinY) / FValueAreaHeight + RangeMinY; end; function TDiagramDrawer.dataToPosX(const x: float): integer; var range: Float; begin range := RangeMaxX-RangeMinX; if IsZero(range) then exit(0); result:=round((x-RangeMinX)*FValueAreaWidth / range)+FValueAreaX; end; function TDiagramDrawer.dataToPosY(const y: float): integer; var range: Float; begin range := RangeMaxY-RangeMinY; if IsZero(range) then exit(0); result:=FValueAreaBottom-round((y-RangeMinY)*FValueAreaHeight / range); end; function TDiagramDrawer.pixelSizeX: float; begin if FValueAreaWidth=0 then exit(1); result:=abs((RangeMaxX-RangeMinX) / FValueAreaWidth); end; function TDiagramDrawer.pixelSizeY: float; begin if FValueAreaHeight=0 then exit(1); result:=abs((RangeMaxY-RangeMinY) / FValueAreaHeight); end; { TAbstractDiagramModel } procedure TAbstractDiagramModel.doModified(row:longint); begin if row=-1 then FmodifiedSinceSplineCalc:=2 else if (row<>-1) and (dataPoints(row)>1) then FmodifiedSinceSplineCalc:=2;//it makes no sense to recalculate splines if there no lines are drawn fmodifiedEvents.CallNotifyEvents(self); end; constructor TAbstractDiagramModel.create; begin fmodifiedEvents:=TMethodList.Create; FDestroyEvents:=TMethodList.Create; end; destructor TAbstractDiagramModel.destroy; begin FDestroyEvents.CallNotifyEvents(self); FDestroyEvents.free; fmodifiedEvents.free; inherited destroy; end; procedure TAbstractDiagramModel.calculateSplines(defaultLineStyle: TLineStyle); //taken from Wikipedia var r,i,n,im:longint; xpi,xi,l,alpha:float; h: array of float = nil; z: array of float = nil; my: array of float = nil; needSplines: boolean; begin //TODO: find a way to remove the old spline data if it is no longer used (problem even if no view need them, the user app still can need them for lineApproximationAtX) needSplines:=false; if FmodifiedSinceSplineCalc=0 then exit; if (FmodifiedSinceSplineCalc=1) and (defaultLineStyle<>lsCubicSpline) then exit; for i:=0 to dataRows-1 do case getRowLineStyle(i) of lsDefault: if defaultLineStyle=lsCubicSpline then begin needSplines:=true; break; end; lsCubicSpline: begin needSplines:=true; break; end; end; if not needSplines then begin exit;//SetLength(FSplines,0); end; if defaultLineStyle=lsCubicSpline then FmodifiedSinceSplineCalc:=0 else FmodifiedSinceSplineCalc:=1; SetLength(FSplines,dataRows); for r:=0 to high(FSplines) do begin if ((getRowLineStyle(r)<>lsDefault) or (defaultLineStyle<>lsCubicSpline)) and (getRowLineStyle(r)<>lsCubicSpline) then begin //setlength(FSplines[r],0); continue; end; n:=dataPoints(r); setlength(FSplines[r],n); if n=0 then continue; if n<=1 then begin FSplines[r,0].d:=dataY(r,0); FSplines[r,0].a:=0; FSplines[r,0].b:=0; FSplines[r,0].c:=0; continue; end; setlength(z,n); setlength(my,n); setlength(h,n); data(r,0,xi,FSplines[r,0].d); for i:=0 to n-2 do begin data(r,i+1,xpi,FSplines[r,i+1].d ); h[i]:=xpi-xi; xi:=xpi; end; my[0]:=0;z[0]:=0;z[n-1]:=0; im:=0; for i:=1 to n-2 do begin l:=2*(h[i]+h[im]) - h[im]*my[im]; if abs(l)<h[i] then my[i]:=my[i-1] else my[i]:=h[i]/l; if abs(h[i])<DiagramEpsilon then z[i]:=z[i-1] else if abs(h[im])<DiagramEpsilon then begin z[i]:=z[i-1]; im:=i; end else begin alpha:=3*(FSplines[r,i+1].d-FSplines[r,i].d)/h[i] - 3*(FSplines[r,i].d-FSplines[r,i-1].d)/h[im]; z[i]:=(alpha-h[im]*z[im])/l; im:=i; end; end; FSplines[r,n-1].b:=0; im:=n-1; for i:=n-2 downto 0 do begin FSplines[r,i].b:=z[i] - my[i]*FSplines[r,i+1].b; if abs(h[i])< DiagramEpsilon then begin FSplines[r,i].c:=FSplines[r,i+1].c; FSplines[r,i].a:=FSplines[r,i+1].a; end else begin FSplines[r,i].c:=(FSplines[r,i+1].d-FSplines[r,i].d)/h[i] - h[i]*(FSplines[r,i+1].b+2*FSplines[r,i].b)/3; FSplines[r,i].a:=(FSplines[r,i+1].b-FSplines[r,i].b)/(3*h[i]); im:=i; end; end; end; end; procedure TAbstractDiagramModel.SetOnModified(const AValue: TNotifyEvent); begin if FOnModified=AValue then exit; fmodifiedEvents.Remove(TMethod(FOnModified)); FOnModified:=AValue; fmodifiedEvents.Add(TMethod(FOnModified)); end; function TAbstractDiagramModel.dataRows: longint; begin result:=1; end; function TAbstractDiagramModel.dataTitle(i: longint): string; begin result:='data'; end; procedure TAbstractDiagramModel.setupCanvasForData(i: longint; c: TCanvas); begin ; end; function TAbstractDiagramModel.setData(i, j: longint; const x, y: float):integer; begin result:=j; end; function TAbstractDiagramModel.addData(i: longint; const x, y: float): integer; begin result:=-1; end; procedure TAbstractDiagramModel.removeData(i, j: longint); begin ; end; function TAbstractDiagramModel.minX(i: longint): float; begin if dataPoints(i)>0 then result:=dataX(i,0) else result:=0; end; function TAbstractDiagramModel.maxX(i: longint): float; begin if dataPoints(i)>0 then result:=dataX(i,dataPoints(i)-1) else result:=0; end; function TAbstractDiagramModel.minY(i: longint): float; var j:longint; begin result:=PInfinity; for j:=0 to dataPoints(i)-1 do result:=min(result,dataY(i,j)); end; function TAbstractDiagramModel.maxY(i: longint): float; var j:longint; begin result:=PInfinity; for j:=0 to dataPoints(i)-1 do result:=max(result,dataY(i,j)); end; function TAbstractDiagramModel.getFlags: TModelFlags; begin result:=[]; end; function TAbstractDiagramModel.getRowFlags(i:longint): TModelRowFlags; begin result:=[]; end; function TAbstractDiagramModel.getRowLineStyle(i: longint): TLineStyle; begin Result:=lsDefault; end; function TAbstractDiagramModel.getRowPointStyle(i: longint): TPointStyle; begin Result:=psDefault; end; function TAbstractDiagramModel.find(i: longint; const x: float; const y: float; const xtolerance: float; const ytolerance: float): longint; var j:longint; px,py,ryt: float; begin result:=-1; if IsNan(y) then begin for j:=0 to dataPoints(i)-1 do if abs(dataX(i,j)-x) <= xtolerance then exit(j); end else begin ryt:=ytolerance; if IsNan(ryt) then ryt:=xtolerance; for j:=0 to dataPoints(i)-1 do begin data(i,j,px,py); if (abs(px-x) <= xtolerance) and (abs(py-y) <= ytolerance) then exit(j); end; end; end; function TAbstractDiagramModel.findAndGet(i: longint; var x: float; var y: float; const xtolerance: float; const ytolerance: float): longint; begin result:=find(i,x,y,xtolerance,ytolerance); if result<>-1 then data(i,result,x,y); end; function TAbstractDiagramModel.findWithRow(out i: longint; const x: float; const y: float; const xtolerance: float; const ytolerance: float): longint; var j:longint; begin result:=-1; for j:=0 to dataRows-1 do begin result:=find(j,x,y,xtolerance,ytolerance); if result<>-1 then begin i:=j; exit; end; end; end; function TAbstractDiagramModel.findWithRowAndGet(out i: longint; var x: float; var y: float; const xtolerance: float; const ytolerance: float): longint; var j:longint; begin result:=-1; for j:=0 to dataRows-1 do begin result:=findAndGet(j,x,y,xtolerance,ytolerance); if result<>-1 then begin i:=j; exit; end; end; end; function TAbstractDiagramModel.dataX(i, j: longint): float; var t:float; begin data(i,j,result,t); end; function TAbstractDiagramModel.dataY(i, j: longint): float; var t:float; begin data(i,j,t,result); end; function TAbstractDiagramModel.minX: float; var i:longint; begin result:=PInfinity; for i:=0 to dataRows-1 do result:=min(result,minX(i)); end; function TAbstractDiagramModel.maxX: float; var i:longint; begin result:=MInfinity; for i:=0 to dataRows-1 do result:=max(result,maxX(i)); end; function TAbstractDiagramModel.minY: float; var i:longint; begin result:=PInfinity; for i:=0 to dataRows-1 do result:=min(result,minY(i)); end; function TAbstractDiagramModel.maxY: float; var i:longint; begin result:=MInfinity; for i:=0 to dataRows-1 do result:=max(result,maxY(i)); end; function TAbstractDiagramModel.lineApproximationAtX(const defaultLineStyle:TLineStyle; i:longint; const x: float): float; var j:longint; x0,y0,x1,y1,x2,y2: float; spline: TDiagramSplinePiece; ls:TLineStyle; begin if dataPoints(i)=0 then exit(nan); if dataPoints(i)=1 then exit(dataY(i,0)); if x<minX(i) then exit(dataY(i,0)); if x>maxX(i) then exit(dataY(i,dataPoints(i)-1)); if FmodifiedSinceSplineCalc<>0 then calculateSplines(defaultLineStyle); ls:=getRowLineStyle(i); if ls=lsDefault then ls:=defaultLineStyle; case ls of lsNone, lsLinear: begin data(i,0,x1,y1); for j:=1 to dataPoints(i)-1 do begin data(i,j,x2,y2); if (x>=x1) and (x<=x2) then if abs(x1-x2)>DiagramEpsilon then exit((x-x1)*(y2-y1)/(x2-x1)+y1) else exit((y1+y2)/2); //better not really correct result than crash x1:=x2;y1:=y2; end; end; lsCubicSpline: begin data(i,0,x1,y1); if (length(FSplines)<i) or (length(FSplines[i])<dataPoints(i)) then exit(nan); //wtf for j:=1 to dataPoints(i)-1 do begin data(i,j,x2,y2); if (x>=x1) and (x<=x2) then exit(calcSpline(FSplines[i,j-1],x-x1)); x1:=x2;y1:=y2; end; end; lsLocalCubicSpline: begin data(i,0,x1,y1); data(i,1,x2,y2); FillChar(spline,sizeof(spline),0); updateSpline3P(spline,x1-2*(x2-x1),y1,x1,y1,x2,y2); for j:=1 to dataPoints(i)-1 do begin //next point x0:=x1;y0:=y1; x1:=x2;y1:=y2; data(i,j,x2,y2); updateSpline3P(spline,x0,y0,x1,y1,x2,y2); if (x>=x0) and (x<=x1) then exit(calcSpline(spline,x)); end; //last point with connection to virtual point far right updateSpline3P(spline,x1,y1,x2,y2,x2+2*(x2-x1),y2); //draw spline if (x>=x1) and (x<=x2) then exit(calcSpline(spline,x)); end; end; result:=nan; end; function TAbstractDiagramModel.findLineApproximation(const defaultLineStyle:TLineStyle; const x, y: float; const ytolerance: float ): longint; var i:longint; ly, bestdelta: float; begin result:=-1; bestdelta:=ytolerance; for i:=0 to dataRows-1 do begin if (x<minX(i)) or (x>maxX(i)) then continue; ly:=lineApproximationAtX(defaultLineStyle, i,x); if isNan(ly) then continue; if abs(ly-y) <= bestdelta then begin bestdelta:=abs(ly-y); result:=i; end; end; end; procedure TAbstractDiagramModel.addModifiedHandler(event: TNotifyEvent); begin fmodifiedEvents.Add(TMethod(event)); end; procedure TAbstractDiagramModel.removeModifiedHandler(event: TNotifyEvent); begin fmodifiedEvents.Remove(TMethod(event)); end; procedure TAbstractDiagramModel.addDestroyHandler(event: TNotifyEvent); begin FDestroyEvents.Add(TMethod(event)); end; procedure TAbstractDiagramModel.removeDestroyHandler(event: TNotifyEvent); begin FDestroyEvents.remove(TMethod(event)); end; { TDiagramDataListModel } function TDiagramDataListModel.getDataList(i:Integer): TDataList; begin result:=TDataList(FLists[i]); end; function TDiagramDataListModel.GetFlags: TModelFlags; begin result:=FFlags; end; function TDiagramDataListModel.getRowFlags(i: longint): TModelRowFlags; begin if (i<0) or (i>=FLists.Count) then exit([]); Result:=lists[i].Flags; end; function TDiagramDataListModel.getRowLineStyle(i: longint): TLineStyle; begin if (i<0) or (i>=FLists.Count) then exit(lsDefault); Result:=lists[i].LineStyle; end; function TDiagramDataListModel.getRowPointStyle(i: longint): TPointStyle; begin if (i<0) or (i>=FLists.Count) then exit(psDefault); Result:=lists[i].PointStyle; end; procedure TDiagramDataListModel.SetFlags(const AValue: TModelFlags); begin if FFlags=AValue then exit; FFlags:=AValue; doModified(-1); end; constructor TDiagramDataListModel.create; begin inherited; FLists:=TFPList.Create; end; destructor TDiagramDataListModel.destroy; begin deleteLists; FLists.Free; inherited destroy; end; procedure TDiagramDataListModel.deleteLists; var i:longint; begin for i:=0 to FLists.count-1 do TDataList(flists[i]).free; flists.clear; end; procedure TDiagramDataListModel.setDataRows(c: longint); const colors:array[0..7] of TColor=(clBlue,clRed,clGreen,clMaroon,clFuchsia,clTeal,clNavy,clBlack); var i:longint; begin if flists.count<c then begin i:=flists.count; flists.count:=c; for i:=i to c-1 do flists[i]:=TDataList.Create(self,i,colors[i and $7]); end else if flists.count>c then begin for i:=c to flists.count-1 do TDataList(flists[i]).free; FLists.Count:=c; end; end; procedure TDiagramDataListModel.deleteDataRow(i: longint); begin lists[i].free; FLists.Delete(i); for i:=i to flists.count-1 do lists[i].FRowNumber:=i; doModified(-1); end; function TDiagramDataListModel.addDataList:TDataList; const colors:array[0..7] of TColor=(clBlue,clRed,clGreen,clMaroon,clFuchsia,clTeal,clNavy,clBlack); begin Result:=TDataList.Create(self,flists.count,colors[FLists.Count and $7]); FLists.Add(Result); end; function TDiagramDataListModel.dataRows: longint; begin Result:=FLists.Count; end; function TDiagramDataListModel.dataTitle(i: longint): string; begin if (i>=0) and (i<FLists.Count) then Result:=lists[i].title else result:=''; end; procedure TDiagramDataListModel.setupCanvasForData(i: longint; c: TCanvas); begin if (i>=0) and (i<FLists.Count) then begin c.pen.Color:=lists[i].color; c.brush.Color:=lists[i].color; end; end; function TDiagramDataListModel.dataPoints(i: longint): longint; begin if (i>=0) and (i<FLists.Count) then result:=lists[i].pointCount else result:=0; end; procedure TDiagramDataListModel.data(i, j: longint; out x, y: float); begin if (i>=0) and (i<FLists.Count) then lists[i].point(j,x,y) else begin x:=nan; y:=nan; end; end; function TDiagramDataListModel.setData(i, j: longint; const x, y: float):integer; begin if not (mfEditable in Flags) then exit(-1); if (i<0) or (i>=FLists.Count) then exit(-1); result:=lists[i].setPoint(j,x,y); end; function TDiagramDataListModel.addData(i: longint; const x, y: float): integer; begin if not (mfEditable in Flags) then exit(-1); if (i<0) or (i>=FLists.Count) then exit(-1); result:=lists[i].addPoint(x,y); end; procedure TDiagramDataListModel.removeData(i, j: longint); begin if not (mfEditable in Flags) then exit; if (i<0) or (i>=FLists.Count) then exit; lists[i].removePoint(j); end; function TDiagramDataListModel.minX(i: longint): float; begin if (i>=0) and (i<FLists.Count) then exit(lists[i].minX) else exit(NaN); end; function TDiagramDataListModel.maxX(i: longint): float; begin if (i>=0) and (i<FLists.Count) then exit(lists[i].maxX) else exit(NaN); end; function TDiagramDataListModel.minY(i: longint): float; begin if (i>=0) and (i<FLists.Count) then exit(lists[i].minY) else exit(NaN); end; function TDiagramDataListModel.maxY(i: longint): float; begin if (i>=0) and (i<FLists.Count) then exit(lists[i].maxY) else exit(NaN); end; { TDiagramView } procedure TDiagramView.modelChanged(sender:Tobject); begin FDrawer.FModelModified:=true; Invalidate; end; procedure TDiagramView.modelDestroyed(sender: Tobject); begin FModel:=nil; end; procedure TDiagramView.layoutChanged(sender: Tobject); begin FDrawer.FLayoutModified:=true; Invalidate; end; procedure TDiagramView.DoOnResize; begin FDrawer.Diagram.Width:=width; if height<FDrawer.Diagram.Height-FDrawer.FValueAreaHeight then FDrawer.Diagram.Height:=FDrawer.Diagram.Height-FDrawer.FValueAreaHeight else FDrawer.Diagram.Height:=Height; if assigned(fmodel) then FDrawer.FModelModified:=true; inherited DoOnResize; end; procedure TDiagramView.SetAllowedEditActions(const AValue: TDiagramEditActions ); begin if FAllowedEditActions=AValue then exit; FAllowedEditActions:=AValue; ; end; procedure TDiagramView.SetModel(const AValue: TAbstractDiagramModel); begin SetModel(AValue,false); end; procedure TDiagramView.SetPointMovement(const AValue: TDiagramPointMovement); begin if FPointMovement=AValue then exit; FPointMovement:=AValue; end; constructor TDiagramView.create(aowner:TComponent); begin inherited; FDrawer:=TDiagramDrawer.create; FDrawer.Diagram.width:=Width; FDrawer.Diagram.height:=height; FDrawer.FLAxis.FModifiedEvent:=@layoutChanged; FDrawer.FRAxis.FModifiedEvent:=@layoutChanged; FDrawer.FTAxis.FModifiedEvent:=@layoutChanged; FDrawer.FBAxis.FModifiedEvent:=@layoutChanged; FDrawer.FXMAxis.FModifiedEvent:=@layoutChanged; FDrawer.FYMAxis.FModifiedEvent:=@layoutChanged; FDrawer.legend.FModifiedEvent:=@layoutChanged; FDrawer.FModifiedEvent:=@layoutChanged; FSelPoint:=-1; FHighlightPoint.x:=NaN; FPointMovement:=pmAffectNeighbours; end; destructor TDiagramView.destroy; begin FDrawer.Free; inherited destroy; end; procedure TDiagramView.SetModel(amodel: TAbstractDiagramModel; takeOwnership: boolean); begin if assigned(fmodel) then begin FModel.removeModifiedHandler(@modelChanged); FModel.removeDestroyHandler(@modelDestroyed); end; FDrawer.SetModel(amodel,takeOwnership); FModel:=amodel; if assigned(fmodel) then begin FModel.addModifiedHandler(@modelChanged); FModel.addDestroyHandler(@modelDestroyed); FDrawer.FModelModified:=true; end; end; procedure TDiagramView.paint; begin if not assigned(FDrawer.FModel) then exit; if FDrawer.FLayoutModified or FDrawer.FModelModified then FDrawer.update(); canvas.Draw(0,0,FDrawer.Diagram); if not IsNan(FHighlightPoint.x) then begin canvas.Pen.Style:=psSolid; canvas.Brush.Style:=bsSolid; canvas.Pen.Color:=clBlue; canvas.Brush.Color:=clYellow; canvas.EllipseC(FDrawer.dataToPosX(FHighlightPoint.x),FDrawer.dataToPosY(FHighlightPoint.y),3,3); end; if FSelPoint<>-1 then begin canvas.Pen.Style:=psSolid; canvas.Brush.Style:=bsSolid; canvas.Pen.Color:=clRed; canvas.Brush.Color:=clYellow; canvas.EllipseC(FDrawer.dataToPosX(FModel.dataX(FSelRow,FSelPoint)),FDrawer.dataToPosY(FModel.dataY(FSelRow,FSelPoint)),3,3); end; FDrawer.FModelModified:=false; FDrawer.FLayoutModified:=false; end; procedure TDiagramView.mouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var fx,fy:float; i:longint; begin inherited mouseDown(Button, Shift, X, Y); if not assigned(FDrawer.FModel) then exit; if mfEditable in FModel.getFlags then begin if ([eaMovePoints, eaDeletePoints]*FAllowedEditActions<>[]) then begin fX:=FDrawer.posToDataX(x); fY:=FDrawer.posToDataY(y); FSelPoint:=fmodel.findWithRow(FSelRow, fX,fY,2*FDrawer.PointSize*FDrawer.pixelSizeX,2*FDrawer.PointSize*FDrawer.pixelSizeY); FSelPointMoving:=FSelPoint<>-1; FHighlightPoint.x:=nan; end; if (eaAddPoints in FAllowedEditActions) and not FSelPointMoving then begin fX:=FDrawer.posToDataX(x); fY:=FDrawer.posToDataY(y); i:=fmodel.findLineApproximation(FDrawer.LineStyle, fx,fy,10*FDrawer.pixelSizeY); if i<>-1 then begin FSelRow:=i; FSelPoint:= FModel.addData(i,fx,fy); FSelPointMoving:=FSelPoint<>-1; end; end; if eaDeletePoints in FAllowedEditActions then SetFocus; end; end; procedure TDiagramView.mouseMove(Shift: TShiftState; X, Y: Integer); var i,j:longint; fx,fy:float; begin if (not assigned(FModel)) or (FModel.dataRows=0) then begin inherited mouseMove(Shift, X, Y); exit; end; if (FSelPoint<>-1) and (FSelPointMoving) then begin //j:=fmodel.findAndGet(FSelRow, FSelPoint.X,FSelPoint.Y,2*FDrawer.PointSize*FDrawer.pixelSizeX,2*FDrawer.PointSize*FDrawer.pixelSizeY); {if j=-1 then begin FSelPoint:=nan; Repaint; exit; end;} j:=fmodel.setData(FSelRow,FSelPoint,FDrawer.posToDataX(X),FDrawer.posToDataY(Y)); if PointMovement=pmAffectNeighbours then if j<FSelPoint then fmodel.setData(FSelRow,FSelPoint,FDrawer.posToDataX(X),FDrawer.posToDataY(Y)) else if j>FSelPoint then fmodel.setData(FSelRow,FSelPoint,FDrawer.posToDataX(X),FDrawer.posToDataY(Y)); FSelPoint:=j; end else if (mfEditable in FModel.getFlags) and ([eaMovePoints, eaDeletePoints]*FAllowedEditActions<>[]) then begin fX:=FDrawer.posToDataX(x); fY:=FDrawer.posToDataY(y); j:=fmodel.findWithRowAndGet(i, fX,fY,2*FDrawer.PointSize*FDrawer.pixelSizeX,2*FDrawer.PointSize*FDrawer.pixelSizeY); if IsNan(FHighlightPoint.x) and (j<>-1) then begin FHighlightPoint.x:=fx; FHighlightPoint.y:=fy; Repaint; end else if not IsNan(FHighlightPoint.x) and (j=-1) then begin FHighlightPoint.x:=NaN; Repaint; end; end; inherited mouseMove(Shift, X, Y); //so it is modified when mouse move is called end; procedure TDiagramView.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FSelPointMoving:=false; if (FSelPoint<>-1) and not (eaDeletePoints in FAllowedEditActions) then begin FSelPoint:=-1; repaint; end; inherited MouseUp(Button, Shift, X, Y); if not assigned(FDrawer.FModel) then exit; end; procedure TDiagramView.KeyUp(var Key: Word; Shift: TShiftState); begin inherited KeyUp(Key, Shift); if (key=VK_DELETE) and (eaDeletePoints in FAllowedEditActions) and (FSelPoint <>-1) and (assigned(fmodel)) then begin FModel.removeData(FSelRow,FSelPoint); if FSelPoint>=FModel.dataPoints(FSelRow) then FSelPoint:=FModel.dataPoints(FSelRow)-1; end; end; procedure TDiagramView.DoExit; begin inherited DoExit; FSelPoint:=-1; FHighlightPoint.x:=nan; Repaint; end; { TLegend } procedure TLegend.Setvisible(const AValue: boolean); begin if Fvisible=AValue then exit; Fvisible:=AValue; domodified; end; procedure TLegend.doModified; begin if assigned(FModifiedEvent) then FModifiedEvent(self); end; procedure TLegend.Setauto(const AValue: boolean); begin if Fauto=AValue then exit; Fauto:=AValue; doModified; end; procedure TLegend.SetColor(const AValue: TColor); begin if FColor=AValue then exit; FColor:=AValue; doModified; end; procedure TLegend.SetHeight(const AValue: longint); begin if FHeight=AValue then exit; FHeight:=AValue; doModified; end; procedure TLegend.SetWidth(const AValue: longint); begin if FWidth=AValue then exit; FWidth:=AValue; doModified; end; { TDiagramFixedWidthCircularDataListModel } function TDiagramFixedWidthCircularDataListModel.setData(i, j: longint; const x, y: float): integer; begin if dataPoints(i)=0 then exit; if (j=0) or (j=dataPoints(i)-1) then begin inherited setData(i, 0, dataX(i,0), y); inherited setData(i,dataPoints(i)-1, dataX(i,dataPoints(i)-1), y); result:=j; end else result:=inherited setData(i, j, x, y); end; function TDiagramFixedWidthCircularDataListModel.addData(i: longint; const x, y: float): integer; begin if x < minX(i) then exit(-1); if x > maxX(i) then exit(-1); Result:=inherited addData(i, x, y); end; procedure TDiagramFixedWidthCircularDataListModel.removeData(i, j: longint); begin if (j=0) or (j=dataPoints(i)-1) then exit; inherited removeData(i, j); end; { TDiagramModelMerger } function TDiagramModelMerger.GetRowVisible(i: integer): boolean; begin if (i>=length(FRowVisible)) or (i<0) then exit(true); result:=FRowVisible[i]; end; procedure TDiagramModelMerger.SetBaseModel(const AValue: integer); begin if FBaseModel=AValue then exit; FBaseModel:=AValue; doModified(-1); end; procedure TDiagramModelMerger.SetHideCertainRows(const AValue: boolean); begin if FHideCertainRows=AValue then exit; FHideCertainRows:=AValue; if not AValue then SetLength(FRowVisible,0); end; procedure TDiagramModelMerger.SetModel(i: longint; const AValue: TAbstractDiagramModel); begin SetModel(i,AValue,false); end; procedure TDiagramModelMerger.SetModel(i: longint; const AValue: TAbstractDiagramModel; takeOwnerShip: boolean=false); begin if (i<0) then exit; if (i>=fmodels.Count) then begin addModel(AValue); exit(); end; Models[i].removeModifiedHandler(@subModelModified); TObject(ownerShipModels[i]).Free; fmodels[i]:=AValue; if takeOwnership then ownerShipModels[i]:=AValue else ownerShipModels[i]:=nil; //tricky: TObject(nil).free is valid (and does nothing) AValue.addModifiedHandler(@subModelModified); AValue.addDestroyHandler(@subModelDestroyed); FmodifiedSinceSplineCalc:=max(FmodifiedSinceSplineCalc,avalue.FmodifiedSinceSplineCalc); doModified(-1); end; procedure TDiagramModelMerger.SetRowVisible(i: integer; const AValue: boolean); var j:longint; begin if i<0 then exit; if i>=length(FRowVisible) then begin j:=length(FRowVisible); setlength(FRowVisible,i+1); for j:=j to high(FRowVisible) do FRowVisible[i]:=true; end; FRowVisible[i]:=AValue; end; procedure TDiagramModelMerger.subModelModified(sender: TObject); begin doModified(-1); end; procedure TDiagramModelMerger.subModelDestroyed(sender: TObject); begin fmodels.Remove(sender); ownerShipModels.Remove(sender); doModified(-1); end; function TDiagramModelMerger.rowToRealRow(i: longint; out m, r: longint): boolean; var j: Integer; begin m:=-1; result:=false; if FHideCertainRows then begin if fmodels.Count=0 then exit; m:=0; r:=0; j:=0; while m<fmodels.count do begin while r<TAbstractDiagramModel(FModels[m]).dataRows do begin if (j>high(FRowVisible)) or (FRowVisible[j]) then j+=1; if i=j then exit; r+=1; end; r:=0; m+=1; end; end else for j:=0 to FModels.count-1 do if i<TAbstractDiagramModel(FModels[j]).dataRows then begin r:=i; m:=j; exit(true); end else i-=TAbstractDiagramModel(FModels[j]).dataRows; end; function TDiagramModelMerger.GetModel(i: longint): TAbstractDiagramModel; begin if (i<0) or (i>=fmodels.Count) then exit(nil); result:=TAbstractDiagramModel(FModels[i]); end; procedure TDiagramModelMerger.addModel(model: TAbstractDiagramModel; takeOwnership: boolean); begin FModels.Add(model); if takeOwnership then ownerShipModels.Add(model) else ownerShipModels.add(nil); //tricky: TObject(nil).free is valid (and does nothing) model.addModifiedHandler(@subModelModified); model.addDestroyHandler(@subModelDestroyed); FmodifiedSinceSplineCalc:=max(FmodifiedSinceSplineCalc,Model.FmodifiedSinceSplineCalc); doModified(-1); end; procedure TDiagramModelMerger.replaceModel(oldModel, newModel: TAbstractDiagramModel; takeOwnership: boolean); var i:integer; begin i:=FModels.IndexOf(oldModel); if i<0 then addModel(newModel,takeOwnership) else SetModel(i,newModel,takeOwnership); end; procedure TDiagramModelMerger.removeModel(model: TAbstractDiagramModel); begin deleteModel(FModels.IndexOf(model)); end; procedure TDiagramModelMerger.removeAllModels(); var i:longint; begin for i:=ownerShipModels.count-1 downto 0 do deleteModel(i); FModels.Clear; ownerShipModels.Clear; doModified(-1); end; procedure TDiagramModelMerger.deleteModel(i: longint); begin if (i<0) or (i>=fmodels.Count) then exit; Models[i].removeModifiedHandler(@subModelModified); Models[i].removeDestroyHandler(@subModelDestroyed); TObject(ownerShipModels[i]).Free; FModels.Delete(i); ownerShipModels.Delete(i); doModified(-1); end; constructor TDiagramModelMerger.create; begin inherited create; FModels:=TFPList.Create; ownerShipModels:=TFPList.Create; end; constructor TDiagramModelMerger.create(model: TAbstractDiagramModel; takeOwnership: boolean); begin create; addModel(model, takeOwnership); end; constructor TDiagramModelMerger.create(model1, model2: TAbstractDiagramModel; takeOwnership1: boolean; takeOwnership2: boolean); begin create; addModel(model1, takeOwnership1); addModel(model2, takeOwnership2); end; destructor TDiagramModelMerger.destroy; var t1,t2:TFPList; begin removeAllModels(); t1:=fmodels; t2:=ownerShipModels; inherited destroy; t1.Free; t2.free; end; function TDiagramModelMerger.dataRows: longint; var i:longint; begin result:=0; for i:=0 to FModels.Count-1 do result+=TAbstractDiagramModel(FModels[i]).dataRows; if FHideCertainRows then for i:=0 to max(result-1,high(FRowVisible)) do if not FRowVisible[i] then result-=1; end; function TDiagramModelMerger.dataTitle(i: longint): string; var m,r: integer; begin if not rowToRealRow(i,m,r) then exit(''); Result:=TAbstractDiagramModel(FModels[m]).dataTitle(r); end; procedure TDiagramModelMerger.setupCanvasForData(i: longint; c: TCanvas); var m,r: integer; begin if not rowToRealRow(i,m,r) then exit(); TAbstractDiagramModel(FModels[m]).setupCanvasForData(r, c); end; function TDiagramModelMerger.dataPoints(i: longint): longint; var m,r: integer; begin if not rowToRealRow(i,m,r) then exit(0); Result:=TAbstractDiagramModel(FModels[m]).dataPoints(r); end; procedure TDiagramModelMerger.data(i, j: longint; out x, y: float); var m,r: integer; begin if not rowToRealRow(i,m,r) then begin x:=nan; y:=nan; exit(); end; TAbstractDiagramModel(FModels[m]).data(r, j, x, y); end; function TDiagramModelMerger.setData(i, j: longint; const x, y: float ): integer; var m,r: integer; begin if not rowToRealRow(i,m,r) then exit(-1); Result:=TAbstractDiagramModel(FModels[m]).setData(r, j, x, y); end; function TDiagramModelMerger.addData(i: longint; const x, y: float): integer; var m,r: integer; begin if not rowToRealRow(i,m,r) then exit(-1); Result:=TAbstractDiagramModel(FModels[m]).addData(r, x, y); end; procedure TDiagramModelMerger.removeData(i, j: longint); var m,r: integer; begin if not rowToRealRow(i,m,r) then exit(); TAbstractDiagramModel(FModels[m]).removeData(r, j); end; function TDiagramModelMerger.minX(i: longint): float; var m,r: integer; begin if not rowToRealRow(i,m,r) then exit(0); Result:=TAbstractDiagramModel(FModels[m]).minX(r); end; function TDiagramModelMerger.maxX(i: longint): float; var m,r: integer; begin if not rowToRealRow(i,m,r) then exit(0); Result:=TAbstractDiagramModel(FModels[m]).maxX(r); end; function TDiagramModelMerger.minY(i: longint): float; var m,r: integer; begin if not rowToRealRow(i,m,r) then exit(PInfinity); Result:=TAbstractDiagramModel(FModels[m]).minY(r); end; function TDiagramModelMerger.maxY(i: longint): float; var m,r: integer; begin if not rowToRealRow(i,m,r) then exit(MInfinity); Result:=TAbstractDiagramModel(FModels[m]).maxY(r); end; function TDiagramModelMerger.getFlags: TModelFlags; begin if FModels.Count=0 then exit([]); if FBaseModel<=fmodels.count then Result:=TAbstractDiagramModel(FModels[FBaseModel]).getFlags else Result:=TAbstractDiagramModel(FModels[0]).getFlags; end; function TDiagramModelMerger.getRowFlags(i: longint): TModelRowFlags; var m,r: integer; begin if not rowToRealRow(i,m,r) then exit([]); Result:=TAbstractDiagramModel(FModels[m]).getRowFlags(r); end; function TDiagramModelMerger.getRowLineStyle(i: longint): TLineStyle; var m,r: integer; begin if not rowToRealRow(i,m,r) then exit(lsDefault); Result:=TAbstractDiagramModel(FModels[m]).getRowLineStyle(r); end; function TDiagramModelMerger.getRowPointStyle(i: longint): TPointStyle; var m,r: integer; begin if not rowToRealRow(i,m,r) then exit(psDefault); Result:=TAbstractDiagramModel(FModels[m]).getRowPointStyle(r); end; end.
unit Auxo.Binding.Component; interface uses System.Classes, System.Generics.Collections, Auxo.Data.Component, Auxo.Binding.Core, Auxo.Core.Observer, Auxo.Data.Core; type TAuxoBinding = class; TAuxoBindLink = class(TCollectionItem) private FComponent: TComponent; FMember: string; procedure SetMember(const Value: string); procedure SetComponent(const Value: TComponent); protected function GetDisplayName: string; override; public procedure Assign(Source: TPersistent); override; published property Component: TComponent read FComponent write SetComponent; property Member: string read FMember write SetMember; end; TAuxoBinding = class(TComponent, IObserver) private FSource: TAuxoSource; FLinks: TOwnedCollection; FBinding: IComponentBinding; function GetLink(I: Integer): TAuxoBindLink; procedure SetLink(I: Integer; const Value: TAuxoBindLink); procedure SetSource(const Value: TAuxoSource); procedure Notify(Subject: ISubject; Action: TGUID); public function Locate(Component: TComponent): Integer; procedure AddLink(Component: TComponent); procedure RemoveLink(Component: TComponent); property Index[I: Integer]: TAuxoBindLink read GetLink write SetLink; default; procedure AfterConstruction; override; procedure BeforeDestruction; override; published property Links: TOwnedCollection read FLinks write FLinks; property Source: TAuxoSource read FSource write SetSource; end; implementation uses System.StrUtils, System.SysUtils; { TAuxoBinding } procedure TAuxoBinding.AddLink(Component: TComponent); var Link: TAuxoBindLink; begin if not Assigned(Component) then raise Exception.Create('Um controle válido deve ser informado'); if Locate(Component) < 0 then; begin FLinks.BeginUpdate; try Link := TAuxoBindLink(FLinks.Add); Link.Component := Component; finally FLinks.EndUpdate; end; end; end; procedure TAuxoBinding.AfterConstruction; begin inherited; FLinks := TOwnedCollection.Create(Self, TAuxoBindLink); FBinding := TComponentBinding.Create; end; procedure TAuxoBinding.BeforeDestruction; begin inherited; FLinks.Free; FBinding := nil; end; function TAuxoBinding.GetLink(I: Integer): TAuxoBindLink; begin Result := TAuxoBindLink(FLinks.Items[I]); end; function TAuxoBinding.Locate(Component: TComponent): Integer; begin Result := FLinks.Count - 1; while (Result >= 0) and (TAuxoBindLink(FLinks.Items[Result]).Component <> Component) do Dec(Result); end; procedure TAuxoBinding.Notify(Subject: ISubject; Action: TGUID); var I: Integer; Link: TAuxoBindLink; begin for I := 0 to FLinks.Count-1 do begin Link := FLinks.Items[I] as TAuxoBindLink; FBinding.Items[Link.Component] := Link.Member; end; if Action = TAuxoSource.INS_ACTION then begin FBinding.SetSource(Source.Access); FBinding.ToControls; end; if Action = TAuxoSource.POST_ACTION then begin FBinding.SetSource(Source.Access); FBinding.ToSource; end; if Action = TAuxoSource.LOAD_ACTION then begin FBinding.SetSource(Source.Access); FBinding.ToControls; end; end; procedure TAuxoBinding.RemoveLink(Component: TComponent); var I: Integer; begin I := Locate(Component); if I >= 0 then FLinks.Delete(I); end; procedure TAuxoBinding.SetLink(I: Integer; const Value: TAuxoBindLink); begin FLinks.Items[I] := Value; end; procedure TAuxoBinding.SetSource(const Value: TAuxoSource); begin if Assigned(FSource) and (FSource <> Value) then (FSource as ISubject).UnregisterObserver(Self) else if Assigned(Value) then (Value as ISubject).RegisterObserver(Self, [TAuxoSource.INS_ACTION, TAuxoSource.POST_ACTION]); FSource := Value; end; { TAuxoBindLink } procedure TAuxoBindLink.Assign(Source: TPersistent); var Link: TAuxoBindLink; begin inherited; if Source is TAuxoBindLink then begin Link := TAuxoBindLink(Source); Self.Component := Link.FComponent; Self.Member := Link.FMember; end; end; function TAuxoBindLink.GetDisplayName: string; begin if not Assigned(FComponent) then Exit('(null) - ' + FMember); Result := FComponent.Name + ' - ' + FMember; end; procedure TAuxoBindLink.SetComponent(const Value: TComponent); begin FComponent := Value; end; procedure TAuxoBindLink.SetMember(const Value: string); begin FMember := Value; // if FComponent = nil then // (Collection.Owner as TAuxoBinding).FBinding[FMember] := FComponent // else //; (Collection.Owner as TAuxoBinding).FBinding[FComponent] := FMember; end; end.
// ---------------------------------------------------------------------------- // Unit : PxSocket.pas - a part of PxLib // Author : Matthias Hryniszak // Date : 2005-03-29 // Version : 1.0 // Description : System-independent socket implementation // Changes log : 2005-03-29 - initial version // ToDo : - Linux port. // - Testing. // ---------------------------------------------------------------------------- unit PxSocket; {$I PxDefines.inc} interface uses Classes, SysUtils, {$IFDEF WIN32} Winsock, {$ENDIF} PxBase, PxThread; type TPxClientSocket = class (TPxBaseObject) private FSocket: TSocket; public constructor Create(ASocket: TSocket); destructor Destroy; override; end; TPxTCPClientSocket = class (TPxClientSocket) function Send(var Data; DataSize: Integer): Integer; function Recv(var Buffer; BufferSize: Integer): Integer; end; TPxUDPClientSocket = class (TPxClientSocket) function SendTo(var Data; DataSize: Integer; Addr: TSockAddrIn; AddrSize: Integer): Integer; function RecvTo(var Buffer; BufferSize: Integer; var Addr: TSockAddrIn; var AddrSize: Integer): Integer; end; TPxServerSocket = class; TPxServerSocketClientThread = class (TPxThread) private FSocket: TPxClientSocket; FServer: TPxServerSocket; public constructor Create(AServer: TPxServerSocket; ASocket: TPxClientSocket); destructor Destroy; override; property Server: TPxServerSocket read FServer; property Socket: TPxClientSocket read FSocket; end; TPxServerSocketClientThreadClass = class of TPxServerSocketClientThread; TPxServerSocketClientThreadList = class (TList) private function GetItem(Index: Integer): TPxServerSocketClientThread; public property Items[Index: Integer]: TPxServerSocketClientThread read GetItem; default; end; TPxServerSocket = class (TPxThread) private FSocket: TSocket; FClientClass: TPxServerSocketClientThreadClass; FClients: TPxServerSocketClientThreadList; protected procedure Execute; override; public constructor Create(Port: Word; AClientClass: TPxServerSocketClientThreadClass); destructor Destroy; override; property Clients: TPxServerSocketClientThreadList read FClients; end; implementation uses PxLog; { TPxBaseSocket } { TPxClientSocket } constructor TPxClientSocket.Create(ASocket: TSocket); begin inherited Create; FSocket := ASocket; end; destructor TPxClientSocket.Destroy; begin if FSocket <> INVALID_SOCKET then Winsock.closesocket(FSocket); FSocket := INVALID_SOCKET; inherited Destroy; end; { TPxTCPClientSocket } function TPxTCPClientSocket.Send(var Data; DataSize: Integer): Integer; begin Result := Winsock.send(FSocket, Data, DataSize, 0); end; function TPxTCPClientSocket.Recv(var Buffer; BufferSize: Integer): Integer; begin Result := Winsock.recv(FSocket, Buffer, BufferSize, 0); end; { TPxUDPClientSocket } function TPxUDPClientSocket.SendTo(var Data; DataSize: Integer; Addr: TSockAddrIn; AddrSize: Integer): Integer; begin Result := Winsock.sendto(FSocket, Data, DataSize, 0, Addr, AddrSize); end; function TPxUDPClientSocket.RecvTo(var Buffer; BufferSize: Integer; var Addr: TSockAddrIn; var AddrSize: Integer): Integer; begin Result := Winsock.recvfrom(FSocket, Buffer, BufferSize, 0, Addr, AddrSize); end; { TPxServerSocketClientThread } constructor TPxServerSocketClientThread.Create(AServer: TPxServerSocket; ASocket: TPxClientSocket); begin inherited Create(True); FServer := AServer; FSocket := ASocket; if Assigned(Server) then Server.Clients.Add(Self); Resume; end; destructor TPxServerSocketClientThread.Destroy; begin if Assigned(Server) then Server.Clients.Remove(Self); inherited; end; { TPxServerSocketClientThreadList } { Private declarations } function TPxServerSocketClientThreadList.GetItem(Index: Integer): TPxServerSocketClientThread; begin Result := TObject(Get(Index)) as TPxServerSocketClientThread; end; { TPxServerSocket } { Protected declarations } procedure TPxServerSocket.Execute; var S: TSocket; A: TSockAddrIn; L: Integer; begin repeat L := SizeOf(A); FillChar(A, L, 0); S := accept(FSocket, @A, @L); if S <> INVALID_SOCKET then FClientClass.Create(Self, TPxTCPClientSocket.Create(S)); until Terminated; end; { Public declarations } constructor TPxServerSocket.Create(Port: Word; AClientClass: TPxServerSocketClientThreadClass); var A: TSockAddrIn; begin inherited Create(True); FreeOnTerminate := True; FSocket := Winsock.socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if FSocket = INVALID_SOCKET then raise Exception.Create('Error while creating server socket'); A.sin_family := AF_INET; A.sin_port := htons(Port); A.sin_addr.S_addr := INADDR_ANY; if Winsock.bind(FSocket, A, SizeOf(A)) <> 0 then begin Winsock.closesocket(FSocket); FSocket := INVALID_SOCKET; raise Exception.Create('Error while binding server socket (another instance already running?)'); end; if Winsock.listen(FSocket, 5) <> 0 then raise Exception.Create('Error while listenting on server socket'); FClients := TPxServerSocketClientThreadList.Create; FClientClass := AClientClass; Resume; end; destructor TPxServerSocket.Destroy; var I: Integer; begin for I := FClients.Count - 1 downto 0 do FClients[I].Free; FreeAndNil(FClients); inherited Destroy; end; { *** } var Initialized: Boolean = False; procedure Initialize; {$IFDEF WIN32} var WSAData: TWSAData; {$ENDIF} begin {$IFDEF WIN32} if WSAStartup($101, WSAData) <> 0 then begin Log('Error while starting Winsock library'); Halt(10); end; Initialized := True; {$ENDIF} end; procedure Finalize; begin {$IFDEF WIN32} if Initialized then WSACleanup; {$ENDIF} end; initialization Initialize; finalization Finalize; end.
unit WorkWithExcel; interface uses SysUtils, ComObj, Variants, Grids; var Excel, WorkBook, Sheet: Variant; function StartExcel(Visible: Boolean): Boolean; function OpenWorkBook(FileName: string): Boolean; function SaveWorkBook(Filename: string): Boolean; procedure StopExcel; procedure SheetToGrid(Sheet: Variant; var Grid: TStringGrid); function NewWorkbook: Boolean; function AddSheet(Workbook: Variant): Boolean; implementation function StartExcel(Visible: Boolean): Boolean; begin try Excel := CreateOLEObject('Excel.Application'); if not VarIsNull(Excel) then begin Excel.Visible := Visible; Excel.DisplayAlerts := False; Result := True; end else Result := False; except Result := False; end; end; function NewWorkbook: Boolean; begin try if not VarIsNull(Excel) then begin Workbook := Excel.Workbooks.Add; Result := True; end else Result := False; except Result := False; end; end; function AddSheet(Workbook: Variant): Boolean; begin try if not VarIsNull(Workbook) then begin //Workbook := Excel.Workbooks.Add; Sheet := Workbook.Sheets.Add; Result := True; end else Result := False; except Result := False; end; end; procedure StopExcel; begin try if not VarIsEmpty(Excel) then begin if (Excel.Workbooks.Count > 0) and (not Excel.Visible) then begin Excel.WindowState := $FFFFEFD4; Excel.Visible := True; end else Excel.Quit; //Excel.Free; //FreeAndNil(Excel); Excel := UnAssigned; end; except end; end; function OpenWorkBook(FileName: string): Boolean; begin Result := False; try if not VarIsNull(Excel) then begin WorkBook := Excel.Workbooks.Open(FileName); if not VarIsNull(WorkBook) then begin Sheet := WorkBook.WorkSheets.Item[1]; //Sheet.Cells.SpecialCells($0000000B).Activate; Result := True; end else Result := False; end; except Result := False; end; end; function SaveWorkBook(Filename: string): Boolean; begin Result := False; try if not VarIsNull(Excel) then begin if not VarIsNull(WorkBook) then begin WorkBook.SaveAs(Filename); Result := True; end; end; except Result := False; end; end; procedure SheetToGrid(Sheet: Variant; var Grid: TStringGrid); var X, Y: Integer; i, k: Integer; begin try if not VarIsNull(Sheet) then begin Sheet.Cells.SpecialCells($0000000B).Activate; X := Excel.ActiveCell.Column+3; Y := Excel.ActiveCell.Row; Grid.ColCount := X; Grid.RowCount := Y; for i := 0 to Y do begin for k := 0 to X do begin Grid.Cells[k,i] := Excel.Cells.Item[i+1,k+1].Value; end; end; Grid.Cells[4,0] := 'Шаблон'; Grid.Cells[5,0] := 'X'; Grid.Cells[6,0] := 'Y'; end; except end; end; end.
program Exercicio_5; var e : real; i, n : integer; function fatorial(const a: integer) : integer; var j, fat_a : integer; begin fat_a := 1; for j := a downto 1 do begin fat_a := fat_a * j; end; fatorial := fat_a; end; begin { Inicializando 'e' } e := 1; write('Digite um valor inteiro positivo: '); readln(n); for i := 1 to n do begin e := e + (1/fatorial(i)); end; writeln('O valor de "e": ', e:10:3); end.
{ Replace substring in model file names of records that have models. If model already contains sReplaceWith part, it will be skipped. } unit ReplaceLtex; const sReplaceWhat = '\dungeons\'; // replace what substring sReplaceWith = '\dwemer\'; // replace with substring sModelElements = 'Model\MODL,Male world model\MOD2,Female world model\MOD3,Female world model\MOD4,Male 1st Person\MOD4,Female 1st Person\MOD5'; var slModel: TStringList; function Initialize: integer; begin slModel := TStringList.Create; slModel.Delimiter := ','; slModel.StrictDelimiter := True; slModel.DelimitedText := sModelElements; end; function Process(e: IInterface): integer; var i: integer; begin for i := 0 to slModel.Count - 1 do // skip models that already contain sReplaceWith, comment this line out to replace everywhere if Pos(sReplaceWith, GetElementEditValues(e, slModel[i])) = 0 then SetElementEditValues(e, slModel[i], StringReplace(GetElementEditValues(e, slModel[i]), sReplaceWhat, sReplaceWith, [rfIgnoreCase])); end; function Finalize: integer; begin slModel.Free; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, SynEditHighlighter, SynHighlighterPas, StdCtrls, SynEdit, ComCtrls, ToolWin, ExtCtrls, SynEditCodeFolding, SynUnicode, JclDebug, JclHookExcept, TypInfo; type TForm1 = class(TForm) SynEdit1: TSynEdit; ListBox1: TListBox; SynEdit2: TSynEdit; SynPasSyn1: TSynPasSyn; ToolBar1: TToolBar; ToolButton1: TToolButton; Splitter1: TSplitter; Splitter2: TSplitter; ToolButton2: TToolButton; Memo1: TMemo; Splitter3: TSplitter; procedure FormCreate(Sender: TObject); procedure ToolButton1Click(Sender: TObject); procedure ListBox1Click(Sender: TObject); procedure ToolButton2Click(Sender: TObject); procedure SynEdit1GutterClick(Sender: TObject; Button: TMouseButton; X, Y, Line: Integer; Mark: TSynEditMark); private { Private declarations } public procedure AppException(Sender: TObject; E: Exception); procedure LogException(ExceptObj: TObject; ExceptAddr: Pointer; IsOS: Boolean); { Public declarations } end; TExceptHandler = class(TObject) procedure OnException(Sender: TObject; E: Exception); end; var Form1: TForm1; ExceptHandler: TExceptHandler; implementation uses Unit2; {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin JclAddExceptNotifier(Form1.LogException); // Application.OnException := AppException; with SynEdit1 do begin CodeFolding.Enabled := true; CodeFolding.FolderBarColor := clWindow; CodeFolding.FolderBarLinesColor := clHighlight; CodeFolding.IndentGuides := True; CodeFolding.HighlighterFoldRegions := true; // CodeFolding.CollapsingMarkStyle := TSynCollapsingMarkStyle(0); CodeFolding.CollapsedCodeHint := true; CodeFolding.ShowCollapsedLine := true; CodeFolding.HighlightIndentGuides := true; InsertMode := true; Lines.LoadFromFile('uHighlighterProcs_res.pas'); InitCodeFolding; end; with SynEdit2 do begin CodeFolding.Enabled := true; CodeFolding.FolderBarColor := clWindow; CodeFolding.FolderBarLinesColor := clHighlight; CodeFolding.IndentGuides := True; CodeFolding.HighlighterFoldRegions := true; // CodeFolding.CollapsingMarkStyle := TSynCollapsingMarkStyle(0); CodeFolding.CollapsedCodeHint := true; CodeFolding.ShowCollapsedLine := true; CodeFolding.HighlightIndentGuides := true; InsertMode := true; end; end; procedure TForm1.ToolButton1Click(Sender: TObject); var SubFromLine, SubToLine, i: integer; begin ListBox1.Clear; for i := 0 to SynEdit1.AllFoldRanges.AllCount - 1 do begin if not (SynEdit1.AllFoldRanges[i].SubFoldRanges = nil) and (SynEdit1.AllFoldRanges[i].SubFoldRanges.Count > 0) then begin SubFromLine := SynEdit1.AllFoldRanges[i].SubFoldRanges.FoldRanges[0].FromLine; SubToLine := SynEdit1.AllFoldRanges[i].SubFoldRanges.FoldRanges[0].ToLine; end; ListBox1.Items.AddObject( format('Lines:%d - %d, level: %d, ColapsedBy:%d, real: %d,%d sub: %d,%d', [ SynEdit1.AllFoldRanges[i].FromLine, SynEdit1.AllFoldRanges[i].ToLine, SynEdit1.AllFoldRanges[i].Level, SynEdit1.AllFoldRanges[i].CollapsedBy, SynEdit1.GetRealLineNumber(SynEdit1.AllFoldRanges[i].FromLine), SynEdit1.GetRealLineNumber(SynEdit1.AllFoldRanges[i].ToLine), SubFromLine, SubToLine]) , SynEdit1.AllFoldRanges[i]); end; end; procedure TForm1.ListBox1Click(Sender: TObject); var i: integer; FoldRange: TSynEditFoldRange; begin SynEdit2.Lines.Clear; FoldRange := TSynEditFoldRange(ListBox1.Items.Objects[ListBox1.ItemIndex]); if FoldRange.CollapsedLines.Count > 0 then for i := FoldRange.CollapsedLines.Count - 1 downto 0 do begin SynEdit2.Lines.Add(FoldRange.CollapsedLines[i]); end; SynEdit2.InitCodeFolding; end; procedure TForm1.ToolButton2Click(Sender: TObject); var StringList: TUnicodeStrings; i: integer; begin // i :=SynEdit1.AllFoldRanges.FoldRanges[0].FromLine; //SynEdit1.AllFoldRanges.FoldRanges[0] StringList := SynEdit1.AllFoldRanges.FoldRanges[0].CollapsableLinesForLine(25, nil); if StringList <> nil then for i := 0 to StringList.Count - 1 do begin Memo1.Lines.Add(StringList[i]); end; end; procedure TExceptHandler.OnException(Sender: TObject; E: Exception); var Info: TJclLocationInfo; // addr:Pointer; begin //HandleError(PChar(E.Message)); if GetLocationInfo(Pointer(e.HelpContext), Info) then begin MessageDlg(Format('%s: Addr:%p; unit:%s [%d] %s %s', [ Info.BinaryFileName, Info.Address, Info.UnitName, Info.LineNumber, Info.ProcedureName, Info.SourceName]), mtError, [mbOK], 0); end; end; // процедура, вызываемая при возникновении исключения procedure AnyExceptionNotify( ExceptObj: TObject; ExceptAddr: Pointer; OSException: Boolean); begin with Form2 do begin mmLog.Lines.BeginUpdate; mmLog.Clear; JclLastExceptStackListToStrings(mmLog.Lines, false, True, True); mmLog.Lines.EndUpdate; Show; end; end; procedure TForm1.AppException(Sender: TObject; E: Exception); var Info: TJclLocationInfo; // addr:Pointer; begin //HandleError(PChar(E.Message)); if GetLocationInfo(Pointer(e.HelpContext), Info) then begin MessageDlg(Format('%s: Addr:%p; unit:%s [%d] %s %s', [ Info.BinaryFileName, Info.Address, Info.UnitName, Info.LineNumber, Info.ProcedureName, Info.SourceName]), mtError, [mbOK], 0); end; end; procedure TForm1.LogException(ExceptObj: TObject; ExceptAddr: Pointer; IsOS: Boolean); var TmpS: string; ModInfo: TJclLocationInfo; I: Integer; ExceptionHandled: Boolean; HandlerLocation: Pointer; ExceptFrame: TJclExceptFrame; begin with Form2 do begin TmpS := 'Exception ' + ExceptObj.ClassName; if ExceptObj is Exception then TmpS := TmpS + ': ' + Exception(ExceptObj).Message; if IsOS then TmpS := TmpS + ' (OS Exception)'; mmLog.Lines.Add(TmpS); ModInfo := GetLocationInfo(ExceptAddr); mmLog.Lines.Add(Format( ' Exception occured at $%p (Module "%s", Procedure "%s", Unit "%s", Line %d)', [ModInfo.Address, ModInfo.UnitName, ModInfo.ProcedureName, ModInfo.SourceName, ModInfo.LineNumber])); if stExceptFrame in JclStackTrackingOptions then begin mmLog.Lines.Add(' Except frame-dump:'); I := 0; ExceptionHandled := False; while ({chkShowAllFrames.Checked or }not ExceptionHandled) and (I < JclLastExceptFrameList.Count) do begin ExceptFrame := JclLastExceptFrameList.Items[I]; ExceptionHandled := ExceptFrame.HandlerInfo(ExceptObj, HandlerLocation); if (ExceptFrame.FrameKind = efkFinally) or (ExceptFrame.FrameKind = efkUnknown) or not ExceptionHandled then HandlerLocation := ExceptFrame.CodeLocation; ModInfo := GetLocationInfo(HandlerLocation); TmpS := Format( ' Frame at $%p (type: %s', [ExceptFrame.FrameLocation, GetEnumName(TypeInfo(TExceptFrameKind), Ord(ExceptFrame.FrameKind))]); if ExceptionHandled then TmpS := TmpS + ', handles exception)' else TmpS := TmpS + ')'; mmLog.Lines.Add(TmpS); if ExceptionHandled then mmLog.Lines.Add(Format( ' Handler at $%p', [HandlerLocation])) else mmLog.Lines.Add(Format( ' Code at $%p', [HandlerLocation])); mmLog.Lines.Add(Format( ' Module "%s", Procedure "%s", Unit "%s", Line %d', [ModInfo.UnitName, ModInfo.ProcedureName, ModInfo.SourceName, ModInfo.LineNumber])); Inc(I); end; end; mmLog.Lines.Add(''); Show; end; end; procedure TForm1.SynEdit1GutterClick(Sender: TObject; Button: TMouseButton; X, Y, Line: Integer; Mark: TSynEditMark); begin ToolButton1Click(Sender); end; initialization //... // ExceptProc:=@ExceptHandler; // инициализация механизма перехвата исключений Include(JclStackTrackingOptions, stRawMode); Include(JclStackTrackingOptions, stExceptFrame); JclStartExceptionTracking; // JclAddExceptNotifier(TForm1.LogException); end.
unit uFrmCadProdutoTransferencia; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UFrmFormDataSet, System.Actions, Vcl.ActnList, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, PBNumEdit, Vcl.Mask, Vcl.DBCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxDBEdit, siComp, siLngLnk; type TFrmProdutoTransferencia = class(TFrmFormDataSet) Panel2: TPanel; panelProdutos: TPanel; GroupBox1: TGroupBox; DBGrid1: TDBGrid; dbCodigo: TDBEdit; Label1: TLabel; dbDescripcion: TDBEdit; Label4: TLabel; Label5: TLabel; dbCantidad: TDBEdit; btnAddProduto: TBitBtn; btnCancel: TBitBtn; panelControles: TPanel; btnNovoItem: TBitBtn; BtnAlterarItem: TBitBtn; BtnExcluirItem: TBitBtn; GroupBox2: TGroupBox; lbDepositoOrigem: TLabel; GroupBox3: TGroupBox; lbDepositoDestino: TLabel; GroupBox4: TGroupBox; dbObs: TDBEdit; dbOrigem: TDBEdit; dbDestino: TDBEdit; dbObsItem: TDBEdit; lblObsItem: TLabel; siLangLinked_FrmProdutoTransferencia: TsiLangLinked; procedure FormShow(Sender: TObject); procedure acSalvarExecute(Sender: TObject); procedure btnNovoItemClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnAddProdutoClick(Sender: TObject); procedure dbCodigoEnter(Sender: TObject); procedure dbCodigoExit(Sender: TObject); procedure dbCantidadEnter(Sender: TObject); procedure dbCantidadExit(Sender: TObject); procedure dbCodigoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dbCantidadKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGrid1CellClick(Column: TColumn); procedure dbObsExit(Sender: TObject); procedure dbOrigemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dbDestinoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure BtnAlterarItemClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure dbObsItemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dbObsItemEnter(Sender: TObject); procedure FormActivate(Sender: TObject); private { Private declarations } public { Public declarations } jaSalvou: boolean; procedure buscaDeposito(vTipo: string); procedure selecionaProduto; end; var FrmProdutoTransferencia: TFrmProdutoTransferencia; implementation {$R *.dfm} uses UFrmPesquisaPadrao, uDMPesquisa, uDM, uLib, UFrmConsultaEstoqueDE, uDMDADOSCDS, UFrmConsultaEstoqueDE2; procedure TFrmProdutoTransferencia.acSalvarExecute(Sender: TObject); var id_transferencia: integer; origem, destino: integer; id_produto: integer; qtde: Real; begin // inherited; id_transferencia := 0; id_produto := 0; qtde := 0; if DMDadosCDS.cdsTransferenciaItem.State in [dsEdit,dsInsert] then DMDadosCDS.cdsTransferenciaItem.Cancel; dmdadoscds.cdsTransferencia.edit; dmdadoscds.cdsTransferencia.fieldbyname('data').AsDateTime := fnGetDataHora; dmdadoscds.cdsTransferencia.fieldbyname('id_usuario').AsInteger := fnGetIDUsuarioLogado; dmdadoscds.cdsTransferencia.fieldbyname('status').AsInteger := 6; DMDadosCDS.cdsTransferenciaItem.First; while not dmdadosCds.cdsTransferenciaItem.eof do begin DMDadosCDS.cdsTransferenciaItem.Edit; dmdadoscds.cdsTransferenciaItem.FieldByName('status').AsInteger := 6; DMDadosCDS.cdsTransferenciaItem.post; dmdadoscds.cdsTransferenciaItem.Next; end; if (dmdadoscds.cdsTransferencia.ApplyUpdates(0) = 0) then begin jaSalvou := true; ShowMessage(' La transferencia fue hecha existosamente.'); end else begin jaSalvou := false; showMessage('No fue posible hacer la transferencia'); end; close; end; procedure TFrmProdutoTransferencia.btnAddProdutoClick(Sender: TObject); begin inherited; dmdadoscds.cdsTransferenciaItem.edit; dmdadoscds.cdsTransferenciaItem.Post; DMDadosCDS.gMsg := ''; dmdadoscds.cdsTransferenciaItem.ApplyUpdates(0); if dmdadoscds.gMsg <> '' then begin dmdadoscds.cdsTransferenciaItem.CancelUpdates; dbCantidad.SetFocus; showMessage(dmdadoscds.gMsg); end else begin //só executar esse trecho quando conseguir bloquear corretamente o produto panelProdutos.Enabled := not panelProdutos.Enabled; panelControles.Enabled := not panelControles.Enabled; btnAddProduto.Enabled := not btnAddProduto.Enabled; btnCancel.enabled := not btnCancel.enabled; end; end; procedure TFrmProdutoTransferencia.BtnAlterarItemClick(Sender: TObject); begin inherited; panelProdutos.Enabled := not panelProdutos.Enabled; panelControles.Enabled := not panelControles.Enabled; btnAddProduto.Enabled := not btnAddProduto.Enabled; btnCancel.enabled := not btnCancel.enabled; dmdadoscds.cdsTransferenciaItem.edit; dbCodigo.Enabled := false; dbCantidad.SetFocus; end; procedure TFrmProdutoTransferencia.btnCancelClick(Sender: TObject); begin inherited; dmdadoscds.cdsTransferenciaItem.Cancel; panelControles.Enabled := not panelControles.Enabled; panelProdutos.Enabled := not panelProdutos.Enabled; btnAddProduto.Enabled := not btnAddProduto.Enabled; btnCancel.enabled := not btnCancel.enabled; end; procedure TFrmProdutoTransferencia.btnNovoItemClick(Sender: TObject); begin inherited; panelProdutos.Enabled := not panelProdutos.Enabled; panelControles.Enabled := not panelControles.Enabled; dbCodigo.Enabled := true; dmdadoscds.cdsTransferenciaItem.Append; dmdadoscds.cdsTransferenciaItem.FieldByName('id_trans_item').AsInteger := FnRetornaChave('id_trans_item'); dbCodigo.SetFocus; btnAddProduto.Enabled := not btnAddProduto.Enabled; btnCancel.enabled := not btnCancel.enabled; end; procedure TFrmProdutoTransferencia.buscaDeposito(vTipo: string); var vListaCampos: TStringList; sql: string; begin vListaCampos := TStringList.create; vListaCampos.add('id_deposito'); vListaCampos.add('nome'); sql := ' select * from deposito &filtro' ; FrmPesquisaPadrao := TFrmPesquisaPadrao.Create(self); FrmPesquisaPadrao.Caption := ' :: PESQUISAR: DEPOSITO ::'; FrmPesquisaPadrao.DataSource := dmdadosPesquisa.dsDepositoPesquisa; FrmPesquisaPadrao.Tabela := dmdadosPesquisa.qDepositoPesquisa; FrmPesquisaPadrao.TabelaNome := 'deposito'; FrmPesquisaPadrao.CampoPesquisa := 'descricao'; FrmPesquisaPadrao.CampoRetorno := 'id_deposito'; FrmPesquisaPadrao.SQL := sql; FrmPesquisaPadrao.Operador := 'like'; FrmPesquisaPadrao.CampoExibir := vListaCampos; FrmPesquisaPadrao.ShowModal; if FrmPesquisaPadrao.Retorno <> '' then begin if vTipo = 'origem' then begin dbOrigem.Field.AsInteger := DMDadosPesquisa.qDepositoPesquisa.FieldByName('id_deposito').AsInteger; lbDepositoOrigem.Caption := DMDadosPesquisa.qDepositoPesquisa.FieldByName('descricao').AsString; lbDepositoOrigem.Visible := true; dbDestino.SetFocus; dbOrigem.Enabled := false; DMDadosCDS.cdsTransferencia.post; DMDadosCDS.cdsTransferencia.edit; end else if vTipo = 'destino' then begin if DMDadosPesquisa.qDepositoPesquisa.FieldByName('id_deposito').AsInteger <> dbOrigem.Field.AsInteger then begin dbDestino.field.AsInteger := DMDadosPesquisa.qDepositoPesquisa.FieldByName('id_deposito').AsInteger; lbDepositoDestino.Caption := DMDadosPesquisa.qDepositoPesquisa.FieldByName('descricao').AsString; lbDepositoDestino.Visible := true; dbObs.setfocus; dbDestino.Enabled := false; DMDadosCDS.cdsTransferencia.post; DMDadosCDS.cdsTransferencia.edit; end else begin showMessage('El deposito destino debe ser diferente al deposito de origem!'); dbDestino.SetFocus; end; end; end else begin if vTipo = 'origem' then begin if dbOrigem.enabled then dbOrigem.SetFocus; end else begin if dbDestino.Enabled then dbDestino.SetFocus; end; end; end; procedure TFrmProdutoTransferencia.dbCantidadEnter(Sender: TObject); begin inherited; fnedtEnter(self); end; procedure TFrmProdutoTransferencia.dbCantidadExit(Sender: TObject); begin inherited; fnedtExit(sender); end; procedure TFrmProdutoTransferencia.dbCantidadKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if key = vk_return then begin if FrmConsultaEstoqueDE2.saldoTmp >= strtoint(dbCantidad.Text) then begin dbObsItem.SetFocus; end else begin ShowMessage('Saldo Insuficiente'); dbCantidad.SetFocus; end; //dbObsItem.SetFocus; // btnAddProdutoClick(self); // // //se nao deu nenhum erro manter do jeito que ta // if dmdadoscds.gMsg = '' then // begin // btnNovoItemClick(self); // end // else // begin // if not (dmdadosCds.cdsTransferenciaItem.FieldByName('id_produto').asInteger > 0) then // begin // btnCancelClick(self); // end; // // // end; // // end; end; procedure TFrmProdutoTransferencia.dbCodigoEnter(Sender: TObject); begin inherited; fnedtEnter(Sender); end; procedure TFrmProdutoTransferencia.dbCodigoExit(Sender: TObject); var Ctrl: TWinControl; begin inherited; fnedtExit(Sender); Ctrl := ActiveControl; if (dbCodigo.Text = '') and (Ctrl.Name <> 'dbCantidad') then begin btnCancelClick(self); end; end; procedure TFrmProdutoTransferencia.dbCodigoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if key = vk_return then begin selecionaProduto; end; end; procedure TFrmProdutoTransferencia.dbOrigemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var deposito: integer; begin inherited; if key = vk_return then begin if dbOrigem.Text = '' then begin buscaDeposito('origem'); end else begin if TryStrToInt(dbOrigem.Text,deposito) then begin //consultar diretamente o deposito e colocar o nome DMDadosPesquisa.qDepositoPesquisa.close; DMDadosPesquisa.qDepositoPesquisa.SQL.Clear; DMDadosPesquisa.qDepositoPesquisa.SQL.Add('select * from deposito &filtro'); DMDadosPesquisa.qDepositoPesquisa.Macros.MacroByName('filtro').AsRaw := ' where id_deposito = :id_deposito '; DMDadosPesquisa.qDepositoPesquisa.params.ParamByName('id_deposito').AsInteger := deposito; DMDadosPesquisa.qDepositoPesquisa.open; if DMDadosPesquisa.qDepositoPesquisa.RecordCount > 0 then begin dbOrigem.Field.AsInteger := DMDadosPesquisa.qDepositoPesquisa.FieldByName('id_deposito').AsInteger; lbDepositoOrigem.Caption := DMDadosPesquisa.qDepositoPesquisa.FieldByName('descricao').AsString; lbDepositoOrigem.Visible := true; dbDestino.SetFocus; dbOrigem.Enabled := false; DMDadosCDS.cdsTransferencia.post; DMDadosCDS.cdsTransferencia.edit; end else begin ShowMessage('No hay registro para el deposito informado'); dbOrigem.SetFocus; end; DMDadosPesquisa.qDepositoPesquisa.Macros.MacroByName('filtro').AsRaw := ''; DMDadosPesquisa.qDepositoPesquisa.Close; end else begin ShowMessage('Deposito Inválido'); end; end; end; end; procedure TFrmProdutoTransferencia.dbDestinoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var deposito: integer; begin inherited; if key = vk_return then begin if dbDestino.Text = '' then begin buscaDeposito('destino'); end else begin if tryStrToInt(dbDestino.Text,deposito) then begin //consultar diretamente o deposito e carrega-lo DMDadosPesquisa.qDepositoPesquisa.close; DMDadosPesquisa.qDepositoPesquisa.SQL.Clear; DMDadosPesquisa.qDepositoPesquisa.SQL.Add('select * from deposito &filtro'); DMDadosPesquisa.qDepositoPesquisa.Macros.MacroByName('filtro').AsRaw := ' where id_deposito = :id_deposito '; DMDadosPesquisa.qDepositoPesquisa.params.ParamByName('id_deposito').AsInteger := deposito; DMDadosPesquisa.qDepositoPesquisa.open; if DMDadosPesquisa.qDepositoPesquisa.RecordCount > 0 then begin dbDestino.field.AsInteger := DMDadosPesquisa.qDepositoPesquisa.FieldByName('id_deposito').AsInteger; lbDepositoDestino.Caption := DMDadosPesquisa.qDepositoPesquisa.FieldByName('descricao').AsString; lbDepositoDestino.Visible := true; dbObs.setfocus; dbDestino.Enabled := false; DMDadosCDS.cdsTransferencia.post; DMDadosCDS.cdsTransferencia.edit; end else begin ShowMessage('No hay registro para el deposito informado'); dbDestino.SetFocus; end; DMDadosPesquisa.qDepositoPesquisa.Macros.MacroByName('filtro').AsRaw := ''; DMDadosPesquisa.qDepositoPesquisa.Close; end else begin showMessage('Deposito invalido'); end; end; end; end; procedure TFrmProdutoTransferencia.DBGrid1CellClick(Column: TColumn); begin inherited; if btnCancel.Enabled then begin btnCancelClick(self); end; end; procedure TFrmProdutoTransferencia.dbObsExit(Sender: TObject); begin inherited; btnNovoItem.setfocus; end; procedure TFrmProdutoTransferencia.dbObsItemEnter(Sender: TObject); begin inherited; fnedtEnter(self); end; procedure TFrmProdutoTransferencia.dbObsItemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if key = vk_return then begin btnAddProdutoClick(self); //se nao deu nenhum erro manter do jeito que ta if dmdadoscds.gMsg = '' then begin btnNovoItemClick(self); end else begin if not (dmdadosCds.cdsTransferenciaItem.FieldByName('id_produto').asInteger > 0) then begin btnCancelClick(self); end; end; end; end; procedure TFrmProdutoTransferencia.FormActivate(Sender: TObject); begin inherited; siLangLinked_FrmProdutoTransferencia.Language := DMDados.siLang_DMDados.Language; end; procedure TFrmProdutoTransferencia.FormClose(Sender: TObject; var Action: TCloseAction); begin if not jaSalvou then begin if MessageDlg('Desea realmente abandonar el lanzamiento?',mtConfirmation,mbYesNo,0) = mrYes then begin if DMDadosCDS.cdsTransferenciaItem.RecordCount > 0 then begin DMDadosCDS.cdsTransferenciaItem.cancelUpdates; DMDadosCDS.cdsTransferenciaItem.First; while not DMDadosCDS.cdsTransferenciaItem.eof do begin dmdadosCDS.cdsTransferenciaItem.Delete; DMDadosCDS.cdsTransferenciaItem.Next; end; dmdadoscds.cdsTransferencia.ApplyUpdates(0); DMDadosCDS.cdsTransferencia.CancelUpdates; dmdadosCds.cdsTransferencia.delete; dmdadoscds.cdsTransferencia.ApplyUpdates(0); end; //habilita para fechar a janela Action := caFree; end else begin Action := caNone; end; end; end; procedure TFrmProdutoTransferencia.FormCreate(Sender: TObject); begin inherited; jaSalvou := false; end; procedure TFrmProdutoTransferencia.FormShow(Sender: TObject); begin inherited; if modo = 'cadastrar' then begin dmdadoscds.cdsTransferencia.Close; dmdadoscds.cdsTransferencia.Params.ParamByName('id_transferencia').AsInteger := -1; dmdadoscds.cdsTransferencia.Open; dmdadoscds.cdsTransferencia.Append; dmdadoscds.cdsTransferencia.FieldByName('id_transferencia').AsInteger := FnRetornaChave('id_transferencia'); dmdadoscds.cdsTransferencia.FieldByName('status').AsInteger := 1; end; dbOrigem.SetFocus; end; procedure TFrmProdutoTransferencia.selecionaProduto; begin //selecionar apenas produtos que não estao na origem //se origem é 1, exibir saldo de todos os depósitos menos do depósito 1 if not Assigned(FrmConsultaEstoqueDE2) then begin FrmConsultaEstoqueDE2 := TFrmConsultaEstoqueDE2.Create(nil); end; frmConsultaEstoqueDE2.moedaVenda := 'U$'; FrmConsultaEstoqueDE2.Origem := 'TRANSFERENCIA'; frmConsultaEstoqueDE2.FiltraMarca := 0; frmConsultaEstoqueDE2.FiltroDepositoOrigem := dborigem.field.AsInteger; frmConsultaEstoqueDE2.ShowModal; if FrmConsultaEstoqueDE2.selecionou then begin if FrmConsultaEstoqueDE2.saldoTmp <> 0 then begin if FrmConsultaEstoqueDE2.id_produto > 0 then begin if FrmConsultaEstoqueDE2.id_deposito > 0 then begin DMDadoscds.cdsTransferenciaItem.FieldByName('id_produto').AsInteger := FrmConsultaEstoqueDE2.id_produto; DMDadoscds.cdsTransferenciaItem.FieldByName('descricao').AsString := FrmConsultaEstoqueDE2.descricao; DMDadoscds.cdsTransferenciaItem.FieldByName('qtde').AsFloat := 1; DMDadoscds.cdsTransferenciaItem.FieldByname('custocif').AsFloat := FrmConsultaEstoqueDE2.CustoCif; DMDadoscds.cdsTransferenciaItem.FieldByName('custofob').AsFloat := FrmConsultaEstoqueDE2.CustoFob; DMDadoscds.cdsTransferenciaItem.FieldByName('status').AsInteger := 1; dmdadoscds.cdsTransferenciaItem.FieldByName('obs').AsString := dbObsItem.TextHint; dbCantidad.SetFocus; end; end; end else begin ShowMessage('Saldo Insulficiente'); end; end; end; end.
unit Expedicao.Interfaces.uSeguradoraPersistencia; interface uses Generics.Collections, Expedicao.Models.uSeguradora; type ISeguradoraPersistencia = interface ['{E6A477DC-2540-42E5-B82D-AE96F7A40680}'] function ObterListaSeguradora: TList<TSeguradora>; function ObterSeguradora(pSeguradoraOID: Integer): TSeguradora; function IncluirSeguradora(pSeguradora: TSeguradora): Boolean; function AlterarSeguradora(pSeguradora: TSeguradora): Boolean; function ExcluirSeguradora(pSeguradoraOID: Integer): Boolean; end; implementation end.
unit CodeEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type TCodeEditMoveCaret = procedure(const Col, Row: longint) of object; TEditOption = (eoAutoIdentMode, eoBackspaceUnindents, eoSmartTab, eoInsertmode); TEditOptions = set of TEditOption; TCodeEdit = class(TCustomRichEdit) private FontWidth: longint; FontHeight: longint; FMoveCaret: TCodeEditMoveCaret; FOptions: TEditOptions; CurShape1: TBitmap; CurShape2: TBitmap; FRow: integer; FCol: integer; FSelecting: boolean; FSelectPoint: integer; FCheckingHightLight: boolean; FFileName: string; FFiled: boolean; function GetInsertMode: boolean; procedure SetOptions(const Value: TEditOptions); procedure SetInsertMode(const Value: boolean); procedure SetCol(const Value: integer); procedure SetRow(const Value: integer); procedure SetSelecting(const Value: boolean); procedure SetSelectPoint(const Value: integer); function GetActualCol: integer; function GetActualRow: integer; procedure WMSETFOCUS(var Message: TMessage); message WM_SETFOCUS; procedure WMPAINT(var Message: TMessage); message WM_PAINT; // Funciones de edicion function Ident: integer; procedure InsertTab; function DoBackSpaceUnindents: boolean; procedure DoBackSpace; procedure DoDelete; procedure FillRowAndInsert; procedure InsertSpaces(const Line: Integer; const Count: integer); function IdentCount(const Line: Integer): integer; procedure MovePage(const Direction: integer); // Utilidades varias function LineCount: longint; procedure ShapeCaret; procedure RemoveRightSpaces; function BlankString(const Count: integer): string; function FirstNonBlank(const Line: Integer): longint; function CurrText: TTextAttributes; function CharFromLine(const line: Integer): integer; procedure SetCursorShapes; procedure UpDateCaretPos; procedure SyntaxHighLight; procedure DoHighLight(const From, Count: integer); procedure CheckSelection(Shift: TShiftState); function VisibleLinesCount: integer; procedure SetUpdateState(Updating: Boolean); procedure UpDateLine(const Line: integer); function GetLineEditLength: integer; function GetSource: TStrings; protected procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Change; override; private procedure LocateCaret; procedure LocateInsertPoint; procedure WriteChar(const Ch: Char); property Selecting: boolean read FSelecting write SetSelecting; property SelectPoint: integer read FSelectPoint write SetSelectPoint; property ActualCol: integer read GetActualCol; property ActualRow: integer read GetActualRow; property LineEditLength: integer read GetLineEditLength; public constructor Create(AOwner: TComponent); override; procedure UpDateFontSize; procedure HighLightLine(const Line: integer); procedure CheckHighLightAllText; procedure SetLineAttr(const Line: integer; const Color: TColor; const FontStyles: TFontStyles); property ReadOnly; property OnSelectionChange; property Options: TEditOptions read FOptions write SetOptions; property InsertMode: boolean read GetInsertMode write setInsertMode; property OnChange; property OnMoveCaret: TCodeEditMoveCaret read FMoveCaret write FMoveCaret; property Col: integer read FCol write SetCol; property Row: integer read FRow write SetRow; property Source: TStrings read GetSource; property FileName: string read FFileName write FFileName; property Filed: boolean read FFiled write FFiled; end; procedure Register; implementation uses RichEdit, ShellAPI, ReInit, Parser; const MAXCARPERLINE = 255; // TTokenType = (ttSymbol, ttInteger, ttFloat, ttString, ttKeyWord, ttComment, ttUnknow); TokenColor: array[TTokenType] of TColor = (clBlack, clBlue, clBlue, clRed, clBlack, clGray, clAqua); TokenStyle: array[TTokenType] of TFontStyles = ([], [], [], [], [fsBold], [fsItalic], []); var Scanner: TScanner; procedure Register; begin RegisterComponents('Gospel', [TCodeEdit]); end; function Max(const A, B: variant): variant; begin if A > B then Result := A else Result := B; end; function Min(const A, B: longint): longint; begin if A < B then Result := A else Result := B; end; { TCodeEdit } procedure TCodeEdit.SetCursorShapes; begin with CurShape1 do begin Width := FontWidth; Height := FontHeight; with Canvas do begin Brush.Color := clWhite; FillRect(Rect(0, 0, Width, Height)); Brush.Color := clBlack; Rectangle(0, 0, Width, MulDiv(4, Height, 5)); end; end; with CurShape2 do begin Width := FontWidth; Height := FontHeight; with Canvas do begin Brush.Color := clWhite; FillRect(Rect(0, 0, Width, Height)); Brush.Color := clBlack; Rectangle(0, 0, Width, MulDiv(3, Height, 5)); end; end; end; // Devuelve el indice del primer caracter de una linea function TCodeEdit.CharFromLine(const line: integer): integer; begin Result := SendMessage(Handle, EM_LINEINDEX, line, 0); end; function TCodeEdit.IdentCount(const Line: longint): integer; function GetSpaces(const Ln: longint): integer; var S: string; begin Result := 0; S := Lines.Strings[Ln]; while (Result < length(S)) and (S[Result + 1] = #32) do inc(Result); if Result = length(S) then Result := 0; end; var L: integer; begin L := Line; repeat Dec(L); Result := GetSpaces(L); until (Result > 0) or (L = 0) or ((Length(Lines.Strings[L]) > 0) and (Lines.Strings[L][1] <> ' ')); end; function TCodeEdit.BlankString(const Count: integer): string; begin SetLength(Result, Count); FillChar(PChar(Result)^, Count, ' '); end; procedure TCodeEdit.InsertSpaces(const Line: longint; const Count: integer); var Str: string; begin Str := Lines.Strings[Line]; Insert(#13#10 + BlankString(Count), Str, Col); Lines.Strings[Line] := Str; end; function TCodeEdit.Ident: integer; var Line: longint; begin // Linea donde se encuentra el cursor Line := SendMessage(Handle, EM_LINEFROMCHAR, -1, 0); Result := IdentCount(succ(Line)); InsertSpaces(Line, Result); end; function TCodeEdit.FirstNonBlank(const Line: longint): longint; begin if Lines[Line] = '' then Result := MAXLONGINT else begin Result := 1; while (Result < Length(Lines[Line])) and (Lines[Line][Result] = ' ') do inc(Result); end; end; function TCodeEdit.DoBackSpaceUnindents: boolean; var TheRow: longint; Line: string; index: integer; function BlankLine: boolean; var i: longint; begin if LineEditLength = 0 then Result := true else begin i := 1; while (i < LineEditLength) and (Lines[ActualRow][i] = ' ') do inc(i); Result := Lines[ActualRow][i] = ' '; end; end; function CanUnindent: boolean; begin if Col = 1 then Result := false else if BlankLine then Result := true else if ActualCol > LineEditLength then Result := false else if Col = FirstNonBlank(ActualRow) then Result := true else Result := false; end; begin Result := CanUnindent; if Result then begin RemoveRightSpaces; TheRow := pred(ActualRow); index := FirstNonBlank(TheRow); while ActualCol <= index do begin dec(TheRow); index := FirstNonBlank(TheRow); end; Line := Lines[ActualRow]; Lines[ActualRow] := BlankString(pred(index)) + Copy(Line, ActualCol + 1, Length(Line)); Col := index; end; end; procedure TCodeEdit.InsertTab; var TheRow: longint; Line: string; index: integer; Count: integer; begin TheRow := pred(ActualRow); while (TheRow >= 0) and (ActualCol >= Length(Lines[TheRow])) do dec(TheRow); if TheRow >= 0 then begin Line := Lines[TheRow]; index := Col; while (index < Length(Line)) and not ((Line[index] = ' ') and (Line[succ(index)] <> ' ')) do inc(index); Line := Lines[ActualRow]; if Length(Line) < ActualCol then Count := Length(Line) else Count := ActualCol; Insert(BlankString(Index - Count), Line, Col); Lines[ActualRow] := Line; Col := succ(Index); end; end; procedure TCodeEdit.RemoveRightSpaces; var i: integer; S: string; begin S := Lines[ActualRow]; i := Length(S); if i > 0 then begin while (i > 0) and (S[i] = #32) do dec(i); if i < Length(S) then Lines[ActualRow] := Copy(S, 0, i); end; end; procedure TCodeEdit.ShapeCaret; begin { if ActualCol > LineEditLength then CreateCaret(Handle, CurShape2.Handle, 0, 0) else CreateCaret(Handle, CurShape1.Handle, 0, 0); ShowCaret(Handle); } end; procedure TCodeEdit.FillRowAndInsert; var Count: integer; begin Count := ActualCol - LineEditLength; Lines[ActualRow] := Lines[ActualRow] + BlankString(Count); end; function TCodeEdit.LineCount: longint; begin Result := SendMessage(Handle, EM_GETLINECOUNT, 0, 0); end; function TCodeEdit.CurrText: TTextAttributes; begin if SelLength > 0 then Result := SelAttributes else Result := DefAttributes; end; procedure TCodeEdit.UpDateFontSize; var BM: TBitmap; begin BM := TBitmap.Create; with BM.Canvas do begin Font.Name := CurrText.Name; Font.Size := CurrText.Size; FontWidth := TextWidth('a'); FontHeight := TextHeight('a'); end; BM.free; if (CurShape1 <> nil) and (CurShape2 <> nil) then SetCursorShapes; end; constructor TCodeEdit.Create(AOwner: TComponent); begin inherited; FOptions := [eoInsertMode, eoAutoIdentMode, eoBackspaceUnindents, eoSmartTab]; CurShape1 := TBitmap.Create; CurShape2 := TBitmap.Create; WantTabs := true; WordWrap := false; PlainText := true; ScrollBars := ssBoth; FCol := 1; FRow := 1; end; procedure TCodeEdit.WMSETFOCUS(var Message: TMessage); begin inherited; UpDateFontSize; //CreateCaret(WindowHandle, CurShape1.Handle, 0, 0); //ShowCaret(WindowHandle); end; procedure TCodeEdit.CheckSelection(Shift: TShiftState); begin if ssShift in Shift then Selecting := true else Selecting := false; end; procedure TCodeEdit.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; case Key of VK_Left: begin CheckSelection(Shift); if ssCtrl in Shift then begin SelStart := SendMessage(Handle, EM_FINDWORDBREAK, WB_MOVEWORDLEFT, SelStart); UpDateCaretPos; end else Col := Col - 1; end; VK_Right: begin CheckSelection(Shift); if ssCtrl in Shift then begin SelStart := SendMessage(Handle, EM_FINDWORDBREAK, WB_MOVEWORDRIGHT, SelStart); UpDateCaretPos; end else Col := Col + 1; end; VK_Home: begin CheckSelection(Shift); if ssCtrl in Shift then Row := succ(SendMessage(Handle, EM_GETFIRSTVISIBLELINE, 0, 0)) else Col := 1; end; VK_End: begin CheckSelection(Shift); RemoveRightSpaces; if ssCtrl in Shift then Row := SendMessage(Handle, EM_GETFIRSTVISIBLELINE, 0, 0) + pred(VisibleLinesCount) else Col := succ(LineEditLength); end; VK_Up: begin CheckSelection(Shift); if ssCtrl in Shift then SendMessage(Handle, EM_SCROLL, SB_LINEUP, 0); Row := Row - 1; end; VK_Down: begin CheckSelection(Shift); if ssCtrl in Shift then SendMessage(Handle, EM_SCROLL, SB_LINEDOWN, 0); Row := Row + 1; end; VK_NEXT: begin CheckSelection(Shift); if ssCtrl in Shift then begin Row := LineCount; Col := succ(LineEditLength); end else MovePage(SB_PAGEDOWN); end; VK_PRIOR: begin CheckSelection(Shift); if ssCtrl in Shift then begin Row := 1; Col := 1; end else MovePage(SB_PAGEUP); end; VK_Insert: if Shift = [] then InsertMode := not InsertMode; VK_TAB: if eoSmartTab in Options then InsertTab; VK_BACK: begin if not ((eoBackspaceUnindents in Options) and DoBackSpaceUnindents) then DoBackSpace; end; VK_DELETE: begin DoDelete; end; end; if Key in [VK_Left, VK_Right, VK_Home, VK_End, VK_Up, VK_Down, VK_NEXT, VK_PRIOR, VK_TAB, VK_BACK, VK_DELETE] then Key := 0; end; procedure TCodeEdit.KeyPress(var Key: Char); begin inherited; if (Key = #13) and (eoAutoIdentMode in Options) then begin Col := succ(Ident); Row := Row + 1; SyntaxHighLight; UpDateLine(pred(ActualRow)); Key := #0; end; if (Key = #9) and (eoSmartTab in Options) then Key := #0; if Key >= #32 then begin WriteChar(Key); Key := #0; end; end; procedure TCodeEdit.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var A: TPoint; P: TPoint; begin CheckSelection(Shift); if Button = mbLeft then begin SendMessage(Handle, EM_POSFROMCHAR, longint(@A), 0); P.X := X + FontWidth div 2 - (X - A.X + FontWidth div 2) mod FontWidth; P.Y := Y - (Y - A.Y) mod FontHeight; //SetCaretPos(P.X, P.Y); Col := succ((P.X - A.X) div FontWidth); Row := succ((P.Y - A.Y) div FontHeight); end; end; procedure TCodeEdit.SetOptions(const Value: TEditOptions); begin FOptions := Value; end; function TCodeEdit.GetInsertMode: boolean; begin Result := eoInsertmode in Options; end; procedure TCodeEdit.setInsertMode(const Value: boolean); begin if Value then FOptions := FOptions + [eoInsertMode] else FOptions := FOptions - [eoInsertMode]; end; procedure TCodeEdit.SetCol(const Value: integer); begin if (Value > 0) and (Value < MAXCARPERLINE) and (Value <> FCol) then begin FCol := Value; LocateCaret; if Assigned(FMoveCaret) then FMoveCaret(Col, Row); end; end; procedure TCodeEdit.SetRow(const Value: integer); begin if (Value > 0) and (Value <= LineCount) and (Value <> FRow) then begin RemoveRightSpaces; FRow := Value; LocateCaret; if Assigned(FMoveCaret) then FMoveCaret(Col, Row); end; end; procedure TCodeEdit.LocateCaret; var A: TPoint; begin LocateInsertPoint; // Poner en A el margen superior y el margen derecho SendMessage(Handle, EM_POSFROMCHAR, longint(@A), 0); // Calcular la posicion donde debe ir el cursor y situarlo SetCaretPos(A.X + FontWidth * ActualCol, A.Y + FontHeight * ActualRow); ShapeCaret; end; procedure TCodeEdit.LocateInsertPoint; var CharRange: TCharRange; CarPos: integer; begin CarPos := CharFromLine(ActualRow) + Min(ActualCol, LineEditLength); if Selecting then begin CharRange.cpMin := Min(CarPos, SelectPoint); CharRange.cpMax := Max(CarPos, SelectPoint); end else begin CharRange.cpMin := CarPos; CharRange.cpMax := CarPos; end; SendMessage(Handle, EM_EXSETSEL, 0, Longint(@CharRange)); end; procedure TCodeEdit.WriteChar(const Ch: Char); var Text: PChar; UpDate: boolean; begin if ActualCol > LineEditLength then FillRowAndInsert; UpDate := SelLength > 0; Text := PChar(Ch); SendMessage(Handle, EM_REPLACESEL, integer(True), integer(@Text)); if UpDate then begin Selecting := false; UpDateCaretPos; end else Col := Col + 1; end; procedure TCodeEdit.SetSelecting(const Value: boolean); begin if Value and not Selecting then SelectPoint := SelStart; FSelecting := Value; end; procedure TCodeEdit.SetSelectPoint(const Value: integer); begin FSelectPoint := Value; end; function TCodeEdit.GetActualCol: integer; begin Result := pred(Col); end; function TCodeEdit.GetActualRow: integer; begin Result := pred(Row); end; procedure TCodeEdit.DoBackSpace; var CharRange: TCharRange; begin if ActualCol > LineEditLength then Col := Col -1 else begin SendMessage(Handle, EM_EXGETSEL, 0, Longint(@CharRange)); if CharRange.cpMin = CharRange.cpMax then begin CharRange.cpMin := pred(CharRange.cpMax); SendMessage(Handle, EM_EXSETSEL, 0, Longint(@CharRange)); end; Selecting := false; SendMessage(Handle, EM_REPLACESEL, integer(True), integer(PChar(''))); UpDateCaretPos; end; end; procedure TCodeEdit.DoDelete; var CharRange: TCharRange; begin if Col > LineEditLength then FillRowAndInsert; SendMessage(Handle, EM_EXGETSEL, 0, Longint(@CharRange)); if CharRange.cpMin = CharRange.cpMax then begin if ActualCol = LineEditLength then CharRange.cpMax := CharRange.cpMin + 2 else CharRange.cpMax := succ(CharRange.cpMin); SendMessage(Handle, EM_EXSETSEL, 0, Longint(@CharRange)); end; Selecting := false; SendMessage(Handle, EM_REPLACESEL, integer(True), integer(PChar(''))); UpDateCaretPos; end; procedure TCodeEdit.UpDateCaretPos; var CarPos: integer; begin CarPos := SelStart; Row := succ(SendMessage(Handle, EM_EXLINEFROMCHAR, 0, CarPos)); Col := succ(CarPos - SendMessage(Handle, EM_LINEINDEX, ActualRow, 0)); ShapeCaret; end; procedure TCodeEdit.DoHighLight(const From, Count: integer); var CharRange: TCharRange; ScanResult: boolean; CaretPos: integer; begin FCheckingHightLight := true; CaretPos := SelStart; Scanner.Source := Text; Scanner.Index := From; SetUpDateState(true); repeat ScanResult := Scanner.NextToken; if ScanResult then begin CharRange.cpMin := pred(Scanner.Position); CharRange.cpMax := CharRange.cpMin + Length(Scanner.Token); SendMessage(Handle, EM_EXSETSEL, 0, Longint(@CharRange)); SelAttributes.Color := TokenColor[Scanner.TokenType]; SelAttributes.Style := TokenStyle[Scanner.TokenType]; end; until (Scanner.Index >= From + Count) or not ScanResult; LocateCaret; SelStart := CaretPos; SetUpDateState(false); FCheckingHightLight := false; end; procedure TCodeEdit.SyntaxHighLight; begin HighLightLine(Row); end; procedure TCodeEdit.CheckHighLightAllText; begin Lines.BeginUpdate; DoHighLight(1, SendMessage(Handle, WM_GETTEXTLENGTH, 0, 0)); Lines.EndUpdate; end; procedure TCodeEdit.Change; begin if not FCheckingHightLight then SyntaxHighLight; inherited; end; procedure TCodeEdit.WMPAINT(var Message: TMessage); begin inherited; ShapeCaret; end; procedure TCodeEdit.MovePage(const Direction: integer); var L, R: integer; begin L := Row - succ(SendMessage(Handle, EM_GETFIRSTVISIBLELINE, 0, 0)); SendMessage(Handle, EM_SCROLL, Direction, 0); R := succ(SendMessage(Handle, EM_GETFIRSTVISIBLELINE, 0, 0)); if (R + L > LineCount) or ((R = 1) and (L > 0)) then Row := R else Row := R + L; end; function TCodeEdit.VisibleLinesCount: integer; var A: TPoint; begin SendMessage(Handle, EM_POSFROMCHAR, longint(@A), 0); Result := (Height - A.y) div FontHeight; end; procedure TCodeEdit.SetUpdateState(Updating: Boolean); begin if Showing then SendMessage(Handle, WM_SETREDRAW, Ord(not Updating), 0); if not Updating then begin { Refresh; Perform(CM_TEXTCHANGED, 0, 0); } UpDateLine(ActualRow); end; end; function TCodeEdit.GetLineEditLength: integer; begin Result := SendMessage(Handle, EM_LINELENGTH, SendMessage(Handle, EM_LINEINDEX, ActualRow, 0), 0); end; procedure TCodeEdit.UpDateLine(const Line: integer); var R: TRect; A, B: TPoint; CharLine: integer; begin CharLine := SendMessage(Handle, EM_LINEINDEX, Line, 0); SendMessage(Handle, EM_POSFROMCHAR, longint(@A), CharLine); SendMessage(Handle, EM_POSFROMCHAR, longint(@B), CharLine + SendMessage(Handle, EM_LINELENGTH, CharLine, 0)); R := Rect(A.x, A.y, B.x + FontWidth, succ(A.y + FontHeight)); RedrawWindow(Handle, @R, 0, RDW_INVALIDATE); end; procedure TCodeEdit.SetLineAttr(const Line: integer; const Color: TColor; const FontStyles: TFontStyles); var CharRange: TCharRange; CaretPos: integer; begin CharRange.cpMin := SendMessage(Handle, EM_LINEINDEX, pred(Line), 0); if CharRange.cpMin > 0 then begin FCheckingHightLight := true; CharRange.cpMax := CharRange.cpMin + SendMessage(Handle, EM_LINELENGTH, CharRange.cpMin, 0); CaretPos := SelStart; SendMessage(Handle, WM_SETREDRAW, Ord(False), 0); SendMessage(Handle, EM_EXSETSEL, 0, Longint(@CharRange)); SelAttributes.Color := Color; SelAttributes.Style := FontStyles; LocateCaret; SelStart := CaretPos; SendMessage(Handle, WM_SETREDRAW, Ord(True), 0); Refresh; Perform(CM_TEXTCHANGED, 0, 0); FCheckingHightLight := false; end; end; procedure TCodeEdit.HighLightLine(const Line: integer); var Len: integer; Pos: integer; begin Pos := succ(SendMessage(Handle, EM_LINEINDEX, pred(Line), 0)); if Pos > 0 then begin Len := SendMessage(Handle, EM_LINELENGTH, Pos, 0); DoHighLight(Pos, Len); end; end; function TCodeEdit.GetSource: TStrings; begin Result := Lines; end; initialization Scanner := TScanner.Create; Scanner.SkipComments := false; Scanner.QuietErrors := true; finalization Scanner.free; end.
unit uvcvideo; interface { Automatically converted by H2Pas 1.0.0 from uvcvideo.h The following command line parameters were used: -e -p uvcvideo.h } { Pointers to basic pascal types, inserted by h2pas conversion program.} { Type PLongint = ^Longint; PSmallInt = ^SmallInt; PByte = ^Byte; PWord = ^Word; PDWord = ^DWord; PDouble = ^Double; }{ Type P__u8 = ^__u8; Puvc_menu_info = ^uvc_menu_info; Puvc_xu_control_mapping = ^uvc_xu_control_mapping; Puvc_xu_control_query = ^uvc_xu_control_query; } {$IFDEF FPC} {$PACKRECORDS C} {$ENDIF} {$ifndef __LINUX_UVCVIDEO_H_} {$define __LINUX_UVCVIDEO_H_} {//#include <linux/ioctl.h>} const _IOC_NRBITS = 8; _IOC_TYPEBITS = 8; _IOC_SIZEBITS = 14; _IOC_DIRBITS = 2; _IOC_NRMASK = (1 shl _IOC_NRBITS)-1; _IOC_TYPEMASK = (1 shl _IOC_TYPEBITS)-1; _IOC_SIZEMASK = (1 shl _IOC_SIZEBITS)-1; _IOC_DIRMASK = (1 shl _IOC_DIRBITS)-1; _IOC_NRSHIFT = 0; _IOC_TYPESHIFT = _IOC_NRSHIFT+_IOC_NRBITS; _IOC_SIZESHIFT = _IOC_TYPESHIFT+_IOC_TYPEBITS; _IOC_DIRSHIFT = _IOC_SIZESHIFT+_IOC_SIZEBITS; { * Direction bits. } _IOC_NONE = 0; _IOC_WRITE = 1; _IOC_READ = 2; {//#include <linux/types.h>} type __u8 = byte; __u16 = word; __u32 = LongWord; { * Dynamic controls } { Data types for UVC control data } const UVC_CTRL_DATA_TYPE_RAW = 0; UVC_CTRL_DATA_TYPE_SIGNED = 1; UVC_CTRL_DATA_TYPE_UNSIGNED = 2; UVC_CTRL_DATA_TYPE_BOOLEAN = 3; UVC_CTRL_DATA_TYPE_ENUM = 4; UVC_CTRL_DATA_TYPE_BITMASK = 5; { Control flags } UVC_CTRL_FLAG_SET_CUR = 1 shl 0; UVC_CTRL_FLAG_GET_CUR = 1 shl 1; UVC_CTRL_FLAG_GET_MIN = 1 shl 2; UVC_CTRL_FLAG_GET_MAX = 1 shl 3; UVC_CTRL_FLAG_GET_RES = 1 shl 4; UVC_CTRL_FLAG_GET_DEF = 1 shl 5; { Control should be saved at suspend and restored at resume. } UVC_CTRL_FLAG_RESTORE = 1 shl 6; { Control can be updated by the camera. } UVC_CTRL_FLAG_AUTO_UPDATE = 1 shl 7; UVC_CTRL_FLAG_GET_RANGE = (((UVC_CTRL_FLAG_GET_CUR or UVC_CTRL_FLAG_GET_MIN) or UVC_CTRL_FLAG_GET_MAX) or UVC_CTRL_FLAG_GET_RES) or UVC_CTRL_FLAG_GET_DEF; type Puvc_menu_info = ^uvc_menu_info; uvc_menu_info = record value : __u32; name : array[0..31] of __u8; end; {__user } Puvc_xu_control_mapping = ^uvc_xu_control_mapping; uvc_xu_control_mapping = record id : __u32; name : array[0..31] of __u8; entity : array[0..15] of __u8; selector : __u8; size : __u8; offset : __u8; v4l2_type : __u32; data_type : __u32; menu_info : Puvc_menu_info; menu_count : __u32; reserved : array[0..3] of __u32; end; { Video Class-Specific Request Code, } { defined in linux/usb/video.h A.8. } {__user } Puvc_xu_control_query = ^uvc_xu_control_query; uvc_xu_control_query = record _unit : __u8; selector : __u8; query : __u8; size : __u16; data : ^__u8; end; const UVCIOC_CTRL_MAP = LongInt(((_IOC_READ or _IOC_WRITE) shl _IOC_DIRSHIFT) or (Ord('u') shl _IOC_TYPESHIFT) or ($20 shl _IOC_NRSHIFT) or (SizeOf(uvc_xu_control_mapping) shl _IOC_SIZESHIFT)); UVCIOC_CTRL_QUERY = LongInt(((_IOC_READ or _IOC_WRITE) shl _IOC_DIRSHIFT) or (Ord('u') shl _IOC_TYPESHIFT) or ($21 shl _IOC_NRSHIFT) or (SizeOf(uvc_xu_control_query) shl _IOC_SIZESHIFT)); {$endif} implementation end.
unit tgdatastructs; {$mode objfpc}{$H+} interface uses Classes, SysUtils, tgSettings; type TTgConnectionState = (TgDisconnected, TgFirstTimeConnected, TgRequestingSync, TgDownloadedData, TgProcessedData, TgConnected, TgUploadingData); TDeviceId = Record name: string; serial: string; description: TstringList; ip: string; end; TSession = Record size: integer; lograte: integer; folderName: string; folderAlias: String; dateTime1: String; dateTime2: String; totalSamples: Integer; alarmType: Integer; alarmRate: Integer; mute: Integer; muteTime: Integer; visAlarm: Boolean; audAlarm: Boolean; emailAlarm: Boolean; totalDataFiles: Integer; end; TConnectStatus = record globalAlarmStatus: TGlobalAlarmStatus; vpnStatus: TTgConnectionState; temperatureStatus: Boolean; end; {TRealtimeDevice = Record //statusDone: Boolean; sensorsDone: Boolean; settingsChange: Boolean; end; } TRealtimeSensor = Record temperature: Single; A1:Integer; A2:Integer; status: TSensorAlarmStatus; end; TSensorAlarmTriggers = Record a1triggered: Boolean; a2triggered: Boolean; end; TSensorAlarmTrigArray = array of TSensorAlarmTriggers; TRTSensorArray = array[0..719] of TRealtimeSensor; TSensorProfile = Record pos: integer; serial: string; name: string; a1: integer; a2: integer; a1triggered: Boolean; a2triggered: Boolean; watch: Boolean; filtered: Boolean; tags: Integer; deltaT: integer; realtimeUpdate: TRTSensorArray; end; TSensorProfileArray = array of TSensorProfile; TtgDataStruct = Record devId: TDeviceId; session: TSession; connectStatus: TConnectStatus; profile: TSensorProfileArray; end; AlarmsRecord = Record sample: Integer; dateTimeStr: string; alarm: Integer; end; AlarmsRecordArr = array of AlarmsRecord; TTempRecord = record temp: Double; tag: string; end; TSensorData = array of TTempRecord; TLoadMail = (lmCurrent, lmSaved, lmBlank); TGraphAxis = record xmarks: integer; ymin: integer; ymax: integer; ymarks: integer; axisgridon: boolean; end; implementation end.
unit AboutForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, VersionSupport, lclintf, ComCtrls; type { TAboutDialog } TAboutDialog = class(TForm) btnWebsite: TButton; Image1: TImage; lblVersion: TLabel; lblProgramName: TLabel; PageControl1: TPageControl; pnlLabels: TPanel; pnlTop: TPanel; tsLicense: TTabSheet; tsChangelog: TTabSheet; txtLicense: TMemo; txtChangelog: TMemo; procedure btnWebsiteClick(Sender: TObject); procedure FormCreate(Sender: TObject); private public end; var AboutDialog: TAboutDialog; implementation {$R *.lfm} { TAboutDialog } procedure TAboutDialog.FormCreate(Sender: TObject); begin lblVersion.Caption := 'Version ' + VersionSupport.GetFileVersion; end; procedure TAboutDialog.btnWebsiteClick(Sender: TObject); begin OpenURL('http://www.ianmtz.com'); end; end.
unit Csr; interface type HCkBinData = Pointer; HCkPrivateKey = Pointer; HCkCsr = Pointer; HCkPublicKey = Pointer; HCkString = Pointer; function CkCsr_Create: HCkCsr; stdcall; procedure CkCsr_Dispose(handle: HCkCsr); stdcall; procedure CkCsr_getCommonName(objHandle: HCkCsr; outPropVal: HCkString); stdcall; procedure CkCsr_putCommonName(objHandle: HCkCsr; newPropVal: PWideChar); stdcall; function CkCsr__commonName(objHandle: HCkCsr): PWideChar; stdcall; procedure CkCsr_getCompany(objHandle: HCkCsr; outPropVal: HCkString); stdcall; procedure CkCsr_putCompany(objHandle: HCkCsr; newPropVal: PWideChar); stdcall; function CkCsr__company(objHandle: HCkCsr): PWideChar; stdcall; procedure CkCsr_getCompanyDivision(objHandle: HCkCsr; outPropVal: HCkString); stdcall; procedure CkCsr_putCompanyDivision(objHandle: HCkCsr; newPropVal: PWideChar); stdcall; function CkCsr__companyDivision(objHandle: HCkCsr): PWideChar; stdcall; procedure CkCsr_getCountry(objHandle: HCkCsr; outPropVal: HCkString); stdcall; procedure CkCsr_putCountry(objHandle: HCkCsr; newPropVal: PWideChar); stdcall; function CkCsr__country(objHandle: HCkCsr): PWideChar; stdcall; procedure CkCsr_getDebugLogFilePath(objHandle: HCkCsr; outPropVal: HCkString); stdcall; procedure CkCsr_putDebugLogFilePath(objHandle: HCkCsr; newPropVal: PWideChar); stdcall; function CkCsr__debugLogFilePath(objHandle: HCkCsr): PWideChar; stdcall; procedure CkCsr_getEmailAddress(objHandle: HCkCsr; outPropVal: HCkString); stdcall; procedure CkCsr_putEmailAddress(objHandle: HCkCsr; newPropVal: PWideChar); stdcall; function CkCsr__emailAddress(objHandle: HCkCsr): PWideChar; stdcall; procedure CkCsr_getLastErrorHtml(objHandle: HCkCsr; outPropVal: HCkString); stdcall; function CkCsr__lastErrorHtml(objHandle: HCkCsr): PWideChar; stdcall; procedure CkCsr_getLastErrorText(objHandle: HCkCsr; outPropVal: HCkString); stdcall; function CkCsr__lastErrorText(objHandle: HCkCsr): PWideChar; stdcall; procedure CkCsr_getLastErrorXml(objHandle: HCkCsr; outPropVal: HCkString); stdcall; function CkCsr__lastErrorXml(objHandle: HCkCsr): PWideChar; stdcall; function CkCsr_getLastMethodSuccess(objHandle: HCkCsr): wordbool; stdcall; procedure CkCsr_putLastMethodSuccess(objHandle: HCkCsr; newPropVal: wordbool); stdcall; procedure CkCsr_getLocality(objHandle: HCkCsr; outPropVal: HCkString); stdcall; procedure CkCsr_putLocality(objHandle: HCkCsr; newPropVal: PWideChar); stdcall; function CkCsr__locality(objHandle: HCkCsr): PWideChar; stdcall; procedure CkCsr_getState(objHandle: HCkCsr; outPropVal: HCkString); stdcall; procedure CkCsr_putState(objHandle: HCkCsr; newPropVal: PWideChar); stdcall; function CkCsr__state(objHandle: HCkCsr): PWideChar; stdcall; function CkCsr_getVerboseLogging(objHandle: HCkCsr): wordbool; stdcall; procedure CkCsr_putVerboseLogging(objHandle: HCkCsr; newPropVal: wordbool); stdcall; procedure CkCsr_getVersion(objHandle: HCkCsr; outPropVal: HCkString); stdcall; function CkCsr__version(objHandle: HCkCsr): PWideChar; stdcall; function CkCsr_GenCsrBd(objHandle: HCkCsr; privKey: HCkPrivateKey; csrData: HCkBinData): wordbool; stdcall; function CkCsr_GenCsrPem(objHandle: HCkCsr; privKey: HCkPrivateKey; outStr: HCkString): wordbool; stdcall; function CkCsr__genCsrPem(objHandle: HCkCsr; privKey: HCkPrivateKey): PWideChar; stdcall; function CkCsr_GetPublicKey(objHandle: HCkCsr; pubkey: HCkPublicKey): wordbool; stdcall; function CkCsr_GetSubjectField(objHandle: HCkCsr; oid: PWideChar; outStr: HCkString): wordbool; stdcall; function CkCsr__getSubjectField(objHandle: HCkCsr; oid: PWideChar): PWideChar; stdcall; function CkCsr_LoadCsrPem(objHandle: HCkCsr; csrPemStr: PWideChar): wordbool; stdcall; function CkCsr_SaveLastError(objHandle: HCkCsr; path: PWideChar): wordbool; stdcall; function CkCsr_SetSubjectField(objHandle: HCkCsr; oid: PWideChar; value: PWideChar; asnType: PWideChar): wordbool; stdcall; implementation {$Include chilkatDllPath.inc} function CkCsr_Create; external DLLName; procedure CkCsr_Dispose; external DLLName; procedure CkCsr_getCommonName; external DLLName; procedure CkCsr_putCommonName; external DLLName; function CkCsr__commonName; external DLLName; procedure CkCsr_getCompany; external DLLName; procedure CkCsr_putCompany; external DLLName; function CkCsr__company; external DLLName; procedure CkCsr_getCompanyDivision; external DLLName; procedure CkCsr_putCompanyDivision; external DLLName; function CkCsr__companyDivision; external DLLName; procedure CkCsr_getCountry; external DLLName; procedure CkCsr_putCountry; external DLLName; function CkCsr__country; external DLLName; procedure CkCsr_getDebugLogFilePath; external DLLName; procedure CkCsr_putDebugLogFilePath; external DLLName; function CkCsr__debugLogFilePath; external DLLName; procedure CkCsr_getEmailAddress; external DLLName; procedure CkCsr_putEmailAddress; external DLLName; function CkCsr__emailAddress; external DLLName; procedure CkCsr_getLastErrorHtml; external DLLName; function CkCsr__lastErrorHtml; external DLLName; procedure CkCsr_getLastErrorText; external DLLName; function CkCsr__lastErrorText; external DLLName; procedure CkCsr_getLastErrorXml; external DLLName; function CkCsr__lastErrorXml; external DLLName; function CkCsr_getLastMethodSuccess; external DLLName; procedure CkCsr_putLastMethodSuccess; external DLLName; procedure CkCsr_getLocality; external DLLName; procedure CkCsr_putLocality; external DLLName; function CkCsr__locality; external DLLName; procedure CkCsr_getState; external DLLName; procedure CkCsr_putState; external DLLName; function CkCsr__state; external DLLName; function CkCsr_getVerboseLogging; external DLLName; procedure CkCsr_putVerboseLogging; external DLLName; procedure CkCsr_getVersion; external DLLName; function CkCsr__version; external DLLName; function CkCsr_GenCsrBd; external DLLName; function CkCsr_GenCsrPem; external DLLName; function CkCsr__genCsrPem; external DLLName; function CkCsr_GetPublicKey; external DLLName; function CkCsr_GetSubjectField; external DLLName; function CkCsr__getSubjectField; external DLLName; function CkCsr_LoadCsrPem; external DLLName; function CkCsr_SaveLastError; external DLLName; function CkCsr_SetSubjectField; external DLLName; end.
unit XStringsTestes; interface uses DUnitX.TestFramework, XStrings; type [TestFixture] TXStringsTestes = class(TObject) private FXStrings: TXStrings; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure ValidarSomenteNumeros; overload; [Test] [TestCase('Caso 1', 'A0-245%4$38&86893,024543886893')] [TestCase('Caso 2', '111.111.111-11,11111111111')] procedure ValidarSomenteNumeros(AStringASerValidada: String; AResultadoEsperado: String);overload; [Test] procedure ValidarOExceptionDoMetodoExemploMetodoComExcecao; end; implementation procedure TXStringsTestes.Setup; begin FXStrings := TXStrings.Create; end; procedure TXStringsTestes.TearDown; begin if Assigned(FXStrings) then FXStrings.Free; end; procedure TXStringsTestes.ValidarSomenteNumeros; var Aux: String; Resultado : string; begin Resultado := '024543886893'; Aux := FXStrings.SomenteNumeros('A0-2,45%4$38&¨8689.3'); //Assert.IsTrue(Aux = '024543886893', 'String de entrada A0-2,45%4$38&¨8689.3 deveria retornar 024543886893 mas retornou ' + Aux); Assert.AreEqual(Resultado , Aux, 'String de entrada A0-2,45%4$38&¨8689.3 deveria retornar 024543886893 mas retornou ' + Aux); end; procedure TXStringsTestes.ValidarSomenteNumeros(AStringASerValidada: String; AResultadoEsperado: String); var Aux: String; begin Aux := FXStrings.SomenteNumeros(AStringASerValidada); Assert.IsTrue(Aux = AResultadoEsperado, 'String de entrada ' + AStringASerValidada + ' deveria retornar ' + AResultadoEsperado + ' mas retornou ' + Aux); end; procedure TXStringsTestes.ValidarOExceptionDoMetodoExemploMetodoComExcecao; begin // FXStrings.Descricao := 'Teste'; Assert.WillRaise(FXStrings.ExemploMetodoComExcecao, nil, 'Exceção do método ExemploMetodoComExcecao não aconteceu!'); end; initialization TDUnitX.RegisterTestFixture(TXStringsTestes); end.
{******************************************************************************* Falcon Sistemas www.falconsistemas.com.br suporte@falconsistemas.com.br Written by Marlon Nardi - ALL RIGHTS RESERVED. https://github.com/craftpip/jquery-confirm *******************************************************************************} {$IF CompilerVersion >= 24.0} // XE3 ou superior {$LEGACYIFEND ON} {$IFEND} unit UniFSConfirm; interface uses Classes, TypInfo, SysUtils, System.UITypes, uniGUIApplication, uniGUITypes, uniGUIClasses, UniFSCommon; const FSAbout = 'store.falconsistemas.com.br'; PackageVersion = '1.0.2.45'; type TTypeConfirm = (Confirm, ConfirmOther, Alert, Dialog, Prompt); TTypeColor = (blue, green, orange, purple, dark_, red); TTheme = (light, dark, modern, supervan, material, bootstrap); TConfirmButton = (Other, Yes, No, Ok); TTypePrompt = (text, password); TTypeCharCase = (LowerCase_, Normal_, UpperCase_); TButtonCallBack = reference to procedure(ConfirmButton: TConfirmButton); TPromptCallBack = reference to procedure(ConfirmButton: TConfirmButton; Result: string); TMaskCallBack = reference to procedure(); TUniFSScreenMask = class(TPersistent) private FEnabled: Boolean; FText: string; public constructor Create; published property Enabled: Boolean read FEnabled write FEnabled; property Text: string read FText write FText; end; TUniFSPrompt = class(TPersistent) private FTypePrompt: TTypePrompt; FRequiredField: Boolean; FTextRequiredField: string; FCharCase: TTypeCharCase; public constructor Create; published property TypePrompt: TTypePrompt read FTypePrompt write FTypePrompt; property RequiredField: Boolean read FRequiredField write FRequiredField; property TextRequiredField: string read FTextRequiredField write FTextRequiredField; property CharCase: TTypeCharCase read FCharCase write FCharCase; end; {$IF CompilerVersion >= 23.0} [ComponentPlatformsAttribute(pidWin32 or pidWin64 {$IF CompilerVersion >= 34.0}or pidLinux64{$IFEND})] {$IFEND} TUniFSConfirm = class(TUniComponent) protected function GetVersion: string; function GetAbout: string; function GetStrTypeConfirm(TypeConfirm: TTypeConfirm): string; function GetStrTypeColor(TypeColor: TTypeColor): string; function GetStrTheme(Theme: TTheme): string; function GetStrTypePrompt(TypePrompt: TTypePrompt): string; function GetStrTypeCharCase(TypeCharCase: TTypeCharCase): string; procedure WebCreate; override; procedure DOHandleEvent(EventName: string; Params: TUniStrings); override; procedure LoadCompleted; override; procedure RemoveInvalidChar(var InputText: string); function BoolToStr(const value: boolean): string; {Versions Old Delphi} function BuildJS(TypeConfirm: TTypeConfirm): string; procedure ExecJS(JS: string); private FTitle: string; FContent: string; FTheme: TTheme; FTypeColor: TTypeColor; FTypeAnimated: Boolean; FDraggable: Boolean; FEscapeKey: Boolean; FCloseIcon: Boolean; FIcon: string; FRTL: Boolean; FboxWidth: string; FBackgroundDismiss: Boolean; FButtonTextConfirm: string; FButtonTextCancel: string; FButtonTextOther: string; FButtonTextOK: string; FButtonEnterConfirm: Boolean; FScreenMask: TUniFSScreenMask; FPromptType: TUniFSPrompt; FMsgPrompt: string; FButtonCallBack: TButtonCallBack; FPromptCallBack: TPromptCallBack; published property Title: string read FTitle write FTitle; property Content: string read FContent write FContent; property Theme: TTheme read FTheme write FTheme; property TypeColor: TTypeColor read FTypeColor write FTypeColor; property TypeAnimated: Boolean read FTypeAnimated write FTypeAnimated; property Draggable: Boolean read FDraggable write FDraggable; property EscapeKey: Boolean read FEscapeKey write FEscapeKey; property CloseIcon: Boolean read FCloseIcon write FCloseIcon; property Icon: string read FIcon write FIcon; property RTL: Boolean read FRTL write FRTL; property boxWidth: string read FboxWidth write FboxWidth; property BackgroundDismiss: Boolean read FBackgroundDismiss write FBackgroundDismiss; property ButtonTextConfirm: string read FButtonTextConfirm write FButtonTextConfirm; property ButtonTextCancel: string read FButtonTextCancel write FButtonTextCancel; property ButtonTextOther: string read FButtonTextOther write FButtonTextOther; property ButtonTextOK: string read FButtonTextOK write FButtonTextOK; property ButtonEnterConfirm: Boolean read FButtonEnterConfirm write FButtonEnterConfirm; property ScreenMask: TUniFSScreenMask read FScreenMask write FScreenMask; property PromptType: TUniFSPrompt read FPromptType write FPromptType; property About : string read GetAbout; property Version : string read GetVersion; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Clear; procedure ShowMask(Msg: string); overload; procedure ShowMask(Msg: string; Percent: Integer); overload; procedure ShowMask(Msg, JSName: string); overload; procedure ShowMaskUpdate(Msg: string; Percent: Integer); overload; procedure RemoveMask; procedure Alert(const Title, Content: string); overload; procedure Alert(const Title, Content, Icon: string; Color: TTypeColor; Theme: TTheme); overload; procedure Alert(const Title, Content, Icon: string; Color: TTypeColor; Theme: TTheme; BC: TButtonCallBack); overload; procedure Prompt(const Title, Msg: string; PC: TPromptCallBack); overload; procedure Prompt(const Title, Msg, Icon: string; Color: TTypeColor; Theme: TTheme; PC: TPromptCallBack); overload; procedure Question(const Title, Content: string; BC: TButtonCallBack; const TP: TTypeConfirm = Confirm); overload; procedure Question(const Title, Content, Icon: string; BC: TButtonCallBack; const TP: TTypeConfirm = Confirm); overload; procedure Question(const Title, Content, Icon: string; Color: TTypeColor; Theme: TTheme; BC: TButtonCallBack; const TP: TTypeConfirm = Confirm); overload; procedure Mask(const Msg: string; M: TMaskCallBack); end; procedure Register; implementation procedure Register; begin RegisterComponents('uniGUI Falcon', [TUniFSConfirm]); end; { TUniFSConfirm } procedure TUniFSConfirm.Alert(const Title, Content: string); begin FTitle := Title; FContent := Content; ExecJS('$.alert({'+BuildJS(TTypeConfirm.Alert)+'});'); end; procedure TUniFSConfirm.Alert(const Title, Content, Icon: string; Color: TTypeColor; Theme: TTheme); begin FIcon := Icon; FTypeColor := Color; FTheme := Theme; Alert(Title, Content); end; procedure TUniFSConfirm.Alert(const Title, Content, Icon: string; Color: TTypeColor; Theme: TTheme; BC: TButtonCallBack); begin FButtonCallBack := BC; Alert(Title, Content, Icon, Color, Theme); end; function TUniFSConfirm.BoolToStr(const value: boolean): string; begin if value then Result := 'true' else Result := 'false'; end; function TUniFSConfirm.BuildJS(TypeConfirm: TTypeConfirm): string; var StrBuilder: TStringBuilder; begin RemoveInvalidChar(FTitle); RemoveInvalidChar(FContent); StrBuilder := TStringBuilder.Create; try with StrBuilder do begin Append('title: '''+FTitle+''','); Append('content: '''+FContent+''', '); Append('icon: '''+FIcon+''', '); Append('type: '''+GetStrTypeColor(FTypeColor)+''', '); Append('theme: '''+GetStrTheme(FTheme)+''', '); Append('closeIcon: '+BoolToStr(FCloseIcon)+', '); Append('typeAnimated: '+BoolToStr(FTypeAnimated)+', '); Append('draggable: '+BoolToStr(FDraggable)+', '); Append('escapeKey: '+BoolToStr(FEscapeKey)+', '); Append('backgroundDismiss: '+BoolToStr(FBackgroundDismiss)+', '); Append('rtl: '+BoolToStr(FRTL)+', '); Append('useBootstrap: false, '); Append('boxWidth: '''+FboxWidth+''', '); if (TypeConfirm = TTypeConfirm.Confirm) or (TypeConfirm = TTypeConfirm.ConfirmOther) then begin Append('buttons: {'); Append(' confirma: { '); if FButtonEnterConfirm then Append(' keys: ["enter"], '); Append(' text: '''+FButtonTextConfirm+''', '); Append(' action: function() {'); if ScreenMask.Enabled then Append(' $(''body'').preloader({text: '''+ScreenMask.Text+'''}); '); Append(' ajaxRequest('+Self.JSName+', "Confirm", ["Button="+"Yes"]); '); Append(' } '); Append(' },'); Append(' cancela: { '); Append(' text: '''+FButtonTextCancel+''', '); Append(' action: function() {'); if ScreenMask.Enabled then Append(' $(''body'').preloader({text: '''+ScreenMask.Text+'''}); '); Append(' ajaxRequest('+Self.JSName+', "Confirm", ["Button="+"No"]); '); Append(' } '); Append(' },'); if TypeConfirm = TTypeConfirm.ConfirmOther then begin Append(' outro: { '); Append(' text: '''+FButtonTextOther+''', '); Append(' action: function() {'); if ScreenMask.Enabled then Append(' $(''body'').preloader({text: '''+ScreenMask.Text+'''}); '); Append(' ajaxRequest('+Self.JSName+', "Confirm", ["Button="+"Other"]); '); Append(' } '); Append(' }'); end; Append('}'); end; if TypeConfirm = TTypeConfirm.Prompt then begin Append('content: '); Append(' ''<form action="" class="formName">'' + '); Append(' ''<div class="fs-form-group">'' + '); Append(' ''<label class="fs-label">'+FMsgPrompt+'</label>'' + '); if FPromptType.RequiredField then Append(' ''<input style="text-transform: '+GetStrTypeCharCase(FPromptType.CharCase)+ '" type="'+GetStrTypePrompt(FPromptType.TypePrompt)+'" class="name fs-form-control" autofocus required />'' + ') else Append(' ''<input style="text-transform: '+GetStrTypeCharCase(FPromptType.CharCase)+ '" type="'+GetStrTypePrompt(FPromptType.TypePrompt)+'" class="name fs-form-control" autofocus />'' + '); Append(' ''</div>'' + '); Append(' ''</form>'', '); Append('buttons: {'); Append(' formSubmit: { '); if FButtonEnterConfirm then Append(' keys: ["enter"], '); Append(' text: '''+FButtonTextConfirm+''', '); Append(' action: function() {'); if FPromptType.RequiredField then begin Append('if (this.$content.find(''.name'').val() === "") { '); Append(' $.alert({title:'''+FPromptType.TextRequiredField+''', content:'' '', useBootstrap: false, boxWidth: '''+FboxWidth+'''}); '); Append(' return false; '); Append('}'); end; if ScreenMask.Enabled then Append(' $(''body'').preloader({text: '''+ScreenMask.Text+'''}); '); if FPromptType.CharCase = TTypeCharCase.Normal_ then Append(' ajaxRequest('+Self.JSName+', "Prompt", ["Button="+"Yes","result="+this.$content.find(''.name'').val()]); ') else Append(' ajaxRequest('+Self.JSName+', "Prompt", ["Button="+"Yes","result="+this.$content.find(''.name'').val().to'+ GetStrTypeCharCase(FPromptType.CharCase)+'()]); '); Append(' } '); Append(' },'); Append(' cancel: { '); Append(' text: '''+FButtonTextCancel+''', '); Append(' action: function() {'); if ScreenMask.Enabled then Append(' $(''body'').preloader({text: '''+ScreenMask.Text+'''}); '); Append(' ajaxRequest('+Self.JSName+', "Prompt", ["Button="+"No"]); '); Append(' } '); Append(' }'); Append('},'); Append('onContentReady: function () { '); Append(' var jc = this; '); Append(' this.$content.find(''form'').on(''submit'', function (e) { '); Append(' e.preventDefault(); '); Append(' jc.$$formSubmit.trigger(''click''); '); Append(' }); '); Append('} '); end; if (TypeConfirm = TTypeConfirm.Alert) and (Assigned(FButtonCallBack)) then begin Append('buttons: {'); Append(' specialKey: { '); Append(' text: '''+Self.ButtonTextOK+''', '); if FButtonEnterConfirm then Append(' keys: ["enter"], '); Append(' action: function() {'); if ScreenMask.Enabled then Append(' $(''body'').preloader({text: '''+ScreenMask.Text+'''}); '); Append(' ajaxRequest('+Self.JSName+', "Alert", ["Button="+"Ok"]); '); Append(' } '); Append(' }'); Append('}'); end else if TypeConfirm = TTypeConfirm.Alert then begin Append('buttons: {'); Append(' specialKey: { '); Append(' text: '''+Self.ButtonTextOK+''', '); Append(' keys: ["enter"] '); Append(' }'); Append('}'); end; end; Result := StrBuilder.ToString; finally FreeAndNil(StrBuilder); end; end; procedure TUniFSConfirm.Clear; begin FTitle := EmptyStr; FContent := EmptyStr; FIcon := EmptyStr; FCloseIcon := False; end; constructor TUniFSConfirm.Create(AOwner: TComponent); begin inherited; FScreenMask := TUniFSScreenMask.Create; FPromptType := TUniFSPrompt.Create; FTheme := TTheme.modern; FButtonTextConfirm := 'Confirma'; FButtonTextCancel := 'Cancela'; FButtonTextOther := 'Outro'; FButtonTextOK := 'Ok'; FButtonEnterConfirm := True; FboxWidth := '420px'; FIcon := 'far fa-smile-wink'; end; destructor TUniFSConfirm.Destroy; begin inherited; FreeAndNil(FScreenMask); FreeAndNil(FPromptType); end; procedure TUniFSConfirm.DOHandleEvent(EventName: string; Params: TUniStrings); begin inherited; if EventName = 'Confirm' then begin if Assigned(FButtonCallBack) then begin if Params.Values['Button'] = 'Yes' then FButtonCallBack(TConfirmButton.Yes); if Params.Values['Button'] = 'No' then FButtonCallBack(TConfirmButton.No); if Params.Values['Button'] = 'Ok' then FButtonCallBack(TConfirmButton.Ok); if Params.Values['Button'] = 'Other' then FButtonCallBack(TConfirmButton.Other); end; end; if EventName = 'Prompt' then begin if Assigned(FPromptCallBack) then begin if Params.Values['Button'] = 'Yes' then FPromptCallBack(TConfirmButton.Yes, Params.Values['result']); if Params.Values['Button'] = 'No' then FPromptCallBack(TConfirmButton.No, EmptyStr); if Params.Values['Button'] = 'Ok' then FButtonCallBack(TConfirmButton.Ok); if Params.Values['Button'] = 'Other' then FButtonCallBack(TConfirmButton.Other); end; end; if EventName = 'Alert' then begin if Assigned(FButtonCallBack) then begin if Params.Values['Button'] = 'Ok' then FButtonCallBack(TConfirmButton.Ok); FButtonCallBack := nil; end; end; if (EventName <> EmptyStr) and (Params.Values['Button'] <> EmptyStr) then ExecJS('$(''body'').preloader(''remove'');'); end; procedure TUniFSConfirm.ExecJS(JS: string); begin UniSession.AddJS(JS); end; function TUniFSConfirm.GetAbout: string; begin Result := FSAbout; end; function TUniFSConfirm.GetStrTypePrompt(TypePrompt: TTypePrompt): string; begin Result := GetEnumName(TypeInfo(TTypePrompt), Integer(TypePrompt)); end; function TUniFSConfirm.GetStrTheme(Theme: TTheme): string; begin Result := GetEnumName(TypeInfo(TTheme), Integer(Theme)); end; function TUniFSConfirm.GetStrTypeCharCase(TypeCharCase: TTypeCharCase): string; begin Result := GetEnumName(TypeInfo(TTypeCharCase), Integer(TypeCharCase)); Result := StringReplace(Result, '_','',[rfReplaceAll]); end; function TUniFSConfirm.GetStrTypeColor(TypeColor: TTypeColor): string; begin Result := GetEnumName(TypeInfo(TTypeColor), Integer(TypeColor)); Result := StringReplace(Result, '_','',[rfReplaceAll]); end; function TUniFSConfirm.GetStrTypeConfirm(TypeConfirm: TTypeConfirm): string; begin Result := GetEnumName(TypeInfo(TTypeConfirm), Integer(TypeConfirm)); end; function TUniFSConfirm.GetVersion: string; begin Result := PackageVersion; end; procedure TUniFSConfirm.LoadCompleted; begin inherited; end; procedure TUniFSConfirm.Mask(const Msg: string; M: TMaskCallBack); begin Self.ExecJS('$(''body'').preloader({text: '''+Msg+'''});'); if Assigned(M) then RemoveMask; end; procedure TUniFSConfirm.Prompt(const Title, Msg, Icon: string; Color: TTypeColor; Theme: TTheme; PC: TPromptCallBack); begin FIcon := Icon; FTypeColor := Color; FTheme := Theme; Prompt(Title, Msg, PC); end; procedure TUniFSConfirm.Prompt(const Title, Msg: string; PC: TPromptCallBack); begin FPromptCallBack := PC; FTitle := Title; FMsgPrompt := Msg; FContent := EmptyStr; Self.ExecJS('$.confirm({'+BuildJS(TTypeConfirm.Prompt)+'});'); end; procedure TUniFSConfirm.RemoveInvalidChar(var InputText: string); begin InputText := StringReplace(InputText,#$D,'',[rfReplaceAll]); InputText := StringReplace(InputText,#$A,'',[rfReplaceAll]); InputText := StringReplace(InputText,#$D#$A,'',[rfReplaceAll]); InputText := StringReplace(InputText,#13,'',[rfReplaceAll]); InputText := StringReplace(InputText,#13#10,'',[rfReplaceAll]); InputText := StringReplace(InputText,'"','',[rfReplaceAll]); InputText := StringReplace(InputText,'''','',[rfReplaceAll]); end; procedure TUniFSConfirm.RemoveMask; begin ExecJS('$(''body'').preloader(''remove'');'); UniSession.Synchronize(); end; procedure TUniFSConfirm.ShowMask(Msg, JSName: string); begin Self.ExecJS('$('''+JSName+''').preloader({text: '''+Msg+'''});'); UniSession.Synchronize(); end; procedure TUniFSConfirm.ShowMask(Msg: string; Percent: Integer); begin Self.ExecJS('$(''body'').preloader({text: '''+Msg+''',percent:'''+IntToStr(Percent)+'''});'); UniSession.Synchronize(); end; procedure TUniFSConfirm.ShowMaskUpdate(Msg: string; Percent: Integer); begin Self.ExecJS('$(''body'').preloader(''update'',{text: '''+Msg+''',percent:'''+IntToStr(Percent)+'''});'); UniSession.Synchronize(); end; procedure TUniFSConfirm.ShowMask(Msg: string); begin Self.ExecJS('$(''body'').preloader({text: '''+Msg+'''});'); UniSession.Synchronize(); end; procedure TUniFSConfirm.Question(const Title, Content, Icon: string; BC: TButtonCallBack; const TP: TTypeConfirm); begin FIcon := Icon; Question(Title, Content, BC, TP); end; procedure TUniFSConfirm.Question(const Title, Content, Icon: string; Color: TTypeColor; Theme: TTheme; BC: TButtonCallBack; const TP: TTypeConfirm); begin FIcon := Icon; FTypeColor := Color; FTheme := Theme; Question(Title, Content, BC, TP); end; procedure TUniFSConfirm.Question(const Title, Content: string; BC: TButtonCallBack; const TP: TTypeConfirm); begin FButtonCallBack := BC; FTitle := Title; FContent := Content; Self.ExecJS('$.confirm({'+BuildJS(TP)+'});'); end; procedure TUniFSConfirm.WebCreate; begin inherited; JSComponent := TJSObject.JSCreate('Object'); end; { TUniFSScreenMask } constructor TUniFSScreenMask.Create; begin FText := 'Processing'; end; { TUniFSPrompt } constructor TUniFSPrompt.Create; begin FTextRequiredField := 'Field riquired'; FCharCase := TTypeCharCase.Normal_; end; initialization UniAddCSSLibrary(CDN+'falcon/css/jquery-confirm.min.css?v=3', CDNENABLED, [upoFolderUni, upoPlatformBoth]); UniAddCSSLibrary(CDN+'falcon/css/preloader.css?v=3', CDNENABLED, [upoFolderUni, upoPlatformBoth]); UniAddCSSLibrary(CDN+'falcon/css/jquery-confirm-style.css?v=8', CDNENABLED, [upoFolderUni, upoPlatformBoth]); UniAddJSLibrary(CDN+'falcon/js/jquery-confirm.min.js?v=3', CDNENABLED, [upoFolderUni, upoPlatformBoth]); UniAddJSLibrary(CDN+'falcon/js/jquery.preloader.js?v=1', CDNENABLED, [upoFolderUni, upoPlatformBoth]); end.
unit FilePropsUnit; // --------------------------------------- // Display / Edit WCP data file properties // --------------------------------------- // 25.07.06 // 14.05.10 No. records/channels and other data added, complete file header text displayed // 15.09.11 Displays now have scroll bars // 25.07.13 Updated to compile under both Delphi XE2/3 and 7 // 26.08.13 No. of sign. figure increased in scale factor table // 27.08.13 Recording start date now displayed // 20.09.15 Displays WinWCP program version which created file. // 03.06.20 Total record size, data block and analysis block size now dispkayed interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, maths, ComCtrls ; type TFilePropsDlg = class(TForm) bCancel: TButton; bOK: TButton; PageControl1: TPageControl; TabProperties: TTabSheet; TabCalTable: TTabSheet; TabFileHeader: TTabSheet; meProperties: TMemo; ChannelTable: TStringGrid; meFileHeader: TMemo; procedure FormShow(Sender: TObject); procedure bOKClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure bCancelClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FilePropsDlg: TFilePropsDlg; implementation uses MDIForm, WCPFIleUnit; const ChNum = 0 ; ChName = 1 ; ChCal = 2 ; ChUnits = 3 ; {$R *.dfm} procedure TFilePropsDlg.FormShow(Sender: TObject); // -------------------------------------- // Initialisations when form is displayed // -------------------------------------- var ch : Integer ; Header : TStringList ; pANSIBuf : PANSIChar ; ANSIHeader : ANSIString ; begin { Set channel calibration table } ChannelTable.cells[ChNum,0] := 'Ch.' ; ChannelTable.colwidths[ChNum] := ChannelTable.DefaultColWidth div 2 ; ChannelTable.cells[ChName,0] := 'Name' ; ChannelTable.colwidths[ChName] := ChannelTable.DefaultColWidth ; ChannelTable.cells[ChCal,0] := 'V/Units' ; ChannelTable.colwidths[ChCal] := (5*ChannelTable.DefaultColWidth) div 4 ; ChannelTable.cells[ChUnits,0] := 'Units' ; ChannelTable.colwidths[ChUnits] := ChannelTable.DefaultColWidth ; ChannelTable.RowCount := WCPFile.RawFH.NumChannels + 1; ChannelTable.options := [goEditing,goHorzLine,goVertLine] ; for ch := 0 to WCPFile.RawFH.NumChannels-1 do begin ChannelTable.cells[ChNum,ch+1] := IntToStr(ch) ; ChannelTable.cells[ChName,ch+1] := WCPFile.Channel[ch].ADCName ; ChannelTable.cells[ChCal,ch+1] := Format( '%.6g',[WCPFile.Channel[ch].ADCCalibrationFactor] ) ; ChannelTable.cells[ChUnits,ch+1] := WCPFile.Channel[ch].ADCUnits ; end ; // Display file properties meProperties.Lines.Clear ; meProperties.Lines.Add(format('File version: %.2f',[WCPFile.RawFH.Version])) ; meProperties.Lines.Add(format('WinWCP version: %s',[WCPFile.RawFH.ProgVersion])) ; meProperties.Lines.Add(format('Date Created: %s',[WCPFile.RawFH.CreationTime])) ; if WCPFile.RawFH.RecordingStartTimeSecs > 0.0 then meProperties.Lines.Add(format('Recording started at: %s',[WCPFile.RawFH.RecordingStartTime])) ; meProperties.Lines.Add(format('ID: %s',[WCPFile.RawFH.IdentLine])) ; meProperties.Lines.Add(format('No. of records: %d',[WCPFile.RawFH.NumRecords])) ; meProperties.Lines.Add(format('No. of channels: %d',[WCPFile.RawFH.NumChannels])) ; meProperties.Lines.Add(format('No. of samples/channels: %d',[WCPFile.RawFH.NumSamples])) ; meProperties.Lines.Add(format('File header size (bytes): %d',[WCPFile.RawFH.NumBytesInHeader])) ; meProperties.Lines.Add(format('Record size (bytes): %d', [WCPFile.RawFH.NumAnalysisBytesPerRecord+2*WCPFile.RawFH.NumChannels*WCPFile.RawFH.NumSamples])) ; meProperties.Lines.Add(format('Record analysis block size (bytes): %d',[WCPFile.RawFH.NumAnalysisBytesPerRecord])) ; meProperties.Lines.Add(format('Record data block size (bytes): %d',[2*WCPFile.RawFH.NumChannels*WCPFile.RawFH.NumSamples])) ; meProperties.Lines.Add(format('Sample value range: %d to %d',[-WCPFile.RawFH.MaxADCValue-1,WCPFile.RawFH.MaxADCValue])) ; // Display file header FileSeek( WCPFile.RawFH.FileHandle, 0, 0 ) ; pANSIBuf := AllocMem( WCPFile.RawFH.NumBytesInHeader ) ; FileRead(WCPFile.RawFH.FileHandle, pANSIBuf^, WCPFile.RawFH.NumBytesInHeader ) ; pANSIBuf[WCPFile.RawFH.NumBytesInHeader-1] := #0 ; ANSIHeader := ANSIString( pANSIBuf ) ; meFileHeader.Lines.Text := String(ANSIHeader) ; FreeMem( pANSIBuf ) ; end; procedure TFilePropsDlg.bOKClick(Sender: TObject); // ------------------------------- // Update changes to file settings // ------------------------------- var ch : Integer ; begin { Channel calibration } for ch := 0 to WCPFile.RawFH.NumChannels-1 do begin WCPFile.Channel[ch].ADCName := ChannelTable.cells[ChName,ch+1] ; WCPFile.Channel[ch].ADCCalibrationFactor := ExtractFloat( ChannelTable.cells[ChCal,ch+1], WCPFile.Channel[ch].ADCCalibrationFactor); WCPFile.Channel[ch].ADCUnits := ChannelTable.cells[ChUnits,ch+1] ; end ; // Save to file header WCPFile.SaveHeader( WCPFile.RawFH ) ; Main.NewFileUpdate ; Close ; end; procedure TFilePropsDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree ; end; procedure TFilePropsDlg.bCancelClick(Sender: TObject); begin Close ; end; end.
unit WinshoeGUIIntegrator; interface { NOTE - This unit must NOT appear in any Winshoes uses clauses. This is a ONE way relationship and is linked in IF the user uses this component. This is done to preserve the isolation from the massive FORMS unit. 13-JAN-2000 MTL: Moved to new Palette Scheme (Winshoes Servers) } uses Classes, Winshoes; type TWinshoeGUIIntegrator = class(TWinshoeGUIIntegratorBase) private protected fbApplicationHasPriority: boolean; public constructor Create(AOwner: TComponent); override; procedure Process; override; published property ApplicationHasPriority: Boolean read fbApplicationHasPriority write fbApplicationHasPriority; end; // Procs procedure Register; implementation uses Forms, SysUtils, Windows; procedure Register; begin RegisterComponents('Winshoes Misc', [TWinshoeGUIIntegrator]); end; constructor TWinshoeGUIIntegrator.Create(AOwner: TComponent); begin inherited; fbApplicationHasPriority := True; end; procedure TWinshoeGUIIntegrator.Process; {TODO - Much of this can be made slightly faster by moving certain checks into the Winshoe component itself} var Msg: TMsg; begin inherited; // Only process if calling client is in the main thread if GetCurrentThreadID <> MainThreadID then exit; if ApplicationHasPriority then begin Application.ProcessMessages; end else begin // This guarantees it won't ever call Application.Idle if PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE) then Application.HandleMessage; end; end; end.
unit ExcelTableTests; interface uses TestFrameWork, ExcelTable; type TExcelTableTests = class(TTestCase) private FExcelTable: TExcelTable; FFileName: string; protected procedure SetUp; override; procedure TearDown; override; published procedure TestReadingFile; end; implementation uses SysUtils, Variants; { TExcelTableTests } procedure TExcelTableTests.SetUp; begin inherited; FExcelTable := TExcelTable.Create; FExcelTable.FirstCol := 1; FExcelTable.FirstRow := 1; FFileName := ExtractFilePath(ParamStr(0)) + '\BaseTests\MadeBagan.xls'; end; procedure TExcelTableTests.TearDown; begin inherited; FreeAndNil(FExcelTable); end; procedure TExcelTableTests.TestReadingFile; var i, j: integer; begin // загрузился ли FExcelTable.LoadFromFile(FFileName); // количество столбцов и строк совпадает ли Check(FExcelTable.Columns.Count = FExcelTable.DataColCount, 'Количество прочитанных столбцов не равно количеству столбцов данных'); Check(FExcelTable.Rows.Count = FExcelTable.DataRowCount, 'Количество прочитанных строк не равно количеству строк данных'); //проверяем на месте ли значения with FExcelTable do begin for i := VarArrayLowBound(Data, 1) to VarArrayHighBound(Data, 1) do for j := VarArrayLowBound(Data, 2) to VarArrayHighBound(Data, 2) do Check(trim(varAsType(FExcelTable.Data[i, j], varOleStr)) = FExcelTable.Rows[i-1][j-1].AsString, Format('Неравенство значений (%d, %d)', [i, j])); end; end; initialization RegisterTest('BaseTests\BaseTable\TExcelTableTests', TExcelTableTests.Suite); end.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) 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., 675 Mass Ave, Cambridge, MA 02139, USA. ***************************************************************** The following delphi code is based on Emule (0.46.2.26) Kad's implementation http://emule.sourceforge.net and KadC library http://kadc.sourceforge.net/ ***************************************************************** } { Description: DHT special 128 bit integer functions } unit int128; interface uses sysutils,windows,synsock; type CU_INT128=array[0..3] of cardinal; pCU_INT128=^CU_INT128; pbytearray=^tbytearray; tbytearray=array[0..1023] of byte; procedure CU_INT128_xor(inValue:pCu_INT128; value:pCu_INT128); function CU_INT128_tohexstr(value:pCu_INT128; reversed:boolean = true ):string; procedure CU_INT128_fill(inValue:pCu_INT128; value:pCu_INT128); overload; procedure CU_Int128_fill(m_data:pCU_INT128; value:pCU_INT128; numBits:cardinal); overload; function CU_INT128_Compare(Value1:pCu_INT128; value2:pCu_INT128):boolean; function CU_INT128_compareTo(m_data:pCU_INT128; value:cardinal):integer; overload; function CU_Int128_compareTo(m_data:pCU_Int128; other:pCU_INT128):integer; overload; function CU_INT128_getBitNumber(m_data:pCU_INT128; bit:cardinal):cardinal; procedure CU_Int128_setBitNumber(m_data:pCU_INT128; bit:cardinal; value:cardinal); procedure CU_Int128_shiftLeft(m_data:pCU_INT128; bits:cardinal); procedure CU_Int128_setValue(m_data:pCU_INT128; value:cardinal); procedure CU_Int128_add(m_data:pCU_INT128; value:pCU_Int128); overload; procedure CU_Int128_add(m_data:pCU_INT128; value:cardinal); overload; function CU_INT128_MinorOf(m_data:pCU_INT128; value:cardinal):boolean; overload; function CU_INT128_MinorOf(m_data:pCU_INT128; value:pCU_INT128):boolean; overload; function CU_INT128_Majorof(m_data:pCU_INT128; value:pCU_INT128):boolean; procedure CU_Int128_toBinaryString(m_data:pCU_INT128; var str:string; trim:boolean=false); procedure CU_Int128_setValueBE(m_data:pCU_INT128; valueBE:pbytearray); procedure CU_INT128_fillNXor(Destination:pCU_INT128; initialValue:pCU_INT128; xorvalue:pCU_INT128); procedure CU_INT128_copytoBuffer(source:pCU_INT128; destination:pbytearray); procedure CU_INT128_copyFromBuffer(source:pbytearray; destination:pCU_INT128); var m_data:CU_INT128; implementation uses helper_strings; procedure CU_INT128_copyFromBuffer(source:pbytearray; destination:pCU_INT128); begin move(source[0],destination[0],4); move(source[4],destination[1],4); move(source[8],destination[2],4); move(source[12],destination[3],4); end; procedure CU_INT128_copytoBuffer(source:pCU_INT128; destination:pbytearray); begin move(source[0],destination[0],4); move(source[1],destination[4],4); move(source[2],destination[8],4); move(source[3],destination[12],4); end; procedure CU_INT128_fillNXor(Destination:pCU_INT128; initialValue:pCU_INT128; xorvalue:pCU_INT128); begin destination[0]:=initialValue[0] xor xorvalue[0]; destination[1]:=initialValue[1] xor xorvalue[1]; destination[2]:=initialValue[2] xor xorvalue[2]; destination[3]:=initialValue[3] xor xorvalue[3]; end; procedure CU_Int128_setValue(m_data:pCU_INT128; value:cardinal); begin m_data[0]:=0; m_data[1]:=0; m_data[2]:=0; m_data[3]:=value; end; procedure CU_Int128_setValueBE(m_data:pCU_INT128; valueBE:pbytearray); var i:integer; begin m_data[0]:=0; m_data[1]:=0; m_data[2]:=0; m_data[3]:=0; for i:=0 to 15 do m_data[i div 4]:=m_data[i div 4] or (cardinal(valueBE[i]) shl (8*(3-(i mod 4)))); end; procedure CU_Int128_shiftLeft(m_data:pCU_INT128; bits:cardinal); var temp:CU_INT128; indexShift,i:integer; bit64Value,shifted:int64; begin if ((bits=0) or ( ((m_data[0]=0) and (m_data[1]=0) and (m_data[2]=0) and (m_data[3]=0)) ) ) then exit; if bits>127 then begin CU_Int128_setValue(m_data,0); exit; end; temp[0]:=0; temp[1]:=0; temp[2]:=0; temp[3]:=0; indexShift:=integer(bits) div 32; shifted:=0; i:=3; while (i>=indexShift) do begin bit64Value:=int64(m_data[i]); shifted:=shifted+(bit64Value shl int64(bits mod 32)); temp[i-indexShift]:=cardinal(shifted); shifted:=shifted shr 32; dec(i); end; for i:=0 to 3 do m_data[i]:=temp[i]; end; procedure CU_Int128_add(m_data:pCU_INT128; value:pCU_Int128); var sum:int64; i:integer; begin if CU_INT128_compareTo(value,0)=0 then exit; sum:=0; for i:=3 downto 0 do begin sum:=sum+m_data[i]; sum:=sum+value[i]; m_data[i]:=cardinal(sum); sum:=sum shr 32; end; end; procedure CU_Int128_add(m_data:pCU_INT128; value:cardinal); var temp:CU_INT128; begin if value=0 then exit; CU_Int128_SetValue(@temp,value); CU_Int128_add(m_data,@temp); end; function CU_INT128_getBitNumber(m_data:pCU_INT128; bit:cardinal):cardinal; var uLongNum,shift:integer; begin result:=0; if (bit>127) then exit; ulongNum:=bit div 32; shift:=31-(bit mod 32); result:= ((m_data[ulongNum] shr shift) and 1); end; procedure CU_Int128_setBitNumber(m_data:pCU_INT128; bit:cardinal; value:cardinal); var ulongNum,shift:integer; begin ulongNum:=bit div 32; shift:=31-(bit mod 32); m_data[ulongNum]:=m_data[ulongNum] or (1 shl shift); if value=0 then m_data[ulongNum]:=m_data[ulongNum] xor (1 shl shift); end; function CU_INT128_compareTo(m_data:pCU_INT128; value:cardinal):integer; begin if ((m_data[0]>0) or (m_data[1]>0) or (m_data[2]>0) or (m_data[3]>value)) then begin result:=1; exit; end; if m_data[3]<value then begin result:=-1; exit; end; result:=0; end; function CU_INT128_Compare(Value1:pCu_INT128; value2:pCu_INT128):boolean; begin result:=((Value1[0]=Value2[0]) and (Value1[1]=Value2[1]) and (Value1[2]=Value2[2]) and (Value1[3]=Value2[3])); end; procedure CU_INT128_xor(inValue:pCu_INT128; value:pCu_INT128); begin inValue[0]:=inValue[0] xor value[1]; inValue[1]:=inValue[1] xor value[1]; inValue[2]:=inValue[2] xor value[2]; inValue[3]:=inValue[3] xor value[3]; end; procedure CU_INT128_fill(inValue:pCu_INT128; value:pCu_INT128); begin inValue[0]:=value[0]; inValue[1]:=value[1]; inValue[2]:=value[2]; inValue[3]:=value[3]; end; procedure CU_Int128_fill(m_data:pCU_INT128; value:pCU_INT128; numBits:cardinal); var i:integer; numULONGs:cardinal; begin // Copy the whole ULONGs numULONGs:=numBits div 32; for i:=0 to numULONGs-1 do begin m_data[i]:=value[i]; end; // Copy the remaining bits for i:=(32*numULONGs) to numBits-1 do CU_INT128_setBitNumber(m_data,i, CU_INT128_getBitNumber(value,i)); // Pad with random bytes (Not seeding based on time to allow multiple different ones to be created in quick succession) for i:=numBits to 127 do CU_INT128_setBitNumber(m_data,i, (random(2))); end; procedure CU_Int128_toBinaryString(m_data:pCU_INT128; var str:string; trim:boolean=false); var b,i:integer; begin str:=''; for i:=0 to 127 do begin b:=CU_Int128_getBitNumber(m_data,i); if ((not trim) or (b<>0)) then begin str:=str+Format('%d',[b]); trim:=false; end; end; if length(str)=0 then str:='0'; end; function CU_INT128_tohexstr(value:pCu_INT128; reversed:boolean = true):string; var num:cardinal; begin setLength(result,16); if reversed then begin num:=synsock.ntohl(value[0]); move(num,result[1],4); num:=synsock.ntohl(value[1]); move(num,result[5],4); num:=synsock.ntohl(value[2]); move(num,result[9],4); num:=synsock.ntohl(value[3]); move(num,result[13],4); end else begin move(value[0],result[1],4); move(value[1],result[5],4); move(value[2],result[9],4); move(value[3],result[13],4); end; result:=bytestr_to_hexstr(result); end; function CU_INT128_MinorOf(m_data:pCU_INT128; value:cardinal):boolean; begin result:=(CU_INT128_compareTo(m_data,value)<0); end; function CU_INT128_MinorOf(m_data:pCU_INT128; value:pCU_INT128):boolean; overload; begin result:=(CU_INT128_compareTo(m_data,value)<0); end; function CU_INT128_Majorof(m_data:pCU_INT128; value:pCU_INT128):boolean; overload; begin result:=(CU_INT128_compareTo(m_data,value)>0); end; function CU_Int128_compareTo(m_data:pCU_Int128; other:pCU_INT128):integer; var i:integer; begin result:=0; for i:=0 to 3 do begin if m_data[i]<other[i] then begin result:=-1; exit; end; if m_data[i]>other[i] then begin result:=1; exit; end; end; end; end.
unit edMain; interface uses Windows, Messages, SysUtils, Classes, MMSystem, D3DX8, {$IFDEF DXG_COMPAT}DirectXGraphics{$ELSE}Direct3D8{$ENDIF}, glWindow, glApplication, glGraphics, glCanvas, glError, glConst, glUtil, glSound, glDialogs, glSprite, glControls, edPanels; type THeader = record Version: Integer; Description: string[255]; Width, Height: Integer; end; TTile = record Index: Integer; Collide: Boolean; end; TWindow1 = class(TWindow) private FileWork: string; MapHeader: THeader; SpriteEngine: TSpriteEngine; PanelSprite: TPanelSprite; PanelTile: TPanelTile; public procedure LoadFromFile(const FileName: string); procedure SaveToFile(const FileName: string); procedure New; procedure DoInitialize; override; procedure DoCreate; override; procedure DoMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure DoCommand(ID: Integer); override; procedure DoFrame(Sender: TObject; TimeDelta: Single); procedure DoIdleFrame(Sender: TObject; TimeDelta: Single); procedure CreateSprite(XPos, YPos: Integer; Index: Integer); procedure CreateTileAnim(XPos, YPos: Integer; Index: Integer); end; TGraphics1 = class(TGraphics) private procedure DoInitialize; override; public { Public declarations } end; TBackground = class(TBackgroundSprite) protected end; TActor = class(TImageSprite) private PosX: Integer; PosY: Integer; protected procedure DoMove(MoveCount: Integer); override; end; var Window1: TWindow1; Graphics1: TGraphics1; Background: TBackground; const PATH_IMG = 'Media\Img\'; PATH_SOUND = 'Media\Sound\'; Path_MUSIC = 'Media\Music\'; implementation procedure TWindow1.LoadFromFile(const FileName: string); var FileHeader: file of THeader; FileTile: file of TTile; Tile: TTile; Header: THeader; I, J: Integer; begin if Length(FileName) = 0 then Exit; FileWork := FileName; AssignFile(FileHeader, FileName); {$I-} Reset(FileHeader); {$I+} if IORESULT <> 0 then begin CloseFile(FileHeader); Exit; end; Read(FileHeader, Header); CloseFile(FileHeader); MapHeader := Header; Background.SetMapSize(MapHeader.Width, MapHeader.Height); AssignFile(FileTile, FileName); {$I-} Reset(FileTile); {$I+} if IORESULT <> 0 then begin CloseFile(FileTile); Exit; end; Seek(FileTile, SizeOf(FileHeader)); try for I := 0 to Background.MapWidth - 1 do for J := 0 to Background.MapHeight - 1 do begin Read(FileTile, Tile); Background.Chips[I, J] := Tile.Index; Background.CollisionMap[I, J] := Tile.Collide; end; finally CloseFile(FileTile); end; Caption := Format('%s - XBomber', [ExtractFileName(FileWork)]); end; procedure TWindow1.SaveToFile(const FileName: string); var FileHeader: file of THeader; FileTile: file of TTile; Tile: TTile; Header: THeader; I, J: Integer; begin if Length(FileName) = 0 then Exit; FileWork := FileName; AssignFile(FileHeader, FileName); if FileExists(FileName) then Reset(FileHeader) else Rewrite(FileHeader); Header := MapHeader; write(FileHeader, Header); CloseFile(FileHeader); AssignFile(FileTile, FileName); if FileExists(FileName) then Reset(FileTile) else Rewrite(FileTile); Seek(FileTile, SizeOf(FileHeader)); try for I := 0 to Background.MapWidth - 1 do for J := 0 to Background.MapHeight - 1 do begin Tile.Index := Background.Chips[I, J]; Tile.Collide := Background.CollisionMap[I, J]; Write(FileTile, Tile); end; finally CloseFile(FileTile); end; Caption := Format('%s - XBomber', [ExtractFileName(FileWork)]); end; procedure TWindow1.New; var I, J: Integer; begin for I := 0 to Background.MapHeight - 1 do for J := 0 to Background.MapWidth - 1 do begin Background.Chips[J, I] := 0; Background.CollisionMap[J, I] := False; end; end; procedure TWindow1.DoFrame(Sender: TObject; TimeDelta: Single); var I, J: Integer; Pos: TPoint; begin if Window1.Key[VK_F2] then Application.Pause; if Window1.Key[VK_ESCAPE] then Application.Terminate; SpriteEngine.Move(1000 div 60); SpriteEngine.Dead; Graphics1.Clear; Graphics1.BeginScene; Canvas.SpriteBegin; Canvas.Draw(192, 128, Pictures.Item[2], 0); SpriteEngine.Draw; GetCursorPos(Pos); case IndexPage of 0: Canvas.Draw(Pos.X- Window.Left, Pos.Y- Window.Top, Pictures.Item[0], PanelTile.Index); 1: Canvas.Draw(Pos.X- Window.Left, Pos.Y- Window.Top, Pictures.Item[1], PanelSprite.Index * 10); end; PanelSprite.Draw; PanelTile.Draw; Canvas.SpriteEnd; Graphics1.EndScene; Graphics1.Flip; end; procedure TWindow1.DoIdleFrame(Sender: TObject; TimeDelta: Single); begin if Window1.Key[VK_F3] then Application.UnPause; if Window1.Key[VK_ESCAPE] then Application.Terminate; Graphics1.Clear; Graphics1.BeginScene; Graphics1.EndScene; Graphics1.Flip; end; procedure TWindow1.DoInitialize; begin Application.OnDoFrame := DoFrame; Application.OnDoIdleFrame := DoIdleFrame; end; procedure TWindow1.DoCreate; begin BorderStyle := bsSingle; MenuName := 1; Left := 0; Top := 0; Width := 640; Height := 480; ClientRect := Bounds(0, 0, Width, Height); Caption := 'Mapa - XBomber'; MapHeader.Version := 1; MapHeader.Description := 'XBomber'; MapHeader.Width := 13; MapHeader.Height := 11; Position := poCenter; end; procedure TWindow1.DoMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if MapFocus then case IndexPage of 0: begin //Background.Chips[(X div 16) - (Round(Background.X) div 16), (Y div 16) - (Round(Background.Y) div 16)] := PanelTile.Index; if PanelTile.Index > 0 then begin Background.CollisionMap[(X div 16) - (Round(Background.X) div 16), (Y div 16) - (Round(Background.Y) div 16)] := True; if PanelTile.Index = 2 then CreateTileAnim(192+24+((X div 16) - (Round(Background.X) div 16)) * 16, 128+35+((Y div 16) - (Round(Background.Y) div 16)) * 16, 0); end else Background.CollisionMap[(X div 16) - (Round(Background.X) div 16), (Y div 16) - (Round(Background.Y) div 16)] := False; end; 1: CreateSprite(((X div 16) - (Round(Background.X) div 16)) * 16, ((Y div 16) - (Round(Background.Y) div 16)) * 16, PanelSprite.Index); end; MapFocus := True; end; procedure TWindow1.DoCommand(ID: Integer); begin case ID of 1000: begin if Length(FileWork) = 0 then begin if MessageBox(Handle, PChar(Format(MSG_BOXSAVE, ['Mapa.map'])), MSG_CONFIRM, MB_YESNOCANCEL + MB_ICONEXCLAMATION) = IDYES then begin SaveToFile(SaveFile(0)); if Length(FileWork) > 0 then New; end else New; end else New; end; 1001: LoadFromFile(OpenFile(0)); 1002: begin if Length(FileWork) = 0 then SaveToFile(SaveFile(0)) else SaveToFile(FileWork); end; 1003: SaveToFile(SaveFile(0)); 1005: MessageBox(0, 'Em implementação', 'Em implementação', MB_OK); 1006: Application.Terminate; end; end; procedure TWindow1.CreateSprite(XPos, YPos: Integer; Index: Integer); begin with TActor.Create(SpriteEngine) do begin Image := Pictures.Find('Bomberman'); X := XPos; Y := YPos; PosX := XPos; PosY := YPos; Z := 3; Width := Image.Width; Height := Image.Height; AnimStart := Index * 10; AnimCount := 10; AnimLooped := True; AnimSpeed := 15 / 1000; AnimPos := Random(9); // Angle := 0.0; Shadow := False; Center := D3DXVector2(32, 32); Shadow := False; end; end; procedure TWindow1.CreateTileAnim(XPos, YPos: Integer; Index: Integer); begin with TImageSprite.Create(SpriteEngine) do begin Image := Pictures.Find('Tile'); X := XPos; Y := YPos; Z := 3; Width := Image.Width; Height := Image.Height; AnimStart := 2; AnimCount := 4; AnimLooped := True; AnimSpeed := 15 / 1000; AnimPos := 2; Angle := 0.0; Shadow := False; Center := D3DXVector2(32, 32); Shadow := False; end; end; procedure TGraphics1.DoInitialize; var I, J: Integer; begin Randomize; Window1.SpriteEngine := TSpriteEngine.Create(nil); Window1.SpriteEngine.SurfaceRect := Bounds(0, 0, Window1.Width, Window1.Height); Pictures := TPictures.Create(TPicture); with Pictures.Add do begin Name := 'Tile'; PatternWidth := 16; PatternHeight := 16; SkipWidth := 0; SkipHeight := 0; TransparentColor := clFuchsia; FileName := PATH_IMG + 'Tile.bmp'; end; with Pictures.Add do begin Name := 'Bomberman'; PatternWidth := 17; PatternHeight := 24; SkipWidth := 0; SkipHeight := 0; TransparentColor := clBlack; FileName := PATH_IMG + 'Bomberman.bmp'; end; with Pictures.Add do begin Name := 'Background'; PatternWidth := 256; PatternHeight := 224; SkipWidth := 0; SkipHeight := 0; TransparentColor := clFuchsia; FileName := PATH_IMG + 'Background.bmp'; end; Background := TBackground.Create(Window1.SpriteEngine); with Background do begin Image := Pictures.Find('Tile'); SetMapSize(Window1.MapHeader.Width, Window1.MapHeader.Height); X := 192 + 24; Y := 128 + 35; Z := -1; Width := Image.Width; Height := Image.Height; Tile := False; for I := 0 to MapWidth - 1 do for J := 0 to MapHeight - 1 do begin Chips[I, J] := 0; CollisionMap[I, J] := False; end; end; Window1.PanelSprite := TPanelSprite.Create; with Window1.PanelSprite do begin Initialize; Left := 10; Top := 10; Width := 2 * 17; Height := 24 + 16; end; Window1.PanelTile := TPanelTile.Create; with Window1.PanelTile do begin Initialize; Left := 10; Top := 80; Width := 5 * 16; Height := (1 * 16) + 16; end; Canvas.Brush.Color := D3DCOLOR_ARGB(255, 100, 100, 255); Canvas.Font.Color := clWhite; end; procedure TActor.DoMove(MoveCount: Integer); begin inherited DoMove(MoveCount); X := Background.X + PosX; Y := Background.Y + PosY; end; end.
{ Demo of JsonDataObjects library used by xEdit Check source code for available API calls https://github.com/ahausladen/JsonDataObjects } unit JsonDemo; procedure Demo1; var Obj: TJsonObject; begin Obj := TJsonBaseObject.Parse('{ "foo": "bar", "array": [ 10, 20 ] }'); try AddMessage(Obj.S['foo']); AddMessage(IntToStr(Obj.A['array'].Count)); AddMessage(IntToStr(Obj.A['array'].I[0])); AddMessage(IntToStr(Obj.A['array'].I[1])); //procedure LoadFromFile(const FileName: string; Utf8WithoutBOM: Boolean = True); //procedure SaveToFile(const FileName: string; Compact: Boolean = True; Encoding: TEncoding = nil; Utf8WithoutBOM: Boolean = True); //Obj.SaveToFile('c:\Demo1.json', False, TEncoding.UTF8, True); finally Obj.Free; end; end; procedure Demo2; var Obj, ChildObj: TJsonObject; begin Obj := TJsonObject.Create; try // easy access Obj['foo'] := 'bar'; // normal (and faster) access Obj.S['bar'] := 'foo'; // automatic array creation, Obj is the owner of 'array' Obj.A['array'].Add(10); Obj.A['array'].Add(20); // automatic object creation, 'array' is the owner of ChildObj ChildObj := Obj.A['array'].AddObject; ChildObj['value'] := 12.3; // automatic array creation, ChildObj is the owner of 'subarray' ChildObj.A['subarray'].Add(100); ChildObj.A['subarray'].Add(200); AddMessage(Obj.ToJSON({Compact:=}False)); finally Obj.Free; end; end; procedure Demo3; var Obj, ClonedObj: TJsonObject; begin Obj := TJsonObject.Parse('{ "foo": [ "bar", {}, null, true, false, { "key": "value" } ] }'); try ClonedObj := TJsonObject.Create; try // Make a copy of Obj ClonedObj.Assign(Obj); AddMessage(ClonedObj.ToJSON(False)); finally ClonedObj.Free; end; finally Obj.Free; end; end; procedure DemoFO4; var Obj: TJsonObject; begin if wbGameMode <> gmFO4 then begin AddMessage('Demo is available in FO4Edit only.'); Exit; end; // loading from BSA/BA2 Obj := TJsonObject.Create; try Obj.LoadFromResource('meshes\clothes\wastelander\glovesf.ssf'); AddMessage(Obj.ToJSON({Compact:=}False)); finally Obj.Free; end; end; function Initialize: Integer; begin SetJDOLineBreak(#13#10); // default #10 //SetJDOIndentChar(#9); // default #9 //SetJDOUseUtcTime(True); // default True //SetJDONullConvertsToValueTypes(False); // default False AddMessage('---------- Demo1 ----------'); Demo1; AddMessage('---------- Demo2 ----------'); Demo2; AddMessage('---------- Demo3 ----------'); Demo3; AddMessage('---------- Demo FO4 ----------'); DemoFO4; Result := 1; end; end.
unit Board; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls, BoardRepresentation; type TBoard = class(TImage) const MAX_SIZE = 1599; DOT_COLOR = $000C600C; private { Private declarations } rects: array [0..MAX_SIZE] of TRect; procedure drawRects(x, y: integer); //rozmiary planszy procedure drawGround(x, y: integer); //rozmiary planszy procedure drawLines(x, y: integer); //rysowanie granic boiska procedure drawBall(x, y: integer; col: TColor); //x, y względem boiska procedure drawBall(x, y: integer); //x, y względem boiska procedure drawRect(x, y: integer); //x, y względem boiska //x ,y względem boiska, ruch pilki do punktu x, y procedure drawLine(x, y: integer; col: TColor);//x ,y względem boiska procedure drawLine(fromx, fromy, tox, toy: integer; col: TColor); procedure test(); procedure drawTBoardPoint(var pt: TBoardPoint; x, y: integer); const RECT_SIZE = 38; BALL_RADIUS = 3; protected { Protected declarations } public { Public declarations } lastBallPosX: integer; lastBallPosY: integer; sizeX: integer; sizeY: integer; myBoardRep: TBoardRep; constructor Create(AOwner: TComponent); override; procedure setSize(x, y: integer); procedure makeMove(x, y, playerNo: integer); //x ,y - wspolrzedne punktu docelowego procedure drawFromBR(var rep: TBoardRep); function giveClickedPoint(): TPoint; //daje współrzędne punktu procedure drawUndo(move: TSegment); procedure drawRedo(move: TSegment); published { Published declarations } end; procedure Register; implementation constructor TBoard.Create(AOwner: TComponent); begin inherited Create(AOwner); self.Top := 0; end; procedure Register; begin RegisterComponents('Additional', [TBoard]); end; procedure TBoard.setSize(x, y: integer); begin sizeX := x; sizeY := y; self.drawGround(x, y); self.drawRects(x, y); self.drawLines(x, y); self.lastBallPosX := x div 2; self.lastBallPosY := y div 2; self.drawBall(x div 2, y div 2); end; procedure TBoard.drawGround(x, y: integer); begin self.Height := (x + 2) * RECT_SIZE; self.Width := (y + 4) * RECT_SIZE; self.SetBounds(0, 0, (x + 2) * RECT_SIZE, (y + 4) * RECT_SIZE); self.Paint; self.Update; self.Canvas.Pen.Color := clGreen; self.Canvas.Rectangle(self.BoundsRect); self.Canvas.Brush.Color := clGreen; self.Canvas.FillRect(self.BoundsRect); end; procedure TBoard.drawRects(x, y: integer); var counterX, counterY, counter: integer; begin counterX := 0; counterY := 0; counter := 0; self.Canvas.Brush.Color := $000C600C; for counterX := -1 to x + 1 do begin for counterY := -2 to y + 2 do begin //rects[counter] := Rect(counterX * (RECT_SIZE) + 1, counterY * // (RECT_SIZE) + 1, (counterX + 1) * (RECT_SIZE) - 1, (counterY + 1) * // (RECT_SIZE) - 1); // //self.Canvas.FillRect(rects[counter]); //counter := counter + 1; self.drawBall(counterX, counterY, DOT_COLOR); end; end; end; procedure TBoard.drawLines(x, y: integer); begin self.Canvas.Pen.Color := clWhite; self.Canvas.Pen.Width := 3; //bok lewy self.Canvas.Line(RECT_SIZE, 2 * RECT_SIZE, RECT_SIZE, (y + 2) * RECT_SIZE); //bok prawy self.Canvas.Line(RECT_SIZE * (x + 1), 2 * RECT_SIZE, RECT_SIZE * (x + 1), (y + 2) * RECT_SIZE); //górne krawędzie self.Canvas.Line(RECT_SIZE, 2 * RECT_SIZE, RECT_SIZE * (x div 2), 2 * RECT_SIZE); self.Canvas.Line(RECT_SIZE * (x div 2 + 2), 2 * RECT_SIZE, RECT_SIZE * (x + 1), 2 * RECT_SIZE); //górna bramka self.Canvas.Line(RECT_SIZE * (x div 2), RECT_SIZE, RECT_SIZE * (x div 2 + 2), RECT_SIZE); self.Canvas.Line(RECT_SIZE * (x div 2), RECT_SIZE, RECT_SIZE * (x div 2), RECT_SIZE * 2); self.Canvas.Line(RECT_SIZE * (x div 2 + 2), RECT_SIZE, RECT_SIZE * (x div 2 + 2), RECT_SIZE * 2); //dolne krawędzie self.Canvas.Line(RECT_SIZE, (y + 2) * RECT_SIZE, RECT_SIZE * (x div 2), (y + 2) * RECT_SIZE); self.Canvas.Line(RECT_SIZE * (x div 2 + 2), (y + 2) * RECT_SIZE, RECT_SIZE * (x + 1), (y + 2) * RECT_SIZE); //dolna bramka self.Canvas.Line(RECT_SIZE * (x div 2), RECT_SIZE * (y + 3), RECT_SIZE * (x div 2 + 2), RECT_SIZE * (y + 3)); self.Canvas.Line(RECT_SIZE * (x div 2), RECT_SIZE * (y + 2), RECT_SIZE * (x div 2), RECT_SIZE * (y + 3)); self.Canvas.Line(RECT_SIZE * (x div 2 + 2), RECT_SIZE * (y + 2), RECT_SIZE * (x div 2 + 2), RECT_SIZE * (y + 3)); self.Canvas.Pen.Width := 2; end; procedure TBoard.drawBall(x, y: integer; col: TColor); begin self.Canvas.Brush.Color := col; self.Canvas.Pen.Color := col; self.Canvas.Ellipse((x + 1) * RECT_SIZE - BALL_RADIUS, (y + 2) * RECT_SIZE - BALL_RADIUS, (x + 1) * RECT_SIZE + BALL_RADIUS, (y + 2) * RECT_SIZE + BALL_RADIUS); self.Canvas.FloodFill((x + 1) * RECT_SIZE, (y + 2) * RECT_SIZE, color, fsBorder); end; procedure TBoard.drawBall(x, y: integer); begin self.drawBall(lastBallPosX, lastBallPosY, clGreen); self.drawRect(x - 1, y - 1); self.drawBall(x, y, clWhite); lastBallPosX := x; lastBallPosY := y; end; procedure TBoard.drawRect(x, y: integer); begin self.Canvas.Brush.Color := $000C600C; self.Canvas.FillRect(rects[sizeY + 4 * x + 2 + y]); end; procedure TBoard.makeMove(x, y, playerNo: integer); var col: TColor; begin if playerNo = 1 then begin col := clYellow; end else begin col := clRed; end; self.Canvas.Pen.Color := col; self.drawLine(x, y, col); self.drawBall(lastBallPosX, lastBallPosY, DOT_COLOR); //self.drawBall(lastBallPosX, lastBallPosY, col); self.drawBall(x, y, clWhite); self.myBoardRep.addMove(lastBallPosX, lastBallPosY, x, y, playerNo); lastBallPosX := x; lastBallPosY := y; end; procedure TBoard.drawLine(x, y: integer; col: TColor); begin self.Canvas.Pen.Color:=col; self.Canvas.Line((lastBallPosX + 1) * RECT_SIZE, (lastBallPosY + 2) * RECT_SIZE, (x + 1) * RECT_SIZE, (y + 2) * RECT_SIZE); end; procedure TBoard.test; begin end; procedure TBoard.drawLine(fromx, fromy, tox, toy: integer; col: TColor); begin self.Canvas.Pen.Color := col; self.Canvas.Line((fromx + 1) * RECT_SIZE, (fromy + 2) * RECT_SIZE, (tox + 1) * RECT_SIZE, (toy + 2) * RECT_SIZE); end; procedure TBoard.drawFromBR(var rep: TBoardRep); var counterx, countery: integer; begin self.setSize(rep.sizeX, rep.sizeY); for counterx := 1 to rep.sizeX - 1 do begin for countery := 1 to rep.sizeY - 1 do begin self.drawTBoardPoint(rep.points[counterx, countery], counterx, countery); end; end; self.lastBallPosX := rep.ballPosX; self.lastBallPosY := rep.ballPosY; self.drawBall(rep.ballPosX, rep.ballPosY, clWhite); self.myBoardRep := rep; end; procedure TBoard.drawTBoardPoint(var pt: TBoardPoint; x, y: integer); var counter, tempVar: integer; tempMove: TPoint; moves: TPossibleMoves; begin tempVar := pt.pt; moves := TPossibleMoves.Create(); for counter := 0 to 7 do begin tempMove := moves.Next(); if (tempVar and 1) = 1 then begin if ((tempVar shr 1) and 1) = 1 then begin self.drawLine(x, y, x - tempMove.X, y + tempMove.Y, clYellow); end else begin self.drawLine(x, y, x - tempMove.X, y + tempMove.Y, clRed); end; self.drawBall(x - tempMove.X, y + tempMove.Y, DOT_COLOR); end; tempVar := tempVar shr 2; end; end; function TBoard.giveClickedPoint(): TPoint; // (-1, -1) jeżeli żaden nie jest var res, clicked: TPoint; begin clicked := self.ScreenToClient(mouse.CursorPos); if ((clicked.X + self.BALL_RADIUS) mod self.RECT_SIZE > self.BALL_RADIUS * 3) or ((clicked.Y + self.BALL_RADIUS) mod self.RECT_SIZE > self.BALL_RADIUS * 3) then begin res.X := -1; res.Y := -1; end else begin res.X := (clicked.X + self.BALL_RADIUS * 2) div self.RECT_SIZE - 1; res.Y := (clicked.Y + self.BALL_RADIUS * 2) div self.RECT_SIZE - 2; end; if (res.X < 0) or (res.X > self.sizeX) or (res.Y > self.sizeY) or (res.Y < 0) then begin if not (((res.Y = self.sizeY + 1) or (res.Y = -1)) and (abs(self.sizeX div 2 - res.X) <= 1)) then begin res.X := -1; res.Y := -1; end; end; giveClickedPoint := res; end; procedure TBoard.drawUndo(move: TSegment); var counter: integer; temp: ^TSegment; begin self.myBoardRep.removeMove(move.fromx, move.fromy, move.tox, move.toy); self.lastBallPosY:=move.fromy; self.lastBallPosX:=move.fromx; self.drawLine(move.fromx, move.fromy, move.tox, move.toy, clGreen); self.drawBall(move.tox, move.toy, DOT_COLOR); self.drawBall(move.fromx, move.fromy, clWhite); self.drawTBoardPoint(self.myBoardRep.points[move.fromx, move.fromy - 1], move.fromx, move.fromy - 1); self.drawTBoardPoint(self.myBoardRep.points[move.fromx, move.fromy + 1], move.fromx, move.fromy + 1); self.drawTBoardPoint(self.myBoardRep.points[move.fromx + 1, move.fromy], move.fromx + 1, move.fromy); self.drawTBoardPoint(self.myBoardRep.points[move.fromx - 1, move.fromy], move.fromx - 1, move.fromy); self.drawBall(move.fromx, move.fromy + 1, DOT_COLOR); self.drawBall(move.fromx, move.fromy - 1, DOT_COLOR); self.drawBall(move.fromx - 1, move.fromy, DOT_COLOR); self.drawBall(move.fromx + 1, move.fromy, DOT_COLOR); end; procedure TBoard.drawRedo(move: TSegment); begin self.makeMove(move.tox, move.toy, move.byWho); end; end.
{ Disable PreVis in selected exterior worldspaces/cells. Supports Fallout 4 only. } unit FO4DisableExteriorPreVis; var plugin: IInterface; function Process(e: IInterface): Integer; var r: IInterface; begin if Signature(e) <> 'CELL' then Exit; // exterior cells only (comment out to work on interiors too) if GetElementEditValues(e, 'DATA\Is Interior Cell') = '1' then Exit; // operate on the last override e := WinningOverride(e); // skip cells without precombination if not ElementExists(e, 'PCMB') then Exit; // create new plugin if not Assigned(plugin) then begin if MessageDlg('Create new plugin [YES] or use the last one [NO]?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then plugin := AddNewFile else plugin := FileByIndex(Pred(FileCount)); if not Assigned(plugin) then begin Result := 1; Exit; end; end; // skip already copied if GetFileName(e) = GetFileName(plugin) then Exit; // add masters AddRequiredElementMasters(e, plugin, False); try // copy cell as override r := wbCopyElementToFile(e, plugin, False, True); // setting No PreVis flag and removing PreVis data SetElementNativeValues(r, 'Record Header\Record Flags', GetElementNativeValues(r, 'Record Header\Record Flags') or $80); RemoveElement(r, 'VISI'); RemoveElement(r, 'RVIS'); RemoveElement(r, 'PCMB'); RemoveElement(r, 'XCRI'); except on Ex: Exception do begin AddMessage('Failed to copy: ' + FullPath(e)); AddMessage(' reason: ' + Ex.Message); end end; end; function Finalize: integer; begin if Assigned(plugin) then SortMasters(plugin); end; end.
{ Convert selected BOOK records to SCRL records. FormIDs are unchanged. } unit UserScript; var baserecord: IInterface; //============================================================================ function Initialize: integer; begin // RallyScroll "Scroll of Rally" [SCRL:000A44B5] baserecord := RecordByFormID(FileByIndex(0), $000A44B5, True); if not Assigned(baserecord) then begin AddMessage('Can not find base record'); Result := 1; Exit; end; end; //============================================================================ function Process(e: IInterface): integer; var r: IInterface; formid: Cardinal; begin if Signature(e) <> 'BOOK' then Exit; r := wbCopyElementToFile(baserecord, GetFile(e), True, True); if not Assigned(r) then begin AddMessage('Can''t copy base record as new'); Result := 1; Exit; end; SetElementEditValues(r, 'EDID', GetElementEditValues(e, 'EDID')); SetElementEditValues(r, 'FULL', GetElementEditValues(e, 'FULL')); SetElementEditValues(r, 'DESC', GetElementEditValues(e, 'DESC')); SetElementEditValues(r, 'Model\MODL', GetElementEditValues(e, 'Model\MODL')); SetElementEditValues(r, 'DATA\Value', GetElementEditValues(e, 'DATA\Value')); SetElementEditValues(r, 'DATA\Weight', GetElementEditValues(e, 'DATA\Weight')); formid := GetLoadOrderFormID(e); RemoveNode(e); SetLoadOrderFormID(r, formid); end; end.
unit DVDBurnerParam; interface uses Windows, Messages; type BURNER_ID = ( USR_STAR_BURN = 0, USR_NERO_BURN ); const WM_PROGRESS_PERCNET = WM_USER + 1800; // 进度消息 WM_DVD_BURNER = WM_USER + 1701; // DVDBurner消息 {**************************************************************** uMsg : WM_DVD_BURNER; wParam : DVDBURNER_EVENT lParam : BOOL bSuccessful 是否成功 ****************************************************************} type DVDBURNER_EVENT = ( DBE_GETDRIVER_END, // 取刻录机信息结束 DBE_PREPAREBURN_END, // 准备刻录结束 DBE_GETNEROVERSION_END, // 取Nero版本结束 DBE_CREATEISO_END, // 生成ISO文件结束 DEE_BURNDVD_END, // 刻录DVD结束 DBE_ISOTODVD_END, // ISO刻录为DVD结束 DBE_ERASE_END, // 擦除结束 DBE_SPACE_NOT_ENOUGH, // 光盘容量不足,请提示换光盘 DBE_GETDISKINFO_END, // 取光盘信息结束 DBE_ERROR // 发生错误 ); type TDiskInfo = record m_DiskType: DWORD; // 碟片类型 m_szDiskType: array[0..63] of AnsiChar; // 碟片类型名称 m_bIsEmpty: BOOL; // 是否为空碟 m_bIsErasable:BOOL; // 是否可以擦除 m_bWritable: BOOL; // 是否可以再写 m_ullFreeSpace : int64; // 碟片上的空间 //unsigned __int64 m_ullTotalFileSize; // 刻录这个文件所需的空间 end; pCDiskInfo = ^TDiskInfo; implementation end.
unit TextEditor.CodeFolding.Hint.Indicator; interface uses System.Classes, Vcl.Controls, TextEditor.CodeFolding.Hint.Indicator.Colors, TextEditor.Glyph, TextEditor.Types; const TEXTEDITOR_CODE_FOLDING_HINT_INDICATOR_DEFAULT_OPTIONS = [hioShowBorder, hioShowMark]; type TTextEditorCodeFoldingHintIndicator = class(TPersistent) strict private FColors: TTextEditorCodeFoldingHintIndicatorColors; FGlyph: TTextEditorGlyph; FMarkStyle: TTextEditorCodeFoldingHintIndicatorMarkStyle; FOptions: TTextEditorCodeFoldingHintIndicatorOptions; FPadding: TTextEditorCodeFoldingHintIndicatorPadding; FVisible: Boolean; FWidth: Integer; procedure SetGlyph(const AValue: TTextEditorGlyph); public constructor Create; destructor Destroy; override; procedure Assign(ASource: TPersistent); override; published property Colors: TTextEditorCodeFoldingHintIndicatorColors read FColors write FColors; property Glyph: TTextEditorGlyph read FGlyph write SetGlyph; property MarkStyle: TTextEditorCodeFoldingHintIndicatorMarkStyle read FMarkStyle write FMarkStyle default imsThreeDots; property Options: TTextEditorCodeFoldingHintIndicatorOptions read FOptions write FOptions default TEXTEDITOR_CODE_FOLDING_HINT_INDICATOR_DEFAULT_OPTIONS; property Padding: TTextEditorCodeFoldingHintIndicatorPadding read FPadding write FPadding; property Visible: Boolean read FVisible write FVisible default True; property Width: Integer read FWidth write FWidth default 26; end; implementation constructor TTextEditorCodeFoldingHintIndicator.Create; begin inherited; FColors := TTextEditorCodeFoldingHintIndicatorColors.Create; FGlyph := TTextEditorGlyph.Create; FPadding := TTextEditorCodeFoldingHintIndicatorPadding.Create(nil); FGlyph.Visible := False; FMarkStyle := imsThreeDots; FVisible := True; FOptions := TEXTEDITOR_CODE_FOLDING_HINT_INDICATOR_DEFAULT_OPTIONS; FWidth := 26; end; destructor TTextEditorCodeFoldingHintIndicator.Destroy; begin FColors.Free; FGlyph.Free; FPadding.Free; inherited; end; procedure TTextEditorCodeFoldingHintIndicator.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorCodeFoldingHintIndicator) then with ASource as TTextEditorCodeFoldingHintIndicator do begin Self.FVisible := FVisible; Self.FMarkStyle := FMarkStyle; Self.FWidth := FWidth; Self.FColors.Assign(FColors); Self.FGlyph.Assign(FGlyph); Self.FPadding.Assign(FPadding); end else inherited Assign(ASource); end; procedure TTextEditorCodeFoldingHintIndicator.SetGlyph(const AValue: TTextEditorGlyph); begin FGlyph.Assign(AValue); end; end.
unit xxmFReg; interface uses xxm; type TXxmFragmentClass=class of TXxmFragment; TXxmFragmentRegistry=class(TObject) private Size,Count:integer; Registry:array of record FName:string; FType:TXxmFragmentClass; end; public FilesRootPath:string; //TODO: virtual directories constructor Create; destructor Destroy; override; procedure RegisterClass(FName:string;FType:TXxmFragmentClass); function GetClass(FName:string):TXxmFragmentClass; end; var XxmFragmentRegistry:TXxmFragmentRegistry; implementation uses SysUtils, Registry; { TXxmFragmentRegistry } constructor TXxmFragmentRegistry.Create; begin inherited Create; Size:=0; Count:=0; FilesRootPath:=''; end; destructor TXxmFragmentRegistry.Destroy; begin SetLength(Registry,0); inherited; end; procedure TXxmFragmentRegistry.RegisterClass(FName: string; FType: TXxmFragmentClass); begin if Count=Size then begin inc(Size,64); SetLength(Registry,Size); end; Registry[Count].FName:=LowerCase(FName);//case insensitive? Registry[Count].FType:=FType; //sort? binary tree? inc(Count); end; type EXxmFragmentNotFound=class(Exception) end; function TXxmFragmentRegistry.GetClass(FName: string): TXxmFragmentClass; begin i:=0; l:=LowerCase(FName); while (i<Count) and not(Registry[i].FName=l) do inc(i); if (i<Count) then Result:=Registry[i].FType else Result:=nil; end; initialization XxmFragmentRegistry:=TXxmFragmentRegistry.Create; finalization XxmFragmentRegistry.Free; end.
unit UFormMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient; type TfFormMain = class(TForm) Group1: TGroupBox; EditIP: TLabeledEdit; EditPort: TLabeledEdit; Check1: TCheckBox; Group2: TGroupBox; BtnSend: TButton; BtnQuery: TButton; Memo1: TMemo; IdClient1: TIdTCPClient; EditID: TLabeledEdit; procedure FormCreate(Sender: TObject); procedure IdClient1Connected(Sender: TObject); procedure IdClient1Disconnected(Sender: TObject); procedure IdClient1Status(ASender: TObject; const AStatus: TIdStatus; const AStatusText: String); procedure Check1Click(Sender: TObject); procedure BtnSendClick(Sender: TObject); procedure BtnQueryClick(Sender: TObject); private { Private declarations } procedure UpdateControl(const nConn: Boolean); //更新状态 procedure WriteLog(const nEvent: string); //记录日志 public { Public declarations } end; var fFormMain: TfFormMain; implementation {$R *.dfm} uses IdGlobal, ULibFun, UProtocol; procedure TfFormMain.FormCreate(Sender: TObject); begin UpdateControl(False); end; procedure TfFormMain.WriteLog(const nEvent: string); begin Memo1.Lines.Insert(0, FormatDateTime('hh:nn:ss.zzz', Now()) + #9 + nEvent); end; procedure TfFormMain.UpdateControl(const nConn: Boolean); begin BtnSend.Enabled := nConn; BtnQuery.Enabled := nConn; if not nConn then Check1.Checked := False; //xxxxx end; procedure TfFormMain.IdClient1Connected(Sender: TObject); begin UpdateControl(True); end; procedure TfFormMain.IdClient1Disconnected(Sender: TObject); begin UpdateControl(False); end; procedure TfFormMain.IdClient1Status(ASender: TObject; const AStatus: TIdStatus; const AStatusText: String); begin WriteLog(AStatusText); end; procedure TfFormMain.Check1Click(Sender: TObject); begin if ActiveControl <> Check1 then Exit; IdClient1.Disconnect; if Check1.Checked then try IdClient1.Host := EditIP.Text; IdClient1.Port := StrToInt(EditPort.Text); IdClient1.Connect; except on nErr: Exception do begin WriteLog(nErr.Message); Check1.Checked := False; end; end; end; procedure TfFormMain.BtnSendClick(Sender: TObject); var nFrame: TFrameData; nData: TRunData; nBuf: TIdBytes; begin WriteLog('上传数据'); InitFrameData(nFrame); InitRunData(nData); with nFrame do begin FStation := SwapWordHL( StrToInt(EditID.Text) ); FCommand := cFrame_CMD_UpData; FExtCMD := cFrame_Ext_RunData; end; with nData do begin I00 := 1; I01 := 2; I02 := 3; PutValFloat(1.1, VD300); PutValFloat(1.2, VD304); PutValFloat(1.3, VD308); PutValFloat(1.4, VD312); PutValFloat(1.5, VD316); PutValFloat(1.6, VD320); PutValFloat(1.7, VD324); PutValFloat(1.8, VD328); PutValFloat(1.9, VD332); PutValFloat(2.0, VD336); PutValFloat(20.1, VD340); PutValFloat(200.2, VD348); PutValFloat(2000.3, VD352); PutValFloat(20000.4, VD356); V3650 := 4; V3651 := 5; V3652 := 6; V3653 := 7; V3654 := 8; V3655 := 9; V3656 := 10; V3657 := 11; V20000 := 12; V20001 := 13; V20002 := 14; end; nBuf := BuildRunData(@nFrame, @nData); IdClient1.IOHandler.Write(nBuf); end; procedure TfFormMain.BtnQueryClick(Sender: TObject); var nFrame: TFrameData; nParams: TRunParams; nBuf: TIdBytes; nInt: Integer; begin WriteLog('查询数据'); InitFrameData(nFrame); with nFrame do begin FStation := SwapWordHL( StrToInt(EditID.Text) ); FCommand := cFrame_CMD_QueryData; FExtCMD := cFrame_Ext_RunParam; FDataLen := 0; FData[0] := cFrame_End; end; with IdClient1.IOHandler do begin nBuf := RawToBytes(nFrame, FrameValidLen(@nFrame)); Write(nBuf); SetLength(nBuf, 0); ReadBytes(nBuf, 8, False); //读取协议开始定长数据 if BytesToString(nBuf, 0, 3, Indy8BitEncoding) <> cFrame_Begin then //帧头无效 begin InputBuffer.Clear; Exit; end; if nBuf[7] > 0 then ReadBytes(nBuf, nBuf[7], True); //读取数据 ReadBytes(nBuf, 1, True); //读取帧尾 nInt := Length(nBuf); if Char(nBuf[nInt - 1]) <> cFrame_End then //帧尾无效 begin InputBuffer.Clear; Exit; end; WriteLog('查询成功'); end; end; end.
unit rcIssuesActivity; {$mode objfpc}{$H+} interface uses Classes, SysUtils, rcObject, rcArrayManager; type TIssuesActivity = class(TRCObject); type { TActivities } TActivities = class(TRCArrayManager) private function GetItem(index: Integer): TIssuesActivity; public property Item[index: Integer]: TIssuesActivity read GetItem; function Add(AObject: TIssuesActivity): TIssuesActivity; function GetItemBy(AID: Integer): TIssuesActivity; end; implementation { TActivities } function TActivities.GetItem(index: Integer): TIssuesActivity; begin Result := inherited GetItem(index) as TIssuesActivity; end; function TActivities.Add(AObject: TIssuesActivity): TIssuesActivity; begin Result := inherited Add(AObject) as TIssuesActivity; end; function TActivities.GetItemBy(AID: Integer): TIssuesActivity; begin Result := inherited GetItemBy(AID) as TIssuesActivity; end; end.
unit uIniSettings; {$mode objfpc}{$H+} interface uses Classes, SysUtils, contnrs, IniFiles; const sNoValue = 'ValueNotAssigned'; type { TSettingsClass } TSettingsClass = class private FIniKeys: TstringList; FIniSection: string; FModified: boolean; // function CheckKeyName(const KeyName: string): Boolean; protected property IniKeys: TstringList read FIniKeys; public property IniSection: string read FIniSection; // procedure RegisterIniKey(const KeyName: string; const DefaultValue: string = sNoValue); function GetIniValue(const KeyName: string): string; procedure SetIniValue(const KeyName, Value: string); property Modified: boolean read FModified; // constructor Create(const aIniSection: string); destructor Destroy; override; end; { TSettingsHolder } TSettingsHolder = class private FSettingsList: TObjectList; FSourcePath: string; // function IniSectionExists(const aIniSection: string): Boolean; protected function IsModified: boolean; public property SettingsList: TObjectList read FSettingsList; property SourcePath: string read FSourcePath write FSourcePath; // function RegisterIniSection(const aIniSection: string): TSettingsClass; function GetSettingsByIniSection(const aIniSection: string): TSettingsClass; // function CheckExists: boolean; virtual; abstract; function Load: Boolean; virtual; function Update: Boolean; virtual; abstract; // constructor Create; destructor Destroy; override; end; { TIniSettingsReader } TIniSettingsReader = class(TSettingsHolder) private FIniFile: TMemIniFile ; function GetIniFile: TMemIniFile ; public property IniFile: TMemIniFile read GetIniFile; // function CheckExists: boolean; override; function Load: Boolean; override; function Update: Boolean; override; procedure BackupFile; // constructor Create; destructor Destroy; override; end; { TAppSettings } TAppSettings = class private FIniSettingsReader: TIniSettingsReader; function GetSettingsByIniSection(const aIniSection: string): TSettingsClass; protected procedure init; virtual; procedure DefaultValues; virtual; public constructor Create; destructor Destroy; override; function RegisterIniSection(const aIniSection: string): TSettingsClass; function GetIniValue(const aIniSection, KeyName: string): string; procedure SetIniValue(const aIniSection, KeyName, Value: string); function CheckExists: Boolean; function IsEmpty: boolean; virtual; abstract; procedure Update; class function IsIniValueEmpty(const Value: string): boolean; end; implementation const sIniFileExt = '.conf'; sBackupIniFileExt = '.bconf'; { TAppSettings } procedure TAppSettings.init; begin FIniSettingsReader.Load; end; procedure TAppSettings.DefaultValues; begin // end; constructor TAppSettings.Create; begin inherited Create; FIniSettingsReader := TIniSettingsReader.Create; init; DefaultValues; end; destructor TAppSettings.Destroy; begin FIniSettingsReader.Free; inherited Destroy; end; function TAppSettings.RegisterIniSection(const aIniSection: string): TSettingsClass; begin result := FIniSettingsReader.RegisterIniSection(aIniSection) end; function TAppSettings.GetSettingsByIniSection(const aIniSection: string): TSettingsClass; begin result := FIniSettingsReader.GetSettingsByIniSection(aIniSection) end; function TAppSettings.GetIniValue(const aIniSection, KeyName: string): string; begin result := GetSettingsByIniSection(aIniSection).GetIniValue(KeyName); end; procedure TAppSettings.SetIniValue(const aIniSection, KeyName, Value: string); begin GetSettingsByIniSection(aIniSection).SetIniValue(KeyName, Value); end; function TAppSettings.CheckExists: Boolean; begin result := FIniSettingsReader.CheckExists; end; procedure TAppSettings.Update; begin FIniSettingsReader.Update; end; class function TAppSettings.IsIniValueEmpty(const Value: string): boolean; begin result := Value = sNoValue end; { TIniSettingsReader } function TIniSettingsReader.GetIniFile: TMemIniFile; begin if not Assigned(FIniFile) then try finifile := TMemIniFile.Create(SourcePath); except Result := nil; raise Exception.Create('error in TIniSettingsReader.GetIniFile!'); end; result := FIniFile; end; function TIniSettingsReader.CheckExists: boolean; begin Result := FileExists(SourcePath); end; function TIniSettingsReader.Load: Boolean; var i, j: Integer; IniSection, KeyName, KeyValue, DefaultValue: string; lsc: TSettingsClass; begin Result := inherited Load; if not result then Exit; try with IniFile do begin for i := 0 to SettingsList.Count-1 do begin lsc := (SettingsList.Items[i] as TSettingsClass); IniSection := lsc.IniSection; for j := 0 to lsc.IniKeys.Count-1 do begin KeyName := lsc.IniKeys.Names[j]; DefaultValue := lsc.IniKeys.ValueFromIndex[j]; KeyValue := ReadString(IniSection,KeyName,DefaultValue); if Trim(KeyValue) = sNoValue then KeyValue := DefaultValue; lsc.IniKeys.ValueFromIndex[j] := KeyValue; end; end; Result := True; end; except Result := False; raise Exception.Create('Error on TIniSettingsReader.Load!'); end; end; function TIniSettingsReader.Update: Boolean; var i, j: Integer; lsc: TSettingsClass; IniSection, KeyName, ActualValue: string; begin BackupFile; try with IniFile do begin for I := 0 to SettingsList.Count-1 do begin lsc := SettingsList.Items[i] as TSettingsClass; IniSection := lsc.IniSection; for j := 0 to lsc.IniKeys.Count-1 do begin KeyName := lsc.IniKeys.Names[j]; ActualValue := lsc.IniKeys.ValueFromIndex[j]; WriteString(IniSection,KeyName,ActualValue); end; end; UpdateFile; end; Result := True; except result := False; raise Exception.Create('Error on TIniSettingsReader.Update!'); end; end; procedure TIniSettingsReader.BackupFile; var backup_fn: TFileName; begin if not CheckExists then Exit; backup_fn := ChangeFileExt(ParamStr(0), sBackupIniFileExt); try if FileExists(backup_fn) then DeleteFile(backup_fn); IniFile.Rename(backup_fn, False); IniFile.UpdateFile; DeleteFile(SourcePath); IniFile.Rename(SourcePath, false); IniFile.UpdateFile; except raise exception.Create('Error on TIniSettingsReader.Backup!'); end; end; constructor TIniSettingsReader.Create; begin inherited Create; SourcePath := ChangeFileExt(ParamStr(0), sIniFileExt); end; destructor TIniSettingsReader.Destroy; begin if IsModified then Update; FIniFile.Free; inherited Destroy; end; { TSettingsHolder } function TSettingsHolder.IniSectionExists(const aIniSection: string): Boolean; var i: Integer; begin Result := False; for i := 0 to FSettingsList.Count-1 do if SameText(aIniSection, (SettingsList.Items[i] as TSettingsClass).IniSection) then begin Result := True; Break; end; end; function TSettingsHolder.RegisterIniSection(const aIniSection: string): TSettingsClass; begin if not IniSectionExists(aIniSection) then begin result := TSettingsClass.Create(aIniSection); SettingsList.Add(result); end else raise Exception.Create(aIniSection +' is aready registered!'); end; function TSettingsHolder.GetSettingsByIniSection(const aIniSection: string): TSettingsClass; var i: Integer; begin Result := nil; for i := 0 to SettingsList.Count - 1 do if SameText(aIniSection, (FSettingsList.Items[i] as TSettingsClass).IniSection) then begin result := SettingsList.Items[i] as TSettingsClass; Break; end; if result = nil then raise Exception.Create('Section '+aIniSection+' is not registered'); end; function TSettingsHolder.Load: Boolean; begin Result := CheckExists; end; function TSettingsHolder.IsModified: boolean; var i: integer; begin result := false; for i := 0 to FSettingsList.Count-1 do if (FSettingsList.Items[i] as TSettingsClass).Modified then begin result := true; break; end; end; constructor TSettingsHolder.Create; begin inherited Create; FSettingsList := TObjectList.Create; FSettingsList.OwnsObjects := True; end; destructor TSettingsHolder.Destroy; begin FSettingsList.Free; inherited Destroy; end; { TSettingsClass } function TSettingsClass.CheckKeyName(const KeyName: string): Boolean; begin Result := (IniKeys.IndexOfName(KeyName)>=0); if not Result then raise Exception.Create('['+Self.IniSection+']'+KeyName+' not registered!' + ' -GetIniValue'); end; procedure TSettingsClass.RegisterIniKey(const KeyName: string; const DefaultValue: string); begin IniKeys.Add(KeyName + '=' + DefaultValue); end; function TSettingsClass.GetIniValue(const KeyName: string): string; begin result := sNoValue; if CheckKeyName(KeyName) then result := Trim(IniKeys.Values[KeyName]) else raise Exception.Create('No such Keyname '+KeyName); end; procedure TSettingsClass.SetIniValue(const KeyName, Value: string); var LOldValue: string; begin if CheckKeyName(KeyName) then begin LOldValue := GetIniValue(KeyName); if LOldValue <> Value then begin IniKeys.Values[KeyName] := Value; FModified := True; end; end; end; constructor TSettingsClass.Create(const aIniSection: string); begin inherited Create; FModified := False; FIniSection := aIniSection; FIniKeys := TStringList.Create; FIniKeys.CaseSensitive := False; end; destructor TSettingsClass.Destroy; begin FIniKeys.Free; inherited Destroy; end; end.
unit FrmLocationConfig; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Grids, StdCtrls, FrmBase, uDBFieldData, ActiveX, uDefine, uTransform, uControlInf; type TLocationConfigForm = class(TBaseForm) pnl1: TPanel; pnl2: TPanel; pnl3: TPanel; strngrdLocation: TStringGrid; grpAdd: TGroupBox; grpDel: TGroupBox; btnAdd: TButton; grpQuery: TGroupBox; btnDel: TButton; lblTitle: TLabel; procedure FormShow(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnDelClick(Sender: TObject); private { Private declarations } procedure RefreshStringGridFromDB; public { Public declarations } class function DisplayOutForm(AHandle: THandle): Boolean; end; implementation uses FrmAddLocations; {$R *.dfm} { TLocationConfigForm } class function TLocationConfigForm.DisplayOutForm( AHandle: THandle): Boolean; var LocationConfigForm: TLocationConfigForm; begin LocationConfigForm := TLocationConfigForm.Create(Application, AHandle); try if LocationConfigForm.ShowModal = mrOk then begin Result := True; end else Result := False; finally if Assigned(LocationConfigForm) then FreeAndNil(LocationConfigForm); end; end; procedure TLocationConfigForm.RefreshStringGridFromDB; var IXMLDBData: IXMLGuoSenDeviceSystemType; begin CoInitialize(nil); IXMLDBData := NewGuoSenDeviceSystem; try IXMLDBData.DBData.OperaterType := 'Read'; IXMLDBData.DBData.DBTable := CSLocationDBName; IXMLDBData.DBData.SQL := 'Select a.Id, b.Name as LocationTypeName, a.Name as LocationName, a.Address ' + ' From LocationInfo a, LocationTypeInfo b ' + ' where (a.LocationTypeId = b.Id) '; //装载ColData的内容 AddLocationInfoColData(IXMLDBData); //从数据库中加载数据到RowData中 gDatabaseControl.QueryDataByXMLData(IXMLDBData); //显示到StringGrid DisXMLDataToStringGrid(IXMLDBData, strngrdLocation); finally IXMLDBData := nil; CoUninitialize; end; end; procedure TLocationConfigForm.FormShow(Sender: TObject); begin SetStringGridStyle(strngrdLocation); strngrdLocation.ColWidths[0] := 20; strngrdLocation.ColWidths[1] := 50; strngrdLocation.ColWidths[4] := 400; RefreshStringGridFromDB; end; procedure TLocationConfigForm.btnAddClick(Sender: TObject); begin if TAddLocationsForm.DisplayOutForm(Handle) then begin ShowMessage('添加成功'); RefreshStringGridFromDB; end; end; procedure TLocationConfigForm.btnDelClick(Sender: TObject); var IXMLDBData: IXMLGuoSenDeviceSystemType; IXMLRowItem: IXMLRowItemType; begin if gDatabaseControl.GetTableCountFromDB(CSLocationDBName, EmptyStr) <= 0 then begin ShowMessage('数据库中没有放置点数据'); Exit; end; if (strngrdLocation.Row > 0) and (strngrdLocation.Row < strngrdLocation.RowCount) then begin if MessageDlg('确定要删除选中行吗?', mtConfirmation, [mbYes, mbNo], 0) = MrYes then begin CoInitialize(nil); IXMLDBData := NewGuoSenDeviceSystem; try IXMLDBData.DBData.OperaterType := 'write'; IXMLDBData.DBData.DBTable := CSLocationDBName; AddLocationInfoColData(IXMLDBData); IXMLRowItem := IXMLDBData.DBData.RowData.Add; IXMLRowItem.ID := StrToInt(strngrdLocation.Cells[1, strngrdLocation.Row]); gDatabaseControl.DelLocationByXMLData(IXMLDBData); RefreshStringGridFromDB; finally IXMLDBData := nil; CoUninitialize; end; end; end; end; end.
unit roUtils; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, IniFiles, TypInfo; type TroSearchRec = TSearchRec; TroStrings = TStrings; TroStringList = TStringList; TroFileStream = TFileStream; TroWIN32FindData = TWin32FindData; { µ÷ÊÔÓà } procedure Alert; overload; procedure Alert(const s : string); overload; procedure Alert(i : integer); overload; { Qustom request} function CustomRequest(const s : string): boolean; { Request for item deleting} function DeleteRequest: boolean; { Show message S with icon mtWarning } procedure ShowWarning(const S:string); { Show message S with icon mtError } procedure ShowError(const s:string); function IsNTFamily: boolean; { Returns formated string, represented float value} function FormatFloatStr(const S: AnsiString; Thousands: Boolean): string; function GetCaptionFontSize: integer; function GetTitleFont: hFont; function CheckLimits(Value, MinValue, MaxValue : integer) : integer; //overload; //function CheckLimits(Value : real; MinValue, MaxValue : integer) : integer; overload; function IntToByte(const Value : integer) : byte; register; //Nick function HexToInt(HexStr : AnsiString) : Int64; function MakeMessage(Msg : Longint; WParam : WPARAM; LParam : LPARAM; aResult : LRESULT) : TMessage; { Returns percent i2 of i1} function SumTrans(i1, i2 : integer): integer; { Returns max value from i1 and i2} function Maxi(i1, i2 : integer) : integer; { Returns min value from i1 and i2} function Mini(i1, i2 : integer) : integer; { Set value to Minvalue or Maxvalue if it not placed between them} function LimitIt(Value, MinValue, MaxValue : integer): integer; { Returns True if Value is valid float} function IsValidFloat(const Value: AnsiString; var RetValue: Extended): Boolean; function GetAnimation: Boolean; procedure SetAnimation(Value: Boolean); { Returns string s1 if L, else return s2} function iff(L : boolean; const s1, s2 : string) : string; { Returns TObject o1 if L, else return o2} function iffo(L : boolean; o1, o2 : TObject) : TObject; { Returns integer o1 if L, else return o2} function iffi(L : boolean; i1, i2 : integer) : integer; function IsIDERunning: boolean; function IsWOW64Proc: Windows.bool; { Returns True if value placed berween i1 and i2} function Between(Value, i1, i2 : integer) : boolean; { Change values of i1 and i2} procedure Changei(var i1, i2 : integer); { Rounds value F up to two chars after a point} function CurRound(f : real) : real; { Delay in milliseconds} procedure Delay(MSecs: Integer); function GetCents(Value : Extended) : smallint; // Properties function HasProperty(Component : TObject; PropName: String ): Boolean; function GetIntProp(Component: TObject; PropName: String): Integer; procedure SetIntProp(Component: TObject; PropName: String; Value: Integer); function GetObjProp(Component: TObject; PropName: String): TObject; procedure SetObjProp(Component: TObject; PropName: String; Value: TObject); function CheckSetProp(Component: TObject; PropName, Value: String): Boolean; function SetSetPropValue(Component: TObject; PropName, ValueName: String; Value : boolean): Boolean; implementation uses Dialogs; var hKern32: HMODULE = 0; IsDebuggerPresent : function (): Boolean; stdcall; IsWow64Process : function (hProc : THandle; out Is64 : Windows.bool): Windows.Bool; stdcall; procedure Alert; overload; begin ShowWarning('Alert'); end; procedure Alert(i : integer); overload; begin ShowWarning(IntToStr(i)); end; procedure Alert(const s : string); overload; begin ShowWarning(s); end; procedure ShowError(const s:string); begin MessageDlg(s, mtError, [mbOk], 0); end; procedure ShowWarning(const S:string); begin MessageDlg(s, mtWarning, [mbOk], 0); end; function IsNTFamily: boolean; begin Result := (Win32MajorVersion > 5) or ((Win32MajorVersion = 5) and (Win32MinorVersion >= 1)); end; function CustomRequest(const s : string): boolean; begin Result := MessageDlg(s, mtConfirmation, [mbYes, mbNo], 0) = mrYes; end; function DeleteRequest: boolean; begin Result := MessageDlg('Delete this item?', mtConfirmation, [mbYes, mbNo], 0) = mrYes; end; function FormatFloatStr(const S: AnsiString; Thousands: Boolean): string; var I, MaxSym, MinSym, Group: Integer; IsSign: Boolean; begin { Result := ''; MaxSym := Length(S); IsSign := (MaxSym > 0) and CharInSet(S[1], ['-', '+']); if IsSign then MinSym := 2 else MinSym := 1; I := Pos(DecimalSeparator, S); if I > 0 then MaxSym := I - 1; I := Pos('E', AnsiUpperCase(S)); if I > 0 then MaxSym := Mini(I - 1, MaxSym); Result := Copy(S, MaxSym + 1, MaxInt); Group := 0; for I := MaxSym downto MinSym do begin Result := S[I] + Result; Inc(Group); if (Group = 3) and Thousands and (I > MinSym) then begin Group := 0; Result := ThousandSeparator + Result; end; end; if IsSign then Result := S[1] + Result; } end; function GetCaptionFontSize: integer; var NonClientMetrics: TNonClientMetrics; begin NonClientMetrics.cbSize := SizeOf(NonClientMetrics); if SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, @NonClientMetrics, 0) then Result := NonClientMetrics.lfCaptionFont.lfHeight else Result := 0; end; function GetTitleFont: hFont; var NonClientMetrics: TNonClientMetrics; begin NonClientMetrics.cbSize := SizeOf(NonClientMetrics); if SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, @NonClientMetrics, 0) then Result := CreateFontIndirect(NonClientMetrics.lfCaptionFont) else Result := 0; end; function CheckLimits(Value, MinValue, MaxValue : integer) : integer; begin if Value < MinValue then Result := MinValue else if Value > MaxValue then Result := MaxValue else Result := Value; end; function IntToByte(const Value : integer) : byte; register; // Nick asm test eax, $80000000 jz @q1 mov al, 0 ret @q1: test eax, $FFFFFF00 jnz @q2 ret @q2: mov al, 255 end; function HexToInt(HexStr : AnsiString) : Int64; var i : byte; begin if HexStr = '' then begin Result := 0; Exit; end; HexStr := UpperCase(HexStr); if HexStr[length(HexStr)] = 'H' then Delete(HexStr,length(HexStr),1); Result := 0; for i := 1 to length(HexStr) do begin Result := Result shl 4; if CharInSet(HexStr[i], ['0'..'9']) then Result := Result + (byte(HexStr[i]) - 48) else if CharInSet(HexStr[i], ['A'..'F']) then Result := Result + (byte(HexStr[i]) - 55) else begin Result := 0; break; end; end; end; function MakeMessage(Msg : Longint; WParam : WPARAM; LParam : LPARAM; aResult : LRESULT) : TMessage; begin Result.Msg := Msg; Result.WParam := WParam; Result.LParam := LParam; Result.Result := aResult; end; function SumTrans(i1, i2 : integer): integer; begin Result := Round(i2 + (100 - i2) * (i1 / 100)); end; function Maxi(i1, i2 : integer) : integer; begin if i1 > i2 then Result := i1 else Result := i2; end; function Mini(i1, i2 : integer) : integer; begin if i1 > i2 then Result := i2 else Result := i1; end; function LimitIt(Value, MinValue, MaxValue : integer): integer; begin if Value < MinValue then Result := MinValue else if Value > MaxValue then Result := MaxValue else Result := Value; end; procedure Changei(var i1, i2 : integer); var i : integer; begin i := i2; i2 := i1; i1 := i; end; function IsValidFloat(const Value: AnsiString; var RetValue: Extended): Boolean; var I: Integer; Buffer: array[0..63] of Char; begin // Result := False; // for I := 1 to Length(Value) do // if not CharInSet(Value[I], [DecimalSeparator, '-', '+', '0'..'9', 'e', 'E']) then // Exit; // Result := TextToFloat(StrPLCopy(Buffer, Value, // SizeOf(Buffer) - 1), RetValue {$IFDEF WIN32}, fvExtended {$ENDIF}); end; function GetAnimation: Boolean; var Info: TAnimationInfo; begin Info.cbSize := SizeOf(TAnimationInfo); if SystemParametersInfo(SPI_GETANIMATION, SizeOf(Info), @Info, 0) then Result := Info.iMinAnimate <> 0 else Result := False; end; procedure SetAnimation(Value: Boolean); var Info: TAnimationInfo; begin Info.cbSize := SizeOf(TAnimationInfo); BOOL(Info.iMinAnimate) := Value; SystemParametersInfo(SPI_SETANIMATION, SizeOf(Info), @Info, 0); end; function iff(L : boolean; const s1, s2 : string) : string; begin if l then Result := s1 else Result := s2; end; function iffo(L : boolean; o1, o2 : TObject) : TObject; begin if l then Result := o1 else Result := o2; end; function iffi(L : boolean; i1, i2 : integer) : integer; begin if l then Result := i1 else Result := i2; end; function IsIDERunning: boolean; begin if Assigned(roUtils.IsDebuggerPresent) then Result := roUtils.IsDebuggerPresent else Result := True; end; function IsWOW64Proc: Windows.bool; begin if Assigned(IsWow64Process) then begin if not IsWow64Process(GetCurrentProcess, Result) then Result := False; end else Result := False; end; function Between(Value, i1, i2 : integer) : boolean; begin if i1 < i2 then Result := (Value >= i1) and (Value <= i2) else Result := (Value <= i1) and (Value >= i2); end; function CurRound(f : real) : real; begin Result := Round((f+0.000001)*100)/100; end; procedure Delay(MSecs: Integer); var FirstTickCount : DWord; begin FirstTickCount := GetTickCount; repeat Application.ProcessMessages until ((GetTickCount - FirstTickCount) >= DWord(MSecs)); end; function GetCents(Value : Extended) : smallint; var e : extended; begin e := Value; Result := Round(Frac(e) * 100); end; // Prop Info function HasProperty(Component : TObject; PropName: String ): Boolean; begin Result := GetPropInfo(Component.ClassInfo, PropName) <> nil; end; function GetObjProp(Component: TObject; PropName: String): TObject; var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo = nil then Result := nil else Result := TObject(GetObjectProp(Component, ptrPropInfo, TObject)); end; procedure SetObjProp(Component: TObject; PropName: String; Value: TObject); var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo <> nil then SetObjectProp(Component, ptrPropInfo, Value); end; function CheckSetProp(Component: TObject; PropName, Value: String): Boolean; var PropInfo : PPropInfo; TypeInfo: PTypeInfo; i : integer; S: TIntegerSet; begin Result := False; PropInfo := GetPropInfo(Component.ClassInfo, PropName); if PropInfo <> nil then begin Integer(S) := GetOrdProp(Component, PropInfo); TypeInfo := GetTypeData(PropInfo^.PropType^)^.CompType^; for I := 0 to SizeOf(Integer) * 8 - 1 do if I in S then if GetEnumName(TypeInfo, I) = Value then begin Result := True; Break end; end; end; {$IFNDEF DELPHI6UP} function SetToString(PropInfo: PPropInfo; Value: Integer): string; var S: TIntegerSet; TypeInfo: PTypeInfo; I: Integer; begin Result := ''; Integer(S) := Value; TypeInfo := GetTypeData(PropInfo^.PropType^)^.CompType^; for I := 0 to SizeOf(Integer) * 8 - 1 do if I in S then begin if Result <> '' then Result := Result + ','; Result := Result + GetEnumName(TypeInfo, I); end; end; {$ENDIF} function SetSetPropValue(Component: TObject; PropName, ValueName: String; Value : boolean): Boolean; var PropInfo : PPropInfo; i : integer; s : string; begin Result := False; PropInfo := GetPropInfo(Component.ClassInfo, PropName); if PropInfo <> nil then begin Integer(I) := GetOrdProp(Component, PropInfo); s := SetToString(PropInfo, I); if Value then begin if pos(s, ValueName) < 1 then begin s := s + ',' + ValueName; SetSetProp(Component, PropInfo, s); end; end else begin i := pos(',' + ValueName, s); if i > 0 then Delete(s, i, Length(',' + ValueName)) else begin i := pos(ValueName + ',', s); if i > 0 then Delete(s, i, Length(',' + ValueName)) else begin i := pos(ValueName, s); if i > 0 then Delete(s, i, Length(ValueName)) else Exit; end; end; SetSetProp(Component, PropInfo, s); end; end; end; function GetIntProp(Component: TObject; PropName: String): Integer; var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo = nil then Result := -1 else Result := Integer(GetOrdProp(Component, ptrPropInfo)); end; procedure SetIntProp(Component: TObject; PropName: String; Value: Integer); var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo <> nil then SetOrdProp(Component, ptrPropInfo, Value); end; function AeroIsEnabled : boolean; var b : Longbool; begin Result := True; {if (Win32MajorVersion >= 6) then begin b := False; if Assigned(_DwmIsCompositionEnabled) then Result := _DwmIsCompositionEnabled(b) = S_OK else begin InitDwmApi; if hDWMAPI > 0 then begin _DwmIsCompositionEnabled := GetProcAddress(hDWMAPI, 'DwmIsCompositionEnabled'); if Assigned(_DwmIsCompositionEnabled) then Result := _DwmIsCompositionEnabled(b) = S_OK; end end; end; Result := Result and b;} end; end.
{******************************************************************************* Title: T2Ti ERP Fenix Description: Service relacionado à tabela [PAPEL] The MIT License Copyright: Copyright (C) 2020 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (alberteije@gmail.com) @version 1.0.0 *******************************************************************************} unit PapelService; interface uses Papel, System.SysUtils, System.Generics.Collections, ServiceBase, MVCFramework.DataSet.Utils; type TPapelService = class(TServiceBase) private class procedure AnexarObjetosVinculados(AListaPapel: TObjectList<TPapel>); overload; class procedure AnexarObjetosVinculados(APapel: TPapel); overload; public class function ConsultarLista: TObjectList<TPapel>; class function ConsultarListaFiltroValor(ACampo: string; AValor: string): TObjectList<TPapel>; class function ConsultarObjeto(AId: Integer): TPapel; class procedure Inserir(APapel: TPapel); class function Alterar(APapel: TPapel): Integer; class function Excluir(APapel: TPapel): Integer; end; var sql: string; implementation { TPapelService } class procedure TPapelService.AnexarObjetosVinculados(APapel: TPapel); begin end; class procedure TPapelService.AnexarObjetosVinculados(AListaPapel: TObjectList<TPapel>); var Papel: TPapel; begin for Papel in AListaPapel do begin AnexarObjetosVinculados(Papel); end; end; class function TPapelService.ConsultarLista: TObjectList<TPapel>; begin sql := 'SELECT * FROM PAPEL ORDER BY ID'; try Result := GetQuery(sql).AsObjectList<TPapel>; AnexarObjetosVinculados(Result); finally Query.Close; Query.Free; end; end; class function TPapelService.ConsultarListaFiltroValor(ACampo, AValor: string): TObjectList<TPapel>; begin sql := 'SELECT * FROM PAPEL where ' + ACampo + ' like "%' + AValor + '%"'; try Result := GetQuery(sql).AsObjectList<TPapel>; AnexarObjetosVinculados(Result); finally Query.Close; Query.Free; end; end; class function TPapelService.ConsultarObjeto(AId: Integer): TPapel; begin sql := 'SELECT * FROM PAPEL WHERE ID = ' + IntToStr(AId); try GetQuery(sql); if not Query.Eof then begin Result := Query.AsObject<TPapel>; AnexarObjetosVinculados(Result); end else Result := nil; finally Query.Close; Query.Free; end; end; class procedure TPapelService.Inserir(APapel: TPapel); begin APapel.ValidarInsercao; APapel.Id := InserirBase(APapel, 'PAPEL'); end; class function TPapelService.Alterar(APapel: TPapel): Integer; begin APapel.ValidarAlteracao; Result := AlterarBase(APapel, 'PAPEL'); end; class function TPapelService.Excluir(APapel: TPapel): Integer; begin APapel.ValidarExclusao; Result := ExcluirBase(APapel.Id, 'PAPEL'); end; end.
unit CDSHooksServer; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) 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 HL7 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. } interface uses SysUtils, Classes, Generics.Collections, IdHTTPServer, IdContext, IdCustomHTTPServer, AdvObjects, AdvGenerics, AdvJson, FHIRSupport, FHIRClient, CDSHooksUtilities, ServerUtilities, FHIRServerContext; type TCDSHooksProcessor = class (TAdvObject) private Frequest: TCDSHookRequest; Fresponse: TCDSHookResponse; FClient: TFhirClient; procedure SetClient(const Value: TFhirClient); procedure Setrequest(const Value: TCDSHookRequest); procedure Setresponse(const Value: TCDSHookResponse); public destructor Destroy; override; function Link : TCDSHooksProcessor; overload; property request : TCDSHookRequest read Frequest write Setrequest; property response : TCDSHookResponse read Fresponse write Setresponse; property Client : TFhirClient read FClient write SetClient; function execute : boolean; virtual; function addCard(summary, detail, indicator, sourceLabel, sourceUrl : String) : TCDSHookCard; end; TCDSHooksProcessorClass = class of TCDSHooksProcessor; TCDSHooksService = class (TAdvObject) private Procedure HandleRequest(base : String; server: TFHIRServerContext; secure : boolean; session : TFHIRSession; context: TIdContext; request: TIdHTTPRequestInfo; response: TIdHTTPResponseInfo); overload; protected FEngines : TList<TCDSHooksProcessorClass>; Procedure require(test : boolean; msg : String); function HandleRequest(server: TFHIRServerContext; secure : boolean; session : TFHIRSession; context: TIdContext; request: TCDSHookRequest) : TCDSHookResponse; overload; virtual; function ProcessRequestEngines(server: TFHIRServerContext; secure : boolean; session : TFHIRSession; context: TIdContext; request: TCDSHookRequest; response : TCDSHookResponse) : boolean; public Constructor Create; override; Destructor Destroy; override; function hook : string; virtual; // see the hook catalog (http://cds-hooks.org/#hook-catalog) function name : String; virtual; function description : String; virtual; function id : String; virtual; // must be unique across this server procedure registerPreFetch(json : TJsonObject); virtual; end; TCDSHooksServer = class (TFHIRServerWorker) private FServices : TAdvMap<TCDSHooksService>; function GetActive: boolean; Procedure HandleServiceList(response: TIdHTTPResponseInfo); function getBase(secure : boolean; basePath : String; request : TIdHTTPRequestInfo) : string; public Constructor Create(ServerContext : TAdvObject); Destructor Destroy; override; procedure RegisterService(service : TCDSHooksService); Procedure HandleRequest(secure : boolean; basePath : String; session : TFHIRSession; context: TIdContext; request: TIdHTTPRequestInfo; response: TIdHTTPResponseInfo); property Active : boolean read GetActive; end; implementation { TCDSHooksServer } constructor TCDSHooksServer.Create(ServerContext : TAdvObject); begin inherited Create(ServerContext); FServices := TAdvMap<TCDSHooksService>.create; end; destructor TCDSHooksServer.Destroy; begin FServices.Free; inherited; end; function TCDSHooksServer.GetActive: boolean; begin result := FServices.Count > 0; end; function TCDSHooksServer.getBase(secure : boolean; basePath : String; request: TIdHTTPRequestInfo): string; begin if secure then result := 'https://'+request.Host+basePath else result := 'http://'+request.Host+basePath end; procedure TCDSHooksServer.HandleRequest(secure: boolean; basePath : String; session: TFHIRSession; context: TIdContext; request: TIdHTTPRequestInfo; response: TIdHTTPResponseInfo); begin if request.Document = basePath+'/cds-services' then handleServiceList(response) else if FServices.ContainsKey(request.Document.Substring(basePath.Length + 14)) then FServices[request.Document.Substring(basePath.Length + 14)].handleRequest(getBase(secure, basePath, request), TFHIRServerContext(ServerContext), secure, session, context, request, response) else begin response.ResponseNo := 404; response.ContentText := 'Document '+request.Document+' not found'; end; end; procedure TCDSHooksServer.HandleServiceList(response: TIdHTTPResponseInfo); var json, jsvc : TJsonObject; services : TJsonArray; svc : TCDSHooksService; id : String; begin json := TJsonObject.Create; try services := json.forceArr['services']; for id in FServices.SortedKeys do begin svc := FServices[id]; jsvc := services.addObject; jsvc.str['hook'] := svc.hook; jsvc.str['name'] := svc.name; jsvc.str['description'] := svc.description; jsvc.str['id'] := svc.id; svc.registerPreFetch(jsvc); end; response.ResponseNo := 200; response.ResponseText := 'OK'; response.ContentType := 'application/json'; response.ContentText := TJSONWriter.writeObjectStr(json,true); finally json.Free; end; end; procedure TCDSHooksServer.RegisterService(service: TCDSHooksService); begin FServices.Add(service.id, service); end; { TCDSHooksService } constructor TCDSHooksService.Create; begin inherited; FEngines := TList<TCDSHooksProcessorClass>.create; end; function TCDSHooksService.description: String; begin raise Exception.Create('Must override description() in '+className); end; procedure TCDSHooksService.HandleRequest(base : String; server: TFHIRServerContext; secure: boolean; session: TFHIRSession; context: TIdContext; request: TIdHTTPRequestInfo; response: TIdHTTPResponseInfo); var jrequest : TJsonObject; req : TCDSHookRequest; resp : TCDSHookResponse; begin require(request.CommandType = hcPOST, 'Request to cds-hooks service must be a POST'); require(request.ContentType = 'application/json', 'Request to cds-hooks service must be a POST'); require((request.PostStream <> nil) and (request.PostStream.Size > 0), 'Request to cds-hooks service must include a body'); try jrequest := TJSONParser.Parse(request.PostStream); try req := TCDSHookRequest.Create(jrequest); try req.lang := request.AcceptLanguage; req.baseURL := base; resp := HandleRequest(server, secure, session, context, req); try response.ResponseNo := 200; response.ResponseText := 'OK'; response.ContentType := 'application/json'; response.ContentText := resp.asJson; finally resp.free; end; finally req.free; end; finally jrequest.Free; end; except on e : Exception do begin response.ResponseNo := 200; response.ResponseText := 'OK'; response.ContentType := 'test/plain'; response.ContentText := e.Message; end; end; end; destructor TCDSHooksService.Destroy; begin FEngines.Free; inherited; end; function TCDSHooksService.HandleRequest(server: TFHIRServerContext; secure: boolean; session: TFHIRSession; context: TIdContext; request: TCDSHookRequest): TCDSHookResponse; begin raise Exception.Create('Must override HandleRequest in '+className); end; function TCDSHooksService.hook: string; begin raise Exception.Create('Must override hook() in '+className); end; function TCDSHooksService.id: String; begin result := hook; end; function TCDSHooksService.name: String; begin raise Exception.Create('Must override name() in '+className); end; function TCDSHooksService.ProcessRequestEngines(server: TFHIRServerContext; secure: boolean; session: TFHIRSession; context: TIdContext; request: TCDSHookRequest; response: TCDSHookResponse): boolean; var client : TFhirClient; t : TCDSHooksProcessorClass; p : TCDSHooksProcessor; begin if FEngines.Count = 0 then exit(false); client := server.Storage.createClient('en', server.ValidatorContext, session); try for t in FEngines do begin p := t.Create; try p.request := request.Link; p.response := response.Link; p.Client := client.link; if p.execute then exit(true); finally p.Free; end; end; server.Storage.Yield(client, nil); except on e : Exception do begin server.Storage.Yield(client, e); raise; end; end; end; procedure TCDSHooksService.registerPreFetch(json: TJsonObject); begin end; Procedure TCDSHooksService.require(test: boolean; msg: String); begin if not test then raise Exception.Create(msg); end; { TCDSHooksProcessor } function TCDSHooksProcessor.addCard(summary, detail, indicator, sourceLabel, sourceUrl : String): TCDSHookCard; begin result := TCDSHookCard.Create; try result.summary := summary; result.detail := detail; result.indicator := indicator; result.sourceLabel := sourceLabel; result.sourceURL := sourceUrl; response.cards.Add(result.Link); finally result.free; end; end; destructor TCDSHooksProcessor.Destroy; begin Frequest.Free; Fresponse.Free; FClient.Free; inherited; end; function TCDSHooksProcessor.execute: boolean; begin result := false; end; function TCDSHooksProcessor.Link: TCDSHooksProcessor; begin result := TCDSHooksProcessor(inherited Link); end; procedure TCDSHooksProcessor.SetClient(const Value: TFhirClient); begin FClient.Free; FClient := Value; end; procedure TCDSHooksProcessor.Setrequest(const Value: TCDSHookRequest); begin Frequest.Free; Frequest := Value; end; procedure TCDSHooksProcessor.Setresponse(const Value: TCDSHookResponse); begin Fresponse.Free; Fresponse := Value; end; end.
unit TextEditor.Colors; interface uses System.Classes, System.UITypes, TextEditor.Types; type TTextEditorColors = class(TPersistent) strict private FBackground: TColor; FForeground: TColor; FOnChange: TTextEditorCodeColorEvent; FReservedWord: TColor; procedure SetBackground(const AColor: TColor); procedure SetForeground(const AColor: TColor); public constructor Create; procedure Assign(ASource: TPersistent); override; published property Background: TColor read FBackground write SetBackground default TColors.SysWindow; property Foreground: TColor read FForeground write SetForeground default TColors.SysWindowText; property OnChange: TTextEditorCodeColorEvent read FOnChange write FOnChange; property ReservedWord: TColor read FReservedWord write FReservedWord default TColors.SysWindowText; end; implementation constructor TTextEditorColors.Create; begin inherited; FBackground := TColors.SysWindow; FForeground := TColors.SysWindowText; FReservedWord := TColors.SysWindowText; end; procedure TTextEditorColors.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorColors) then with ASource as TTextEditorColors do begin Self.FBackground := FBackground; Self.FForeground := FForeground; Self.FReservedWord := FReservedWord; if Assigned(Self.FOnChange) then Self.FOnChange(ccBoth); end else inherited Assign(ASource); end; procedure TTextEditorColors.SetBackground(const AColor: TColor); begin if AColor <> FBackground then begin FBackground := AColor; if Assigned(FOnChange) then FOnChange(ccBackground); end; end; procedure TTextEditorColors.SetForeground(const AColor: TColor); begin if AColor <> FForeground then begin FForeground := AColor; if Assigned(FOnChange) then FOnChange(ccForeground); end; end; end.
{***************************************************************************} { } { DelphiUIAutomation } { } { Copyright 2015 JHC Systems Limited } { } {***************************************************************************} { } { 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 HostMain; interface uses RestServer, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Menus, Vcl.Grids, Vcl.Mask, Vcl.ToolWin, Vcl.ExtCtrls, Vcl.ImgList, System.ImageList, Vcl.Buttons; type TForm1 = class(TForm) Edit2: TEdit; Button1: TButton; Button2: TButton; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; TabSheet3: TTabSheet; Edit3: TEdit; Edit4: TEdit; Edit5: TEdit; CheckBox1: TCheckBox; CheckBox2: TCheckBox; RadioButton1: TRadioButton; RadioButton2: TRadioButton; RadioButton3: TRadioButton; StatusBar1: TStatusBar; ComboBox1: TComboBox; MainMenu1: TMainMenu; File1: TMenuItem; Hel1: TMenuItem; Exit1: TMenuItem; About1: TMenuItem; PopupMenu1: TPopupMenu; PopupMenu2: TMenuItem; AutomatedEdit1: TEdit; AutomatedCombobox1: TCombobox; AutomatedCombobox2: TCombobox; AutomationStringGrid1: TStringGrid; AutomatedMaskEdit1: TMaskEdit; RichEdit1: TRichEdit; TreeView1: TTreeView; PopupMenu3: TPopupMenu; Popup11: TMenuItem; Popup21: TMenuItem; Edit1: TEdit; ListBox1: TListBox; LinkLabel1: TLinkLabel; Panel6: TPanel; Panel7: TPanel; ToolBar1: TToolBar; ToolButton3: TToolButton; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton4: TToolButton; Panel8: TPanel; ToolBar2: TToolBar; ToolButton5: TToolButton; ToolButton6: TToolButton; ToolButton7: TToolButton; ToolButton8: TToolButton; ImageList1: TImageList; AutomatedStaticText1: TStaticText; ListBox2: TListBox; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; SpeedButton3: TSpeedButton; Button3: TButton; PopupMenu4: TPopupMenu; Menu11: TMenuItem; Menu21: TMenuItem; Menu31: TMenuItem; procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure PopupMenu2Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ToolButton1Click(Sender: TObject); procedure ToolButton5Click(Sender: TObject); procedure ToolButton7Click(Sender: TObject); procedure LinkLabel1Click(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button3Click(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure SpeedButton3Click(Sender: TObject); procedure ToolButton2Click(Sender: TObject); procedure ToolButton4Click(Sender: TObject); private { Private declarations } FRestServer : TRestServer; procedure CreateServer(port: word); procedure DestroyServer; procedure LogMessage(const msg: String); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin ShowMessage (edit1.Text + ' | ' + edit2.Text); end; procedure TForm1.Button2Click(Sender: TObject); begin ShowMessage ('Cancelled'); end; procedure TForm1.Button3Click(Sender: TObject); begin ShowMessage(self.caption); end; procedure TForm1.Exit1Click(Sender: TObject); begin ShowMessage('Oh well done'); end; procedure TForm1.FormCreate(Sender: TObject); begin createServer(4723); AutomationStringGrid1.Cells[0,0] := 'Title 1'; AutomationStringGrid1.Cells[1,0] := 'Title 2'; AutomationStringGrid1.Cells[2,0] := 'Title 3'; AutomationStringGrid1.Cells[3,0] := 'Title 4'; AutomationStringGrid1.Cells[4,0] := 'Title 5'; AutomationStringGrid1.Cells[0,1] := 'Row 1, Col 0'; AutomationStringGrid1.Cells[1,1] := 'Row 1, Col 1'; AutomationStringGrid1.Cells[2,1] := 'Row 1, Col 2'; AutomationStringGrid1.Cells[3,1] := 'Row 1, Col 3'; AutomationStringGrid1.Cells[4,1] := 'Row 1, Col 4'; AutomationStringGrid1.Cells[0,3] := 'Row 3, Col 0'; AutomationStringGrid1.Cells[1,3] := 'Row 3, Col 1'; AutomationStringGrid1.Cells[2,3] := 'Row 3, Col 2'; AutomationStringGrid1.Cells[3,3] := 'Row 3, Col 3'; AutomationStringGrid1.Cells[4,3] := 'Row 3, Col 4'; end; procedure TForm1.FormDestroy(Sender: TObject); begin FRestServer.Free; end; procedure TForm1.LinkLabel1Click(Sender: TObject); begin ShowMessage ('LinkLabel1Click'); end; procedure TForm1.PopupMenu2Click(Sender: TObject); begin ShowMessage ('Popup menu clicked'); end; procedure TForm1.SpeedButton1Click(Sender: TObject); begin ShowMessage('SpeedButton1Click'); end; procedure TForm1.SpeedButton2Click(Sender: TObject); begin ShowMessage('SpeedButton2Click'); end; procedure TForm1.SpeedButton3Click(Sender: TObject); begin ShowMessage('SpeedButton3Click'); end; procedure TForm1.ToolButton1Click(Sender: TObject); begin ShowMessage ('ToolButton1Click'); end; procedure TForm1.ToolButton2Click(Sender: TObject); begin ShowMessage ('ToolButton2Click'); end; procedure TForm1.ToolButton4Click(Sender: TObject); begin ShowMessage ('ToolButton4Click'); end; procedure TForm1.ToolButton5Click(Sender: TObject); begin ShowMessage ('ToolButton5Click'); end; procedure TForm1.ToolButton7Click(Sender: TObject); begin ShowMessage ('ToolButton7Click'); end; procedure TForm1.CreateServer(port: word); begin FRestServer := TRestServer.Create(self); FRestServer.OnLogMessage := LogMessage; FRestServer.Start(port); end; procedure TForm1.DestroyServer; begin FRestServer.Free; end; procedure TForm1.LogMessage(const msg: String); begin ListBox2.Items.Add(msg); end; end.
unit HJYClassHelper; interface uses Windows, SysUtils, dxSpreadSheetCore, cxGridTableView, cxCurrencyEdit, cxSpinEdit, cxGridCustomTableView, Variants, Generics.Collections, cxTL; type TdxSpreadSheetCellHelper = class helper for TdxSpreadSheetCell public procedure ClearFormula; end; TdxSpreadSheetTableColumnHelper = class helper for TdxSpreadSheetTableColumn public procedure ApplyBestFitEx; end; TdxSpreadSheetTableViewHelper = class helper for TdxSpreadSheetTableView public function FindRowIndexByTagName(ATagName: string; AColumnIndex: Integer = 0): Integer; function GetCellString(ARow, ACol: Integer; ADefault: string = ''): string; function GetCellFloat(ARow, ACol: Integer; ADefault: Double = 0): Double; function GetCellCurrency(ARow, ACol: Integer; ADefault: Currency = 0): Currency; function GetCellInteger(ARow, ACol: Integer; ADefault: Integer = 0): Integer; function GetCellVariant(ARow, ACol: Integer): Variant; function GetCellDateTimeStr(ARow, ACol: Integer): string; function GetCellDateStr(ARow, ACol: Integer): string; function CellIsNull(ARow, ACol: Integer): Boolean; function DoGetCells(ARow, ACol: Integer): TdxSpreadSheetCell; procedure ClearCellFormula(ARow, ACol: Integer); procedure SetCellLocked(ARow, ACol: Integer; ALocked: Boolean = True); function GetFirstCellInMergeArea(ARow, ACol: Integer): TdxSpreadSheetCell; function GetMergeCellString(ARow, ACol: Integer; ADefault: string = ''): string; end; TcxGridTableViewHelper = class helper for TcxGridTableView private procedure ColumnGetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: string); public procedure HideZero; end; TcxTreeListHelper = class helper for TcxCustomTreeList public procedure ShowCheckBox(AShow: Boolean = True); function Search(AText: string; AColumn: TcxTreeListColumn; ACycle: Boolean = True): Boolean; end; implementation { TdxSpreadSheetCellHelper } procedure TdxSpreadSheetCellHelper.ClearFormula; begin if IsFormula then PObject(@FData)^.Free; end; { TdxSpreadSheetTableColumnHelper } procedure TdxSpreadSheetTableColumnHelper.ApplyBestFitEx; var ASize: Integer; begin if Visible then begin ASize := CalculateBestFit; if ASize = 0 then ASize := Owner.DefaultSize; if ASize > Size then SetSize(ASize); IsCustomSize := False; end; end; { TdxSpreadSheetTableViewHelper } function TdxSpreadSheetTableViewHelper.CellIsNull(ARow, ACol: Integer): Boolean; var lCell: TdxSpreadSheetCell; begin lCell := Cells[ARow, ACol]; if Assigned(lCell) then Result := VarIsEmpty(lCell.AsVariant) or VarIsNull(lCell.AsVariant) else Result := True; end; procedure TdxSpreadSheetTableViewHelper.ClearCellFormula(ARow, ACol: Integer); var lCell: TdxSpreadSheetCell; begin lCell := Cells[ARow, ACol]; lCell.ClearFormula; end; function TdxSpreadSheetTableViewHelper.DoGetCells(ARow, ACol: Integer): TdxSpreadSheetCell; begin Result := Cells[ARow, ACol]; if Result = nil then Result:= CreateCell(ARow, ACol); end; function TdxSpreadSheetTableViewHelper.FindRowIndexByTagName(ATagName: string; AColumnIndex: Integer): Integer; var I: Integer; lCell: TdxSpreadSheetCell; begin for I := 0 to Rows.Count - 1 do begin lCell := GetFirstCellInMergeArea(I, AColumnIndex); //Cells[I, AColumnIndex]; if Assigned(lCell) and SameText(ATagName, Trim(lCell.AsString)) then begin Result := I; Exit; end; end; Result := -1; end; function TdxSpreadSheetTableViewHelper.GetCellCurrency(ARow, ACol: Integer; ADefault: Currency): Currency; var lCell: TdxSpreadSheetCell; begin lCell := Cells[ARow, ACol]; if Assigned(lCell) then Result := lCell.AsCurrency else Result := ADefault; end; function TdxSpreadSheetTableViewHelper.GetCellDateTimeStr(ARow, ACol: Integer): string; var lStr: string; lDt: TDateTime; begin lStr := Trim(GetCellString(ARow, ACol)); if (lStr <> '') and TryStrToDateTime(lStr, lDt) then Result := QuotedStr(DateTimeToStr(lDt)) else Result := 'null'; end; function TdxSpreadSheetTableViewHelper.GetCellDateStr(ARow, ACol: Integer): string; var lStr: string; lDt: TDateTime; lCell: TdxSpreadSheetCell; begin Result := 'null'; lCell := Cells[ARow, ACol]; if not Assigned(lCell) then Exit; lStr := Trim(lCell.AsString); if (lStr <> '') then begin if TryStrToDate(lStr, lDt) then Result := QuotedStr(DateToStr(lDt)) else begin try Result := QuotedStr(DateToStr(lCell.AsDateTime)); except Result := 'null'; end; end; end; end; function TdxSpreadSheetTableViewHelper.GetCellFloat(ARow, ACol: Integer; ADefault: Double): Double; var lCell: TdxSpreadSheetCell; begin lCell := Cells[ARow, ACol]; if Assigned(lCell) and (Trim(lCell.AsString) <> '#DIV/0!') then Result := lCell.AsFloat else Result := ADefault; end; function TdxSpreadSheetTableViewHelper.GetCellInteger(ARow, ACol: Integer; ADefault: Integer): Integer; var lCell: TdxSpreadSheetCell; begin lCell := Cells[ARow, ACol]; if Assigned(lCell) then Result := lCell.AsInteger else Result := ADefault; end; function TdxSpreadSheetTableViewHelper.GetCellString(ARow, ACol: Integer; ADefault: string): string; var lCell: TdxSpreadSheetCell; begin lCell := Cells[ARow, ACol]; if Assigned(lCell) then Result := lCell.AsString else Result := ADefault; end; function TdxSpreadSheetTableViewHelper.GetCellVariant(ARow, ACol: Integer): Variant; var lCell: TdxSpreadSheetCell; begin lCell := Cells[ARow, ACol]; if Assigned(lCell) then Result := lCell.AsVariant else Result := Null; end; function TdxSpreadSheetTableViewHelper.GetFirstCellInMergeArea(ARow, ACol: Integer): TdxSpreadSheetCell; var ACoordinates: TPoint; begin if Assigned(MergedCells) then begin ACoordinates := MergedCells.CheckCell(ARow, ACol).TopLeft; Result := Cells[ACoordinates.Y, ACoordinates.X]; end else Result := nil; end; function TdxSpreadSheetTableViewHelper.GetMergeCellString(ARow, ACol: Integer; ADefault: string): string; var lCell: TdxSpreadSheetCell; begin lCell := GetFirstCellInMergeArea(ARow, ACol); if Assigned(lCell) then Result := lCell.AsString else Result := ADefault; end; procedure TdxSpreadSheetTableViewHelper.SetCellLocked(ARow, ACol: Integer; ALocked: Boolean); var lCell: TdxSpreadSheetCell; begin lCell := DoGetCells(ARow, ACol); lCell.Style.Locked := ALocked; end; { TcxGridTableViewHelper } procedure TcxGridTableViewHelper.ColumnGetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: string); var lValue: Variant; begin lValue := ARecord.Values[Sender.Index]; if VarIsNull(lValue) or VarIsEmpty(lValue) then AText := '' else if lValue = 0 then AText := ''; end; procedure TcxGridTableViewHelper.HideZero; var I: Integer; lColumn: TcxGridColumn; begin for I := 0 to ColumnCount - 1 do begin lColumn := Columns[I]; if (lColumn.PropertiesClass = TcxCurrencyEditProperties) or (lColumn.PropertiesClass = TcxSpinEditProperties) then begin if not Assigned(lColumn.OnGetDisplayText) then lColumn.OnGetDisplayText := ColumnGetDisplayText; end; end; end; { TcxTreeListHelper } function TcxTreeListHelper.Search(AText: string; AColumn: TcxTreeListColumn; ACycle: Boolean): Boolean; var lNode: TcxTreeListNode; function FindNode(ABeginNode: TcxTreeListNode): TcxTreeListNode; begin Result := Self.FindNodeByText('%' + AText + '%', AColumn, ABeginNode, False, True, False, tlfmLike, nil, True); end; begin lNode := FindNode(Self.FocusedNode); Result := Assigned(lNode); if (Result = False) and (ACycle = True) then begin lNode := FindNode(Self.Root); Result := Assigned(lNode); if not Result then Exit; end; Self.FocusedNode := lNode; Self.FocusedNode.MakeVisible; end; procedure TcxTreeListHelper.ShowCheckBox(AShow: Boolean); var lvNode: TcxTreeListNode; begin Self.BeginUpdate; try OptionsView.CheckGroups := AShow; Root.CheckGroupType := ncgCheckGroup; lvNode := Root.getFirstChild; while Assigned(lvNode) do begin if lvNode.HasChildren then lvNode.CheckGroupType := ncgCheckGroup; lvNode := lvNode.GetNext; end; finally Self.EndUpdate; end; end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Scene3D.Renderer.Passes.AntialiasingTAAPreCustomPass; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$m+} interface uses SysUtils, Classes, Math, Vulkan, PasVulkan.Types, PasVulkan.Math, PasVulkan.Framework, PasVulkan.Application, PasVulkan.FrameGraph, PasVulkan.Scene3D, PasVulkan.Scene3D.Renderer.Globals, PasVulkan.Scene3D.Renderer, PasVulkan.Scene3D.Renderer.Instance; type { TpvScene3DRendererPassesAntialiasingTAAPreCustomPass } TpvScene3DRendererPassesAntialiasingTAAPreCustomPass=class(TpvFrameGraph.TCustomPass) private fInstance:TpvScene3DRendererInstance; public constructor Create(const aFrameGraph:TpvFrameGraph;const aInstance:TpvScene3DRendererInstance); reintroduce; destructor Destroy; override; procedure AcquirePersistentResources; override; procedure ReleasePersistentResources; override; procedure AcquireVolatileResources; override; procedure ReleaseVolatileResources; override; procedure Update(const aUpdateInFlightFrameIndex,aUpdateFrameIndex:TpvSizeInt); override; procedure Execute(const aCommandBuffer:TpvVulkanCommandBuffer;const aInFlightFrameIndex,aFrameIndex:TpvSizeInt); override; end; implementation { TpvScene3DRendererPassesAntialiasingTAAPreCustomPass } constructor TpvScene3DRendererPassesAntialiasingTAAPreCustomPass.Create(const aFrameGraph:TpvFrameGraph;const aInstance:TpvScene3DRendererInstance); begin inherited Create(aFrameGraph); fInstance:=aInstance; Name:='AntialiasingTAAPreCustomPass'; end; destructor TpvScene3DRendererPassesAntialiasingTAAPreCustomPass.Destroy; begin inherited Destroy; end; procedure TpvScene3DRendererPassesAntialiasingTAAPreCustomPass.AcquirePersistentResources; begin inherited AcquirePersistentResources; end; procedure TpvScene3DRendererPassesAntialiasingTAAPreCustomPass.ReleasePersistentResources; begin inherited ReleasePersistentResources; end; procedure TpvScene3DRendererPassesAntialiasingTAAPreCustomPass.AcquireVolatileResources; begin inherited AcquireVolatileResources; end; procedure TpvScene3DRendererPassesAntialiasingTAAPreCustomPass.ReleaseVolatileResources; begin inherited ReleaseVolatileResources; end; procedure TpvScene3DRendererPassesAntialiasingTAAPreCustomPass.Update(const aUpdateInFlightFrameIndex,aUpdateFrameIndex:TpvSizeInt); begin inherited Update(aUpdateInFlightFrameIndex,aUpdateFrameIndex); end; procedure TpvScene3DRendererPassesAntialiasingTAAPreCustomPass.Execute(const aCommandBuffer:TpvVulkanCommandBuffer;const aInFlightFrameIndex,aFrameIndex:TpvSizeInt); var ImageMemoryBarriers:array[0..1] of TVkImageMemoryBarrier; PreviousInFlightFrameIndex:TpvSizeInt; begin inherited Execute(aCommandBuffer,aInFlightFrameIndex,aFrameIndex); PreviousInFlightFrameIndex:=FrameGraph.DrawPreviousInFlightFrameIndex; ImageMemoryBarriers[0]:=TVkImageMemoryBarrier.Create(TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT), TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT), TVkImageLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL), TVkImageLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL), VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, fInstance.TAAHistoryColorImages[FrameGraph.ConvertRelativeToAbsoluteInFlightFrameIndex(aInFlightFrameIndex,-1)].VulkanImage.Handle, TVkImageSubresourceRange.Create(TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT), 0, 1, 0, fInstance.CountSurfaceViews)); ImageMemoryBarriers[1]:=TVkImageMemoryBarrier.Create(TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT), TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT), TVkImageLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL), TVkImageLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL), VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, fInstance.TAAHistoryDepthImages[FrameGraph.ConvertRelativeToAbsoluteInFlightFrameIndex(aInFlightFrameIndex,-1)].VulkanImage.Handle, TVkImageSubresourceRange.Create(TVkImageAspectFlags(VK_IMAGE_ASPECT_DEPTH_BIT), 0, 1, 0, fInstance.CountSurfaceViews)); if (aInFlightFrameIndex<>PreviousInFlightFrameIndex) and fInstance.fTAAEventReady[PreviousInFlightFrameIndex] then begin fInstance.fTAAEventReady[PreviousInFlightFrameIndex]:=false; aCommandBuffer.CmdWaitEvents(1, @fInstance.fTAAEvents[PreviousInFlightFrameIndex].Handle, TVkPipelineStageFlags(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT){ TVkPipelineStageFlags(VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT)}, TVkPipelineStageFlags(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT){ TVkPipelineStageFlags(VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT)}, 0,nil, 0,nil, 2,@ImageMemoryBarriers[0]); aCommandBuffer.CmdResetEvent(fInstance.fTAAEvents[PreviousInFlightFrameIndex].Handle, TVkPipelineStageFlags(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT){ TVkPipelineStageFlags(VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT)}); end else begin aCommandBuffer.CmdPipelineBarrier(TVkPipelineStageFlags(VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT), TVkPipelineStageFlags(VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) or TVkPipelineStageFlags(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT), TVkDependencyFlags(VK_DEPENDENCY_BY_REGION_BIT), 0,nil, 0,nil, 2,@ImageMemoryBarriers[0]); end; end; end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Grids, Vcl.Menus, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnList, Vcl.ActnMan, Vcl.StdCtrls, Vcl.Buttons, Common, MsgList, Vcl.ComCtrls; type TfrmMain = class(TForm) MM: TMainMenu; File1: TMenuItem; NewGame1: TMenuItem; HighScores1: TMenuItem; N1: TMenuItem; Exit1: TMenuItem; Options1: TMenuItem; Options2: TMenuItem; Difficulty1: TMenuItem; Easy1: TMenuItem; Medium1: TMenuItem; Hard1: TMenuItem; Custom1: TMenuItem; Actions: TActionManager; actNewGame: TAction; actExit: TAction; actOptions: TAction; actSetEasy: TAction; actSetMedium: TAction; actSetHard: TAction; actSetCustom: TAction; actResetGame: TAction; Shape1: TShape; tmrTime: TTimer; Pages: TPageControl; tabField: TTabSheet; pTop: TPanel; lblMines: TLabel; lblTime: TLabel; cmdMain: TBitBtn; Field: TStringGrid; tabOptions: TTabSheet; tabHighScores: TTabSheet; tabEnterHighScore: TTabSheet; View1: TMenuItem; MineField1: TMenuItem; Options3: TMenuItem; HighScores2: TMenuItem; procedure FormCreate(Sender: TObject); procedure FieldDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure actOptionsExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure actResetGameExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FieldMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FieldMouseLeave(Sender: TObject); procedure FieldMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure actNewGameExecute(Sender: TObject); procedure tmrTimeTimer(Sender: TObject); procedure pTopResize(Sender: TObject); procedure actSetEasyExecute(Sender: TObject); procedure actSetMediumExecute(Sender: TObject); procedure actSetHardExecute(Sender: TObject); private FLoaded: Boolean; FOptions: TOptions; FCurBox: TBox; FMines: TIntArray; FStarted: TDateTime; FEnded: TDateTime; FWon: Boolean; FWinMsg: TMsgList; FLoseMsg: TMsgList; FNewMsg: TMsgList; procedure ResetGame; procedure ResizeGrid; function TouchCount(ACol, ARow: Integer): Integer; function GetCell(ACol, ARow: Integer): TBox; procedure FloodOpen(ACol, ARow: Integer); procedure UpdateCount; procedure CheckEnded; procedure EndGame(Won: Boolean); function FlaggedCount: Integer; function CalculateScore: Integer; procedure CreateMessages; function PromptNewGame: Boolean; public property Options: TOptions read FOptions write FOptions; property Cells[ACol, ARow: Integer]: TBox read GetCell; end; var frmMain: TfrmMain; implementation {$R *.dfm} uses uOptions, DateUtils, Math; { TfrmMain } procedure TfrmMain.FormCreate(Sender: TObject); var X: Integer; begin ReportMemoryLeaksOnShutdown:= True; FLoaded:= False; Pages.Align:= alClient; for X := 0 to Pages.PageCount-1 do begin Pages.Pages[X].TabVisible:= False; end; tabField.Show; Field.Align:= alClient; FWinMsg:= TMsgList.Create; FLoseMsg:= TMsgList.Create; FNewMsg:= TMsgList.Create; CreateMessages; FOptions.Difficulty:= dfEasy; FOptions.Width:= EASY_WIDTH; FOptions.Height:= EASY_HEIGHT; FOptions.Count:= EASY_COUNT; FOptions.BoxSize:= BOX_SIZE; FOptions.GameChanged:= False; FOptions.SizeChanged:= False; ResetGame; end; procedure TfrmMain.FormDestroy(Sender: TObject); var X, Y: Integer; B: TBox; begin for X := 0 to Field.RowCount - 1 do begin for Y := 0 to Field.ColCount - 1 do begin B:= TBox(Field.Objects[Y, X]); B.Free; end; end; FWinMsg.Free; FLoseMsg.Free; FNewMsg.Free; end; procedure TfrmMain.ResetGame; var X, Y, Z, I: Integer; B: TBox; begin tmrTime.Enabled:= False; Randomize; //First, clear data if FLoaded then begin for X := 0 to Field.RowCount - 1 do begin for Y := 0 to Field.ColCount - 1 do begin B:= Cells[Y, X]; B.Free; end; end; end; //Next, set counts and resize Field.ColCount:= FOptions.Width; Field.RowCount:= FOptions.Height; ResizeGrid; FLoaded:= True; //Then, populate data for X := 0 to Field.RowCount - 1 do begin for Y := 0 to Field.ColCount - 1 do begin B:= TBox.Create(X, Y); Field.Objects[Y, X]:= B; end; end; //Now, set mines in random places FMines:= Common.RandomRange(FOptions.Width * FOptions.Height, FOptions.Count); I:= 0; for X := 0 to Field.RowCount - 1 do begin for Y := 0 to Field.ColCount - 1 do begin B:= Cells[Y, X]; B.HasMine:= False; for Z := 0 to Length(FMines)-1 do begin if FMines[Z] = I then begin B.HasMine:= True; Break; end; end; Inc(I); end; end; //Finally, calculate mines touching each box for X := 0 to Field.RowCount - 1 do begin for Y := 0 to Field.ColCount - 1 do begin B:= Cells[Y, X]; B.Touching:= TouchCount(Y, X); end; end; UpdateCount; FStarted:= 0; FEnded:= 0; tmrTime.Enabled:= True; end; function TfrmMain.TouchCount(ACol, ARow: Integer): Integer; var B, T: TBox; begin Result:= 0; B:= Cells[ACol, ARow]; if ACol > 0 then begin if Cells[ACol-1, ARow].HasMine then Inc(Result); if ARow > 0 then if Cells[ACol-1, ARow-1].HasMine then Inc(Result); if ARow < Field.RowCount-1 then if Cells[ACol-1, ARow+1].HasMine then Inc(Result); end; if ACol < Field.ColCount-1 then begin if Cells[ACol+1, ARow].HasMine then Inc(Result); if ARow > 0 then if Cells[ACol+1, ARow-1].HasMine then Inc(Result); if ARow < Field.RowCount-1 then if Cells[ACol+1, ARow+1].HasMine then Inc(Result); end; if ARow > 0 then if Cells[ACol, ARow-1].HasMine then Inc(Result); if ARow < Field.RowCount-1 then if Cells[ACol, ARow+1].HasMine then Inc(Result); end; procedure TfrmMain.ResizeGrid; var X, DW, DH: Integer; begin for X := 0 to Field.ColCount-1 do Field.ColWidths[X]:= FOptions.BoxSize; for X := 0 to Field.RowCount-1 do Field.RowHeights[X]:= FOptions.BoxSize; ClientWidth:= (FOptions.Width * FOptions.BoxSize) + 8; ClientHeight:= (FOptions.Height * FOptions.BoxSize) + pTop.Height + 10; //Center form with screen // This should be re-done to only move form onto screen if it's outside Left:= (Screen.Width div 2) - (Width div 2); Top:= (Screen.Height div 2) - (Height div 2); end; procedure TfrmMain.tmrTimeTimer(Sender: TObject); var T: Integer; begin //Calculate time elapsed if (FStarted <> 0) and (FEnded = 0) then begin T:= SecondsBetween(FStarted, Now); lblTime.Caption:= IntToStr(T)+' secs'; end; end; function TfrmMain.PromptNewGame: Boolean; begin Result:= MessageDlg(FNewMsg.RandomMsg, mtWarning, [mbYes,mbNo], 0) = mrYes; end; procedure TfrmMain.FormShow(Sender: TObject); begin ResetGame; end; function TfrmMain.GetCell(ACol, ARow: Integer): TBox; begin Result:= TBox(Field.Objects[ACol, ARow]); end; procedure TfrmMain.pTopResize(Sender: TObject); begin cmdMain.Left:= (pTop.ClientWidth div 2) - (cmdMain.Width div 2); end; procedure TfrmMain.actNewGameExecute(Sender: TObject); begin case MessageDlg(FNewMsg.RandomMsg, mtWarning, [mbYes,mbNo], 0) of mrYes: begin ResetGame; end; end; end; procedure TfrmMain.actOptionsExecute(Sender: TObject); var Opt: TfrmOptions; begin Opt:= TfrmOptions.Create(FOptions); try Opt.ShowModal; FOptions:= Opt.Options; if FOptions.SizeChanged then begin ResizeGrid; end; if FOptions.GameChanged then begin ResetGame; end; finally Opt.Free; end; end; procedure TfrmMain.actResetGameExecute(Sender: TObject); begin ResetGame; end; procedure TfrmMain.actSetEasyExecute(Sender: TObject); begin //Set Easy end; procedure TfrmMain.actSetHardExecute(Sender: TObject); begin //Set Hard end; procedure TfrmMain.actSetMediumExecute(Sender: TObject); begin //Set Mediu end; procedure TfrmMain.FloodOpen(ACol, ARow: Integer); var B: TBox; procedure Chk(const C, R: Integer); var T: TBox; begin T:= Cells[C, R]; if (T.Status = bsNone) and (not T.HasMine) then begin T.Status:= bsEmpty; if T.Touching = 0 then FloodOpen(C, R); end; end; begin //Open all empty cells surrounding current B:= Cells[ACol, ARow]; if ACol > 0 then begin Chk(ACol-1, ARow); if ARow > 0 then Chk(ACol-1, ARow-1); if ARow < Field.RowCount-1 then Chk(ACol-1, ARow+1); end; if ACol < Field.ColCount-1 then begin Chk(ACol+1, ARow); if ARow > 0 then Chk(ACol+1, ARow-1); if ARow < Field.RowCount-1 then Chk(ACol+1, ARow+1); end; if ARow > 0 then Chk(ACol, ARow-1); if ARow < Field.RowCount-1 then Chk(ACol, ARow+1); end; function TfrmMain.CalculateScore: Integer; var MC, CC, TM, TN, EM: Integer; begin MC:= FOptions.Count; //Total Mine Count CC:= (FOptions.Width * FOptions.Height); //Total Cell Count TM:= SecondsBetween(FStarted, FEnded); //Seconds taken to complete EM:= CC - MC; //Total empty cell count //TN:= EM * 5; //Time needed TN:= MC * 10; Result:= TN - TM; end; procedure TfrmMain.EndGame(Won: Boolean); begin FEnded:= Now; FWon:= Won; if FWon then begin //Calculate score if MessageDlg(FWinMsg.RandomMsg + sLineBreak + 'Score: '+IntToStr(CalculateScore) + sLineBreak + 'Would you like to start a new game?', mtInformation, [mbYes,mbNo], 0) = mrYes then begin ResetGame; end; end else begin if MessageDlg(FLoseMsg.RandomMsg + sLineBreak + 'Would you like to start a new game?', mtInformation, [mbYes,mbNo], 0) = mrYes then begin ResetGame; end; end; end; function TfrmMain.FlaggedCount: Integer; var X, Y: Integer; B: TBox; begin Result:= 0; for X := 0 to Field.RowCount-1 do begin for Y := 0 to Field.ColCount-1 do begin B:= Cells[Y, X]; if B.Status = bsFlagged then Inc(Result); end; end; end; procedure TfrmMain.CheckEnded; var X, Y, F, N: Integer; B: TBox; begin //Check if all empty cells are opened and mines are flagged F:= 0; //Flagged N:= 0; //Not Opened for X := 0 to Field.RowCount-1 do begin for Y := 0 to Field.ColCount-1 do begin B:= Cells[Y, X]; case B.Status of bsNone, bsUnknown: Inc(N); bsFlagged: Inc(F); end; end; end; if (F = FOptions.Count) and (N = 0) then begin EndGame(True); end; end; procedure TfrmMain.CreateMessages; begin //Win Messages FWinMsg.Clear; FWinMsg.Add('You''ve cleared all the mines!'); FWinMsg.Add('Way to go!'); FWinMsg.Add('That''s what I''m talkin'' bout, baby!'); FWinMsg.Add('That was fucking awesome.'); FWinMsg.Add('You fucking rawk!'); FWinMsg.Add('You saved the day!'); FWinMsg.Add('Keep that shit up pal!'); //FWinMsg.Add(''); //Lose Messages FLoseMsg.Clear; FLoseMsg.Add('What the fuck was that?'); FLoseMsg.Add('You fucking suck.'); FLoseMsg.Add('BOOM! You just killed everyone.'); FLoseMsg.Add('You''re fucking dead.'); FLoseMsg.Add('Your body has been blown to bits.'); FLoseMsg.Add('Killed In Action.'); FLoseMsg.Add('You''ve been fragged!'); FLoseMsg.Add('You''ve been pwned!'); //FLoseMsg.Add(''); //FLoseMsg.Add(''); //FLoseMsg.Add(''); //New Messages FNewMsg.Clear; FNewMsg.Add('Are you sure you want to start a new game?'); FNewMsg.Add('What? New game? Are you sure?'); FNewMsg.Add('Good luck in the field. Continue?'); FNewMsg.Add('Why so serious? New game?'); FNewMsg.Add('Do you absolutely positively want to start a new game?'); //FNewMsg.Add(''); //FNewMsg.Add(''); //FNewMsg.Add(''); //FNewMsg.Add(''); //FNewMsg.Add(''); end; procedure TfrmMain.FieldMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var B, T: TBox; C, R: Integer; XT, YT: Integer; begin if FEnded = 0 then begin Field.MouseToCell(X, Y, C, R); B:= TBox(Field.Objects[C, R]); case Button of TMouseButton.mbLeft: begin case B.Status of bsNone: begin if B.HasMine then begin B.Status:= bsHit; //Trigger hit and lose for XT := 0 to Field.RowCount-1 do begin for YT := 0 to Field.ColCount-1 do begin T:= Cells[YT, XT]; if T <> B then if T.HasMine then if B.Status = bsFlagged then T.Status:= bsShowMine else T.Status:= bsHit; end; end; EndGame(False); end else begin B.Status:= bsEmpty; if B.Touching = 0 then begin FloodOpen(C, R); end; end; end; end; end; TMouseButton.mbRight: begin case B.Status of bsNone: B.Status:= bsFlagged; bsFlagged: B.Status:= bsUnknown; bsUnknown: B.Status:= bsNone; end; end; end; UpdateCount; Field.Invalidate; if FStarted = 0 then FStarted:= Now; if FEnded = 0 then CheckEnded; end; end; procedure TfrmMain.UpdateCount; var X, Y, C: Integer; B: TBox; begin C:= FOptions.Count; for X := 0 to Field.RowCount-1 do begin for Y := 0 to Field.ColCount-1 do begin B:= Cells[Y, X]; if B.Status = bsFlagged then Dec(C); end; end; lblMines.Caption:= IntToStr(C)+' left'; end; procedure TfrmMain.FieldMouseLeave(Sender: TObject); begin if Assigned(FCurBox) then begin FCurBox.Hover:= False; Field.Invalidate; end; end; procedure TfrmMain.FieldMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var B: TBox; C, R: Integer; XT: Integer; YT: Integer; begin Field.MouseToCell(X, Y, C, R); B:= TBox(Field.Objects[C, R]); if B <> FCurBox then begin if Assigned(FCurBox) then FCurBox.Hover:= False; FCurBox:= B; B.Hover:= True; Field.Invalidate; end; end; procedure TfrmMain.FieldDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var C: TCanvas; Br: TBrush; Pn: TPen; B: TBox; R: TRect; procedure DrawNone; begin //Draw nothing end; procedure DrawEmpty; begin //Draw touch count, if > 0 if B.Touching > 0 then begin C.Font.Color:= clBlack; C.Font.Style:= [fsBold]; C.Font.Size:= 12; C.TextOut(R.Left, R.Top, ' '+IntToStr(B.Touching)); end; end; procedure DrawFlagged; begin //Draw flag InflateRect(R, -2, -2); C.Ellipse(R); end; procedure DrawUnknown; begin //Draw a question mark Pn.Style:= psSolid; Br.Style:= bsClear; C.Font.Color:= Pn.Color; C.Font.Style:= [fsBold]; C.Font.Size:= 12; C.TextOut(R.Left, R.Top, ' ?'); end; procedure DrawHit; begin //Draw a hit mine InflateRect(R, -2, -2); Pn.Color:= clRed; C.MoveTo(R.Left, R.Top); C.LineTo(R.Right, R.Bottom); C.MoveTo(R.Right, R.Top); C.LineTo(R.Left, R.Bottom); end; procedure DrawShowMine; begin //Draw an uncovered mine InflateRect(R, -2, -2); Br.Style:= bsSolid; Br.Color:= clGray; Pn.Color:= clGray; C.Ellipse(R); end; begin C:= Field.Canvas; Br:= C.Brush; Pn:= C.Pen; B:= TBox(Field.Objects[ACol, ARow]); if Assigned(B) then begin Br.Style:= bsSolid; case B.Status of bsNone, bsFlagged, bsUnknown: begin if B.Hover then Br.Color:= CLR_HOVER else Br.Color:= CLR_NONE; end; bsEmpty: begin Br.Color:= CLR_DOWN; end; bsHit: begin Br.Color:= clBlack; end; bsShowMine: begin Br.Color:= clNavy; end; end; Pn.Style:= psClear; C.FillRect(Rect); Pn.Style:= psSolid; Br.Style:= bsClear; Pn.Color:= CLR_LINE; Pn.Width:= 1; C.MoveTo(Rect.Right-1, Rect.Top); C.LineTo(Rect.Right-1, Rect.Bottom-1); C.MoveTo(Rect.Left, Rect.Bottom-1); C.LineTo(Rect.Right-1, Rect.Bottom-1); Pn.Color:= clWhite; Pn.Width:= 2; R:= Rect; case B.Status of bsNone: begin DrawNone; end; bsEmpty: begin DrawEmpty; end; bsFlagged: begin DrawFlagged; end; bsUnknown: begin DrawUnknown; end; bsHit: begin DrawHit; end; bsShowMine: begin DrawShowMine; end; end; end; end; end.
unit uFigura; interface uses Graphics, Windows, Classes, uDrawHook, uType, uFiguraInterface; type TFigura = class(TInterfacedObject, IFigura) private FCanvas : TCanvas; FColor : TColor; Position : TFiguraPos; procedure Draw; virtual; procedure Preview(ACanvas: TCanvas); virtual; function GetColor: TColor; procedure SetColor(const Value: TColor); public constructor Create(X: integer); virtual; abstract; procedure MoveLeft; virtual; abstract; procedure MoveRight; virtual; abstract; procedure MoveDown; virtual; abstract; procedure GrandfatherInherited(ACanvas: TCanvas); public property Canvas: TCanvas read FCanvas write FCanvas; property Color : TColor read GetColor write SetColor; // function GetPos : TFiguraPos; function GetLeftPoint : TPoint; function GetRightPoint: TPoint; function GetDownPoint : TPoint; end; // TBaseFigura = class of TFigura; TFiguraRotate = class(TFigura, IFiguraRotate) private FState : TFiguraState; function GetFiguraState: TFiguraState; procedure SetState(const Value: TFiguraState); public procedure Rotate; virtual; // Rotate one property State : TFiguraState read GetFiguraState write SetState default tsTop; end; TLine = Class(TFiguraRotate, IFigura, IFiguraRotate, ILine) public constructor Create(X: integer); override; procedure Preview(ACanvas: TCanvas); override; procedure MoveLeft; override; procedure MoveRight; override; procedure MoveDown; override; procedure Rotate; override; End; TL = Class(TFiguraRotate, IFigura, IFiguraRotate, IL) public constructor Create(X: integer); override; procedure Preview(ACanvas: TCanvas); override; procedure MoveLeft; override; procedure MoveRight; override; procedure MoveDown; override; procedure Rotate; override; End; T_l_ = Class(TFiguraRotate, IFigura, IFiguraRotate, I_l_) public constructor Create(X: integer); override; procedure Preview(ACanvas: TCanvas); override; procedure MoveLeft; override; procedure MoveRight; override; procedure MoveDown; override; procedure Rotate; override; End; TRect = Class(TFigura, IFigura, IRect) public constructor Create(X: integer); override; procedure Preview(ACanvas: TCanvas); override; procedure MoveLeft; override; procedure MoveRight; override; procedure MoveDown; override; End; TPoints = Class(TFigura, IFigura, IPoint) public constructor Create(X: integer); override; procedure Preview(ACanvas: TCanvas); override; procedure MoveLeft; override; procedure MoveRight; override; procedure MoveDown; override; End; function GetFigura(AType: TFiguraType; APosition: Integer): IFigura; implementation { -------------------------------------------------------------------------------------------------------------------- } function GetFigura(AType: TFiguraType; APosition: Integer): IFigura; begin case AType of tft_point: Result := TPoints.Create(APosition); tft_line : Result := TLine.Create(APosition); tft_Rect : Result := TRect.Create(APosition); tft_L : Result := TL.Create(APosition); tft_l_ : Result := T_l_.Create(APosition); else Result := TPoints.Create(APosition); end; end; function TFiguraRotate.GetFiguraState: TFiguraState; begin Result := FState; end; procedure TFiguraRotate.Rotate; begin If FState = tsBotom Then FState := tsLeft else FState := Succ(FState); end; procedure TFiguraRotate.SetState(const Value: TFiguraState); begin FState := Value; end; { ----------------------------------------------------- TFigura ------------------------------------------------------ } procedure TFigura.Draw; begin if Assigned(Surface) then Surface.DrawObject; end; procedure TFigura.GrandfatherInherited(ACanvas: TCanvas); // http://codes.com.ua/2014/05/kak-v-delphi-sdelat-inherited-metoda-ot-dedushki/ type TFigura_ = procedure(ACanvas: TCanvas) of object; var tmp: TFigura_; begin TMethod(tmp).Code := @TFigura.Preview; TMethod(tmp).Data := Self; tmp(ACanvas); end; function TFigura.GetColor: TColor; begin Result := FColor; end; function TFigura.GetDownPoint: TPoint; var I: Integer; begin Result := Point(0,0); For I := Low(Position) To High(Position) Do If Position[i].Y > Result.Y Then Result := Position[i]; end; function TFigura.GetLeftPoint: TPoint; var I: Integer; begin Result := Point(999,0); For I := Low(Position) To High(Position) Do If (Position[i].X < Result.X) and (Position[i].X > 0) Then Result := Position[i]; end; function TFigura.GetRightPoint: TPoint; var I: Integer; begin Result := Point(0,0); For I := Low(Position) To High(Position) Do If Position[i].X > Result.X Then Result := Position[i]; end; function TFigura.GetPos: TFiguraPos; begin Result := Position; end; procedure TFigura.Preview(ACanvas: TCanvas); begin with ACanvas do begin Brush.Color := clWhite; FillRect(Rect(0, 0, 100, 100)); Brush.Style := bsSolid; Brush.Color := Color; end; end; procedure TFigura.SetColor(const Value: TColor); begin FColor := Value; end; { ----------------------------------------------------- TPoints ------------------------------------------------------ } procedure TPoints.Preview(ACanvas: TCanvas); begin inherited Preview(ACanvas); ACanvas.Rectangle(25,25,40,40); end; constructor TPoints.Create(X: integer); begin Position[1].X := X; Position[1].Y := 4; Position[2].X := X; Position[2].Y := 4; Position[3].X := X; Position[3].Y := 4; Position[4].X := X; Position[4].Y := 4; end; procedure TPoints.MoveDown; begin Inc(Position[1].Y); Inc(Position[2].Y); Inc(Position[3].Y); Inc(Position[4].Y); end; procedure TPoints.MoveLeft; begin Dec(Position[1].X); Dec(Position[2].X); Dec(Position[3].X); Dec(Position[4].X); end; procedure TPoints.MoveRight; begin Inc(Position[1].X); Inc(Position[2].X); Inc(Position[3].X); Inc(Position[4].X); end; { -------------------------------------------- TLine ----------------------------------------------------------------- } constructor TLine.Create(X: Integer); begin Position[1].X := X; Position[1].Y := 4; Position[2].X := X+1; Position[2].Y := 4; Position[3].X := X+2; Position[3].Y := 4; Position[4].X := X+3; Position[4].Y := 4; end; procedure TLine.Preview(ACanvas: TCanvas); begin inherited Preview(ACanvas); with ACanvas do begin Rectangle(31,01,45,14); Rectangle(31,15,45,30); Rectangle(31,31,45,45); Rectangle(31,46,45,60); end; end; procedure TLine.MoveDown; begin Inc(Position[1].Y); Inc(Position[2].Y); Inc(Position[3].Y); Inc(Position[4].Y); end; procedure TLine.MoveLeft; begin Dec(Position[1].X); Dec(Position[2].X); Dec(Position[3].X); Dec(Position[4].X); end; procedure TLine.MoveRight; begin Inc(Position[1].X); Inc(Position[2].X); Inc(Position[3].X); Inc(Position[4].X); end; procedure TLine.Rotate; begin Case FState Of tsLeft, tsRight: begin Inc(Position[1].X); Dec(Position[1].Y); Dec(Position[3].X); Inc(Position[3].Y); Dec(Position[4].X); Inc(Position[4].Y); Dec(Position[4].X); Inc(Position[4].Y); end; tsTop, tsBotom: begin Dec(Position[1].X); Inc(Position[1].Y); Inc(Position[3].X); Dec(Position[3].Y); Inc(Position[4].X); Dec(Position[4].Y); Inc(Position[4].X); Dec(Position[4].Y); end; End; inherited Rotate; end; { ----------------------------------------------- TRect -------------------------------------------------------------- } constructor TRect.Create(X: integer); begin Position[1].X := X; Position[1].Y := 3; Position[2].X := X ; Position[2].Y := 4; Position[3].X := X+1; Position[3].Y := 3; Position[4].X := X+1; Position[4].Y := 4; end; procedure TRect.Preview(ACanvas: TCanvas); begin inherited Preview(ACanvas); with ACanvas do begin Rectangle(15,15,30,30); Rectangle(31,15,45,30); Rectangle(31,31,45,45); Rectangle(15,31,30,45); end; end; procedure TRect.MoveDown; begin Inc(Position[1].Y); Inc(Position[2].Y); Inc(Position[3].Y); Inc(Position[4].Y); end; procedure TRect.MoveLeft; begin Dec(Position[1].X); Dec(Position[2].X); Dec(Position[3].X); Dec(Position[4].X); end; procedure TRect.MoveRight; begin Inc(Position[1].X); Inc(Position[2].X); Inc(Position[3].X); Inc(Position[4].X); end; { ------------------------------------------------------ TL ---------------------------------------------------------- } constructor TL.Create(X: integer); begin Position[1].X := X; Position[1].Y := 2; Position[2].X := X; Position[2].Y := 3; Position[3].X := X; Position[3].Y := 4; Position[4].X := X-1; Position[4].Y := 4; FState := tsTop; end; procedure TL.MoveDown; begin Inc(Position[1].Y); Inc(Position[2].Y); Inc(Position[3].Y); Inc(Position[4].Y); end; procedure TL.MoveLeft; begin Dec(Position[1].X); Dec(Position[2].X); Dec(Position[3].X); Dec(Position[4].X); end; procedure TL.MoveRight; begin Inc(Position[1].X); Inc(Position[2].X); Inc(Position[3].X); Inc(Position[4].X); end; procedure TL.Preview(ACanvas: TCanvas); begin GrandfatherInherited(ACanvas); with ACanvas do begin Rectangle(31,01,45,14); Rectangle(31,15,45,30); Rectangle(31,31,45,45); Rectangle(15,31,30,45); end; end; procedure TL.Rotate; begin inherited Rotate; Case FState Of tsTop: begin Dec(Position[1].Y); Inc(Position[2].X); Inc(Position[3].X); Inc(Position[3].X); Inc(Position[3].Y); Dec(Position[4].X); end; tsRight: begin Dec(Position[1].X); Inc(Position[1].Y); Inc(Position[1].Y); Inc(Position[2].Y); Inc(Position[3].X); Dec(Position[4].Y); end; tsBotom: begin Inc(Position[1].X); Dec(Position[1].Y); Dec(Position[3].X); Inc(Position[3].Y); Inc(Position[4].X); Inc(Position[4].X); end; tsLeft: begin Inc(Position[1].X); Dec(Position[2].Y); Dec(Position[3].X); Dec(Position[3].Y); Dec(Position[3].Y); Inc(Position[4].Y); end; End; end; { ----------------------------------------------------- T_l_ --------------------------------------------------------- } constructor T_l_.Create(X: integer); begin Position[1].X := X-1; Position[1].Y := 4; Position[2].X := X; Position[2].Y := 4; Position[3].X := X+1; Position[3].Y := 4; Position[4].X := X; Position[4].Y := 3; FState := tsTop; end; procedure T_l_.MoveDown; begin Inc(Position[1].Y); Inc(Position[2].Y); Inc(Position[3].Y); Inc(Position[4].Y); end; procedure T_l_.MoveLeft; begin Dec(Position[1].X); Dec(Position[2].X); Dec(Position[3].X); Dec(Position[4].X); end; procedure T_l_.MoveRight; begin Inc(Position[1].X); Inc(Position[2].X); Inc(Position[3].X); Inc(Position[4].X); end; procedure T_l_.Preview(ACanvas: TCanvas); begin GrandfatherInherited(ACanvas); with ACanvas do begin Rectangle(31,01,45,14); Rectangle(31,15,45,30); Rectangle(31,31,45,45); Rectangle(15,15,30,30); end; end; procedure T_l_.Rotate; begin inherited Rotate; Case FState Of tsTop: begin Dec(Position[1].Y); Dec(Position[1].X); Inc(Position[3].Y); Inc(Position[3].X); Dec(Position[4].Y); Inc(Position[4].X); end; tsRight: begin Dec(Position[1].Y); Inc(Position[1].X); Inc(Position[3].Y); Dec(Position[3].X); Inc(Position[4].Y); Inc(Position[4].X); end; tsBotom: begin Inc(Position[1].Y); Inc(Position[1].X); Dec(Position[3].Y); Dec(Position[3].X); Inc(Position[4].Y); Dec(Position[4].X); end; tsLeft: begin Dec(Position[3].Y); Inc(Position[3].X); Inc(Position[1].Y); Dec(Position[1].X); Dec(Position[4].Y); Dec(Position[4].X); end; End; end; { -------------------------------------------------------------------------------------------------------------------- } end.
PROGRAM Encryption(INPUT, OUTPUT); {Переводит символы из INPUT в код согласно Chiper и печатает новые символы в OUTPUT} CONST MaxLen = 20; TYPE Str = ARRAY [1..MaxLen] OF 'A' .. 'Z'; Chiper = ARRAY [ 'A'..'Z'] OF CHAR; VAR Msg: Str; Code: Chiper; Len: INTEGER; FileCode: TEXT; Error: BOOLEAN; PROCEDURE Initialize(VAR FileCode: TEXT; VAR Code: Chiper; VAR Error: BOOLEAN); {Присвоить Code шифр замены} VAR Check, Ch: CHAR; BEGIN {Initialize} Error := FALSE; RESET(FileCode); WHILE (NOT EOF(FileCode)) AND (Error = FALSE) DO BEGIN Check := ' '; WHILE (NOT EOLN(FileCode)) AND (Check = ' ') DO READ(FileCode, Check); IF Check IN ['A'..'Z'] THEN BEGIN IF NOT EOLN(FileCode) THEN READ(FileCode, Ch); IF NOT EOLN(FileCode) THEN BEGIN READ(FileCode, Ch); Code[Check] := Ch END ELSE Error := TRUE; END ELSE Error := TRUE; WHILE NOT EOLN(FileCode) DO READ(FileCode, Check); IF NOT EOF THEN READLN(FileCode) END END; {Initialize} PROCEDURE Encode(VAR S: STR); {Выводит символы из Code, соответствующие символам из S} VAR Index: 1..Len; BEGIN {Encode} FOR Index := 1 TO Len DO IF S[Index] IN ['A'..'Z'] THEN WRITE(OUTPUT, Code[S[Index]]) ELSE IF S[Index] = ' ' THEN WRITE(OUTPUT, '%') ELSE WRITE(OUTPUT, S[Index]); WRITELN END; {Encode} BEGIN {Encryption} {Инициализировать Code} ASSIGN(FileCode,'code.txt'); Initialize(FileCode, Code, Error); WHILE (NOT EOF(INPUT)) AND (Error = FALSE) DO BEGIN {читать строку в Msg и распечатать ее} Len := 0; WHILE NOT EOLN(INPUT) AND (Len < MaxLen) DO BEGIN Len := Len + 1; READ(INPUT, Msg[Len]); WRITE(OUTPUT, Msg[Len]) END; READLN(INPUT); WRITELN(OUTPUT); {распечатать кодированное сообщение} Encode(Msg) END; IF Error = TRUE THEN WRITELN(OUTPUT, 'Шифр в файле неверный') END. {Encryption}
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [CONTAS_PARCELAS] The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 1.0 *******************************************************************************} unit ContasParcelasVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils; type [TEntity] [TTable('CONTAS_PARCELAS')] TContasParcelasVO = class(TVO) private FID: Integer; FID_CONTAS_PAGAR_RECEBER: Integer; FID_MEIOS_PAGAMENTO: Integer; FID_CHEQUE_EMITIDO: Integer; FID_CONTA_CAIXA: Integer; FDATA_EMISSAO: TDateTime; FDATA_VENCIMENTO: TDateTime; FDATA_PAGAMENTO: TDateTime; FNUMERO_PARCELA: Integer; FVALOR: Extended; FTAXA_JUROS: Extended; FTAXA_MULTA: Extended; FTAXA_DESCONTO: Extended; FVALOR_JUROS: Extended; FVALOR_MULTA: Extended; FVALOR_DESCONTO: Extended; FTOTAL_PARCELA: Extended; FHISTORICO: String; FSITUACAO: String; public [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_CONTAS_PAGAR_RECEBER', 'Id Contas Pagar Receber', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdContasPagarReceber: Integer read FID_CONTAS_PAGAR_RECEBER write FID_CONTAS_PAGAR_RECEBER; [TColumn('ID_MEIOS_PAGAMENTO', 'Id Meios Pagamento', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdMeiosPagamento: Integer read FID_MEIOS_PAGAMENTO write FID_MEIOS_PAGAMENTO; [TColumn('ID_CHEQUE_EMITIDO', 'Id Cheque Emitido', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdChequeEmitido: Integer read FID_CHEQUE_EMITIDO write FID_CHEQUE_EMITIDO; [TColumn('ID_CONTA_CAIXA', 'Id Conta Caixa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdContaCaixa: Integer read FID_CONTA_CAIXA write FID_CONTA_CAIXA; [TColumn('DATA_EMISSAO', 'Data Emissao', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataEmissao: TDateTime read FDATA_EMISSAO write FDATA_EMISSAO; [TColumn('DATA_VENCIMENTO', 'Data Vencimento', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataVencimento: TDateTime read FDATA_VENCIMENTO write FDATA_VENCIMENTO; [TColumn('DATA_PAGAMENTO', 'Data Pagamento', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataPagamento: TDateTime read FDATA_PAGAMENTO write FDATA_PAGAMENTO; [TColumn('NUMERO_PARCELA', 'Numero Parcela', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property NumeroParcela: Integer read FNUMERO_PARCELA write FNUMERO_PARCELA; [TColumn('VALOR', 'Valor', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Valor: Extended read FVALOR write FVALOR; [TColumn('TAXA_JUROS', 'Taxa Juros', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaJuros: Extended read FTAXA_JUROS write FTAXA_JUROS; [TColumn('TAXA_MULTA', 'Taxa Multa', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaMulta: Extended read FTAXA_MULTA write FTAXA_MULTA; [TColumn('TAXA_DESCONTO', 'Taxa Desconto', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO; [TColumn('VALOR_JUROS', 'Valor Juros', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorJuros: Extended read FVALOR_JUROS write FVALOR_JUROS; [TColumn('VALOR_MULTA', 'Valor Multa', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorMulta: Extended read FVALOR_MULTA write FVALOR_MULTA; [TColumn('VALOR_DESCONTO', 'Valor Desconto', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO; [TColumn('TOTAL_PARCELA', 'Total Parcela', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalParcela: Extended read FTOTAL_PARCELA write FTOTAL_PARCELA; [TColumn('HISTORICO', 'Historico', 450, [ldGrid, ldLookup, ldCombobox], False)] property Historico: String read FHISTORICO write FHISTORICO; [TColumn('SITUACAO', 'Situacao', 8, [ldGrid, ldLookup, ldCombobox], False)] property Situacao: String read FSITUACAO write FSITUACAO; end; implementation initialization Classes.RegisterClass(TContasParcelasVO); finalization Classes.UnRegisterClass(TContasParcelasVO); end.
unit CreateView; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CreateObjectDialog, Vcl.Buttons, DB, MemDS, DBAccess, Ora, Vcl.StdCtrls, BCControls.Edit, Vcl.ImgList, BCDialogs.Dlg, SynEditHighlighter, SynHighlighterSQL, ActnList, ComCtrls, ToolWin, JvExComCtrls, SynEdit, Vcl.ExtCtrls, JvComCtrls, BCControls.PageControl, BCControls.ToolBar, BCControls.DBGrid, System.Actions, GridsEh, DBAxisGridsEh, DBGridEh, BCControls.ImageList, DBGridEhGrouping, ToolCtrlsEh, DBGridEhToolCtrls, DynVarsEh; type TCreateViewDialog = class(TCreateObjectBaseDialog) AddColumnAction: TAction; ColumnButtonPanel: TPanel; ColumnCommentsDBGrid: TBCDBGrid; ColumnCommentsPanel: TPanel; ColumnCommentsTabSheet: TTabSheet; ColumnsDataSource: TOraDataSource; ColumnsDBGrid: TBCDBGrid; ColumnsPanel: TPanel; ColumnsQuery: TOraQuery; ColumnsTabSheet: TTabSheet; CommentEdit: TBCEdit; CommnetLabel: TLabel; DeleteColumnAction: TAction; MoveDownAction: TAction; MoveUpAction: TAction; SelectStatementTabSheet: TTabSheet; SQLPanel: TPanel; SQLSynEdit: TSynEdit; ViewNameEdit: TBCEdit; ViewNameLabel: TLabel; ColumnsToolBar: TBCToolBar; MoveUpToolButton: TToolButton; MoveDownToolButton: TToolButton; AddColumnToolButton: TToolButton; DeleteColumnToolButton: TToolButton; procedure AddColumnActionExecute(Sender: TObject); procedure ColumnCommentsDBGridGetCellParams(Sender: TObject; Column: TColumnEh; AFont: TFont; var Background: TColor; State: TGridDrawState); procedure DeleteColumnActionExecute(Sender: TObject); procedure Formshow(Sender: TObject); procedure MoveDownActionExecute(Sender: TObject); procedure MoveUpActionExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); protected function CheckFields: Boolean; override; procedure CreateSQL; override; procedure Initialize; override; end; function CreateViewDialog: TCreateViewDialog; implementation {$R *.dfm} uses Lib, Vcl.Themes, Winapi.UxTheme, BCCommon.StyleUtils, BCCommon.Messages, BCCommon.Lib; var FCreateViewDialog: TCreateViewDialog; function CreateViewDialog: TCreateViewDialog; begin if not Assigned(FCreateViewDialog) then Application.CreateForm(TCreateViewDialog, FCreateViewDialog); Result := FCreateViewDialog; SetStyledFormSize(TDialog(Result)); end; procedure TCreateViewDialog.FormDestroy(Sender: TObject); begin inherited; FCreateViewDialog := nil; end; procedure TCreateViewDialog.Formshow(Sender: TObject); begin inherited; ViewNameEdit.SetFocus; end; procedure TCreateViewDialog.AddColumnActionExecute(Sender: TObject); begin inherited; ColumnsQuery.Append; end; procedure TCreateViewDialog.DeleteColumnActionExecute(Sender: TObject); begin inherited; ColumnsQuery.Delete; end; procedure TCreateViewDialog.MoveDownActionExecute(Sender: TObject); begin inherited; Lib.MoveGridRowDown(ColumnsQuery); end; procedure TCreateViewDialog.MoveUpActionExecute(Sender: TObject); begin inherited; Lib.MoveGridRowUp(ColumnsQuery); end; function TCreateViewDialog.CheckFields: Boolean; begin Result := False; if Trim(ViewNameEdit.Text) = '' then begin ShowErrorMessage('Set table name.'); ViewNameEdit.SetFocus; Exit; end; if ColumnsQuery.RecordCount = 0 then begin ShowErrorMessage('Set columns.'); Exit; end; Result := True; end; procedure TCreateViewDialog.ColumnCommentsDBGridGetCellParams(Sender: TObject; Column: TColumnEh; AFont: TFont; var Background: TColor; State: TGridDrawState); var LStyles: TCustomStyleServices; begin LStyles := StyleServices; if Column.FieldName = 'COLUMN_NAME' then begin if UseThemes then Background := LStyles.GetSystemColor(clBtnFace) else Background := clBtnFace; end; end; procedure TCreateViewDialog.Initialize; begin inherited; with ColumnsQuery do begin Session := FOraSession; Close; Open; end; end; procedure TCreateViewDialog.CreateSQL; var i: Integer; Columns: string; ColumnComments: WideString; begin SourceSynEdit.Lines.Clear; SourceSynEdit.Lines.BeginUpdate; i := 1; Columns := '('; with ColumnsQuery do begin First; while not Eof do begin Columns := Columns + FieldByName('COLUMN_NAME').AsString; if not FieldByName('COLUMN_COMMENT').IsNull then ColumnComments := ColumnComments + Format('COMMENT ON COLUMN %s.%s.%s IS %s;', [FSchemaParam, ViewNameEdit.Text, Trim(FieldByName('COLUMN_NAME').AsWideString), QuotedStr(FieldByName('COLUMN_COMMENT').AsWideString)]) + CHR_ENTER; Next; if not Eof then Columns := Columns + ', '; if i mod 5 = 0 then begin i := 1; Columns := Columns + CHR_ENTER + ' '; end; Inc(i); end; First; end; Columns := Columns + ') AS'; SourceSynEdit.Lines.Clear; SourceSynEdit.Lines.BeginUpdate; SourceSynEdit.Lines.Text := Format('CREATE OR REPLACE VIEW %s.%s', [FSchemaParam, ViewNameEdit.Text]) + CHR_ENTER + Columns + CHR_ENTER + SQLSynEdit.Text + ';' + CHR_ENTER; Application.ProcessMessages; { comments } if (CommentEdit.Text <> '') or (ColumnComments <> '') then SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + CHR_ENTER; if CommentEdit.Text <> '' then SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + Format('COMMENT ON VIEW %s.%s IS %s;', [ FSchemaParam, ViewNameEdit.Text, QuotedStr(CommentEdit.Text)]) + CHR_ENTER; SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + ColumnComments + CHR_ENTER; Application.ProcessMessages; SourceSynEdit.Lines.Text := Trim(SourceSynEdit.Lines.Text); SourceSynEdit.Lines.EndUpdate; end; end.
{ Add large reference RNAM data to a worldspace 1. Select ESM plugin that adds new references to a worldspace * only new ESMs are listed - see sDefaultPlugins below 2. Select worldspace for which to add large references * only worldspaces for selected ESM without existing RNAM data are listed * remove pre-existing RNAM data manually to update * any worldspace supports large references regardless of static object LOD 3. Click OK to add RNAM data for selected worldspace * CK default 'size' is 512 - see fLargeRefMinSize below * CK adds large references for STAT and MSTT - see sLargeRefBaseObjects below * afterwards generate static LOD for worldspaces with LOD } unit UserScript; const sDefaultPlugins = 'skyrim.esm,update.esm,dawnguard.esm,hearthfires.esm,dragonborn.esm'; sLargeRefBaseObjects = 'STAT MSTT'; fLargeRefMinSize = 512; var cbPlugin, cbWorld: TComboBox; slLargeReferences: TwbFastStringList; //============================================================================ // name of LOD settings file for worldspace function LODSettingsFileName(wrld: IInterface): string; begin Result := 'lodsettings\' + EditorID(wrld) + '.lod'; end; //============================================================================ // does worldspace have a lod? function HasLOD(wrld: IInterface): boolean; begin // a presence of lod settings file Result := ResourceExists(LODSettingsFileName(wrld)); end; //============================================================================ procedure ProcessReference(e: IInterface); var stat: IInterface; Dimensions: TwbVector; fScale: float; Cell: TwbGridCell; begin // skip XESP if ElementExists(e, 'XESP') then Exit; stat := BaseRecord(e); // skip markers if GetElementNativeValues(stat, 'Record Header\Record Flags') and $00800000 = $00800000 then Exit; // skip no model if not ElementExists(stat, 'Model') then Exit; // skip no OBND if not ElementExists(stat, 'OBND') then Exit; // check MSTT has unkown2 flag set if (Signature(stat) = 'MSTT') and (GetElementNativeValues(stat, 'DATA - Flags') and $4 <> $4) then Exit; if ElementExists(e, 'XSCL') then fScale := GetElementEditValues(e, 'XSCL') else fScale := 1.0; // get base object size Dimensions.x := (GetElementNativeValues(stat, 'OBND\X2') - GetElementNativeValues(stat, 'OBND\X1')) * fScale; Dimensions.y := (GetElementNativeValues(stat, 'OBND\Y2') - GetElementNativeValues(stat, 'OBND\Y1')) * fScale; Dimensions.z := (GetElementNativeValues(stat, 'OBND\Z2') - GetElementNativeValues(stat, 'OBND\Z1')) * fScale; // skipping wierd stuff or data if (Dimensions.z = 0) or (Dimensions.y = 0) or (Dimensions.x = 0) then Exit; // rules based on emperical evidence - could be incomplete // technically any reference can be added as large reference, but the game does check bounds and BASE signatures etc. // if in-game checks fail -> LOD does not unload and reference might not load at all // it seems adding up all bounds needs to be > 1743 if (Dimensions.x + Dimensions.y + Dimensions.z) > (fLargeRefMinSize * 3.405) then begin Cell := wbPositionToGridCell(GetPosition(e)); slLargeReferences.AddObject(IntToStr(Cell.x) + ' ' + IntToStr(Cell.y), e); end; end; //============================================================================ procedure IterateWorldspace(e: IInterface); var lst: TList; i: integer; begin lst := TList.Create; AddMessage('Gathering large references added by ' + GetFileName(GetFile(e))); // find all new references added by this plugin // no need to include modified references from master plugins again, since all RNAM data is merged anyways wbFindREFRsByBase(e, sLargeRefBaseObjects, 1, lst); for i := 0 to lst.Count - 1 do ProcessReference(ObjectToElement(lst[i])); lst.Free; end; //============================================================================ // add reference to existing RNAM procedure AddRNAMItem(rnam, e: IInterface); var Cell: TwbGridCell; begin Cell := wbPositionToGridCell(GetPosition(e)); rnam := ElementAssign(ElementByPath(rnam, 'References'), HighInteger, nil, False); SetElementNativeValues(rnam, 'X', Cell.x); SetElementNativeValues(rnam, 'Y', Cell.y); SetElementNativeValues(rnam, 'Ref', GetLoadOrderFormID(e)); end; //============================================================================ // add new RNAM function AddRNAM(wrld, e: IInterface): IInterface; var Cell: TwbGridCell; begin Result := nil; Cell := wbPositionToGridCell(GetPosition(e)); if not ElementExists(wrld, 'RNAM') then begin Result := ElementByPath(Add(wrld, 'RNAM', True), 'RNAM'); end else begin Result := ElementAssign(ElementByPath(wrld, 'RNAM'), HighInteger, nil, False); end SetElementNativeValues(Result, 'X', Cell.x); SetElementNativeValues(Result, 'Y', Cell.y); AddRNAMItem(Result, e); end; //============================================================================ procedure UpdateWorldspace(wrld: IInterface); var i, j: integer; s: string; e, rnam: IInterface; CurrentCell, Cell: TwbGridCell; begin if slLargeReferences.Count = 0 then Exit; AddMessage('Adding ' + IntToStr(slLargeReferences.Count) + ' large references to ' + EditorID(wrld)); i := Pred(slLargeReferences.Count); while i >= 0 do begin e := ObjectToElement(slLargeReferences.Objects[i]); s := slLargeReferences[i]; // add new RNAM rnam := AddRNAM(wrld, e); // remove reference from list slLargeReferences.Delete(i); // add all other references for same cell for j := Pred(i) downto 0 do begin e := ObjectToElement(slLargeReferences.Objects[j]); // go through list sorted by coordinates if (s = slLargeReferences[j]) then begin // add reference to existing RNAM AddRNAMItem(rnam, e); // remove reference from list slLargeReferences.Delete(j); end else break; end; i := Pred(slLargeReferences.Count); end; end; //============================================================================ procedure GenerateWorldspace(wrld: IInterface); begin IterateWorldspace(wrld); UpdateWorldspace(wrld); end; //============================================================================ // skip vanilla plugins function IsDefaultPlugin(s: string): Boolean; var i: integer; sl: TStringList; begin Result := False; sl := TStringList.Create; sl.StrictDelimiter := True; sl.CommaText := sDefaultPlugins; try for i := 0 to Pred(sl.Count) do if Lowercase(s) = sl[i] then begin Result := True; exit; end; finally sl.free; end; end; //============================================================================ // fill plugin drop-down procedure FillPlugins(cmbWorld: TComboBox); var i: integer; f: IInterface; sl: TStringList; begin // filling list of worldspaces sl := TStringList.Create; try sl.Duplicates := dupIgnore; sl.Sorted := True; sl.AddObject(' -- Select a plugin --', nil); for i := Pred(FileCount) downto 0 do begin f := FileByIndex(i); // skip vanilla plugins if IsDefaultPlugin(GetFileName(f)) then Continue; // only ESM for now if not GetIsESM(f) then Continue; sl.AddObject(GetFileName(f), f); end; cmbWorld.Items.Assign(sl); finally sl.Free; end; end; //============================================================================ // fill with worldspaces procedure FillWorldspaces(cmbWorld: TComboBox; f: IInterface); var i, j: integer; wrlds, wrld: IInterface; sl: TStringList; s: string; begin // filling list of worldspaces sl := TStringList.Create; try sl.Duplicates := dupIgnore; sl.Sorted := True; sl.AddObject(' -- Select a worldspace --', nil); wrlds := GroupBySignature(f, 'WRLD'); for j := 0 to Pred(ElementCount(wrlds)) do begin wrld := ElementByIndex(wrlds, j); if ElementType(wrld) <> etMainRecord then Continue; // skip if RNAM data already exists if ElementExists(wrld, 'RNAM') then Continue; sl.AddObject(EditorID(wrld), wrld); end; cmbWorld.Items.Assign(sl); finally sl.Free; end; end; //============================================================================ procedure UpdatecbWorld(Sender: TObject); begin FillWorldspaces(cbWorld, ObjectToElement(cbPlugin.Items.Objects[cbPlugin.ItemIndex])); if cbWorld.Items.Count > 0 then cbWorld.ItemIndex := 0; end; //============================================================================ function CreateLabel(aParent: TControl; x, y: Integer; aCaption: string): TLabel; begin Result := TLabel.Create(aParent); Result.Parent := aParent; Result.Left := x; Result.Top := y; Result.Caption := aCaption; end; //============================================================================ function OptionsForm: IInterface; var frm: TForm; btnOk, btnCancel: TButton; begin Result := nil; frm := TForm.Create(nil); try frm.Caption := 'Generate Large References'; frm.Width := 400; frm.Height := 200; frm.Position := poMainFormCenter; frm.BorderStyle := bsDialog; frm.KeyPreview := True; cbPlugin := TComboBox.Create(frm); cbPlugin.Parent := frm; cbPlugin.Left := 54; cbPlugin.Top := 12; cbPlugin.Width := 260; cbPlugin.Style := csDropDownList; cbPlugin.DropDownCount := 20; cbPlugin.OnSelect := UpdatecbWorld; CreateLabel(frm, 16, cbPlugin.Top + 4, 'Plugin'); FillPlugins(cbPlugin); if cbPlugin.Items.Count > 0 then cbPlugin.ItemIndex := 0; if cbPlugin.Items.Count = 2 then cbPlugin.ItemIndex := 1; cbWorld := TComboBox.Create(frm); cbWorld.Parent := frm; cbWorld.Left := 54; cbWorld.Top := cbPlugin.Top + cbPlugin.Height + 4; cbWorld.Width := 260; cbWorld.Style := csDropDownList; cbWorld.DropDownCount := 20; CreateLabel(frm, 16, cbWorld.Top + 4, 'World'); FillWorldspaces(cbWorld, ObjectToElement(cbPlugin.Items.Objects[cbPlugin.ItemIndex])); if cbWorld.Items.Count > 0 then cbWorld.ItemIndex := 0; btnCancel := TButton.Create(frm); btnCancel.Parent := frm; btnCancel.Caption := 'Cancel'; btnCancel.ModalResult := mrCancel; btnCancel.Left := cbWorld.Left + cbWorld.Width - btnCancel.Width; btnCancel.Top := cbWorld.Top + cbWorld.Height + 8; btnOk := TButton.Create(frm); btnOk.Parent := frm; btnOk.Caption := 'OK'; btnOk.ModalResult := mrOk; btnOk.Left := btnCancel.Left - btnOk.Width - 8; btnOk.Top := btnCancel.Top; frm.Width := cbWorld.Left + cbWorld.Width + 32; frm.Height := btnOk.Top + btnOk.Height + 32; if frm.ShowModal <> mrOk then Exit; Result := ObjectToElement(cbWorld.Items.Objects[cbWorld.ItemIndex]); finally frm.Free; end; end; //============================================================================ function Initialize: integer; var wrld: IInterface; begin Result := 0; slLargeReferences := TwbFastStringList.Create; slLargeReferences.Duplicates := dupAccept; slLargeReferences.Sorted := True; if (wbGameMode <> gmSSE) then begin AddMessage('Game not supported'); Exit; end; wrld := OptionsForm; if Assigned(wrld) then GenerateWorldspace(wrld); slLargeReferences.Free; end; end.
unit XLSUtils; { ******************************************************************************** ******* XLSReadWriteII V1.14 ******* ******* ******* ******* Copyright(C) 1999,2002 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} interface uses Classes, SysUtils, Windows, BIFFRecsII, Graphics; type TNameType = (ntName,ntExternName,ntExternSheet,ntCurrBook); type TIntegerEvent = procedure (Sender: TObject; Value: integer) of object; type TWorkbookOption = (woHidden,woIconized,woHScroll,woVScroll,woTabs); TWorkbookOptions = set of TWorkbookOption; type TShowObjects = (soShowAll,soPlaceholders,soHideAll); type TCalcMode = (cmManual,cmAutomatic,cmAutoExTables); type TStyles = class(TList) private function GetItems(Index: integer): PRecSTYLE; public destructor Destroy; override; procedure Add(Style: PRecSTYLE); procedure Clear; override; property Items[Index: integer]: PRecSTYLE read GetItems; default; end; type TRowOptions = (roZeroHeight,roFormatted); type TRowData = record Row: word; Height: word; FormatIndex: word; Oprtions: TRowOptions; end; type TWorkbookData = class(TPersistent) private FLeft: word; FTop: word; FWidth: word; FHeight: word; FSelectedTab: word; FOptions: TWorkbookOptions; published property Left: word read FLeft write FLeft; property Top: word read FTop write FTop; property Width: word read FWidth write FWidth; property Height: word read FHeight write FHeight; property SelectedTab: word read FSelectedTab write FSelectedTab; property Options: TWorkbookOptions read FOptions write FOptions; end; type TOptionsDialog = class(TPersistent) private FSaveExtLinkVal: boolean; FCalcCount: word; FCalcMode: TCalcMode; FDelta: double; FUserName: string; FShowObjects: TShowObjects; FIteration: boolean; FPrecisionAsDisplayed: boolean; FR1C1Mode: boolean; FRecalcBeforeSave: boolean; FUncalced: boolean; procedure SetUserName(Value: string); published constructor Create; property SaveExtLinkVal: boolean read FSaveExtLinkVal write FSaveExtLinkVal; property CalcCount: word read FCalcCount write FCalcCount; property CalcMode: TCalcMode read FCalcMode write FCalcMode; property Delta: double read FDelta write FDelta; property UserName: string read FUserName write SetUserName; property ShowObjects: TShowObjects read FShowObjects write FShowObjects; property Iteration: boolean read FIteration write FIteration; property PrecisionAsDisplayed: boolean read FPrecisionAsDisplayed write FPrecisionAsDisplayed; property R1C1Mode: boolean read FR1C1Mode write FR1C1Mode; property RecalcBeforeSave: boolean read FRecalcBeforeSave write FRecalcBeforeSave; property Uncalced: boolean read FUncalced write FUncalced; end; function GetHashCode(const Buffer; Count: Integer): Word; assembler; function CPos(C: char; S: string): integer; function ColRowToRC(Col, Row: integer): longword; procedure SplitRC(RC: integer; var Col,Row: integer); procedure NormalizeArea(var C1,R1,C2,R2: integer); function IsMultybyteString(S: string): boolean; function ToMultibyte1bHeader(S: string): string; function BufLenMultibyte1bHeader(S: string): integer; function DecodeUnicodeStr(Version: TExcelVersion; P: PByteArray; Len: integer): string; function HexStringToByteArray(S: string; var PBytes: PByteArray): integer; function ErrorCodeToText(Code: integer): string; function CellErrorErrorCodeTo(Error: TCellError): byte; function ErrorCodeToCellError(Code: integer): TCellError; function ColRowToRefStr(ACol,ARow: integer; AbsCol,AbsRow: boolean): string; function AreaToRefStr(Col1,Row1,Col2,Row2: integer; AbsCol1,AbsRow1,AbsCol2,AbsRow2: boolean): string; function FastReplace(var aSourceString : String; const aFindString, aReplaceString : String; CaseSensitive : Boolean = False) : String; var VAR_WriteUnicodeStrings: boolean; implementation { TOptionsDialog } constructor TOptionsDialog.Create; begin FCalcMode := cmAutomatic; end; procedure TOptionsDialog.SetUserName(Value: string); begin FUserName := Copy(Value,1,255); end; function GetHashCode(const Buffer; Count: Integer): Word; assembler; asm CMP EDX,0 JNE @@2 MOV EAX,0 JMP @@3 @@2: MOV ECX,EDX MOV EDX,EAX XOR EAX,EAX @@1: ROL AX,5 XOR AL,[EDX] INC EDX DEC ECX JNE @@1 @@3: end; function CPos(C: char; S: string): integer; begin for Result := 1 to Length(S) do begin if S[Result] = C then Exit; end; Result := -1; end; function ColRowToRC(Col, Row: integer): longword; begin Result := (Row shl 8) + (Col and $000000FF); end; procedure SplitRC(RC: integer; var Col,Row: integer); begin Col := RC and $000000FF; Row := RC shr 8; end; procedure NormalizeArea(var C1,R1,C2,R2: integer); var T: integer; begin if C1 > C2 then begin T := C1; C1 := C2; C2 := T; end; if R1 > R2 then begin T := R1; R1 := R2; R2 := T; end; end; function IsMultybyteString(S: string): boolean; begin Result := (Length(S) > 0) and (S[1] = #1); end; function ToMultibyte1bHeader(S: string): string; begin if not VAR_WriteUnicodeStrings then Result := #0 + S else begin SetLength(Result,Length(S) * 2); MultiByteToWideChar(0, 0, PChar(S), Length(S),PWideChar(Result), Length(S) * 2); Result := #1 + Result; end; end; function BufLenMultibyte1bHeader(S: string): integer; begin if VAR_WriteUnicodeStrings then Result := Length(S) * 2 + 1 else Result := Length(S) + 1; end; function DecodeUnicodeStr(Version: TExcelVersion; P: PByteArray; Len: integer): string; begin if P[0] = 0 then begin SetLength(Result,Len); Move(Pointer(Integer(P) + 1)^,Pointer(Result)^,Len); end else if Version >= xvExcel97 then Result := WideCharLenToString(PWideChar(Integer(P) + 1),Len) else begin SetLength(Result,Len); Move(Pointer(P)^,Pointer(Result)^,Len); end; end; function ErrorCodeToText(Code: integer): string; begin case Code of $00: Result := CellErrorNames[1]; $07: Result := CellErrorNames[2]; $0F: Result := CellErrorNames[3]; $17: Result := CellErrorNames[4]; $1D: Result := CellErrorNames[5]; $24: Result := CellErrorNames[6]; $2A: Result := CellErrorNames[7]; else Result := '#???'; end; end; function ErrorCodeToCellError(Code: integer): TCellError; var V: byte; begin case Code of $00: V := 1; $07: V := 2; $0F: V := 3; $17: V := 4; $1D: V := 5; $24: V := 6; $2A: V := 7; else V := 0; end; Result := TCellError(V); end; function CellErrorErrorCodeTo(Error: TCellError): byte; begin case Error of errError: Result := $2A; errNull: Result := $00; errDiv0: Result := $07; errValue: Result := $0F; errRef: Result := $17; errName: Result := $1D; errNum: Result := $24; errNA: Result := $2A; else Result := $2A; end; end; function ColRowToRefStr(ACol,ARow: integer; AbsCol,AbsRow: boolean): string; begin Inc(ARow); if AbsCol then begin if ACol < 26 then Result := '$' + Char(Ord('A') + ACol) else Result := '$' + Char(Ord('@') + ACol div 26) + Char(Ord('A') + ACol mod 26); end else begin if ACol < 26 then Result := Char(Ord('A') + ACol) else Result := Char(Ord('@') + ACol div 26) + Char(Ord('A') + ACol mod 26); end; if AbsRow then Result := Result + '$' + IntToStr(ARow) else Result := Result + IntToStr(ARow); end; function AreaToRefStr(Col1,Row1,Col2,Row2: integer; AbsCol1,AbsRow1,AbsCol2,AbsRow2: boolean): string; begin Result := ColRowToRefStr(Col1,Row1,AbsCol1,AbsRow1) + ':' + ColRowToRefStr(Col2,Row2,AbsCol2,AbsRow2); end; function HexStringToByteArray(S: string; var PBytes: PByteArray): integer; var i,p: integer; V: byte; begin Result := Length(S) div 2; ReAllocMem(PBytes,Result); p := 1; for i := 0 to Result - 1 do begin if S[p] in ['0'..'9'] then V := (Ord(S[p]) - Ord('0')) * 16 else V := (Ord(S[p]) - Ord('A') + 10) * 16; Inc(p); if S[p] in ['0'..'9'] then V := V + Ord(S[p]) - Ord('0') else V := V + Ord(S[p]) - Ord('A') + 10; Inc(p); PBytes[i] := V; end; end; Type TFastPosProc = function( const aSourceString, aFindString : String; const aSourceLen, aFindLen, StartPos : integer ) : integer; function FastPos(const aSourceString, aFindString : String; const aSourceLen, aFindLen, StartPos : integer) : integer; var SourceLen : integer; begin SourceLen := aSourceLen; SourceLen := SourceLen - aFindLen; if (StartPos-1) > SourceLen then begin Result := 0; Exit; end; SourceLen := SourceLen - StartPos; SourceLen := SourceLen +2; asm push ESI push EDI push EBX mov EDI, aSourceString add EDI, StartPos Dec EDI mov ESI, aFindString mov ECX, SourceLen Mov Al, [ESI] @ScaSB: Mov Ah, [EDI] cmp Ah,Al jne @NextChar @CompareStrings: mov EBX, aFindLen dec EBX @CompareNext: mov Al, [ESI+EBX] mov Ah, [EDI+EBX] cmp Al, Ah Jz @Matches Mov Al, [ESI] Jmp @NextChar @Matches: Dec EBX Jnz @CompareNext mov EAX, EDI sub EAX, aSourceString inc EAX mov Result, EAX jmp @TheEnd @NextChar: Inc EDI dec ECX jnz @ScaSB mov Result,0 @TheEnd: pop EBX pop EDI pop ESI end; end; function FastPosNoCase(const aSourceString, aFindString : String; const aSourceLen, aFindLen, StartPos : integer) : integer; var SourceLen : integer; begin SourceLen := aSourceLen; SourceLen := SourceLen - aFindLen; if (StartPos-1) > SourceLen then begin Result := 0; Exit; end; SourceLen := SourceLen - StartPos; SourceLen := SourceLen +2; asm push ESI push EDI push EBX mov EDI, aSourceString add EDI, StartPos Dec EDI mov ESI, aFindString mov ECX, SourceLen Mov Al, [ESI] and Al, $df @ScaSB: Mov Ah, [EDI] and Ah, $df cmp Ah,Al jne @NextChar @CompareStrings: mov EBX, aFindLen dec EBX @CompareNext: mov Al, [ESI+EBX] mov Ah, [EDI+EBX] and Al, $df and Ah, $df cmp Al, Ah Jz @Matches Mov Al, [ESI] and Al, $df Jmp @NextChar @Matches: Dec EBX Jnz @CompareNext mov EAX, EDI sub EAX, aSourceString inc EAX mov Result, EAX jmp @TheEnd @NextChar: Inc EDI dec ECX jnz @ScaSB mov Result,0 @TheEnd: pop EBX pop EDI pop ESI end; end; procedure MyMove(const Source; var Dest; Count : Integer); asm cmp ECX,0 Je @JustQuit push ESI push EDI mov ESI, EAX mov EDI, EDX @Loop: Mov AL, [ESI] Inc ESI mov [EDI], AL Inc EDI Dec ECX Jnz @Loop pop EDI pop ESI @JustQuit: end; function FastReplace(var aSourceString : String; const aFindString, aReplaceString : String; CaseSensitive : Boolean = False) : String; var ActualResultLen, CurrentPos, LastPos, BytesToCopy, ResultLen, FindLen, ReplaceLen, SourceLen : Integer; FastPosProc : TFastPosProc; begin if CaseSensitive then FastPosProc := FastPOS else FastPOSProc := FastPOSNoCase; Result := ''; FindLen := Length(aFindString); ReplaceLen := Length(aReplaceString); SourceLen := Length(aSourceString); if ReplaceLen <= FindLen then ActualResultLen := SourceLen else ActualResultLen := SourceLen + (SourceLen * ReplaceLen div FindLen) + ReplaceLen; SetLength(Result,ActualResultLen); CurrentPos := 1; ResultLen := 0; LastPos := 1; if ReplaceLen > 0 then begin repeat CurrentPos := FastPosProc(aSourceString, aFindString,SourceLen, FindLen, CurrentPos); if CurrentPos = 0 then break; BytesToCopy := CurrentPos-LastPos; MyMove(aSourceString[LastPos],Result[ResultLen+1], BytesToCopy); MyMove(aReplaceString[1],Result[ResultLen+1+BytesToCopy], ReplaceLen); ResultLen := ResultLen + BytesToCopy + ReplaceLen; CurrentPos := CurrentPos + FindLen; LastPos := CurrentPos; until false; end else begin repeat CurrentPos := FastPos(aSourceString, aFindString, SourceLen, FindLen, CurrentPos); if CurrentPos = 0 then break; BytesToCopy := CurrentPos-LastPos; MyMove(aSourceString[LastPos], Result[ResultLen+1], BytesToCopy); ResultLen := ResultLen + BytesToCopy + ReplaceLen; CurrentPos := CurrentPos + FindLen; LastPos := CurrentPos; until false; end; Dec(LastPOS); SetLength(Result, ResultLen + (SourceLen-LastPos)); if LastPOS+1 <= SourceLen then MyMove(aSourceString[LastPos+1],Result[ResultLen+1],SourceLen-LastPos); end; { TStyle } procedure TStyles.Add(Style: PRecSTYLE); var P: PRecSTYLE; begin New(P); System.Move(Style^,P^,SizeOf(TRecSTYLE)); inherited Add(P); end; procedure TStyles.Clear; var i: integer; begin for i := 0 to Count - 1 do FreeMem(inherited Items[i]); inherited Clear; end; destructor TStyles.Destroy; begin Clear; inherited; end; function TStyles.GetItems(Index: integer): PRecSTYLE; begin Result := inherited Items[Index]; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) @abstract(Website : http://www.ormbr.com.br) @abstract(Telagram : https://t.me/ormbr) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.dataset.abstract; interface uses DB, Rtti, Generics.Collections, ormbr.dataset.fields, ormbr.session.abstract, dbcbr.mapping.classes, dbcbr.rtti.helper; type // M - Object M TDataSetAbstract<M: class, constructor> = class abstract protected FSession: TSessionAbstract<M>; // Objeto para controle de estado do registro FOrmDataSource: TDataSource; procedure RefreshDataSetOneToOneChilds(AFieldName: string); virtual; procedure DoDataChange(Sender: TObject; Field: TField); virtual; public // Objeto interface com o DataSet passado pela interface. FOrmDataSet: TDataSet; constructor Create(ADataSet: TDataSet; APageSize: Integer; AMasterObject: TObject); overload; virtual; destructor Destroy; override; end; implementation uses dbcbr.mapping.explorer; { TDataSetAbstract<M> } constructor TDataSetAbstract<M>.Create(ADataSet: TDataSet; APageSize: Integer; AMasterObject: TObject); begin FOrmDataSource := TDataSource.Create(nil); FOrmDataSource.DataSet := FOrmDataSet; FOrmDataSource.OnDataChange := DoDataChange; end; destructor TDataSetAbstract<M>.Destroy; begin FOrmDataSource.Free; inherited; end; procedure TDataSetAbstract<M>.DoDataChange(Sender: TObject; Field: TField); var LValue: TDictionary<string, string>; // LContext: TRttiContext; // LObjectType: TRttiType; LColumn: TColumnMapping; LColumns: TColumnMappingList; begin if not (FOrmDataSet.State in [dsInsert, dsEdit]) then Exit; if Field = nil then Exit; if Field.Tag > 0 then Exit; if (Field.FieldKind <> fkData) or (Field.FieldName = cInternalField) then Exit; // Só adiciona a lista se for edição if FOrmDataSet.State in [dsEdit] then begin LValue := FSession.ModifiedFields.Items[M.ClassName]; if LValue <> nil then begin if not LValue.ContainsValue(Field.FieldName) then begin LColumns := TMappingExplorer.GetMappingColumn(M); for LColumn in LColumns do begin if LColumn.ColumnProperty = nil then Continue; if LColumn.ColumnProperty.IsVirtualData then Continue; if LColumn.ColumnProperty.IsNoUpdate then Continue; if LColumn.ColumnProperty.IsAssociation then Continue; if LColumn.ColumnName <> Field.FieldName then Continue; LValue.Add(LColumn.ColumnProperty.Name, Field.FieldName); Break; end; // LObjectType := LContext.GetType(TypeInfo(M)); // for LProperty in LObjectType.GetProperties do // begin // if LProperty.GetColumn.ColumnName = Field.FieldName then // begin // LValue.Add(LProperty.Name, Field.FieldName); // Break; // end; // end; end; end; end; // Atualiza o registro da tabela externa, se o campo alterado // pertencer a um relacionamento OneToOne ou ManyToOne RefreshDataSetOneToOneChilds(Field.FieldName); end; procedure TDataSetAbstract<M>.RefreshDataSetOneToOneChilds(AFieldName: string); begin end; end.
unit ManipulationTextFile; interface uses SysUtils, Windows, Classes; type TStringArray = array of string; TCharacterArray = array of char; function getAnsiStringFromString(const ansiString: string): string; procedure printLinesFromFile(nameFile : String); function readLinesFromFile(nameFile: String) : TStringArray; function getLinesFileWithoutEmptyLines(arrayStrings : TStringArray) : TStringArray; function getSingleStringFromAllLinesFile(nameFile : String) : TCharacterArray; function convertStringToArrayCharacters(singleString : String) : TCharacterArray; function convertArrayCharactersToString(arrayCharacters : TCharacterArray) : String; implementation function getAnsiStringFromString(const ansiString: string): string; begin SetLength(Result, Length(ansiString)); if Length(Result) > 0 then CharToOem(PChar(ansiString), PChar(Result)); end; procedure printLinesFromFile(nameFile : String); var fileHandler : TextFile; lineFile : String; begin Writeln(getAnsiStringFromString('Чтение строк с файла: ' + nameFile)); AssignFile(fileHandler, nameFile); {$I+} try Reset(fileHandler); repeat Readln(fileHandler, lineFile); Writeln(getAnsiStringFromString(lineFile)); until(Eof(fileHandler)); CloseFile(fileHandler); except on e : EInOutError do begin Writeln(getAnsiStringFromString('Ошибка при работе с файлом была найдена. Детали: ') + e.ClassName + '/' + e.Message); end; end; end; function readLinesFromFile(nameFile: String) : TStringArray; var listLinesFile : TStringlist; arrayStrings : TStringArray; counter : Integer; begin listLinesFile := TStringList.Create; try listLinesFile.LoadFromFile(nameFile); SetLength(arrayStrings, listLinesFile.Count); for counter := 0 to listLinesFile.Count-1 do begin arrayStrings[counter] := listLinesFile[counter]; end; finally listLinesFile.Free; end; Result := arrayStrings; end; function getLinesFileWithoutEmptyLines(arrayStrings : TStringArray) : TStringArray; var listLinesFile : TStringlist; arrayStringsWithoutEmptyStrings : TStringArray; counter : Integer; begin listLinesFile := TStringList.Create; try for counter := 0 to Length(arrayStrings) - 1 do begin if (Length(arrayStrings[counter]) <> 0) and (Length(arrayStrings[counter]) <> 2) then begin listLinesFile.Add(arrayStrings[counter]); end; end; SetLength(arrayStringsWithoutEmptyStrings, listLinesFile.Count); for counter := 0 to listLinesFile.Count - 1 do begin arrayStringsWithoutEmptyStrings[counter] := listLinesFile[counter]; end; finally listLinesFile.Free; end; Result := arrayStringsWithoutEmptyStrings; end; function convertStringToArrayCharacters(singleString : String) : TCharacterArray; var arrayCharacters: TCharacterArray; counter : Integer; begin SetLength(arrayCharacters, Length(singleString)); for counter := 1 to Length(singleString) do begin arrayCharacters[counter - 1] := singleString[counter]; end; Result := arrayCharacters; end; function convertArrayCharactersToString(arrayCharacters : TCharacterArray) : String; var singleString : String; counter : Integer; begin SetLength(singleString, Length(arrayCharacters)); for counter := 0 to Length(arrayCharacters)-1 do begin singleString[counter + 1] := arrayCharacters[counter - 1]; end; Result := singleString; end; function getSingleStringFromAllLinesFile(nameFile : String) : TCharacterArray; var listLinesFile : TStringList; singleString : TCharacterArray; counter : Integer; begin listLinesFile := TStringList.Create; try listLinesFile.LoadFromFile(nameFile); singleString := convertStringToArrayCharacters(listLinesFile.Text); finally listLinesFile.Free; end; Result := singleString; end; { function getAllLineFilesFromSingleString(arrayCharacters : TCharacterArray) : TStringArray; var singleString : String; listLinesFile : TStringList; arrayStrings : TStringArray; counter : Integer; begin listLinesFile := TStringList.Create; try singleString := convertArrayCharactersToString(arrayCharacters); listLinesFile.Delimiter := '#13#10'; listLinesFile.DelimitedText := singleString; SetLength(arrayStrings, listLinesFile.Count); for counter := 0 to listLinesFile.Count-1 do begin arrayStrings[counter] := listLinesFile[counter]; end; finally listLinesFile.Free; end; Result := arrayStrings; end; } end.
unit Thread.GravaRemessasVA; interface uses System.Classes, System.Generics.Collections, System.SysUtils, Model.RemessasVA, DAO.RemessasVA, Vcl.Forms, System.UITypes, Model.BancaVA, DAO.BancaVA, uGlobais, Model.ProdutosVA, DAO.ProdutosVA; type Thread_GravaRemessasVA = class(TThread) private { Private declarations } FdPos: Double; FTexto: TStringList; remessa : TRemessasVA; remessas : TObjectList<TRemessasVA>; remessaDAO : TRemessasVADAO; banca : TBancaVA; bancas : TObjectList<TBancaVA>; bancaDAO : TBancaVADAO; produto : TProdutosVA; produtos : TObjectList<TProdutosVA>; produtoDAO : TProdutosVADAO; protected procedure Execute; override; procedure IniciaProcesso; procedure AtualizaProcesso; procedure TerminaProcesso; function DataDevolucao(dtData: TDate; sProduto: String): TDate; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure Thread_GravaRemessasVA.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } { Thread_GravaRemessasVA } uses View.ResultatoProcesso, udm, View.ManutencaoRepartes; procedure Thread_GravaRemessasVA.IniciaProcesso; begin view_ManutencaoRepartesVA.pbRepartes.Visible := True; dm.dsImportaRemessa.Enabled := False; view_ManutencaoRepartesVA.pbRepartes.Position := 0; view_ManutencaoRepartesVA.pbRepartes.Refresh; end; procedure Thread_GravaRemessasVA.Execute; var ocorrenciaTMP: TRemessasVA; iTotal : Integer; iPos : Integer; sMensagem: String; iId: Integer; lLog: TStringList; begin { Place thread code here } try Synchronize(IniciaProcesso); FTexto := TstringList.Create(); Screen.Cursor := crHourGlass; remessaDAO := TRemessasVADAO.Create(); remessa := TRemessasVA.Create(); bancaDAO := TBancaVADAO.Create(); remessas := TObjectList<TRemessasVA>.Create(); produto := TProdutosVA.Create(); produtoDAO := TProdutosVADAO.Create(); produtos := TObjectList<TProdutosVA>.Create(); bancas := bancaDAO.FindByCodigo(StrToIntDef(dm.fdmRemessaCOD_BANCA.AsString,0)); iTotal := dm.fdmRemessa.RecordCount; iPos := 0; FdPos := 0; if not dm.fdmRemessa.IsEmpty then dm.fdmRemessa.First; while not dm.fdmRemessa.Eof do begin sMensagem := ''; remessas := remessaDAO.FindByMovimento(0,dm.fdmRemessaCOD_BANCA.AsInteger, 0, dm.fdmRemessaCOD_PRODUTO.AsString, dm.fdmRemessaDAT_CIRCULACAO.AsDateTime); lLog := TStringList.Create(); if remessas.Count > 0 then begin if remessas[0].Inventario = 0 then begin remessa.Id := remessas[0].Id; remessa.Distribuidor := remessas[0].Distribuidor; remessa.Banca := remessas[0].Banca; remessa.Produto := remessas[0].Produto; remessa.DataRemessa := remessas[0].DataRemessa; remessa.NumeroRemessa := remessas[0].NumeroRemessa; remessa.Remessa := remessas[0].Remessa; remessa.DataRecobertura := remessas[0].DataRecobertura; remessa.Recobertura := remessas[0].Recobertura; remessa.DataChamada := remessas[0].DataChamada; remessa.NumeroDevolucao := remessas[0].NumeroDevolucao; remessa.Encalhe := remessas[0].Encalhe; remessa.ValorCobranca := remessas[0].ValorCobranca; remessa.ValorVenda := remessas[0].ValorVenda; remessa.Inventario := remessas[0].Inventario; lLog.Text := remessas[0].Log; if remessa.Id = 0 then begin lLog.Add('> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now()) + ' inserido por ' + uGlobais.sUsuario); end else begin lLog.Add('> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now()) + ' alterado por ' + uGlobais.sUsuario); end; remessa.Log := lLog.Text; end; end else begin remessa.Id := 0; bancas := bancaDAO.FindByCodigo(dm.fdmRemessaCOD_BANCA.AsInteger); if bancas.Count > 0 then begin remessa.Distribuidor := bancas[0].Distribuidor; end; remessa.Banca := dm.fdmRemessaCOD_BANCA.AsInteger; remessa.Produto := dm.fdmRemessaCOD_PRODUTO.AsString; remessa.DataRemessa := dm.fdmRemessaDAT_CIRCULACAO.AsDateTime; remessa.NumeroRemessa := '0'; remessa.Remessa := dm.fdmRemessaQTD_REMESSA.AsFloat; remessa.DataRecobertura := 0; remessa.Recobertura := 0; remessa.DataChamada := DataDevolucao(remessa.DataRemessa,remessa.Produto); remessa.NumeroDevolucao := '0'; remessa.Encalhe := 0; produtos := produtoDAO.FindByCodigo(dm.fdmRemessaCOD_PRODUTO.AsString); if produtos.Count = 0 then begin remessa.ValorCobranca := 0; remessa.ValorVenda := 0; end else begin remessa.ValorCobranca := produtos[0].Cobranca; remessa.ValorVenda := produtos[0].Venda; end; remessa.Inventario := 0; lLog.Text := ''; if remessa.Id = 0 then begin lLog.Add('> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now()) + ' inserido por ' + uGlobais.sUsuario); end else begin lLog.Add('> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now()) + ' alterado por ' + uGlobais.sUsuario); end; remessa.Log := lLog.Text; end; if remessa.Id > 0 then begin if not remessaDAO.Update(remessa) then begin sMensagem := 'Erro ao alterar a remessa ' + dm.fdmRemessaCOD_BANCA.AsString + '-' + dm.fdmRemessaDAT_CIRCULACAO.AsString + '-' + dm.fdmRemessaCOD_PRODUTO.AsString; end; end else begin if not remessaDAO.Insert(remessa) then begin sMensagem := 'Erro ao incluir a remessa ' + dm.fdmRemessaCOD_BANCA.AsString + '-' + dm.fdmRemessaDAT_CIRCULACAO.AsString + '-' + dm.fdmRemessaCOD_PRODUTO.AsString; end; end; if not sMensagem.IsEmpty then FTexto.Add(sMensagem); dm.fdmRemessa.Next; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); end; finally Screen.Cursor := crDefault; remessaDAO.Free; remessa.Free; bancaDAO.Free; lLog.Free; Synchronize(TerminaProcesso); Self.Free; end; end; procedure Thread_GravaRemessasVA.AtualizaProcesso; begin view_ManutencaoRepartesVA.pbRepartes.Position := FdPos; view_ManutencaoRepartesVA.pbRepartes.Properties.Text := FormatFloat('0.00%',FdPos); view_ManutencaoRepartesVA.pbRepartes.Refresh; end; procedure Thread_GravaRemessasVA.TerminaProcesso; begin dm.fdmRemessa.Close; view_ManutencaoRepartesVA.pbRepartes.Position := 0; view_ManutencaoRepartesVA.pbRepartes.Properties.Text := ''; view_ManutencaoRepartesVA.pbRepartes.Refresh; dm.dsImportaRemessa.Enabled := True; view_ManutencaoRepartesVA.pbRepartes.Visible := False; view_ManutencaoRepartesVA.edtArquivo.Clear; if FTexto.Count > 0 then begin if not Assigned(view_ResultadoProcesso) then begin view_ResultadoProcesso := Tview_ResultadoProcesso.Create(Application); end; view_ResultadoProcesso.edtResultado.Text := FTexto.Text; view_ResultadoProcesso.Show; end; end; function Thread_GravaRemessasVA.DataDevolucao(dtData: TDate; sProduto: string): TDate; var iDia: Integer; dtDataDevolucao: TDate; begin try Result := 0; iDia := 0; produtoDAO := TProdutosVADAO.Create; produtos := produtoDAO.FindByCodigo(sProduto); if produtos.Count > 0 then begin if produtos[0].Diario = 1 then begin iDia := DayOfWeek(dtData); if iDia in [2,3,4,5] then begin dtDataDevolucao := dtData + 1; end else if iDia = 6 then begin dtDataDevolucao := dtData + 3; end else if iDia = 7 then begin dtDataDevolucao := dtData + 2; end else if iDia = 1 then begin dtDataDevolucao := dtData + 2; end; Result := dtDataDevolucao; end; end; finally produtoTMP.Free; produtoDAO.Free; produtos.Free; end; end; end.
unit InfraHibernateAnnotationIntf; interface Uses Classes, {Zeos} ZDbcIntfs, {Infra} InfraCommonIntf, InfraValueTypeIntf; Type TZTypeSetter = procedure (const pStatement: IZPreparedStatement; pIndex: Integer; const pParamValue: IInfraType); TZTypeGetter = procedure (const pResultSet: IZResultSet; pIndex: Integer; const pPropertyValue: IInfraType); IZTypeAnnotation = interface(IElement) ['{224B7552-1AB1-456B-B5C5-C7A85BA60580}'] function GetNullSafeGetter: TZTypeGetter; function GetNullSafeSetter: TZTypeSetter; property NullSafeGet: TZTypeGetter read GetNullSafeGetter; property NullSafeSet: TZTypeSetter read GetNullSafeSetter; procedure Init(pGetter: TZTypeGetter; pSetter: TZTypeSetter); end; IEntity = interface(IElement) ['{28B94C80-55F6-47BB-9E86-8C38514E1980}'] procedure SetName( const Value: String); function GetName: String; property Name: String read GetName write SetName; end; IColumn = interface(IElement) ['{C935A579-F071-44A2-9FE8-E97688943268}'] procedure SetColumnDefinition( const Value: String); function GetColumnDefinition: String; procedure SetInsertable( const Value: Boolean); function GetInsertable: Boolean; procedure SetLength( const Value: Integer); function GetLength: Integer; procedure SetName(const Value: String); function GetName: String; procedure SetNullable( const Value: Boolean); function GetNullable: Boolean; procedure SetPrecision(const Value: Integer); function GetPrecision: Integer; procedure SetScale(const Value: Integer); function GetScale: Integer; procedure SetTable(const Value: String); function GetTable: String; procedure SetUnique(const Value: Boolean); function GetUnique: Boolean; procedure SetUpdatable(const Value: Boolean); function GetUpdatable: Boolean; property ColumnDefinition: String read GetColumnDefinition write SetColumnDefinition; property Insertable: Boolean read GetInsertable write SetInsertable; property Length: Integer read GetLength write SetLength; property Name: String read GetName write SetName; property Nullable: Boolean read GetNullable write SetNullable; property Precision: Integer read GetPrecision write SetPrecision; property Scale: Integer read GetScale write SetScale; property Table: String read GetTable write SetTable; property Unique: Boolean read GetUnique write SetUnique; property Updatable: Boolean read GetUpdatable write SetUpdatable; end; ICollumns = interface(IBaseElement) ['{3B6F6AE0-EB84-47F2-A009-172D235C26A4}'] end; IId = interface(IElement) ['{FCA085B9-06FB-445B-9D95-786F9B5BD07D}'] end; implementation end.
unit uCompression; interface uses System.SysUtils, Classes, System.ZLib; procedure Compress(const ASrc, ADest: string); procedure Decompress(const ASrc, ADest: string); function DoCompression(aContent: TArray<Byte>): TArray<Byte>; function DoDecompression(aContent: TArray<Byte>): TArray<Byte>; function ZCompressString(aText: string; aCompressionLevel: TZCompressionLevel): string; function ZDecompressString(aText: string): string; implementation procedure Compress(const ASrc, ADest: string); var B: array[1..2048] of byte; R: Integer; vSrc: TStream; // source file stream vDest: TStream; // destination file stream vCompressor: TStream; // compression stream begin if not FileExists(ASrc) then raise Exception.Create('Source file does not exist'); vDest := TFileStream.Create(ADest, fmCreate); try vCompressor := TCompressionStream.Create(clMax, vDest); try vSrc := TFileStream.Create(ASrc, fmOpenRead); try repeat R := vSrc.Read(B, SizeOf(B)); if R > 0 then vCompressor.Write(B, R); until R < SizeOf(B); // C.CopyFrom(S, 0); finally vSrc.Free; end; finally vCompressor.Free; end; finally vDest.Free; end; end; procedure Decompress(const ASrc, ADest: string); var B: array[1..2048] of byte; R: Integer; vSrc: TStream; // source file stream vDest: TStream; // destination file stream vDecompressor: TStream; // compression stream begin if not FileExists(ASrc) then raise Exception.Create('Source file does not exist'); vSrc := TFileStream.Create(ASrc, fmOpenRead); try vDecompressor := TDecompressionStream.Create(vSrc); try vDest := TFileStream.Create(ADest, fmCreate or fmShareDenyNone); try repeat R := vDecompressor.Read(B, SizeOf(B)); if R > 0 then vDest.Write(B, R); until R < SizeOf(B); finally vDest.Free; end; finally vDecompressor.Free; end; finally vSrc.Free; end; end; function DoCompression(aContent: TArray<Byte>): TArray<Byte>; var LContentStream, LOutputStream: TBytesStream; LCompressedStream: TZCompressionStream; begin LContentStream := TBytesStream.Create(aContent); try LOutputStream := TBytesStream.Create(nil); try LCompressedStream := TZCompressionStream.Create(LOutputStream, zcDefault, 15 + 16); try LCompressedStream.CopyFrom(LContentStream, 0); finally LCompressedStream.Free; end; Result := Copy(LOutputStream.Bytes, 0, LOutputStream.Size); finally LOutputStream.Free; end; finally LContentStream.Free; end; end; function DoDecompression(aContent: TArray<Byte>): TArray<Byte>; var LContentStream, LOutputStream: TBytesStream; LDecompressedStream: TZDecompressionStream; begin LContentStream := TBytesStream.Create(aContent); try LOutputStream := TBytesStream.Create(nil); try LDecompressedStream := TZDecompressionStream.Create(LContentStream, 15 + 16); try LOutputStream.CopyFrom(LDecompressedStream, 0); finally LDecompressedStream.Free; end; Result := Copy(LOutputStream.Bytes, 0, LOutputStream.Size); finally LOutputStream.Free; end; finally LContentStream.Free; end; end; function ZCompressString(aText: string; aCompressionLevel: TZCompressionLevel): string; var strInput, strOutput: TStringStream; Zipper: TZCompressionStream; begin Result:= ''; strInput:= TStringStream.Create(aText); strOutput:= TStringStream.Create; try Zipper:= TZCompressionStream.Create(strOutput, zcDefault, 15 + 16); try Zipper.CopyFrom(strInput, strInput.Size); finally Zipper.Free; end; Result:= strOutput.DataString; finally strInput.Free; strOutput.Free; end; end; function ZDecompressString(aText: string): string; var strInput, strOutput: TStringStream; Unzipper: TZDecompressionStream; begin Result:= ''; strInput:= TStringStream.Create(aText); strOutput:= TStringStream.Create; try Unzipper:= TZDecompressionStream.Create(strInput); try strOutput.CopyFrom(Unzipper, Unzipper.Size); finally Unzipper.Free; end; Result:= strOutput.DataString; finally strInput.Free; strOutput.Free; end; end; end.
unit UFrmSelectBackupItem; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, VirtualTrees, StdCtrls, ImgList, ComCtrls, ExtCtrls, SyncObjs, UIconUtil, RzPanel, RzDlgBtn, RzTabs, Spin, pngimage, UFmFilter, UFileBaseInfo, UFrameFilter; type // This data record contains all necessary information about a particular file system object. // This can either be a folder (virtual or real) or an image file. PShellObjectData = ^TShellObjectData; TShellObjectData = record FullPath, Display: WideString; IsFolder : Boolean; FileSize : Int64; FileTime : TDateTime; end; TfrmSelectBackupItem = class(TForm) PcMain: TRzPageControl; TsSelectFile: TRzTabSheet; TsGenernal: TRzTabSheet; TsInclude: TRzTabSheet; vstSelectPath: TVirtualStringTree; pl5: TPanel; gbEncrypt: TGroupBox; lbEncPassword: TLabel; lbEncPassword2: TLabel; lbEncPasswordHint: TLabel; lbReqEncPassword: TLabel; lbReqEncPassword2: TLabel; img3: TImage; chkIsEncrypt: TCheckBox; edtEncPassword2: TEdit; edtEncPasswordHint: TEdit; edtEncPassword: TEdit; Panel1: TPanel; GroupBox1: TGroupBox; cbbSyncTime: TComboBox; chkSyncBackupNow: TCheckBox; ChkSyncTime: TCheckBox; seSyncTime: TSpinEdit; Image1: TImage; ilPcMain16: TImageList; chkDisable: TCheckBox; FrameFilter: TFrameFilterPage; Label1: TLabel; tsSelectDes: TRzTabSheet; Panel3: TPanel; Panel4: TPanel; btnOK: TButton; BtnCancel: TButton; btnNext: TButton; Panel2: TPanel; GroupBox3: TGroupBox; Panel5: TPanel; GroupBox2: TGroupBox; LvLocalDes: TListView; lvNetworkDes: TListView; btnAdd: TButton; ilNw16: TImageList; procedure FormCreate(Sender: TObject); procedure vdtBackupFolderHeaderClick(Sender: TVTHeader; Column: TColumnIndex; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure btnOKClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure vstSelectPathGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: String); procedure vstSelectPathFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure vstSelectPathGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure vstSelectPathInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); procedure vstSelectPathInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure vstSelectPathChecked(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure FormShow(Sender: TObject); procedure FrameIncludebtnSelectFileClick(Sender: TObject); procedure FrameExcludebtnSelectFileClick(Sender: TObject); procedure chkIsEncryptClick(Sender: TObject); procedure btnNextClick(Sender: TObject); procedure PcMainPageChange(Sender: TObject); procedure btnAddClick(Sender: TObject); private FDriveStrings: string; function GetDriveString(Index: Integer): string; procedure AddDeskTopPath; procedure ResetSettings; private procedure BindListview; private procedure ReadDefaultSettings; procedure AddSelectPath( FullPath : string ); // Add Path procedure FindSelectPath( Node : PVirtualNode; SelectPathList : TStringList ); // Find Path procedure SetUnChecked( Node : PVirtualNode ); // 清空 Checked procedure SetUnCheckDes; public procedure ClearLastSelected; procedure AddOldSelectPath( PathList : TStringList ); // 添加 已选 function getNewSelectPathList : TStringList; // 获取 新选 function getBackupConfigInfo : TBackupConfigInfo; // 获取 配置信息 public procedure AddLocalDes( DesPath : string ); procedure AddNetworkDes( PcID : string ); function getLocalDesList : TStringList; function getNetworkDesList : TStringList; end; // 默认配置 TReadDefaultSettings = class public procedure Update; private procedure ReadLocalDesAvailableSpace; procedure ReadNetworkDesAvailableSpace; end; const VstSelectBackupPath_FileName = 0; VstSelectBackupPath_FileSize = 1; VstSelectBackupPath_FileTime = 2; var frmSelectBackupItem: TfrmSelectBackupItem; DeskTopPath : string; implementation uses FileCtrl, ShellAPI, Mask, ShlObj, ActiveX, UMyUtil, UFormSetting, UFormUtil, UMyBackupApiInfo, UMyBackupFaceInfo, UMyNetPcInfo; {$R *.DFM} procedure TfrmSelectBackupItem.FormCreate(Sender: TObject); var SFI: TSHFileInfo; i, Count, DriverCount: Integer; DriveMap, Mask: Cardinal; RootNode : PVirtualNode; RootData : PShellObjectData; DriverPath : string; begin BindListview; vstSelectPath.NodeDataSize := SizeOf(TShellObjectData); vstSelectPath.Images := MyIcon.getSysIcon; // Fill root level of image tree. Determine which drives are mapped. DriverCount := 0; DriveMap := GetLogicalDrives; Mask := 1; for i := 0 to 25 do begin if (DriveMap and Mask) <> 0 then Inc(DriverCount); Mask := Mask shl 1; end; // Determine drive strings which are used in the initialization process. Count := GetLogicalDriveStrings(0, nil); SetLength(FDriveStrings, Count); GetLogicalDriveStrings(Count, PChar(FDriveStrings)); // 初始化 磁盘路径 for i := 0 to DriverCount - 1 do begin DriverPath := GetDriveString(i); if not MyHardDisk.getDriverExist( DriverPath ) then Continue; RootNode := vstSelectPath.AddChild( vstSelectPath.RootNode ); RootData := vstSelectPath.GetNodeData( RootNode ); RootData.FullPath := DriverPath; RootData.Display := DriverPath; RootData.FileTime := MyFileInfo.getFileLastWriteTime( DriverPath ); RootData.FileSize := MyHardDisk.getHardDiskAllSize( DriverPath ); RootData.IsFolder := False; end; // 添加 桌面路径 AddDeskTopPath; // 加载配置信息 ResetSettings; end; procedure TfrmSelectBackupItem.FormShow(Sender: TObject); begin PcMain.ActivePage := TsSelectFile; ModalResult := mrCancel; BtnOK.Enabled := False; btnNext.Enabled := False; ReadDefaultSettings; end; procedure TfrmSelectBackupItem.FrameExcludebtnSelectFileClick(Sender: TObject); var SelectPathList : TStringList; begin SelectPathList := getNewSelectPathList; FrameFilter.SetRootPathList( SelectPathList ); FrameFilter.FrameExclude.btnSelectFileClick(Sender); SelectPathList.Free; end; procedure TfrmSelectBackupItem.FrameIncludebtnSelectFileClick(Sender: TObject); var SelectPathList : TStringList; begin SelectPathList := getNewSelectPathList; FrameFilter.SetRootPathList( SelectPathList ); FrameFilter.FrameInclude.btnSelectFileClick(Sender); SelectPathList.Free; end; function TfrmSelectBackupItem.getBackupConfigInfo: TBackupConfigInfo; begin Result := TBackupConfigInfo.Create; Result.SetSyncInfo( ChkSyncTime.Checked, cbbSyncTime.ItemIndex, seSyncTime.Value ); Result.SetBackupInfo( chkSyncBackupNow.Checked, chkDisable.Checked ); Result.SetEncryptInfo( chkIsEncrypt.Checked, edtEncPassword.Text, edtEncPasswordHint.Text ); Result.SetDeleteInfo( False, 3 ); Result.SetIncludeFilterList( FrameFilter.getIncludeFilterList ); Result.SetExcludeFilterList( FrameFilter.getExcludeFilterList ); end; //---------------------------------------------------------------------------------------------------------------------- procedure TfrmSelectBackupItem.AddDeskTopPath; var pitem : PITEMIDLIST; s: string; Node : PVirtualNode; NodeData : PShellObjectData; i : Integer; begin shGetSpecialFolderLocation(handle,CSIDL_DESKTOP,pitem); setlength(s,100); shGetPathFromIDList(pitem,pchar(s)); s := copy( s, 1, Pos( #0, s ) - 1 ); DeskTopPath := s; Node := vstSelectPath.AddChild( vstSelectPath.RootNode ); NodeData := vstSelectPath.GetNodeData( Node ); NodeData.FullPath := DeskTopPath; NodeData.Display := ExtractFileName( DeskTopPath ); NodeData.FileTime := MyFileInfo.getFileLastWriteTime( DeskTopPath ); NodeData.IsFolder := True; end; procedure TfrmSelectBackupItem.AddLocalDes(DesPath: string); var i : Integer; LvLocalDesData : TLocalDesData; begin for i := 0 to LvLocalDes.Items.Count - 1 do begin LvLocalDesData := LvLocalDes.Items[i].Data; LvLocalDes.Items[i].Checked := LvLocalDesData.DesPath = DesPath; end; end; procedure TfrmSelectBackupItem.AddNetworkDes(PcID: string); var i : Integer; NertworkDesData : TNetworkDesData; begin for i := 0 to lvNetworkDes.Items.Count - 1 do begin NertworkDesData := lvNetworkDes.Items[i].Data; lvNetworkDes.Items[i].Checked := NertworkDesData.PcID = PcID; end; end; procedure TfrmSelectBackupItem.AddOldSelectPath(PathList: TStringList); var i : Integer; begin for i := 0 to PathList.Count - 1 do AddSelectPath( PathList[i] ); end; procedure TfrmSelectBackupItem.btnAddClick(Sender: TObject); var DestinationPath : string; begin // 选择目录 DestinationPath := MyHardDisk.getBiggestHardDIsk; if not MySelectFolderDialog.SelectNormal('Select your destination folder', '', DestinationPath) then Exit; DesItemUserApi.AddLocalItem( DestinationPath ); end; procedure TfrmSelectBackupItem.btnCancelClick(Sender: TObject); begin Close; end; procedure TfrmSelectBackupItem.btnNextClick(Sender: TObject); begin PcMain.ActivePageIndex := PcMain.ActivePageIndex + 1; end; procedure TfrmSelectBackupItem.btnOKClick(Sender: TObject); begin Close; ModalResult := mrOk; end; procedure TfrmSelectBackupItem.chkIsEncryptClick(Sender: TObject); var IsShow : Boolean; IsReset : Boolean; begin IsShow := chkIsEncrypt.Checked; lbEncPassword.Enabled := IsShow; edtEncPassword.Enabled := IsShow; lbEncPassword2.Enabled := IsShow; edtEncPassword2.Enabled := IsShow; lbEncPasswordHint.Enabled := IsShow; edtEncPasswordHint.Enabled := IsShow; end; procedure TfrmSelectBackupItem.ClearLastSelected; begin SetUnChecked( vstSelectPath.RootNode ); SetUnCheckDes; end; procedure TfrmSelectBackupItem.ResetSettings; begin FrameFilter.IniFrame; end; //---------------------------------------------------------------------------------------------------------------------- procedure TfrmSelectBackupItem.FindSelectPath(Node: PVirtualNode; SelectPathList : TStringList); var ChildNode : PVirtualNode; NodeData : PShellObjectData; begin ChildNode := Node.FirstChild; while Assigned( ChildNode ) do begin // Disable 的节点跳过 if not ( vsDisabled in ChildNode.States ) then begin if ( ChildNode.CheckState = csCheckedNormal ) then // 找到选择的路径 begin NodeData := vstSelectPath.GetNodeData( ChildNode ); SelectPathList.Add( NodeData.FullPath ); end else if ChildNode.CheckState = csMixedNormal then // 找下一层 FindSelectPath( ChildNode, SelectPathList ); end; ChildNode := ChildNode.NextSibling; end; end; function TfrmSelectBackupItem.GetDriveString(Index: Integer): string; // Helper method to extract a sub string (given by Index) from FDriveStrings. var Head, Tail: PChar; begin Head := PChar(FDriveStrings); Result := ''; repeat Tail := Head; while Tail^ <> #0 do Inc(Tail); if Index = 0 then begin SetString(Result, Head, Tail - Head); Break; end; Dec(Index); Head := Tail + 1; until Head^ = #0; end; function TfrmSelectBackupItem.getLocalDesList: TStringList; var i : Integer; LvLocalDesData : TLocalDesData; begin Result := TStringList.Create; for i := 0 to LvLocalDes.Items.Count - 1 do begin if not LvLocalDes.Items[i].Checked then Continue; LvLocalDesData := LvLocalDes.Items[i].Data; Result.Add( LvLocalDesData.DesPath ); end; end; function TfrmSelectBackupItem.getNetworkDesList: TStringList; var i : Integer; NertworkDesData : TNetworkDesData; begin Result := TStringList.Create; for i := 0 to lvNetworkDes.Items.Count - 1 do begin if not lvNetworkDes.Items[i].Checked then Continue; NertworkDesData := lvNetworkDes.Items[i].Data; Result.Add( NertworkDesData.PcID ); end; end; function TfrmSelectBackupItem.getNewSelectPathList: TStringList; begin Result := TStringList.Create; FindSelectPath( vstSelectPath.RootNode, Result ); end; procedure TfrmSelectBackupItem.PcMainPageChange(Sender: TObject); begin btnNext.Enabled := PcMain.ActivePage <> TsInclude; end; //---------------------------------------------------------------------------------------------------------------------- procedure TfrmSelectBackupItem.AddSelectPath(FullPath: string); var ChildNode : PVirtualNode; NodeData : PShellObjectData; NodeFullPath : string; begin ChildNode := vstSelectPath.RootNode.FirstChild; while Assigned( ChildNode ) do begin NodeData := vstSelectPath.GetNodeData( ChildNode ); NodeFullPath := NodeData.FullPath; // 找到了节点 if FullPath = NodeFullPath then begin ChildNode.CheckState := csCheckedNormal; ChildNode.States := ChildNode.States - [ vsExpanded, vsHasChildren ]; ChildNode.States := ChildNode.States + [ vsDisabled ]; Break; end; // 找到了父节点 if MyMatchMask.CheckChild( FullPath, NodeFullPath ) then begin ChildNode.States := ChildNode.States + [ vsHasChildren ]; ChildNode.CheckState := csMixedNormal; vstSelectPath.ValidateChildren( ChildNode, False ); ChildNode := ChildNode.FirstChild; Continue; end; // 下一个节点 ChildNode := ChildNode.NextSibling; end; end; procedure TfrmSelectBackupItem.BindListview; begin LvLocalDes.SmallImages := MyIcon.getSysIcon; ListviewUtil.BindRemoveData( LvLocalDes ); ListviewUtil.BindRemoveData( lvNetworkDes ); end; procedure TfrmSelectBackupItem.SetUnCheckDes; begin AddLocalDes( '' ); AddNetworkDes( '' ); end; procedure TfrmSelectBackupItem.SetUnChecked(Node: PVirtualNode); var ChildNode : PVirtualNode; NodeData : PShellObjectData; begin ChildNode := Node.FirstChild; while Assigned( ChildNode ) do begin if ChildNode.CheckState <> csUncheckedNormal then begin ChildNode.CheckState := csUncheckedNormal; if vstSelectPath.IsDisabled[ ChildNode ] then begin vstSelectPath.IsDisabled[ ChildNode ] := False; NodeData := vstSelectPath.GetNodeData( ChildNode ); if MyFilePath.getHasChild( NodeData.FullPath ) then vstSelectPath.HasChildren[ ChildNode ] := True; end; SetUnChecked( ChildNode ); end; ChildNode := ChildNode.NextSibling; end; end; procedure TfrmSelectBackupItem.ReadDefaultSettings; var ReadDefaultSettings : TReadDefaultSettings; begin ReadDefaultSettings := TReadDefaultSettings.Create; ReadDefaultSettings.Update; ReadDefaultSettings.Free; end; //---------------------------------------------------------------------------------------------------------------------- procedure TfrmSelectBackupItem.vdtBackupFolderHeaderClick(Sender: TVTHeader; Column: TColumnIndex; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); // Click handler to switch the column on which will be sorted. Since we cannot sort image data sorting is actually // limited to the main column. begin if Button = mbLeft then begin with Sender do begin if Column <> MainColumn then SortColumn := NoColumn else begin if SortColumn = NoColumn then begin SortColumn := Column; SortDirection := sdAscending; end else if SortDirection = sdAscending then SortDirection := sdDescending else SortDirection := sdAscending; Treeview.SortTree(SortColumn, SortDirection, False); end; end; end; end; //---------------------------------------------------------------------------------------------------------------------- procedure TfrmSelectBackupItem.vstSelectPathChecked(Sender: TBaseVirtualTree; Node: PVirtualNode); begin BtnOK.Enabled := True; btnNext.Enabled := True; end; procedure TfrmSelectBackupItem.vstSelectPathFreeNode( Sender: TBaseVirtualTree; Node: PVirtualNode); var Data: PShellObjectData; begin Data := Sender.GetNodeData(Node); Finalize(Data^); // Clear string data. end; procedure TfrmSelectBackupItem.vstSelectPathGetImageIndex( Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var Data: PShellObjectData; begin if ( Column = 0 ) and ( ( Kind = ikNormal ) or ( Kind = ikSelected ) ) then begin Data := Sender.GetNodeData(Node); ImageIndex := MyIcon.getIconByFilePath( Data.FullPath ); end else ImageIndex := -1; end; procedure TfrmSelectBackupItem.vstSelectPathGetText( Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: String); var Data: PShellObjectData; begin Data := Sender.GetNodeData( Node ); if Column = VstSelectBackupPath_FileName then CellText := Data.Display else if Column = VstSelectBackupPath_FileSize then begin if Data.IsFolder then CellText := '' else CellText := MySize.getFileSizeStr( Data.FileSize ) end else if Column = VstSelectBackupPath_FileTime then CellText := DateTimeToStr( Data.FileTime ) else CellText := ''; end; procedure TfrmSelectBackupItem.vstSelectPathInitChildren( Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); var Data, ChildData: PShellObjectData; sr: TSearchRec; FullPath, FileName, FilePath : string; ChildNode: PVirtualNode; LastWriteTimeSystem: TSystemTime; begin Screen.Cursor := crHourGlass; // 搜索目录的信息,找不到则跳过 Data := Sender.GetNodeData(Node); FullPath := MyFilePath.getPath( Data.FullPath ); if FindFirst( FullPath + '*', faAnyfile, sr ) = 0 then begin repeat FileName := sr.Name; if ( FileName = '.' ) or ( FileName = '..' ) then Continue; // 子路径 FilePath := FullPath + FileName; // 桌面路径 if FilePath = DeskTopPath then Continue; // 子节点数据 ChildNode := Sender.AddChild( Node ); ChildData := Sender.GetNodeData(ChildNode); ChildData.FullPath := FilePath; ChildData.Display := MyFileInfo.getFileName( FilePath ); if DirectoryExists( FilePath ) then ChildData.IsFolder := True else begin ChildData.IsFolder := False; ChildData.FileSize := sr.Size end; FileTimeToSystemTime( sr.FindData.ftLastWriteTime, LastWriteTimeSystem ); LastWriteTimeSystem.wMilliseconds := 0; ChildData.FileTime := SystemTimeToDateTime( LastWriteTimeSystem ); // 初始化 if Node.CheckState = csCheckedNormal then // 如果父节点全部Check, 则子节点 check ChildNode.CheckState := csCheckedNormal; Sender.ValidateNode(ChildNode, False); // 子节点数目 Inc( ChildCount ); until FindNext(sr) <> 0; end; FindClose(sr); Screen.Cursor := crDefault; end; procedure TfrmSelectBackupItem.vstSelectPathInitNode( Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var Data: PShellObjectData; begin Data := Sender.GetNodeData(Node); if MyFilePath.getHasChild( Data.FullPath ) then Include(InitialStates, ivsHasChildren); Node.CheckType := ctTriStateCheckBox; end; //---------------------------------------------------------------------------------------------------------------------- { TReadDefaultSettings } procedure TReadDefaultSettings.ReadLocalDesAvailableSpace; var LvLocalDes : TListView; i : Integer; ItemData : TLocalDesData; AvailableSpace : Int64; begin LvLocalDes := frmSelectBackupItem.LvLocalDes; for i := 0 to LvLocalDes.Items.Count - 1 do begin ItemData := LvLocalDes.Items[i].Data; AvailableSpace := MyHardDisk.getHardDiskFreeSize( ItemData.DesPath ); LvLocalDes.Items[i].SubItems[0] := MySize.getFileSizeStr( AvailableSpace ); end; end; procedure TReadDefaultSettings.ReadNetworkDesAvailableSpace; var LvNetworkDes : TListView; i : Integer; ItemData : TNetworkDesData; AvailableSpace : Int64; begin LvNetworkDes := frmSelectBackupItem.lvNetworkDes; for i := 0 to LvNetworkDes.Items.Count - 1 do begin ItemData := LvNetworkDes.Items[i].Data; AvailableSpace := MyNetPcInfoReadUtil.ReadAvaliableSpace( ItemData.PcID ); LvNetworkDes.Items[i].SubItems[0] := MySize.getFileSizeStr( AvailableSpace ); end; end; procedure TReadDefaultSettings.Update; begin with frmSelectBackupItem do begin // Backup Settings ChkSyncTime.Checked := frmSetting.ChkSyncTime.Checked; seSyncTime.Value := frmSetting.seSyncTime.Value; cbbSyncTime.ItemIndex := frmSetting.cbbSyncTime.ItemIndex; chkSyncBackupNow.Checked := True; chkDisable.Checked := False; // Encrypt Settings chkIsEncrypt.Checked := frmSetting.chkIsEncrypt.Checked; edtEncPassword.Text := frmSetting.edtEncPassword.Text; edtEncPassword2.Text := frmSetting.edtEncPassword2.Text; edtEncPasswordHint.Text := frmSetting.edtEncPasswordHint.Text; // Filter Settins FrameFilter.SetDefaultStatus; end; // 读取 目标可用空间 ReadLocalDesAvailableSpace; ReadNetworkDesAvailableSpace; end; end.
unit uNotifyChange; interface uses Windows, SysUtils, Classes; type TNotifyType = (ntLocalOrSharedFolder, ntRegistryKey); TNotifyThread = class(TThread) private FNotifyHandle: THandle; FEvent: THandle; FLastError: DWORD; FCurrentKey: HKEY; FNotifyType: TNotifyType; FObjectName: String; procedure OnChanged; protected procedure Execute; override; public constructor Create(const NotifyType: TNotifyType; const ObjectName: String); property LastError: DWORD read FLastError; end; implementation uses uRegistry; const FILE_NOTIFY_FLAGS = FILE_NOTIFY_CHANGE_FILE_NAME or FILE_NOTIFY_CHANGE_DIR_NAME or FILE_NOTIFY_CHANGE_SIZE or FILE_NOTIFY_CHANGE_LAST_WRITE or FILE_NOTIFY_CHANGE_CREATION; REG_NOTIFY_FLAGS = REG_NOTIFY_CHANGE_NAME or REG_NOTIFY_CHANGE_ATTRIBUTES or REG_NOTIFY_CHANGE_LAST_SET or REG_NOTIFY_CHANGE_SECURITY; constructor TNotifyThread.Create(const NotifyType: TNotifyType; const ObjectName: String); begin inherited Create; FNotifyHandle := INVALID_HANDLE_VALUE; FLastError := ERROR_SUCCESS; FCurrentKey := 0; FNotifyType := NotifyType; FObjectName := ObjectName; end; procedure TNotifyThread.Execute; var RKD: TRegistryKeyData; Handles: array [0..1] of THandle; begin FEvent := CreateEvent(nil, True, False, nil); if FEvent <> 0 then case FNotifyType of ntLocalOrSharedFolder: FNotifyHandle := FindFirstChangeNotification(PChar(FObjectName), True, FILE_NOTIFY_FLAGS); ntRegistryKey: begin RKD := GetRegistryKeyData(FObjectName); if RegOpenKeyEx(RKD.RootKey, PChar(RKD.SubKey), 0, KEY_NOTIFY, FCurrentKey) = ERROR_SUCCESS then FNotifyHandle := RegNotifyChangeKeyValue(FCurrentKey, True, REG_NOTIFY_FLAGS, FEvent, True); end; end; if FNotifyHandle = INVALID_HANDLE_VALUE then FLastError := GetLastError else begin while not Terminated and (FNotifyHandle <> INVALID_HANDLE_VALUE) do begin case FNotifyType of ntLocalOrSharedFolder: begin Handles[0] := FNotifyHandle; Handles[1] := FEvent; case WaitForMultipleObjects(2, PWOHandleArray(@Handles), False, INFINITE) of WAIT_OBJECT_0: if not Terminated then begin OnChanged; if not FindNextChangeNotification(FNotifyHandle) then FLastError := GetLastError; end; WAIT_OBJECT_0 + 1: ; WAIT_FAILED: FLastError := GetLastError; end; end; ntRegistryKey: case WaitForSingleObject(FEvent, INFINITE) of WAIT_OBJECT_0: if not Terminated then begin OnChanged; FNotifyHandle := RegNotifyChangeKeyValue(FCurrentKey, True, REG_NOTIFY_FLAGS, FEvent, True); end; WAIT_FAILED: FLastError := GetLastError; end; end; end; if FNotifyHandle <> INVALID_HANDLE_VALUE then case FNotifyType of ntLocalOrSharedFolder: FindCloseChangeNotification(FNotifyHandle); ntRegistryKey: if FCurrentKey <> 0 then RegCloseKey(FCurrentKey); end; if FEvent <> 0 then begin CloseHandle(FEvent); FEvent := 0; end; end; end; procedure TNotifyThread.OnChanged; begin if FEvent <> 0 then SetEvent(FEvent); end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [CONTABIL_CONTA] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit ContabilContaVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, DB, PlanoContaVO, PlanoContaRefSpedVO; type [TEntity] [TTable('CONTABIL_CONTA')] TContabilContaVO = class(TVO) private FID: Integer; FID_PLANO_CONTA: Integer; FID_CONTABIL_CONTA: Integer; FID_PLANO_CONTA_REF_SPED: Integer; FCLASSIFICACAO: String; FTIPO: String; FDESCRICAO: String; FDATA_INCLUSAO: TDateTime; FSITUACAO: String; FNATUREZA: String; FPATRIMONIO_RESULTADO: String; FLIVRO_CAIXA: String; FDFC: String; FORDEM: String; FCODIGO_REDUZIDO: String; FCODIGO_EFD: String; FPlanoContaNome: String; FPlanoContaSpedDescricao: String; FContabilContaPai: String; FPlanoContaVO: TPlanoContaVO; FPlanoContaRefSpedVO: TPlanoContaRefSpedVO; FContabilContaPaiVO: TContabilContaVO; public constructor Create; override; destructor Destroy; override; [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_PLANO_CONTA', 'Id Plano Conta', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdPlanoConta: Integer read FID_PLANO_CONTA write FID_PLANO_CONTA; [TColumnDisplay('PLANO_CONTA.NOME', 'Plano Conta', 250, [ldGrid, ldLookup, ldComboBox], ftString, 'PlanoContaVO.TPlanoContaVO', True)] property PlanoContaNome: String read FPlanoContaNome write FPlanoContaNome; [TColumn('ID_CONTABIL_CONTA', 'Id Contabil Conta', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdContabilConta: Integer read FID_CONTABIL_CONTA write FID_CONTABIL_CONTA; [TColumnDisplay('CONTABIL_CONTA.DESCRICAO', 'Conta Pai', 250, [ldGrid, ldLookup, ldComboBox], ftString, 'ContabilContaVO.TContabilContaVO', True)] property ContabilContaPai: String read FContabilContaPai write FContabilContaPai; [TColumn('ID_PLANO_CONTA_REF_SPED', 'Id Plano Conta Ref Sped', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdPlanoContaRefSped: Integer read FID_PLANO_CONTA_REF_SPED write FID_PLANO_CONTA_REF_SPED; [TColumnDisplay('PLANO_CONTA_REF_SPED.DESCRICAO', 'Plano Conta Sped', 250, [ldGrid, ldLookup, ldComboBox], ftString, 'PlanoContaRefSpedVO.TPlanoContaRefSpedVO', True)] property PlanoContaSpedDescricao: String read FPlanoContaSpedDescricao write FPlanoContaSpedDescricao; [TColumn('CLASSIFICACAO', 'Classificacao', 240, [ldGrid, ldLookup, ldCombobox], False)] property Classificacao: String read FCLASSIFICACAO write FCLASSIFICACAO; [TColumn('TIPO', 'Tipo', 8, [ldGrid, ldLookup, ldCombobox], False)] property Tipo: String read FTIPO write FTIPO; [TColumn('DESCRICAO', 'Descricao', 450, [ldGrid, ldLookup, ldCombobox], False)] property Descricao: String read FDESCRICAO write FDESCRICAO; [TColumn('DATA_INCLUSAO', 'Data Inclusao', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataInclusao: TDateTime read FDATA_INCLUSAO write FDATA_INCLUSAO; [TColumn('SITUACAO', 'Situacao', 8, [ldGrid, ldLookup, ldCombobox], False)] property Situacao: String read FSITUACAO write FSITUACAO; [TColumn('NATUREZA', 'Natureza', 8, [ldGrid, ldLookup, ldCombobox], False)] property Natureza: String read FNATUREZA write FNATUREZA; [TColumn('PATRIMONIO_RESULTADO', 'Patrimonio Resultado', 8, [ldGrid, ldLookup, ldCombobox], False)] property PatrimonioResultado: String read FPATRIMONIO_RESULTADO write FPATRIMONIO_RESULTADO; [TColumn('LIVRO_CAIXA', 'Livro Caixa', 8, [ldGrid, ldLookup, ldCombobox], False)] property LivroCaixa: String read FLIVRO_CAIXA write FLIVRO_CAIXA; [TColumn('DFC', 'Dfc', 8, [ldGrid, ldLookup, ldCombobox], False)] property Dfc: String read FDFC write FDFC; [TColumn('ORDEM', 'Ordem', 160, [ldGrid, ldLookup, ldCombobox], False)] property Ordem: String read FORDEM write FORDEM; [TColumn('CODIGO_REDUZIDO', 'Codigo Reduzido', 80, [ldGrid, ldLookup, ldCombobox], False)] property CodigoReduzido: String read FCODIGO_REDUZIDO write FCODIGO_REDUZIDO; [TColumn('CODIGO_EFD', 'Codigo Efd', 16, [ldGrid, ldLookup, ldCombobox], False)] property CodigoEfd: String read FCODIGO_EFD write FCODIGO_EFD; [TAssociation('ID', 'ID_PLANO_CONTA')] property PlanoContaVO: TPlanoContaVO read FPlanoContaVO write FPlanoContaVO; [TAssociation('ID', 'ID_PLANO_CONTA_REF_SPED')] property PlanoContaRefSpedVO: TPlanoContaRefSpedVO read FPlanoContaRefSpedVO write FPlanoContaRefSpedVO; [TAssociation('ID', 'ID_CONTABIL_CONTA')] property ContabilContaPaiVO: TContabilContaVO read FContabilContaPaiVO write FContabilContaPaiVO; end; implementation constructor TContabilContaVO.Create; begin inherited; FPlanoContaVO := TPlanoContaVO.Create; FPlanoContaRefSpedVO := TPlanoContaRefSpedVO.Create; /// EXERCICIO /// se nós criamos o objeto abaixo teremos um estouro de pilha. /// ocorre que temos um auto-relacionamento aqui. caso o objeto abaixo /// seja criado ele tentará criar outro do mesmo tipo num laço infinito /// até estourar a pilha. Pense em como resolver esse problema. //FContabilContaPaiVO := TContabilContaVO.Create; end; destructor TContabilContaVO.Destroy; begin FreeAndNil(FPlanoContaVO); FreeAndNil(FPlanoContaRefSpedVO); FreeAndNil(FContabilContaPaiVO); inherited; end; initialization Classes.RegisterClass(TContabilContaVO); finalization Classes.UnRegisterClass(TContabilContaVO); end.
unit MatrixTimingTest; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTimingTest, BaseTestCase, native, BZVectorMath, BZProfiler; type { TMatrixTimingTest } TMatrixTimingTest = class(TVectorBaseTimingTest) protected procedure Setup; override; public {$CODEALIGN RECORDMIN=16} nmtx1,nmtx2, nmtx3 : TNativeBZMatrix4f; mtx1, mtx2, mtx3 : TBZMatrix4f; apl1 : TBZHmgPlane; npl1 : TNativeBZHmgPlane; {$CODEALIGN RECORDMIN=4} published procedure TestAddMatrix; procedure TestAddSingle; procedure TestSubMatrix; procedure TestSubSingle; procedure TestMulMatrix; procedure TestMulSingle; procedure TestMulVector; procedure TestVectorMulMatrix; procedure TestTranposeVectorMulMatrix; procedure TestDivSingle; procedure TestMinus; procedure TestMultiply; procedure TestTranspose; procedure TestGetDeterminant; procedure TestTranslate; procedure TestInvert; procedure TestCreateLookAtMatrix; procedure TestCreateRotationMatrixXAngle; procedure TestCreateRotationMatrixXSinCos; procedure TestCreateRotationMatrixYAngle; procedure TestCreateRotationMatrixYSinCos; procedure TestCreateRotationMatrixZAngle; procedure TestCreateRotationMatrixZSinCos; procedure TestCreateRotationMatrixAxisAngle; procedure TestCreateParallelProjectionMatrix; end; implementation { TMatrixTimingTest } procedure TMatrixTimingTest.Setup; begin inherited Setup; Group := rgMatrix4f; nmtx1.CreateIdentityMatrix; nmtx2.CreateScaleMatrix(nt1); mtx1.CreateIdentityMatrix; mtx2.CreateScaleMatrix(vt1); end; {%region%====[ TMatrixTestCase ]===============================================} procedure TMatrixTimingTest.TestAddMatrix; begin TestDispName := 'Matrix Add Matrix'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nmtx3 := nmtx1 + nmtx2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin mtx3 := mtx1 + mtx2; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestAddSingle; begin TestDispName := 'Matrix Add Single'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nmtx3 := nmtx1 + FS1; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin mtx3 := mtx1 + FS1; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestSubMatrix; begin TestDispName := 'Matrix Sub Matrix'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nmtx3 := nmtx1 - nmtx2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin mtx3 := mtx1 - mtx2; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestSubSingle; begin TestDispName := 'Matrix Sub Single'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nmtx3 := nmtx1 - FS1; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin mtx3 := mtx1 - FS1; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestMulMatrix; begin TestDispName := 'Matrix Multiply Matrix'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nmtx3 := nmtx1 * nmtx2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin mtx3 := mtx1 * mtx2; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestMulSingle; begin TestDispName := 'Matrix Multiply Single'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nmtx3 := nmtx1 * FS1; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin mtx3 := mtx1 * FS1; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestMulVector; begin TestDispName := 'Matrix Multiply Vector'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nt3 := nmtx1 * nt1; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin vt3 := mtx1 * vt1; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestVectorMulMatrix; begin TestDispName := 'Vector Multiply Matrix'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nt3 := nt1 * nmtx1; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin vt3 := vt1 * mtx1; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestTranposeVectorMulMatrix; begin TestDispName := 'Transpose Vector Multiply Matrix'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; nmtx1 := nmtx1.Transpose; for cnt := 1 to Iterations do begin nt3 := nt1 * nmtx1; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; mtx1 := mtx1.Transpose; For cnt:= 1 to Iterations do begin vt3 := vt1 * mtx1; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestDivSingle; begin TestDispName := 'Matrix Divide Single'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nmtx3 := nmtx1 / FS1; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin mtx3 := mtx1 / FS1; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestMinus; begin TestDispName := 'Matrix Negate'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nmtx3 := -nmtx1; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin mtx3 := -mtx1; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestMultiply; begin TestDispName := 'Matrix Component-wise multiplication'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nmtx3 := nmtx1.Multiply(nmtx2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin mtx3 := mtx1.Multiply(mtx2); end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestTranspose; begin TestDispName := 'Matrix Transpose'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nmtx3 := nmtx1.Transpose; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin mtx3 := mtx1.Transpose; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestGetDeterminant; begin TestDispName := 'Matrix Determinant'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin Fs1 := nmtx1.Determinant; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin Fs2 := mtx1.Determinant; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestTranslate; begin TestDispName := 'Matrix Translate'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nmtx3 := nmtx1.Translate(nt1); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin mtx3 := mtx1.Translate(vt1); end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestInvert; begin TestDispName := 'Matrix Invert'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nmtx3 := nmtx2.Invert; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin mtx3 := mtx2.Invert; end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestCreateLookAtMatrix; begin vt1.Create(0,0,10,1); nt1.V := vt1.V; TestDispName := 'Matrix CreateLookAtMatrix;'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nmtx3.CreateLookAtMatrix(nt1,NativeNullHmgPoint,NativeYHmgVector); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin mtx3.CreateLookAtMatrix(vt1,NullHmgPoint,YHmgVector); end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestCreateRotationMatrixXAngle; begin TestDispName := 'Matrix CreateRotationMatrixXAngle;'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nmtx3.CreateRotationMatrixX(pi/2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin mtx3.CreateRotationMatrixX(pi/2); end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestCreateRotationMatrixXSinCos; begin TestDispName := 'Matrix CreateRotationMatrixXSinCos'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nmtx3.CreateRotationMatrixX(1,0); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin mtx3.CreateRotationMatrixX(1,0); end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestCreateRotationMatrixYAngle; begin TestDispName := 'Matrix CreateRotationMatrixYAngle;'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nmtx3.CreateRotationMatrixY(pi/2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin mtx3.CreateRotationMatrixY(pi/2); end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestCreateRotationMatrixYSinCos; begin TestDispName := 'Matrix CreateRotationMatrixYSinCos'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nmtx3.CreateRotationMatrixY(1,0); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin mtx3.CreateRotationMatrixY(1,0); end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestCreateRotationMatrixZAngle; begin TestDispName := 'Matrix CreateRotationMatrixZAngle;'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nmtx3.CreateRotationMatrixZ(pi/2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin mtx3.CreateRotationMatrixZ(pi/2); end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestCreateRotationMatrixZSinCos; begin TestDispName := 'Matrix CreateRotationMatrixZSinCos'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nmtx3.CreateRotationMatrixZ(1,0); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin mtx3.CreateRotationMatrixZ(1,0); end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestCreateRotationMatrixAxisAngle; begin TestDispName := 'Matrix CreateRotationMatrixAxisAngle'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nmtx3.CreateRotationMatrix(NativeZVector,pi/2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin mtx3.CreateRotationMatrix(ZVector,pi/2); end; GlobalProfiler[1].Stop; end; procedure TMatrixTimingTest.TestCreateParallelProjectionMatrix; begin nt1.Create(1,1,0,1); vt1.Create(1,1,0,1); apl1.Create(vt1, ZHmgVector); // create a xy plane at 0 npl1.Create(nt1, NativeZHmgVector); // create a xy plane at 0 TestDispName := 'Matrix CreateParallelProjectionMatrix'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nmtx3.CreateParallelProjectionMatrix(npl1, nt1); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin mtx3.CreateParallelProjectionMatrix(apl1, vt1); end; GlobalProfiler[1].Stop; end; {%endregion%} initialization RegisterTest(REPORT_GROUP_MATRIX4F, TMatrixTimingTest); end.
unit pcnMFeUtil; interface uses Classes, SysUtils, pcnGerador, pcnLeitor, pcnConversao, ACBrUtil, dateutils; type { TComandoMFe } TComandoMFe = class(TPersistent) private FLeitor: TLeitor; FPastaInput : String; FPastaOutput : String; FTimeout : Integer; public constructor Create; destructor Destroy; override; function EnviaComando(numeroSessao: Integer; Nome, Comando : String; TimeOutComando : Integer = 0) : String; function PegaResposta(Resp : String) : String; function AguardaArqResposta(numeroSessao: Integer) : String; function AjustaComando(Comando : String) : String; published property PastaInput : String read FPastaInput write FPastaInput; property PastaOutput : String read FPastaOutput write FPastaOutput; property Timeout : Integer read FTimeout write FTimeout default 30; end; { TIdentificador } TIdentificador = class(TPersistent) private FGerador: TGerador; public constructor Create(AOwner: TGerador); destructor Destroy; override; procedure GerarIdentificador( Identificador : String ); end; { TMetodo } TMetodo = class(TPersistent) private FGerador: TGerador; FIdentificador: TIdentificador; FAdicionarParametros : Boolean; public constructor Create(AOwner: TGerador); destructor Destroy; override; procedure GerarMetodo( Valor : Integer; Componente, Metodo : String ); procedure FinalizarMetodo; property AdicionarParametros : Boolean read FAdicionarParametros write FAdicionarParametros default True; end; { TConstrutor } TConstrutor = class(TPersistent) private FGerador: TGerador; public constructor Create(AOwner: TGerador); destructor Destroy; override; procedure GerarConstructor( Nome, Valor: String ); end; { TParametro } TParametro = class(TPersistent) private FGerador: TGerador; public constructor Create(AOwner: TGerador); destructor Destroy; override; procedure GerarParametro( Nome: String; Valor: Variant; Tipo: TpcnTipoCampo; ParseTextoXML: Boolean = True ); end; implementation { TComandoMFe } constructor TComandoMFe.Create; begin FLeitor := TLeitor.Create; FPastaInput := 'C:\Integrador\Input\'; FPastaOutput := 'C:\Integrador\Output\'; FTimeout := 30; end; destructor TComandoMFe.Destroy; begin FLeitor.Free; inherited Destroy; end; function TComandoMFe.EnviaComando(numeroSessao: Integer; Nome, Comando: String; TimeOutComando : Integer = 0): String; var SL : TStringList; LocTimeOut, ActualTime : TDateTime; NomeArquivo : String; begin Result := ''; SL := TStringList.Create; try NomeArquivo := PathWithDelim(FPastaInput)+Nome+'-'+IntToStr(numeroSessao)+'.tmp'; SL.Add(Comando); SL.SaveToFile(NomeArquivo); // Para evitar a leitura pelo integrador antes do arquivo estar completamente gravado. RenameFile(NomeArquivo, ChangeFileExt(NomeArquivo,'.xml')); ActualTime := Now; if TimeOutComando > 0 then FTimeout := TimeOutComando; if FTimeout <= 0 then LocTimeOut := IncSecond(ActualTime, 30) else LocTimeOut := IncSecond(ActualTime, FTimeout); Result := AguardaArqResposta(numeroSessao); while EstaVazio(Result) and (ActualTime < LocTimeOut) do begin Result := AguardaArqResposta(numeroSessao); Sleep(50); ActualTime := Now; end; finally SL.Free; end; if EstaVazio(Result) then begin if FilesExists(ChangeFileExt(NomeArquivo,'.xml')) then DeleteFile(ChangeFileExt(NomeArquivo,'.xml')); raise Exception.Create('Sem Resposta do Integrador'); end; end; function TComandoMFe.PegaResposta(Resp: String): String; begin FLeitor.Arquivo := Resp; if FLeitor.rExtrai(1, 'Resposta') <> '' then Result := FLeitor.rCampo(tcStr, 'retorno') else if FLeitor.rExtrai(1, 'Erro') <> '' then Result := FLeitor.Grupo else Result := Resp end; function TComandoMFe.AguardaArqResposta(numeroSessao: Integer): String; var SL, SLArqResp : TStringList; I, J, MaxTentativas : Integer; Erro : Boolean; Arquivo: String; begin Result := ''; SL := TStringList.Create; SLArqResp := TStringList.Create; try SLArqResp.Clear; FindFiles(PathWithDelim(FPastaOutput)+'*.xml',SLArqResp); Sleep(50); //Tentar evitar ler arquivo enquanto está sendo escrito for I:=0 to SLArqResp.Count-1 do begin SL.Clear; try SL.LoadFromFile(SLArqResp[I]); //ERRO: Unable to open Arquivo := SL.Text; except J := 0; MaxTentativas := 5; while J < MaxTentativas do begin try Erro := False; Sleep(500); SL.LoadFromFile(SLArqResp[I]); //ERRO: Unable to open Arquivo := SL.Text; except Erro := True; if J = (MaxTentativas-1) then Arquivo := ''; //Caso não consigo abrir, retorna vazio end; if not Erro then Break; Inc(J); end; end; FLeitor.Arquivo := Arquivo; if FLeitor.rExtrai(1, 'Identificador') <> '' then begin if FLeitor.rCampo(tcInt, 'Valor') = numeroSessao then begin Result := Trim(FLeitor.Arquivo); DeleteFile(SLArqResp[I]); Exit; end; end; end; finally SLArqResp.Free; SL.Free; end; end; function TComandoMFe.AjustaComando(Comando: String): String; begin Comando := ChangeLineBreak(Comando,''); while pos(' ', Comando) > 0 do Comando := StringReplace(Comando, ' ', ' ', [rfReplaceAll]); Comando := StringReplace(Comando, '> <', '><', [rfReplaceAll]);; //Comando := StringReplace(Comando,'<'+ENCODING_UTF8+'>','',[rfReplaceAll]); Result := Comando; end; { TMetodo } constructor TMetodo.Create(AOwner: TGerador); begin FGerador := AOwner; FIdentificador := TIdentificador.Create(FGerador); FAdicionarParametros := True; end; destructor TMetodo.Destroy; begin FIdentificador.Free; inherited Destroy; end; procedure TMetodo.GerarMetodo(Valor: Integer; Componente, Metodo: String); begin FGerador.wGrupo('Integrador'); FIdentificador.GerarIdentificador(IntToStr(Valor)); FGerador.wGrupo('Componente Nome="'+Componente+'"'); FGerador.wGrupo('Metodo Nome="'+Metodo+'"'); if AdicionarParametros then FGerador.wGrupo('Parametros'); end; procedure TMetodo.FinalizarMetodo; begin if AdicionarParametros then FGerador.wGrupo('/Parametros'); FGerador.wGrupo('/Metodo'); FGerador.wGrupo('/Componente'); FGerador.wGrupo('/Integrador'); end; { TParametro } constructor TParametro.Create(AOwner: TGerador); begin FGerador := AOwner end; destructor TParametro.Destroy; begin inherited Destroy; end; procedure TParametro.GerarParametro(Nome: String; Valor: Variant; Tipo: TpcnTipoCampo; ParseTextoXML: Boolean); begin FGerador.wGrupo('Parametro'); FGerador.wCampo(tcStr, '', 'Nome', 1, 99, 1, Nome, 'Nome do Parâmetro'); FGerador.wCampo(Tipo , '', 'Valor', 1, 99, 1, Valor, 'Valor do Parâmetro',ParseTextoXML); FGerador.wGrupo('/Parametro'); end; { TConstrutor } constructor TConstrutor.Create(AOwner: TGerador); begin FGerador := AOwner end; destructor TConstrutor.Destroy; begin inherited Destroy; end; procedure TConstrutor.GerarConstructor(Nome, Valor: String); begin FGerador.wGrupo('Construtor'); FGerador.wGrupo('Parametros'); FGerador.wGrupo('Parametro'); FGerador.wCampo(tcStr, '', 'Nome', 1, 99, 1, Nome, 'Nome do Construtor'); FGerador.wCampo(tcStr, '', 'Valor', 1, 99, 1, Valor, 'Valor do Construtor'); FGerador.wGrupo('/Parametro'); FGerador.wGrupo('/Parametros'); FGerador.wGrupo('/Construtor'); end; { TIdentificador } constructor TIdentificador.Create(AOwner: TGerador); begin FGerador := AOwner; end; destructor TIdentificador.Destroy; begin inherited Destroy; end; procedure TIdentificador.GerarIdentificador(Identificador: String); begin FGerador.wGrupo('Identificador'); FGerador.wCampo(tcStr, '', 'Valor', 1, 99, 1, Identificador, 'Valor do Identificador'); FGerador.wGrupo('/Identificador'); end; end.
unit FrmMemoryRecordDropdownSettingsUnit; {$mode delphi} interface uses LCLType, Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, MemoryRecordUnit, CEFuncProc, SynEdit, Menus, betterControls, addresslist, synedittypes; resourcestring rsDDDropdownOtionsFor = 'Dropdown options for '; type { TFrmMemoryRecordDropdownSettings } TFrmMemoryRecordDropdownSettings = class(TForm) btnCancel: TButton; btnOk: TButton; cbDisallowUserInput: TCheckBox; cbOnlyShowDescription: TCheckBox; cbDisplayAsDropdownItem: TCheckBox; doImageList: TImageList; Label1: TLabel; Label2: TLabel; Cut1: TMenuItem; Copy1: TMenuItem; Label3: TLabel; lblFormat: TLabel; Paste1: TMenuItem; Undo1: TMenuItem; Panel0: TPanel; Panel1: TPanel; Panel2: TPanel; PopupMenu1: TPopupMenu; procedure btnOkClick(Sender: TObject); procedure cbDisallowUserInputChange(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure synEditDropdownItemsChange(Sender: TObject); procedure synEditDropdownItemsKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Undo1Click(Sender: TObject); procedure Cut1Click(Sender: TObject); procedure Copy1Click(Sender: TObject); procedure Paste1Click(Sender: TObject); private { private declarations } addressList: TAddresslist; memrec: TMemoryrecord; synEditDropdownItems: TSynEdit; linkedToMemrec: boolean; linkedMemrec: string; public { public declarations } constructor create(memrec: TMemoryrecord; addresslist: TAddresslist); overload; end; implementation {$R *.lfm} { TFrmMemoryRecordDropdownSettings } uses MainUnit,SynPluginMultiCaret; procedure TFrmMemoryRecordDropdownSettings.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin CloseAction:=cafree; end; procedure TFrmMemoryRecordDropdownSettings.FormCreate(Sender: TObject); begin if LoadFormPosition(self) then autosize:=false; end; procedure TFrmMemoryRecordDropdownSettings.FormDestroy(Sender: TObject); begin SaveFormPosition(self); end; procedure TFrmMemoryRecordDropdownSettings.FormShow(Sender: TObject); var wanted: integer; begin if autosize then begin autosize:=false; wanted:=canvas.TextHeight('AjCgyi')*8; if synEditDropdownItems.Height<wanted then height:=height+wanted-synEditDropdownItems.Height; end; synEditDropdownItems.SetFocus; end; procedure TFrmMemoryRecordDropdownSettings.synEditDropdownItemsChange( Sender: TObject); var s: string; options: boolean; mr: TMemoryRecord; begin if (synEditDropdownItems.lines.Count=1) then begin s:=trim(synEditDropdownItems.lines[0]); if length(s)>2 then begin if (s[1]='(') and (s[length(s)]=')') then begin s:=copy(s,2,length(s)-2); mr:=MainForm.addresslist.getRecordWithDescription(s); if mr<>nil then begin cbDisallowUserInput.enabled:=false; cbOnlyShowDescription.enabled:=false; cbDisplayAsDropdownItem.enabled:=false; cbDisallowUserInput.checked:=mr.DropDownReadOnly; cbOnlyShowDescription.checked:=mr.DropDownDescriptionOnly; cbDisplayAsDropdownItem.checked:=mr.DisplayAsDropDownListItem; linkedToMemrec:=true; linkedMemrec:=s; exit; end; end; end; end; linkedToMemrec:=false; if cbDisallowUserInput.enabled=false then cbDisallowUserInput.enabled:=true; if cbOnlyShowDescription.enabled=false then cbOnlyShowDescription.enabled:=true; if cbDisplayAsDropdownItem.enabled=false then cbDisplayAsDropdownItem.enabled:=true; end; procedure TFrmMemoryRecordDropdownSettings.synEditDropdownItemsKeyDown( Sender: TObject; var Key: Word; Shift: TShiftState); begin if key=vk_escape then modalresult:=mrCancel; end; procedure TFrmMemoryRecordDropdownSettings.btnOkClick(Sender: TObject); var i: integer; m: TMemoryRecord; begin if linkedtomemrec then begin memrec.DropDownLinked:=true; memrec.DropDownLinkedMemrec:=linkedMemrec; end else begin memrec.DropDownLinked:=false; memrec.DropDownList.Clear; for i:=0 to synEditDropdownItems.lines.Count-1 do if pos(':', synEditDropdownItems.lines[i])>0 then memrec.DropDownList.add(synEditDropdownItems.lines[i]); memrec.DropDownReadOnly:=cbDisallowUserInput.checked; memrec.DropDownDescriptionOnly:=cbOnlyShowDescription.checked; memrec.DisplayAsDropDownListItem:=cbDisplayAsDropdownItem.checked; end; if addresslist<>nil then //link the other entries to this one begin for i:=0 to addresslist.Count-1 do begin m:=addresslist[i]; if (m.isSelected) and (m<>memrec) then begin m.DropDownLinked:=true; if linkedToMemrec then m.DropDownLinkedMemrec:=linkedMemrec else m.DropDownLinkedMemrec:=memrec.Description; m.DropDownReadOnly:=memrec.DropDownReadOnly; m.DropDownDescriptionOnly:=memrec.DropDownDescriptionOnly; m.DisplayAsDropDownListItem:=memrec.DisplayAsDropDownListItem; end; end; end; modalresult:=mrok; end; procedure TFrmMemoryRecordDropdownSettings.cbDisallowUserInputChange( Sender: TObject); begin label3.visible:=cbDisallowUserInput.checked and cbOnlyShowDescription.checked and cbDisplayAsDropdownItem.checked; end; constructor TFrmMemoryRecordDropdownSettings.create(memrec: TMemoryrecord; addresslist: TAddresslist); var multicaret: TSynPluginMultiCaret; fs: integer; begin inherited create(Application); fs:=font.size; self.memrec:=memrec; self.addressList:=addresslist;; synEditDropdownItems:=TSynEdit.Create(Self); with synEditDropdownItems do begin Name:='synEditDropdownItems'; Text:=''; Parent:=Panel0; Align:=alClient; WantTabs:=false; Options:=[eoKeepCaretX,eoTrimTrailingSpaces]; OnKeyDown:=synEditDropdownItemsKeyDown; OnChange:=synEditDropdownItemsChange; PopupMenu:=PopupMenu1; Gutter.LineNumberPart.Visible:=true; Gutter.ChangesPart.Visible:=true; Gutter.CodeFoldPart.Visible:=false; Gutter.MarksPart.Visible:=false; Gutter.SeparatorPart.Visible:=false; Color:=colorset.TextBackground; Font.color:=colorset.FontColor; Gutter.Color:=clBtnFace; Gutter.LineNumberPart.MarkupInfo.Background:=clBtnFace; Gutter.SeparatorPart.MarkupInfo.Background:=clBtnFace; font.size:=13; end; multicaret:=TSynPluginMultiCaret.Create(synEditDropdownItems); multicaret.EnableWithColumnSelection:=true; multicaret.DefaultMode:=mcmMoveAllCarets; multicaret.DefaultColumnSelectMode:=mcmCancelOnCaretMove; if memrec.DropDownList<>nil then synEditDropdownItems.Lines.AddStrings(memrec.DropDownList); cbDisallowUserInput.checked:=memrec.DropDownReadOnly; cbOnlyShowDescription.checked:=memrec.DropDownDescriptionOnly; cbDisplayAsDropdownItem.checked:=memrec.DisplayAsDropDownListItem; caption:=rsDDDropdownOtionsFor+memrec.description; if memrec.DropDownLinked then begin synEditDropdownItems.Text:='('+memrec.DropDownLinkedMemrec+')'; synEditDropdownItemsChange(synEditDropdownItems); end; end; procedure TFrmMemoryRecordDropdownSettings.Undo1Click(Sender: TObject); begin synEditDropdownItems.Undo; end; procedure TFrmMemoryRecordDropdownSettings.Cut1Click(Sender: TObject); begin synEditDropdownItems.CutToClipboard; end; procedure TFrmMemoryRecordDropdownSettings.Copy1Click(Sender: TObject); begin synEditDropdownItems.CopyToClipboard; end; procedure TFrmMemoryRecordDropdownSettings.Paste1Click(Sender: TObject); begin synEditDropdownItems.PasteFromClipboard; end; end.
unit ReportSys; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, RzTreeVw, frxClass, RzButton, StdCtrls, ExtCtrls, RzPanel, RzSplit, frxDBSet, frxDesgn, DB, ADODB, Menus, RzRadChk; type TReportSysForm = class(TForm) tvReport: TRzTreeView; PTool: TRzSizePanel; MemoSQL: TMemo; BtnSave: TRzBitBtn; ADOQReport: TADOQuery; frxReport3: TfrxReport; frxDBDataset3: TfrxDBDataset; PMReport: TPopupMenu; NModifyTicket: TMenuItem; NRename: TMenuItem; NDelete: TMenuItem; N4: TMenuItem; NCopy: TMenuItem; N6: TMenuItem; NRefresh: TMenuItem; procedure FormShow(Sender: TObject); procedure BtnSaveClick(Sender: TObject); procedure tvReportDblClick(Sender: TObject); procedure NModifyTicketClick(Sender: TObject); procedure NRenameClick(Sender: TObject); procedure tvReportChange(Sender: TObject; Node: TTreeNode); procedure NDeleteClick(Sender: TObject); procedure NCopyClick(Sender: TObject); procedure NRefreshClick(Sender: TObject); procedure FormCreate(Sender: TObject); function frxReport3UserFunction(const MethodName: String; var Params: Variant): Variant; private { Private declarations } currentNode: string; public { Public declarations } procedure refreshTree; procedure GetDirectories(Tree: TRzTreeView; Directory: string; Item: TTreeNode; IncludeFiles: Boolean); function reportFileExists(filename: string): Boolean; function renameReportFile(filename, newFilename: string): Boolean; function readReportSQL(filename: string): string; procedure updateReportSQL(filename: string; sql: string); procedure DeleteReportFile(filename: string); procedure CopyReportFile(filename, newFilename: string); end; var ReportSysForm: TReportSysForm; implementation uses StrUtils, QueryDM, Filter; {$R *.dfm} function MoneyToCn(sourcemoney: Double): string; var strsourcemoney, strobjectmoney: string; thiswei, thispos: string[2]; //thiswei为当前位的大写,thispos为当前位的人民币单位 iwei, pospoint: Integer; //iwei为当前位置,pospoint为小数点的位置 begin strsourcemoney := formatfloat('0.00', sourcemoney); //将浮点数转换成指定格式字符串 if Length(strsourcemoney) > 15 then //超过千亿元 begin ShowMessage('请输入正确的数字,不要超过千亿(15位整数)'); Exit; end; pospoint := Pos('.', strsourcemoney); //小数点位置 for iwei := Length(strsourcemoney) downto 1 do //例如:500.8 = 5 X=4 begin case pospoint - iwei of //小数点位置 - 总长度 = 最后一位单位 -3: thispos := '厘'; -2: thispos := '分'; -1: thispos := '角'; 1: if (pospoint > 2) or (strsourcemoney[iwei] <> '0') then //小数点位置大于零 thispos := '元'; 2: thispos := '拾'; 3: thispos := '佰'; 4: thispos := '仟'; 5: thispos := '万'; 6: thispos := '拾'; 7: thispos := '佰'; 8: thispos := '仟'; 9: thispos := '亿'; 10: thispos := '十'; 11: thispos := '佰'; 12: thispos := '仟'; end; case strsourcemoney[iwei] of //当前数字转换成人民币汉字 '.': Continue; '1': thiswei := '壹'; '2': thiswei := '贰'; '3': thiswei := '叁'; '4': thiswei := '肆'; '5': thiswei := '伍'; '6': thiswei := '陆'; '7': thiswei := '柒'; '8': thiswei := '捌'; '9': thiswei := '玖'; '0': begin thiswei := ''; if iwei < Length(strsourcemoney) then //不是第一位的时候 if (strsourcemoney[iwei + 1] <> '0') and (strsourcemoney[iwei + 1] <> '.') then //当前一位数不是零,即5005 为五千零五。并且 前一位不是. ,即 5.05 为五元五分 thiswei := '零'; if (thispos <> '亿') and (thispos <> '万') and (thispos <> '元') then thispos := '' //单位是十,百、仟 的,为0,则不显示单位。 else thiswei := ''; //若单位为亿、万、元,则前一位0,不显示'零' end; end; strobjectmoney := thiswei + thispos + strobjectmoney; //组合成大写金额 end; strobjectmoney := ansireplacetext(strobjectmoney, '亿万', '亿'); //去掉'亿万'中的'万' if ansicontainsstr(strobjectmoney, '分') then Result := strobjectmoney else begin Result := strobjectmoney; end; end; function Num2CNum(dblArabic: double): string; const _ChineseNumeric = '零壹贰叁肆伍陆柒捌玖'; var sArabic: string; sIntArabic: string; iPosOfDecimalPoint: integer; i: integer; iDigit: integer; iSection: integer; sSectionArabic: string; sSection: string; bInZero: boolean; bMinus: boolean; (* 将字串反向, 例如: 传入 '1234', 传回 '4321' *) function ConvertStr(const sBeConvert: string): string; var x: integer; begin Result := ''; for x := Length(sBeConvert) downto 1 do Result := Result + sBeConvert[x]; end; { of ConvertStr } begin Result := ''; bInZero := True; sArabic := FloatToStr(dblArabic); (* 将数字转成阿拉伯数字字串 *) if sArabic[1] = '-' then begin bMinus := True; sArabic := Copy(sArabic, 2, 254); end else bMinus := False; iPosOfDecimalPoint := Pos('.', sArabic); (* 取得小数点的位置 *) (* 先处理整数的部分 *) if iPosOfDecimalPoint = 0 then sIntArabic := ConvertStr(sArabic) else sIntArabic := ConvertStr(Copy(sArabic, 1, iPosOfDecimalPoint - 1)); (* 从个位数起以每四位数为一小节 *) for iSection := 0 to ((Length(sIntArabic) - 1) div 4) do begin sSectionArabic := Copy(sIntArabic, iSection * 4 + 1, 4); sSection := ''; (* 以下的 i 控制: 个十百千位四个位数 *) for i := 1 to Length(sSectionArabic) do begin iDigit := Ord(sSectionArabic[i]) - 48; if iDigit = 0 then begin (* 1. 避免 '零' 的重覆出现 *) (* 2. 个位数的 0 不必转成 '零' *) if (not bInZero) and (i <> 1) then sSection := '零' + sSection; bInZero := True; end else begin case i of 2: sSection := '拾' + sSection; 3: sSection := '佰' + sSection; 4: sSection := '仟' + sSection; end; sSection := Copy(_ChineseNumeric, 2 * iDigit + 1, 2) + sSection; bInZero := False; end; end; (* 加上该小节的位数 *) if Length(sSection) = 0 then begin if (Length(Result) > 0) and (Copy(Result, 1, 2) <> '零') then Result := '零' + Result; end else begin case iSection of 0: Result := sSection; 1: Result := sSection + '万' + Result; 2: Result := sSection + '亿' + Result; 3: Result := sSection + '兆' + Result; end; end; end; (* 处理小数点右边的部分 *) if iPosOfDecimalPoint > 0 then begin Result := Result + '点'; //AppendStr(Result, '点'); for i := iPosOfDecimalPoint + 1 to Length(sArabic) do begin iDigit := Ord(sArabic[i]) - 48; //AppendStr(Result, Copy(_ChineseNumeric, 2 * iDigit + 1, 2)); Result := Result + Copy(_ChineseNumeric, 2 * iDigit + 1, 2); end; end; (* 其他例外状况的处理 *) if Length(Result) = 0 then Result := '零'; if Copy(Result, 1, 4) = '一十' then Result := Copy(Result, 3, 254); if Copy(Result, 1, 2) = '点' then Result := '零' + Result; (* 是否为负数 *) if bMinus then Result := '负' + Result; end; procedure TReportSysForm.GetDirectories(Tree: TRzTreeView; Directory: string; Item: TTreeNode; IncludeFiles: Boolean); var SearchRec: TSearchRec; ItemTemp: TTreeNode; begin Tree.Items.BeginUpdate; if Directory[Length(Directory)] <> '\' then Directory := Directory + '\'; if FindFirst(Directory + '*.*', faDirectory, SearchRec) = 0 then begin repeat if (SearchRec.Attr and faDirectory = faDirectory) and (SearchRec.Name[1] <> '.') then begin if (SearchRec.Attr and faDirectory > 0) then Item := Tree.Items.AddChild(Item, SearchRec.Name); ItemTemp := Item.Parent; GetDirectories(Tree, Directory + SearchRec.Name, Item, IncludeFiles); Item := ItemTemp; end else begin if IncludeFiles then begin if (SearchRec.Name[1] <> '.') and (RightStr(SearchRec.Name, 3) = 'fr3') then begin Tree.Items.AddChild(Item, SearchRec.Name); end; end; end; until FindNext(SearchRec) <> 0; FindClose(SearchRec); Tree.Items.EndUpdate; end; end; procedure TReportSysForm.FormShow(Sender: TObject); begin ADOQReport.Connection := QueryDataModule.DBConnection; RefreshTree(); end; procedure TReportSysForm.BtnSaveClick(Sender: TObject); begin if currentNode = '' then Exit; try updateReportSQL(currentNode, MemoSQL.Text); Application.MessageBox('脚本更新成功!', '提示', MB_OK + MB_ICONINFORMATION + MB_DEFBUTTON2 + MB_TOPMOST); except end; end; procedure TReportSysForm.tvReportDblClick(Sender: TObject); var s: string; n: TTreeNode; begin MemoSQL.Clear; if RightStr(tvReport.Selected.Text, 3) = 'fr3' then begin n := tvReport.Selected; while n.Parent <> nil do begin s := n.Parent.Text + '\' + s; n := n.Parent; end; currentNode := s + tvReport.Selected.Text; if ReportFileExists(currentNode) then begin MemoSQL.Text := readReportSQL(currentNode); Application.CreateForm(TFilterForm, FilterForm); try with ADOQReport do begin Close; SQL.Clear; FilterForm.adoqReport := ADOQReport; FilterForm.ShowModal; if FilterForm.ret = '' then Exit; SQL.Text := Format(MemoSQL.Text, [FilterForm.ret]); Open; if FileExists(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode) then begin frxReport3.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode); frxReport3.Variables['startDate1'] := FilterForm.DTPStartDate1.Date; frxReport3.Variables['startTime1'] := FilterForm.DTPStartTime1.Time; frxReport3.Variables['endDate1'] := FilterForm.DTPEndDate1.Date; frxReport3.Variables['endTime1'] := FilterForm.DTPEndTime1.Time; frxReport3.Variables['startDate2'] := FilterForm.DTPStartDate2.Date; frxReport3.Variables['startTime2'] := FilterForm.DTPStartTime2.Time; frxReport3.Variables['endDate2'] := FilterForm.DTPEndDate2.Date; frxReport3.Variables['endDate2'] := FilterForm.DTPEndTime2.Time; frxReport3.ShowReport(); end; end; finally FilterForm.Free; end; end; end; end; procedure TReportSysForm.NModifyTicketClick(Sender: TObject); begin if FileExists(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode) then begin frxReport3.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode); frxReport3.DesignReport(); end; end; procedure TReportSysForm.NRenameClick(Sender: TObject); var newNode: string; begin //重命名:文件重命名+INI文件Section改名 if currentNode <> '' then begin newNode := InputBox('请输入新名称 ', '', currentNode); renameReportFile(currentNode, newNode); if FileExists(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode) then begin RenameFile(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode, ExtractFilePath(ParamStr(0)) + 'ReportII\' + newNode); end; RefreshTree(); end; end; procedure TReportSysForm.tvReportChange(Sender: TObject; Node: TTreeNode); var s: string; n: TTreeNode; begin MemoSQL.Clear; if RightStr(tvReport.Selected.Text, 3) = 'fr3' then begin n := tvReport.Selected; while n.Parent <> nil do begin s := n.Parent.Text + '\' + s; n := n.Parent; end; currentNode := s + tvReport.Selected.Text; MemoSQL.Text := readReportSQL(currentNode); end; end; procedure TReportSysForm.NDeleteClick(Sender: TObject); begin if Application.MessageBox('你确定要删除这张报表吗?', '警告', MB_YESNO + MB_ICONWARNING + MB_DEFBUTTON2 + MB_TOPMOST) = IDNO then begin Exit; end; if currentNode <> '' then begin DeleteReportFile(currentNode); if FileExists(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode) then begin DeleteFile(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode); end; RefreshTree(); end; end; procedure TReportSysForm.NCopyClick(Sender: TObject); var newNode: string; begin //重命名:文件重命名+INI文件Section改名 if currentNode <> '' then begin newNode := InputBox('请输入新名称 ', '', currentNode); CopyReportFile(currentNode, newNode); if FileExists(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode) then begin CopyFile(PAnsiChar(ExtractFilePath(ParamStr(0)) + 'ReportII\' + currentNode), PAnsiChar(ExtractFilePath(ParamStr(0)) + 'ReportII\' + newNode), False); end; RefreshTree(); end; end; procedure TReportSysForm.NRefreshClick(Sender: TObject); begin RefreshTree(); end; procedure TReportSysForm.refreshTree; begin tvReport.Items.Clear; GetDirectories(tvReport, ExtractFilePath(ParamStr(0)) + 'ReportII', nil, True); end; procedure TReportSysForm.updateReportSQL(filename, sql: string); var sl: TStringList; begin filename := Copy(filename, 1, Length(filename) - 4); filename := ExtractFilePath(ParamStr(0)) + 'ReportII\' + filename + '.sql'; sl := TStringList.Create; try if FileExists(filename) then sl.LoadFromFile(filename); sl.Text := AnsiToUtf8(sql); sl.SaveToFile(filename); finally sl.Free; end; end; function TReportSysForm.readReportSQL(filename: string): string; var sl: TStringList; begin filename := Copy(filename, 1, Length(filename) - 4); filename := ExtractFilePath(ParamStr(0)) + 'ReportII\' + filename + '.sql'; sl := TStringList.Create; try if FileExists(filename) then sl.LoadFromFile(filename); Result := Utf8ToAnsi(sl.Text); finally sl.Free; end; end; function TReportSysForm.reportFileExists(filename: string): Boolean; begin filename := Copy(filename, 1, Length(filename) - 4); filename := ExtractFilePath(ParamStr(0)) + 'ReportII\' + filename + '.sql'; Result := FileExists(filename); end; function TReportSysForm.renameReportFile(filename, newFilename: string): Boolean; begin filename := Copy(filename, 1, Length(filename) - 4); filename := ExtractFilePath(ParamStr(0)) + 'ReportII\' + filename + '.sql'; newFilename := Copy(newFilename, 1, Length(newFilename) - 4); newFilename := ExtractFilePath(ParamStr(0)) + 'ReportII\' + newFilename + '.sql'; CopyFile(PAnsiChar(filename), PAnsiChar(newFilename), False); if FileExists(filename) then begin DeleteFile(filename); end; end; procedure TReportSysForm.DeleteReportFile(filename: string); begin filename := Copy(filename, 1, Length(filename) - 4); filename := ExtractFilePath(ParamStr(0)) + 'ReportII\' + filename + '.sql'; if FileExists(filename) then begin DeleteFile(filename); end; end; procedure TReportSysForm.CopyReportFile(filename, newFilename: string); begin filename := Copy(filename, 1, Length(filename) - 4); filename := ExtractFilePath(ParamStr(0)) + 'ReportII\' + filename + '.sql'; newFilename := Copy(newFilename, 1, Length(newFilename) - 4); newFilename := ExtractFilePath(ParamStr(0)) + 'ReportII\' + newFilename + '.sql'; CopyFile(PAnsiChar(filename), PAnsiChar(newFilename), False); end; procedure TReportSysForm.FormCreate(Sender: TObject); begin frxReport3.AddFunction('function MoneyToCn(ANumberic: Double): String;', 'Myfunction', '人民币大写金额转换函数'); frxReport3.AddFunction('function Num2CNum(dblArabic: Double): String;', 'Myfunction', '阿拉伯大写金额转换函数'); end; function TReportSysForm.frxReport3UserFunction(const MethodName: String; var Params: Variant): Variant; begin if UpperCase(MethodName) = UpperCase('MoneyToCn') then Result := MoneyToCn(Params[0]); if UpperCase(MethodName) = UpperCase('Num2CNum') then Result := Num2CNum(Params[0]); end; end.
unit jniByteInterpreter; {$mode delphi} interface uses Classes, SysUtils, jni; procedure InitializeJniByteInterpreter(env: PJNIEnv); implementation uses byteinterpreter, commonTypeDefs, unixporthelper; //function readAndParseAddress(address: ptrUint; variableType: TVariableType; customtype: TCustomType=nil; showashexadecimal: Boolean=false; showAsSigned: boolean=false; bytesize:integer=1): string; function byteInterpreter_readAndParseAddressJI(PEnv: PJNIEnv; Obj: JObject; address: jlong; vtype: jint): jstring; cdecl; begin result:=PEnv^.NewStringUTF(PEnv, pchar(readAndParseAddress(address, Tvariabletype(vtype)))); end; function byteInterpreter_readAndParseAddressJIZ(PEnv: PJNIEnv; Obj: JObject; address: jlong; vtype: jint; showAsHexadecimal: jboolean): jstring; cdecl; begin result:=PEnv^.NewStringUTF(PEnv, pchar(readAndParseAddress(address, Tvariabletype(vtype),nil, showAsHexadecimal<>0))); end; function byteInterpreter_readAndParseAddressJIZZ(PEnv: PJNIEnv; Obj: JObject; address: jlong; vtype: jint; showAsHexadecimal: jboolean; showAsSigned: jboolean): jstring; cdecl; begin result:=PEnv^.NewStringUTF(PEnv, pchar(readAndParseAddress(address, Tvariabletype(vtype),nil, showAsHexadecimal<>0, showAsSigned<>0))); end; function byteInterpreter_readAndParseAddressJIZZI(PEnv: PJNIEnv; Obj: JObject; address: jlong; vtype: jint; showAsHexadecimal: jboolean; showAsSigned: jboolean; bytesize: jint): jstring; cdecl; begin result:=PEnv^.NewStringUTF(PEnv, pchar(readAndParseAddress(address, Tvariabletype(vtype),nil, showAsHexadecimal<>0, showAsSigned<>0, bytesize))); end; //parseStringAndWriteToAddress(String value, long address, int variabletype, boolean hexadecimal); function byteInterpreter_parseStringAndWriteToAddress(PEnv: PJNIEnv; Obj: JObject; value: jstring; address: jlong; variabletype: integer; hexadecimal: jboolean): jboolean; var v: string; begin result:=0; try v:=jniGetString(penv, value); ParseStringAndWriteToAddress(v, address, TVariableType(variabletype), hexadecimal<>0); result:=1; except on e: exception do begin log('byteInterpreter_parseStringAndWriteToAddress:'+e.message); end; end; end; const methodcount=5; var jnimethods: array [0..methodcount-1] of JNINativeMethod =( (name: 'readAndParseAddress'; signature: '(JI)Ljava/lang/String;'; fnPtr: @byteInterpreter_readAndParseAddressJI), (name: 'readAndParseAddress'; signature: '(JIZ)Ljava/lang/String;'; fnPtr: @byteInterpreter_readAndParseAddressJIZ), (name: 'readAndParseAddress'; signature: '(JIZZ)Ljava/lang/String;'; fnPtr: @byteInterpreter_readAndParseAddressJIZZ), (name: 'readAndParseAddress'; signature: '(JIZZI)Ljava/lang/String;'; fnPtr: @byteInterpreter_readAndParseAddressJIZZI), (name: 'parseStringAndWriteToAddress'; signature: '(Ljava/lang/String;JIZ)Z'; fnPtr: @byteInterpreter_parseStringAndWriteToAddress) { boolean parseStringAndWriteToAddress(String value, long address, int variabletype, boolean hexadecimal); String value long address int variabletype boolean hexadecimal (Ljava/lang/String;JIZ)Z } ); procedure InitializeJniByteInterpreter(env: PJNIEnv); var c: jclass; begin c:=env^.FindClass(env, 'org/cheatengine/ByteInterpreter'); env^.RegisterNatives(env, c, @jnimethods[0], methodcount); end; end.
unit uPDBGridFilter; interface uses Messages, Classes, Controls, StdCtrls, Forms, DBGrids, uBase, uSession, Vcl.ComCtrls; type TPDBGridFilter = class(TForm) FActive: TCheckBox; FOperator: TComboBox; FNull: TComboBox; FExtender: TButton; FText: TEdit; procedure FormShow(Sender: TObject); procedure FormHide(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FOperatorChange(Sender: TObject); private procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED; procedure WMActivate(var Msg: TWMActivate); message WM_ACTIVATE; protected procedure CreateParams(var Params: TCreateParams); override; public Column: TColumn; end; var PDBGridFilter: TPDBGridFilter; implementation {$R *.dfm} uses Windows, MySQLDB; { TPDBGridFilter **************************************************************} procedure TPDBGridFilter.CMShowingChanged(var Message: TMessage); var Animation: BOOL; begin Include(FFormState, fsShowing); try try if (Showing) then DoShow() else DoHide(); except Application.HandleException(Self); end; if (not Showing) then SetWindowPos(Handle, 0, 0, 0, 0, 0, SWP_HIDEWINDOW or SWP_NOSIZE or SWP_NOMOVE or SWP_NOZORDER) else if (SystemParametersInfo(SPI_GETCLIENTAREAANIMATION, 0, @Animation, 0) and Animation) then AnimateWindow(Handle, 100, AW_VER_POSITIVE or AW_SLIDE or AW_ACTIVATE) else SetWindowPos(Handle, 0, 0, 0, 0, 0, SWP_SHOWWINDOW or SWP_NOSIZE or SWP_NOMOVE or SWP_NOZORDER); DoubleBuffered := Visible; finally Exclude(FFormState, fsShowing); end; end; procedure TPDBGridFilter.CreateParams(var Params: TCreateParams); begin inherited; Params.Style := WS_POPUP or WS_BORDER; Params.WindowClass.Style := Params.WindowClass.Style or CS_DROPSHADOW; if (Assigned(PopupParent)) then Params.WndParent := PopupParent.Handle; end; procedure TPDBGridFilter.FOperatorChange(Sender: TObject); begin FNull.Visible := (FOperator.Text = 'IS'); FText.Visible := not FNull.Visible; end; procedure TPDBGridFilter.FormCreate(Sender: TObject); begin FExtender.Height := FText.Height; FExtender.Width := FExtender.Height; end; procedure TPDBGridFilter.FormHide(Sender: TObject); begin FOperator.Items.BeginUpdate(); FOperator.Items.Clear(); FOperator.Items.EndUpdate(); end; procedure TPDBGridFilter.FormShow(Sender: TObject); begin FOperator.Items.BeginUpdate(); FOperator.Items.Add('='); FOperator.Items.Add('<>'); FOperator.Items.Add('>'); FOperator.Items.Add('<'); if (Column.Field.DataType in TextDataTypes) then begin FOperator.Items.Add('LIKE'); FOperator.Items.Add('NOT LIKE'); end; if (not Column.Field.Required) then FOperator.Items.Add('IS'); FOperator.Items.EndUpdate(); FOperator.ItemIndex := 0; FText.Text := Column.Field.AsString; if (Column.Field.IsNull) then FNull.ItemIndex := 0 else FNull.ItemIndex := 1; FOperatorChange(FOperator); if (FNull.Visible) then ActiveControl := FNull else ActiveControl := FText; end; procedure TPDBGridFilter.WMActivate(var Msg: TWMActivate); begin if ((Msg.Active <> WA_INACTIVE) and Assigned(PopupParent)) then SendMessage(PopupParent.Handle, WM_NCACTIVATE, WPARAM(TRUE), 0); inherited; if (Msg.Active = WA_INACTIVE) then Hide(); end; end.
unit Expedicao.Services.uInfracaoMock; interface uses Generics.Collections, Expedicao.Interfaces.uInfracaoPersistencia, Expedicao.Models.uInfracao; type TInfracaoMock = class (TInterfacedObject, IInfracaoPersistencia) private FListaInfracao: TObjectList<TInfracao>; public constructor Create; destructor Destroy; override; function ObterListaInfracao: TList<TInfracao>; function ObterInfracao(pInfracaoOID: Integer): TInfracao; function IncluirInfracao(pInfracao: TInfracao): Boolean; function AlterarInfracao(pInfracao: TInfracao): Boolean; function ExcluirInfracao(pInfracaoOID: Integer): Boolean; end; implementation uses SysUtils; { TInfracaoMock } constructor TInfracaoMock.Create; var lInfracao: TInfracao; begin FListaInfracao := TObjectList<TInfracao>.Create(true); lInfracao := TInfracao.Create; lInfracao.InfracaoOID := 1; lInfracao.VeiculoOID := 1; lInfracao.Data := StrToDate('14/01/2020'); lInfracao.Hora := '10:55'; lInfracao.AutoInfracao := 'xxxx'; lInfracao.Orgao := 'DETRAN'; lInfracao.Valor := 125.90; lInfracao.AutorInfracao := 1; lInfracao.TipoInfracao := 'M'; FListaInfracao.Add(lInfracao); lInfracao := TInfracao.Create; lInfracao.InfracaoOID := 2; lInfracao.VeiculoOID := 2; lInfracao.Data := StrToDate('20/01/2020'); lInfracao.Hora := '22:30'; lInfracao.AutoInfracao := 'yyys'; lInfracao.Orgao := 'DETRAN'; lInfracao.Valor := 201.50; lInfracao.AutorInfracao := 2; lInfracao.TipoInfracao := 'M'; FListaInfracao.Add(lInfracao); end; destructor TInfracaoMock.Destroy; begin FListaInfracao.Clear; FListaInfracao.Free; inherited; end; function TInfracaoMock.AlterarInfracao(pInfracao: TInfracao): Boolean; var lInfracao: TInfracao; begin Result := False; for lInfracao in FListaInfracao do if lInfracao.InfracaoOID = pInfracao.InfracaoOID then begin lInfracao.VeiculoOID := pInfracao.VeiculoOID; lInfracao.Data := pInfracao.Data; lInfracao.Hora := pInfracao.Hora; lInfracao.AutoInfracao := pInfracao.AutoInfracao; lInfracao.Orgao := pInfracao.Orgao; lInfracao.Valor := pInfracao.Valor; lInfracao.AutorInfracao := pInfracao.AutorInfracao; lInfracao.TipoInfracao := pInfracao.TipoInfracao; Result := True; Exit; end; end; function TInfracaoMock.ExcluirInfracao(pInfracaoOID: Integer): Boolean; var lInfracao: TInfracao; begin Result := False; for lInfracao in FListaInfracao do if lInfracao.InfracaoOID = pInfracaoOID then begin FListaInfracao.Remove(lInfracao); Result := True; Exit; end; end; function TInfracaoMock.IncluirInfracao(pInfracao: TInfracao): Boolean; begin pInfracao.InfracaoOID := FListaInfracao.Count + 1; FListaInfracao.Add(pInfracao); Result := True; end; function TInfracaoMock.ObterInfracao(pInfracaoOID: Integer): TInfracao; var lInfracao: TInfracao; begin Result := nil; for lInfracao in FListaInfracao do if lInfracao.InfracaoOID = pInfracaoOID then begin Result := lInfracao; Exit; end; end; function TInfracaoMock.ObterListaInfracao: TList<TInfracao>; var lInfracao: TInfracao; begin Result := TList<TInfracao>.Create; for lInfracao in FListaInfracao do Result.Add(lInfracao); end; end.
unit uWinProcHelper; {$i LibVer.inc} interface uses Windows; function KillProcess(const aProcess: string): Boolean; function GetProcessHandle(const AProcess : string; dwDesiredAccess : DWORD): THandle; function IsProcessRunning(const AProcess: string): Boolean; implementation uses SysUtils, TLHelp32 {$IFDef LEVEL7} , Variants {$EndIf}; // This three units are safe because they not reference Classes function KillProcess(const aProcess: string): Boolean; var ProcessHandle : THandle; begin ProcessHandle := GetProcessHandle (aProcess, PROCESS_TERMINATE); try Result := TerminateProcess (ProcessHandle, 0); finally if ProcessHandle <> 0 then CloseHandle (ProcessHandle); end; end; function GetProcessHandle(const AProcess : string; dwDesiredAccess : DWORD): THandle; var SnapshotHandle : THandle; ProcessEntry32 : TProcessEntry32; ContinueLoop : Boolean; ProcName : string; ProcId : THandle; begin Result := 0; SnapshotHandle := CreateToolhelp32Snapshot (TH32CS_SNAPPROCESS, 0); try try ProcessEntry32.dwSize := SizeOf (ProcessEntry32); ContinueLoop := Process32First (SnapshotHandle, ProcessEntry32); while ContinueLoop do begin ProcName := ExtractFileName(ProcessEntry32.szExeFile); if CompareText(ProcName, AProcess) = 0 then begin ProcId := ProcessEntry32.th32ProcessID; Result := OpenProcess (dwDesiredAccess, False, ProcID); exit; end; ContinueLoop := Process32Next (SnapshotHandle, ProcessEntry32); end; except if Result <> 0 then CloseHandle (Result); raise; end; finally CloseHandle (SnapshotHandle); end; end; function IsProcessRunning(const AProcess: string): Boolean; begin Result := (GetProcessHandle(AProcess, PROCESS_ALL_ACCESS)) <> 0; end; end.
unit PMBuild; interface uses Windows, Messages, SysUtils, Classes, Graphics, Vectors, Math, OpenGL; {$I ..\..\VSEPrimitiveModel.inc} type TVertex=packed record Vertex: TVector3D; Normal: TVector3D; TexCoord: TVector2D; end; TVertexArray=packed array of TVertex; TFace=packed record Vert1, Vert2, Vert3: Word; end; TIndexArray=packed array of TFace; TLineInfo=record Start, Stride: Integer; end; TVertInfo=record Count, LinesCount: Integer; Lines: array[0..3] of TLineInfo; end; TPMBOnLoadTex=function(const TexName: string): Cardinal of object; TPMBOnBindTex=procedure(ID: Cardinal) of object; TPMBModel=class; TPMBObject=class; TPMBMaterial=class private FModel: TPMBModel; FDiffuse, FAmbient, FSpecular, FEmission: TColor; FID, FShininess: Byte; FTexture: Cardinal; FTextureName: string; FUVCount: Integer; procedure SetTexture(const TexName: string); protected function WriteChunk(Data: TStream): Boolean; procedure ReadChunk(Data: TStream; ChunkSize: Integer); public constructor Create(Model: TPMBModel); destructor Destroy; override; procedure DrawUV; procedure Apply; procedure ApplyUV; procedure EndUV; property Model: TPMBModel read FModel; property ID: Byte read FID; property Diffuse: TColor read FDiffuse write FDiffuse; property Ambient: TColor read FAmbient write FAmbient; property Specular: TColor read FSpecular write FSpecular; property Emission: TColor read FEmission write FEmission; property Shininess: Byte read FShininess write FShininess; property Texture: string read FTextureName write SetTexture; end; TPMBTransform=class private FPMTransform: TPMTransform; function GetTranslateX: Single; procedure SetTranslateX(Value: Single); function GetTranslateY: Single; procedure SetTranslateY(Value: Single); function GetTranslateZ: Single; procedure SetTranslateZ(Value: Single); function GetYaw: Single; procedure SetYaw(Value: Single); function GetPitch: Single; procedure SetPitch(Value: Single); function GetRoll: Single; procedure SetRoll(Value: Single); function GetScaleX: Single; procedure SetScaleX(Value: Single); function GetScaleY: Single; procedure SetScaleY(Value: Single); function GetScaleZ: Single; procedure SetScaleZ(Value: Single); protected procedure Read(Data: TStream); procedure Write(Data: TStream); public constructor Create; procedure SetTranslate(Translate: TVector3D; Normalize: Boolean); procedure ScaleTranslate(Scale: Single); procedure SetScale(Scale: TVector3D; Normalize: Boolean); procedure ScaleScale(Scale: Single); procedure Apply; overload; procedure Apply(var VA: TVertexArray); overload; property TranslateX: Single read GetTranslateX write SetTranslateX; property TranslateY: Single read GetTranslateY write SetTranslateY; property TranslateZ: Single read GetTranslateZ write SetTranslateZ; property Yaw: Single read GetYaw write SetYaw; property Pitch: Single read GetPitch write SetPitch; property Roll: Single read GetRoll write SetRoll; property ScaleX: Single read GetScaleX write SetScaleX; property ScaleY: Single read GetScaleY write SetScaleY; property ScaleZ: Single read GetScaleZ write SetScaleZ; end; TPMBMesh=class private FObj: TPMBObject; FTransform: TPMBTransform; FVisible, FDrawNormals, FHasNormals, FHasUV: Boolean; FHighlightVert: Integer; FDrawVerts: TVertexArray; FVerts: packed array of TPMVertex; FFaces: TIndexArray; FSelected: Boolean; procedure CreateDrawVerts; function GetVertsCount: Integer; function GetVertex(Index: Byte): TPMVertex; procedure SetSelected(Value: Boolean); procedure SetVertex(Index: Byte; Vertex: TPMVertex); protected function WriteChunk(Data: TStream): Boolean; procedure ReadChunk(Data: TStream; ChunkID: Byte; ChunkSize: Integer); public constructor Create(Obj: TPMBObject); destructor Destroy; override; procedure Draw; procedure DrawUV; function Import(MeshData: TStream): Boolean; procedure Relink(Obj: TPMBObject); property Obj: TPMBObject read FObj; property Transform: TPMBTransform read FTransform; property Visible: Boolean read FVisible write FVisible; property DrawNormals: Boolean read FDrawNormals write FDrawNormals; property HasNormals: Boolean read FHasNormals write FHasNormals; property HasUV: Boolean read FHasUV write FHasUV; property VertsCount: Integer read GetVertsCount; property Verts[Index: Byte]: TPMVertex read GetVertex write SetVertex; property HighlightVert: Integer read FHighlightVert write FHighlightVert; property Selected: Boolean read FSelected write SetSelected; end; TPMBPrimitive=class private FSelected: Boolean; procedure SetSelected(Value: Boolean); protected FObj: TPMBObject; FType, FFlags: Byte; FTransform: TPMBTransform; FVerts: TVertexArray; FFaces: TIndexArray; FVisible, FDrawNormals, FTexGenUV, FInvertNormals: Boolean; procedure Quad(At: Integer; V1, V2, V3, V4: Word); function CreateCircle(const Center: TVector3D; Radius: Single; Sector: Byte; Count: Integer; Smooth, DoubleLine: Boolean): TVertInfo; procedure CreateTCLine(FromX, ToX, FromY, ToY: Single; const VertInfo: TVertInfo); procedure CreateTCCircle(CenterX, CenterY, Radius: Single; const VertInfo: TVertInfo); procedure CreateStrip(Line1Start, Line1Stride, Line2Start, Line2Stride, Count: Integer; Smooth: Boolean); function CreateVerts: Boolean; virtual; abstract; function WriteChunk(Data: TStream): Boolean; class function ReadChunk(Obj: TPMBObject; Data: TStream; ChunkSize: Integer): TPMBPrimitive; procedure UpdateFlags; virtual; abstract; function DoWriteChunk(Data: TStream): Boolean; virtual; abstract; procedure DoReadChunk(Data: TStream; ChunkSize: Integer); virtual; abstract; public constructor Create(Obj: TPMBObject); destructor Destroy; override; procedure Draw; procedure DrawUV; procedure Relink(Obj: TPMBObject); property Obj: TPMBObject read FObj; property PriType: Byte read FType; property Transform: TPMBTransform read FTransform; property Visible: Boolean read FVisible write FVisible; property DrawNormals: Boolean read FDrawNormals write FDrawNormals; property TexGenUV: Boolean read FTexGenUV write FTexGenUV; property InvertNormals: Boolean read FInvertNormals write FInvertNormals; property Selected: Boolean read FSelected write SetSelected; end; TPMBPrimitiveCube=class(TPMBPrimitive) private FTexUV: packed array[0..2] of TPMUVRect; FTexMergeSides: array[0..2] of Boolean; function GetUV(Index: Byte): TPMUVRect; procedure SetUV(Index: Byte; Value: TPMUVRect); function GetSplitSides(Index: Byte): Boolean; procedure SetSplitSides(Index: Byte; Value: Boolean); protected function CreateVerts: Boolean; override; procedure UpdateFlags; override; function DoWriteChunk(Data: TStream): Boolean; override; procedure DoReadChunk(Data: TStream; ChunkSize: Integer); override; public constructor Create(Obj: TPMBObject); property TexUV[Index: Byte]: TPMUVRect read GetUV write SetUV; property TexSplitSides[Index: Byte]: Boolean read GetSplitSides write SetSplitSides; end; TPMBPrimitiveSphere = class(TPMBPrimitive) //TODO: Alternative TexGen flag private FSmooth: Boolean; FSlices, FStacks, FSlicesSector, FStacksSector: Byte; FTexUV: TPMUVRect; protected function CreateVerts: Boolean; override; procedure UpdateFlags; override; function DoWriteChunk(Data: TStream): Boolean; override; procedure DoReadChunk(Data: TStream; ChunkSize: Integer); override; public constructor Create(Obj: TPMBObject); property Smooth: Boolean read FSmooth write FSmooth; property Slices: Byte read FSlices write FSlices; property Stacks: Byte read FStacks write FStacks; property SlicesSector: Byte read FSlicesSector write FSlicesSector; property StacksSector: Byte read FStacksSector write FStacksSector; property TexUV: TPMUVRect read FTexUV write FTexUV; end; TPMBPrimitiveCone=class(TPMBPrimitive) private FSmooth: Boolean; FRadiusT, FRadiusB, FSlices, FSlicesSector: Byte; FUVSide: TPMUVRect; FUVBaseT, FUVBaseB: TPMUVCircle; protected function CreateVerts: Boolean; override; procedure UpdateFlags; override; function DoWriteChunk(Data: TStream): Boolean; override; procedure DoReadChunk(Data: TStream; ChunkSize: Integer); override; public constructor Create(Obj: TPMBObject); property Smooth: Boolean read FSmooth write FSmooth; property RadiusT: Byte read FRadiusT write FRadiusT; property RadiusB: Byte read FRadiusB write FRadiusB; property Slices: Byte read FSlices write FSlices; property SlicesSector: Byte read FSlicesSector write FSlicesSector; property UVSide: TPMUVRect read FUVSide write FUVSide; property UVBaseT: TPMUVCircle read FUVBaseT write FUVBaseT; property UVBaseB: TPMUVCircle read FUVBaseB write FUVBaseB; end; TPMBPrimitiveTorus=class(TPMBPrimitive) private protected function CreateVerts: Boolean; override; procedure UpdateFlags; override; function DoWriteChunk(Data: TStream): Boolean; override; procedure DoReadChunk(Data: TStream; ChunkSize: Integer); override; public constructor Create(Obj: TPMBObject); destructor Destroy; override; end; TPMBPrimitiveTube=class(TPMBPrimitive) private protected function CreateVerts: Boolean; override; procedure UpdateFlags; override; function DoWriteChunk(Data: TStream): Boolean; override; procedure DoReadChunk(Data: TStream; ChunkSize: Integer); override; public constructor Create(Obj: TPMBObject); destructor Destroy; override; end; TPMBObject=class private FModel: TPMBModel; FParent: TPMBObject; FID: Cardinal; FVisible: Boolean; FObjects, FPrimitives: TList; FMaterial: TPMBMaterial; FTransform: TPMBTransform; FMesh: TPMBMesh; FSelected: Boolean; function GetID: string; procedure SetID(const ID: string); procedure SetIID(IID: Cardinal); function GetObjectsCount: Integer; function GetObject(Index: Integer): TPMBObject; procedure SetMesh(Mesh: TPMBMesh); function GetPrimitivesCount: Integer; function GetPrimitive(Index: Integer): TPMBPrimitive; procedure SetSelected(Value: Boolean); protected function AddObject(Obj: TPMBObject): Integer; procedure DeleteObject(Obj: TPMBObject); function AddPrimitive(Primitive: TPMBPrimitive): Integer; procedure DeletePrimitive(Primitive: TPMBPrimitive); function WriteChunk(Data: TStream): Boolean; procedure ReadChunk(Data: TStream; ChunkSize: Integer); overload; //read object chunk procedure ReadChunk(Data: TStream); overload; //read subchunks public constructor Create(Model: TPMBModel; Parent: TPMBObject); destructor Destroy; override; procedure DeselectAll; procedure Draw; procedure DrawUV; procedure Relink(Obj: TPMBObject); overload; procedure Relink(Model: TPMBModel); overload; procedure SetVisibility(Visibility: Boolean); property Model: TPMBModel read FModel; property Parent: TPMBObject read FParent; property Visible: Boolean read FVisible write FVisible; property ID: string read GetID write SetID; property IID: Cardinal read FID write SetIID; property ObjectsCount: Integer read GetObjectsCount; property Objects[Index: Integer]: TPMBObject read GetObject; property Material: TPMBMaterial read FMaterial write FMaterial; property Transform: TPMBTransform read FTransform; property Mesh: TPMBMesh read FMesh write SetMesh; //TODO: Merge with Primitives property PrimitivesCount: Integer read GetPrimitivesCount; property Primitives[Index: Integer]: TPMBPrimitive read GetPrimitive; property Selected: Boolean read FSelected write SetSelected; end; TPMBModel=class private FOnLoadTex: TPMBOnLoadTex; FOnBindTex: TPMBOnBindTex; FObjects, FMaterials: TList; function GetObjectsCount: Integer; function GetObject(Index: Integer): TPMBObject; function GetMaterialsCount: Integer; function GetMaterial(Index: Integer): TPMBMaterial; protected function AddObject(Obj: TPMBObject): Integer; procedure DeleteObject(Obj: TPMBObject); function ObjIDExists(ID: Cardinal): Boolean; function AddMaterial(Mat: TPMBMaterial): Integer; procedure DeleteMaterial(Mat: TPMBMaterial); function GetMaterialID: Byte; function LoadTexture(const TexName: string): Cardinal; procedure BindTexture(ID: Cardinal); procedure ReadChunk(Data: TStream); public constructor Create; destructor Destroy; override; procedure DeselectAll; procedure Draw; procedure SetVisibility(Visibility: Boolean); procedure LoadFromFile(const FileName: string); procedure LoadFromStream(Stream: TStream); procedure SaveToFile(const FileName: string); procedure SaveToStream(Stream: TStream); function FindMaterial(ID: Byte): TPMBMaterial; property ObjectsCount: Integer read GetObjectsCount; property Objects[Index: Integer]: TPMBObject read GetObject; property MaterialsCount: Integer read GetMaterialsCount; property Materials[Index: Integer]: TPMBMaterial read GetMaterial; property OnLoadTex: TPMBOnLoadTex read FOnLoadTex write FOnLoadTex; property OnBindTex: TPMBOnBindTex read FOnBindTex write FOnBindTex; end; function PriTypeToString(PriType: Byte): string; procedure ComputeNormalsTriangles(var VA: array of TVertex; const IA: array of TFace); implementation const SCannotRelinkObjectToAnotherModel = 'Cannot relink object to another model'; SCannotSaveModelResultingFileSize = 'Cannot save model: resulting file size is greater than 65535 bytes'; SCannotLoadModelInvalidFirstChunk = 'Cannot load model: invalid first chunk'; STooLongTextureName = 'Too long texture name'; SCannotFindValidMaterialID = 'Cannot find valid Material ID'; SCannotLoadModelInvalidChunkAt = 'Cannot load model: invalid chunk %d at %d'; SCannotLoadModelChunkSizeMismatch = 'Cannot load model: chunk size mismatch'; NormalizeTo=1; type PIDC=^TIDC; TIDC=packed array[1..4] of Char; function ColorTo4f(Color: TColor): TVector4f; var Clr: packed array[0..3] of Byte absolute Color; begin with Result do begin Red:=Clr[0]/255; Green:=Clr[1]/255; Blue:=Clr[2]/255; Alpha:=Clr[3]/255; end; end; function SelI(Expr: Boolean; ValTrue, ValFalse: Integer): Integer; begin if Expr then Result:=ValTrue else Result:=ValFalse; end; procedure ComputeNormalsTriangles(var VA: array of TVertex; const IA: array of TFace); var i: Integer; Normal: TVector3D; begin for i:=0 to High(IA) do with IA[i] do begin if VectorIsEqual(VA[Vert1].Vertex, VA[Vert2].Vertex) or VectorIsEqual(VA[Vert1].Vertex, VA[Vert3].Vertex) or VectorIsEqual(VA[Vert2].Vertex, VA[Vert3].Vertex) then Continue; Assert((Vert1<Length(VA)) and (Vert2<Length(VA)) and (Vert3<Length(VA)), Format('ComputeNormals: too large index %d: %d, %d, %d', [i, Vert1, Vert2, Vert3])); Normal:=TriangleNormal(VA[Vert1].Vertex, VA[Vert2].Vertex, VA[Vert3].Vertex); VA[Vert1].Normal:=VectorAdd(VA[Vert1].Normal, VectorMultiply(Normal, TriangleAngle(VA[Vert1].Vertex, VA[Vert2].Vertex, VA[Vert3].Vertex))); VA[Vert2].Normal:=VectorAdd(VA[Vert2].Normal, VectorMultiply(Normal, TriangleAngle(VA[Vert2].Vertex, VA[Vert3].Vertex, VA[Vert1].Vertex))); VA[Vert3].Normal:=VectorAdd(VA[Vert3].Normal, VectorMultiply(Normal, TriangleAngle(VA[Vert3].Vertex, VA[Vert1].Vertex, VA[Vert2].Vertex))); end; for i:=0 to High(VA) do VectorNormalize(VA[i].Normal); end; {TPMBMaterial} constructor TPMBMaterial.Create(Model: TPMBModel); begin inherited Create; FModel:=Model; FID:=FModel.GetMaterialID; if FID=0 then raise Exception.Create(SCannotFindValidMaterialID); FModel.AddMaterial(Self); FDiffuse:=TColor($FFFFFFFF); FSpecular:=TColor($FFFFFFFF); FAmbient:=TColor($FF404040); FEmission:=TColor($FF000000); FShininess:=64; end; destructor TPMBMaterial.Destroy; begin FModel.DeleteMaterial(Self); inherited Destroy; end; procedure TPMBMaterial.DrawUV; procedure DrawObj(Obj: TPMBObject); var i: Integer; begin if Obj.Material=Self then Obj.DrawUV; for i:=0 to Obj.ObjectsCount-1 do DrawObj(Obj.Objects[i]); end; var i: Integer; begin ApplyUV; for i:=0 to FModel.ObjectsCount-1 do DrawObj(FModel.Objects[i]); EndUV; end; procedure TPMBMaterial.Apply; var Color: TVector4f; begin FModel.BindTexture(FTexture); Color:=ColorTo4f(FDiffuse); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, @Color); Color:=ColorTo4f(FSpecular); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, @Color); Color:=ColorTo4f(FAmbient); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, @Color); Color:=ColorTo4f(FEmission); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, @Color); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, FShininess/2); end; procedure TPMBMaterial.ApplyUV; const ClrWhite: TVector4f = (Red: 1; Green: 1; Blue: 1; Alpha: 1); ClrBlack: TVector4f = (Red: 0; Green: 0; Blue: 0; Alpha: 1); begin Inc(FUVCount); if FUVCount<>1 then Exit; glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, @ClrWhite); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, @ClrBlack); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, @ClrWhite); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, @ClrBlack); FModel.BindTexture(FTexture); glBegin(GL_QUADS); glTexCoord(0, 0); glVertex(0, 0); glTexCoord(1, 0); glVertex(1, 0); glTexCoord(1, 1); glVertex(1, 1); glTexCoord(0, 1); glVertex(0, 1); glEnd; FModel.BindTexture(0); end; procedure TPMBMaterial.EndUV; begin if FUVCount>0 then Dec(FUVCount); end; procedure TPMBMaterial.SetTexture(const TexName: string); begin if Length(TexName)>255 then raise Exception.Create(STooLongTextureName); FTextureName:=TexName; FTexture:=FModel.LoadTexture(TexName); end; function TPMBMaterial.WriteChunk(Data: TStream): Boolean; var ChunkType, TexNameLen: Byte; ChunkSize: Word; ChunkStart: Integer; begin Result:=false; ChunkStart:=Data.Position; ChunkType:=ChunkMaterial; Data.Write(ChunkType, SizeOf(ChunkType)); Data.Write(ChunkSize, SizeOf(ChunkSize)); Data.Write(FID, SizeOf(FID)); TexNameLen:=Length(FTextureName); Data.Write(TexNameLen, SizeOf(TexNameLen)); if TexNameLen>0 then Data.Write(FTextureName[1], TexNameLen); Data.Write(FDiffuse, SizeOf(FDiffuse)); Data.Write(FSpecular, SizeOf(FSpecular)); Data.Write(FAmbient, SizeOf(FAmbient)); Data.Write(FEmission, SizeOf(FEmission)); Data.Write(FShininess, SizeOf(FShininess)); ChunkSize:=Data.Position-ChunkStart; Data.Seek(ChunkStart+SizeOf(ChunkType), soFromBeginning); Data.Write(ChunkSize, SizeOf(ChunkSize)); Data.Seek(0, soFromEnd); Result:=true; end; procedure TPMBMaterial.ReadChunk(Data: TStream; ChunkSize: Integer); var TexNameLen: Byte; begin ChunkSize:=Data.Position+ChunkSize; //ChunkEnd Data.Read(FID, SizeOf(FID)); Data.Read(TexNameLen, SizeOf(TexNameLen)); if TexNameLen<>0 then begin SetLength(FTextureName, TexNameLen); Data.Read(FTextureName[1], TexNameLen); FTexture:=FModel.LoadTexture(FTextureName); end; Data.Read(FDiffuse, SizeOf(FDiffuse)); Data.Read(FSpecular, SizeOf(FSpecular)); Data.Read(FAmbient, SizeOf(FAmbient)); Data.Read(FEmission, SizeOf(FEmission)); Data.Read(FShininess, SizeOf(FShininess)); if Data.Position<>ChunkSize then raise Exception.Create(SCannotLoadModelChunkSizeMismatch); end; {TPMBTransform} constructor TPMBTransform.Create; begin FPMTransform.ScaleX:=512; FPMTransform.ScaleY:=512; FPMTransform.ScaleZ:=512; end; procedure TPMBTransform.SetTranslate(Translate: TVector3D; Normalize: Boolean); var NormScale: Single; begin if Normalize then begin NormScale:=NormalizeTo/Max(Abs(Translate.X), Max(Abs(Translate.Y), Abs(Translate.Z))); Translate.X:=Translate.X*NormScale; Translate.Y:=Translate.Y*NormScale; Translate.Z:=Translate.Z*NormScale; end; with FPMTransform do begin TranslateX:=Round(Translate.X*512); TranslateY:=Round(Translate.Y*512); TranslateZ:=Round(Translate.Z*512); end; end; procedure TPMBTransform.ScaleTranslate(Scale: Single); begin with FPMTransform do begin TranslateX:=Round(Scale*TranslateX); TranslateY:=Round(Scale*TranslateY); TranslateZ:=Round(Scale*TranslateZ); end; end; procedure TPMBTransform.SetScale(Scale: TVector3D; Normalize: Boolean); var NormScale: Single; begin if Normalize then begin NormScale:=NormalizeTo/Max(Abs(Scale.X), Max(Abs(Scale.Y), Abs(Scale.Z))); Scale.X:=Scale.X*NormScale; Scale.Y:=Scale.Y*NormScale; Scale.Z:=Scale.Z*NormScale; end; with FPMTransform do begin ScaleX:=Round(Scale.X*512); ScaleY:=Round(Scale.Y*512); ScaleZ:=Round(Scale.Z*512); end; end; procedure TPMBTransform.ScaleScale(Scale: Single); begin with FPMTransform do begin ScaleX:=Round(Scale*ScaleX); ScaleY:=Round(Scale*ScaleY); ScaleZ:=Round(Scale*ScaleZ); end; end; procedure TPMBTransform.Apply; begin glScale(ScaleX, ScaleY, ScaleZ); glRotate(RadToDeg(Yaw), 0, 1, 0); glRotate(RadToDeg(Pitch), 1, 0, 0); glRotate(RadToDeg(Roll), 0, 0, -1); glTranslate(TranslateX, TranslateY, TranslateZ); end; procedure TPMBTransform.Apply(var VA: TVertexArray); var i: Integer; Scale, NScale, Translate: TVector3D; Yaw, Pitch, Roll: Single; begin with Scale, FPMTransform do begin X:=ScaleX/512; Y:=ScaleY/512; Z:=ScaleZ/512; end; with NScale, FPMTransform do begin X:=512/ScaleX; Y:=512/ScaleY; Z:=512/ScaleZ; end; with Translate, FPMTransform do begin X:=TranslateX/512; Y:=TranslateY/512; Z:=TranslateZ/512; end; Yaw:=RadToDeg(FPMTransform.Yaw*BDegToRad); Pitch:=RadToDeg(FPMTransform.Pitch*BDegToRad); Roll:=RadToDeg(FPMTransform.Roll*BDegToRad); for i:=0 to High(VA) do with VA[i] do begin Vertex:=VectorMultiply(Vertex, Scale); Normal:=VectorMultiply(Normal, NScale); VectorRotateY(-Yaw, Vertex); VectorRotateY(-Yaw, Normal); VectorRotateX(Pitch, Vertex); VectorRotateX(Pitch, Normal); VectorRotateZ(-Roll, Vertex); VectorRotateZ(-Roll, Normal); Vertex:=VectorAdd(Vertex, Translate); VectorNormalize(Normal); end; end; function TPMBTransform.GetTranslateX: Single; begin Result:=FPMTransform.TranslateX/512; end; procedure TPMBTransform.SetTranslateX(Value: Single); begin FPMTransform.TranslateX:=Round(Value*512); end; function TPMBTransform.GetTranslateY: Single; begin Result:=FPMTransform.TranslateY/512; end; procedure TPMBTransform.SetTranslateY(Value: Single); begin FPMTransform.TranslateY:=Round(Value*512); end; function TPMBTransform.GetTranslateZ: Single; begin Result:=FPMTransform.TranslateZ/512; end; procedure TPMBTransform.SetTranslateZ(Value: Single); begin FPMTransform.TranslateZ:=Round(Value*512); end; function TPMBTransform.GetYaw: Single; begin Result:=BDegToRad*FPMTransform.Yaw; end; procedure TPMBTransform.SetYaw(Value: Single); begin FPMTransform.Yaw:=Round(Value*RadToBDeg); end; function TPMBTransform.GetPitch: Single; begin Result:=BDegToRad*FPMTransform.Pitch; end; procedure TPMBTransform.SetPitch(Value: Single); begin FPMTransform.Pitch:=Round(Value*RadToBDeg); end; function TPMBTransform.GetRoll: Single; begin Result:=BDegToRad*FPMTransform.Roll; end; procedure TPMBTransform.SetRoll(Value: Single); begin FPMTransform.Roll:=Round(Value*RadToBDeg); end; function TPMBTransform.GetScaleX: Single; begin Result:=FPMTransform.ScaleX/512; end; procedure TPMBTransform.SetScaleX(Value: Single); begin FPMTransform.ScaleX:=Round(Value*512); end; function TPMBTransform.GetScaleY: Single; begin Result:=FPMTransform.ScaleY/512; end; procedure TPMBTransform.SetScaleY(Value: Single); begin FPMTransform.ScaleY:=Round(Value*512); end; function TPMBTransform.GetScaleZ: Single; begin Result:=FPMTransform.ScaleZ/512; end; procedure TPMBTransform.SetScaleZ(Value: Single); begin FPMTransform.ScaleZ:=Round(Value*512); end; procedure TPMBTransform.Read(Data: TStream); begin Data.Read(FPMTransform, SizeOf(FPMTransform)); end; procedure TPMBTransform.Write(Data: TStream); begin Data.Write(FPMTransform, SizeOf(FPMTransform)); end; {TPMBMesh} constructor TPMBMesh.Create(Obj: TPMBObject); begin inherited Create; FObj:=Obj; FObj.Mesh:=Self; FTransform:=TPMBTransform.Create; FVisible:=true; FHighlightVert:=-1; FHasNormals:=true; FHasUV:=true; end; destructor TPMBMesh.Destroy; begin FTransform.Free; FObj.Mesh:=nil; Finalize(FFaces); Finalize(FVerts); Finalize(FDrawVerts); inherited Destroy; end; procedure TPMBMesh.Draw; var i: Integer; NVert: TVector3D; begin if not FVisible then Exit; CreateDrawVerts; if FSelected then begin glPushAttrib(GL_LIGHTING_BIT or GL_CURRENT_BIT); glColor(0.5, 0.5, 1.0); glEnable(GL_COLOR_MATERIAL); end; glBegin(GL_TRIANGLES); for i:=0 to High(FFaces) do begin glNormal3fv(@FDrawVerts[FFaces[i].Vert1].Normal); glTexCoord2fv(@FDrawVerts[FFaces[i].Vert1].TexCoord); glVertex3fv(@FDrawVerts[FFaces[i].Vert1].Vertex); glNormal3fv(@FDrawVerts[FFaces[i].Vert2].Normal); glTexCoord2fv(@FDrawVerts[FFaces[i].Vert2].TexCoord); glVertex3fv(@FDrawVerts[FFaces[i].Vert2].Vertex); glNormal3fv(@FDrawVerts[FFaces[i].Vert3].Normal); glTexCoord2fv(@FDrawVerts[FFaces[i].Vert3].TexCoord); glVertex3fv(@FDrawVerts[FFaces[i].Vert3].Vertex); end; glEnd; if FSelected then glPopAttrib; glPushAttrib(GL_ENABLE_BIT or GL_LIGHTING_BIT or GL_CURRENT_BIT); glEnable(GL_COLOR_MATERIAL); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glColor3f(1, 1, 1); if FDrawNormals then begin glBegin(GL_LINES); for i:=0 to High(FFaces) do begin NVert:=VectorAdd(FDrawVerts[FFaces[i].Vert1].Vertex, FDrawVerts[FFaces[i].Vert1].Normal); glVertex3fv(@FDrawVerts[FFaces[i].Vert1].Vertex); glVertex3fv(@NVert); NVert:=VectorAdd(FDrawVerts[FFaces[i].Vert2].Vertex, FDrawVerts[FFaces[i].Vert2].Normal); glVertex3fv(@FDrawVerts[FFaces[i].Vert2].Vertex); glVertex3fv(@NVert); NVert:=VectorAdd(FDrawVerts[FFaces[i].Vert3].Vertex, FDrawVerts[FFaces[i].Vert3].Normal); glVertex3fv(@FDrawVerts[FFaces[i].Vert3].Vertex); glVertex3fv(@NVert); end; glEnd; end; if (FHighlightVert>=0) and (FHighlightVert<VertsCount) then begin glBegin(GL_LINES); with FDrawVerts[FHighlightVert].Vertex do begin glVertex3f(X-0.1, Y, Z); glVertex3f(X+0.1, Y, Z); glVertex3f(X, Y-0.1, Z); glVertex3f(X, Y+0.1, Z); glVertex3f(X, Y, Z-0.1); glVertex3f(X, Y, Z+0.1); end; glEnd; end; glPopAttrib; end; procedure TPMBMesh.DrawUV; var i: Integer; begin if not FHasUV then Exit; CreateDrawVerts; if Assigned(FObj.Material) then FObj.Material.ApplyUV; try for i:=0 to High(FFaces) do begin glBegin(GL_LINE_LOOP); glVertex2fv(@FDrawVerts[FFaces[i].Vert1].TexCoord); glVertex2fv(@FDrawVerts[FFaces[i].Vert2].TexCoord); glVertex2fv(@FDrawVerts[FFaces[i].Vert3].TexCoord); glEnd; end; finally if Assigned(FObj.Material) then FObj.Material.EndUV; end; end; function TPMBMesh.Import(MeshData: TStream): Boolean; var VertsCount: Byte; Verts: packed array of TVertex; FacesCount: Word; i: Integer; MinVert, MaxVert, Scale, NScale, Translate: TVector3D; NPhi, NTheta: Single; begin Result:=false; MeshData.Read(VertsCount, SizeOf(VertsCount)); SetLength(Verts, VertsCount+1); MeshData.Read(Verts[0], (VertsCount+1)*SizeOf(TVertex)); MeshData.Read(FacesCount, SizeOf(FacesCount)); SetLength(FFaces, FacesCount); MeshData.Read(FFaces[0], FacesCount*SizeOf(TFace)); for i:=0 to High(Verts) do begin MinVert.X:=Min(MinVert.X, Verts[i].Vertex.X); MinVert.Y:=Min(MinVert.Y, Verts[i].Vertex.Y); MinVert.Z:=Min(MinVert.Z, Verts[i].Vertex.Z); MaxVert.X:=Max(MaxVert.X, Verts[i].Vertex.X); MaxVert.Y:=Max(MaxVert.Y, Verts[i].Vertex.Y); MaxVert.Z:=Max(MaxVert.Z, Verts[i].Vertex.Z); end; Scale.X:=255/(MaxVert.X-MinVert.X); Scale.Y:=255/(MaxVert.Y-MinVert.Y); Scale.Z:=255/(MaxVert.Z-MinVert.Z); NScale.X:=1/Scale.X; NScale.Y:=1/Scale.Y; NScale.Z:=1/Scale.Z; Translate.X:=-(MaxVert.X+MinVert.X)/2; Translate.Y:=-(MaxVert.Y+MinVert.Y)/2; Translate.Z:=-(MaxVert.Z+MinVert.Z)/2; SetLength(FVerts, Length(Verts)); for i:=0 to High(Verts) do with Verts[i], FVerts[i] do begin X:=Max(Min(Round(Scale.X*(Vertex.X+Translate.X)), 127), -128); Y:=Max(Min(Round(Scale.Y*(Vertex.Y+Translate.Y)), 127), -128); Z:=Max(Min(Round(Scale.Z*(Vertex.Z+Translate.Z)), 127), -128); VectorMultiply(Normal, NScale); VectorScale(Normal, -1); VectorNormalize(Normal); if Normal.X<>0 then begin NPhi:=arctan(Normal.Y/Normal.X); if Normal.X<0 then NPhi:=NPhi+pi; end else NPhi:=0; NTheta:=arccos(Normal.Z); Phi:=Round(RadToBDeg*NPhi); Theta:=Round(2*RadToBDeg*NTheta); if TexCoord.X<0 then TexCoord.X:=TexCoord.X-Floor(TexCoord.X) else TexCoord.X:=Frac(TexCoord.X); if TexCoord.Y<0 then TexCoord.Y:=TexCoord.Y-Floor(TexCoord.Y) else TexCoord.Y:=Frac(TexCoord.Y); U:=Round(TexCoord.X*255); V:=Round(TexCoord.Y*255); end; Scale.X:=1/Scale.X; Scale.Y:=1/Scale.Y; Scale.Z:=1/Scale.Z; FTransform.SetScale(Scale, true); Result:=true; end; function TPMBMesh.WriteChunk(Data: TStream): Boolean; var ChunkType: Byte; ChunkSize: Word; ChunkStart, i: Integer; Header: TPMMesh; PMFaces: packed array of TPMFace; begin Result:=false; ChunkStart:=Data.Position; ChunkType:=ChunkObjectMesh; Data.Write(ChunkType, SizeOf(ChunkType)); Data.Write(ChunkSize, SizeOf(ChunkSize)); Header.VertsCount:=Length(FVerts)-1; Header.FacesCount:=Length(FFaces); Header.Flags:=0; if FHasNormals then Header.Flags:=Header.Flags or MeshHasNormals; if FHasUV then Header.Flags:=Header.Flags or MeshHasUV; Data.Write(Header, SizeOf(Header)); FTransform.Write(Data); for i:=0 to High(FVerts) do begin Data.Write(FVerts[i].X, 3*SizeOf(FVerts[0].X)); if FHasNormals then Data.Write(FVerts[i].Phi, SizeOf(FVerts[0].Phi)+SizeOf(FVerts[0].Theta)); if FHasUV then Data.Write(FVerts[i].U, 2*SizeOf(FVerts[0].U)); end; SetLength(PMFaces, Length(FFaces)); for i:=0 to High(FFaces) do begin PMFaces[i].Vert1:=FFaces[i].Vert1; PMFaces[i].Vert2:=FFaces[i].Vert2; PMFaces[i].Vert3:=FFaces[i].Vert3; end; Data.Write(PMFaces[0], Length(PMFaces)*SizeOf(TPMFace)); ChunkSize:=Data.Position-ChunkStart; Data.Seek(ChunkStart+SizeOf(ChunkType), soFromBeginning); Data.Write(ChunkSize, SizeOf(ChunkSize)); Data.Seek(0, soFromEnd); Result:=true; end; procedure TPMBMesh.ReadChunk(Data: TStream; ChunkID: Byte; ChunkSize: Integer); var Header: TPMMesh; PMFaces: packed array of TPMFace; i: Integer; begin ChunkSize:=ChunkSize+Data.Position; Data.Read(Header, SizeOf(Header)); SetLength(FVerts, Header.VertsCount+1); FHasNormals:=Header.Flags and MeshHasNormals <> 0; FHasUV:=Header.Flags and MeshHasUV <> 0; FTransform.Read(Data); for i:=0 to High(FVerts) do begin Data.Read(FVerts[i].X, 3*SizeOf(FVerts[0].X)); if FHasNormals then Data.Read(FVerts[i].Phi, SizeOf(FVerts[0].Phi)+SizeOf(FVerts[0].Theta)); if FHasUV then Data.Read(FVerts[i].U, 2*SizeOf(FVerts[0].U)); end; SetLength(PMFaces, Header.FacesCount); Data.Read(PMFaces[0], Header.FacesCount*SizeOf(TPMFace)); SetLength(FFaces, Header.FacesCount); for i:=0 to Header.FacesCount-1 do begin FFaces[i].Vert1:=PMFaces[i].Vert1; FFaces[i].Vert2:=PMFaces[i].Vert2; FFaces[i].Vert3:=PMFaces[i].Vert3; end; Finalize(PMFaces); if Data.Position<>ChunkSize then raise Exception.Create(SCannotLoadModelChunkSizeMismatch); end; procedure TPMBMesh.CreateDrawVerts; var i: Integer; begin SetLength(FDrawVerts, Length(FVerts)); for i:=0 to High(FVerts) do with FDrawVerts[i], FVerts[i] do begin Vertex.X:=X/128; Vertex.Y:=Y/128; Vertex.Z:=Z/128; if FHasNormals then begin Normal.X:=cos(Phi*BDegToRad)*sin(Theta*BDegToRad/2); Normal.Y:=sin(Phi*BDegToRad)*sin(Theta*BDegToRad/2); Normal.Z:=cos(Theta*BDegToRad/2); end else VectorClear(Normal); if FHasUV then begin TexCoord.X:=U/255; TexCoord.Y:=V/255; end else VectorClear(TexCoord); end; FTransform.Apply(FDrawVerts); if not FHasNormals then ComputeNormalsTriangles(FDrawVerts, FFaces); end; function TPMBMesh.GetVertsCount: Integer; begin Result:=Length(FVerts); end; function TPMBMesh.GetVertex(Index: Byte): TPMVertex; begin if Index<VertsCount then Result:=FVerts[Index]; end; procedure TPMBMesh.Relink(Obj: TPMBObject); begin if Obj=FObj then Exit; FObj.Mesh:=nil; FObj:=Obj; FObj.Mesh:=Self; end; procedure TPMBMesh.SetSelected(Value: Boolean); begin if Value then FObj.Model.DeselectAll; FSelected:=Value; end; procedure TPMBMesh.SetVertex(Index: Byte; Vertex: TPMVertex); begin if Index<VertsCount then FVerts[Index]:=Vertex; end; {TPMBPrimitive} constructor TPMBPrimitive.Create(Obj: TPMBObject); begin inherited Create; FObj:=Obj; FObj.AddPrimitive(Self); FTransform:=TPMBTransform.Create; FVisible:=true; end; destructor TPMBPrimitive.Destroy; begin FObj.DeletePrimitive(Self); FTransform.Free; Finalize(FFaces); Finalize(FVerts); inherited Destroy; end; procedure TPMBPrimitive.Draw; var i: Integer; NVert: TVector3D; begin if not FVisible or not CreateVerts then Exit; if FInvertNormals then for i:=0 to High(FVerts) do VectorScale(FVerts[i].Normal, -1); if FSelected then begin glPushAttrib(GL_LIGHTING_BIT or GL_CURRENT_BIT); glColor(0.5, 0.5, 1.0); glEnable(GL_COLOR_MATERIAL); end; glBegin(GL_TRIANGLES); for i:=0 to High(FFaces) do begin glNormal3fv(@FVerts[FFaces[i].Vert1].Normal); glTexCoord2fv(@FVerts[FFaces[i].Vert1].TexCoord); glVertex3fv(@FVerts[FFaces[i].Vert1].Vertex); glNormal3fv(@FVerts[FFaces[i].Vert2].Normal); glTexCoord2fv(@FVerts[FFaces[i].Vert2].TexCoord); glVertex3fv(@FVerts[FFaces[i].Vert2].Vertex); glNormal3fv(@FVerts[FFaces[i].Vert3].Normal); glTexCoord2fv(@FVerts[FFaces[i].Vert3].TexCoord); glVertex3fv(@FVerts[FFaces[i].Vert3].Vertex); end; glEnd; if FSelected then glPopAttrib; if FDrawNormals then begin glPushAttrib(GL_ENABLE_BIT or GL_LIGHTING_BIT or GL_CURRENT_BIT); glEnable(GL_COLOR_MATERIAL); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glColor3f(1, 1, 1); glBegin(GL_LINES); for i:=0 to High(FFaces) do begin NVert:=VectorAdd(FVerts[FFaces[i].Vert1].Vertex, FVerts[FFaces[i].Vert1].Normal); glVertex3fv(@FVerts[FFaces[i].Vert1].Vertex); glVertex3fv(@NVert); NVert:=VectorAdd(FVerts[FFaces[i].Vert2].Vertex, FVerts[FFaces[i].Vert2].Normal); glVertex3fv(@FVerts[FFaces[i].Vert2].Vertex); glVertex3fv(@NVert); NVert:=VectorAdd(FVerts[FFaces[i].Vert3].Vertex, FVerts[FFaces[i].Vert3].Normal); glVertex3fv(@FVerts[FFaces[i].Vert3].Vertex); glVertex3fv(@NVert); end; glEnd; glPopAttrib; end; end; procedure TPMBPrimitive.DrawUV; var i: Integer; begin if not CreateVerts then Exit; if Assigned(FObj.Material) then FObj.Material.ApplyUV; try for i:=0 to High(FFaces) do begin glBegin(GL_LINE_LOOP); glVertex2fv(@FVerts[FFaces[i].Vert1].TexCoord); glVertex2fv(@FVerts[FFaces[i].Vert2].TexCoord); glVertex2fv(@FVerts[FFaces[i].Vert3].TexCoord); glEnd; end; finally if Assigned(FObj.Material) then FObj.Material.EndUV; end; end; procedure TPMBPrimitive.Quad(At: Integer; V1, V2, V3, V4: Word); begin with FFaces[At] do begin Vert1:=V1; Vert2:=V2; Vert3:=V3; end; with FFaces[At+1] do begin Vert1:=V1; Vert2:=V3; Vert3:=V4; end; end; function TPMBPrimitive.CreateCircle(const Center: TVector3D; Radius: Single; Sector: Byte; Count: Integer; Smooth, DoubleLine: Boolean): TVertInfo; var i, j: Integer; dPhi: Single; V: TVector3D; Stride: Integer; begin Result.Count:=Count+1; Stride:=SelI(Smooth, 1, 2); Result.LinesCount:=SelI(DoubleLine, SelI(Smooth, 2, 4), SelI(Smooth, 1, 2)); for i:=0 to Result.LinesCount-1 do with Result do begin Lines[i].Start:=Length(FVerts)+(i div 2)*2*Count+(i mod 2)*SelI(Smooth, Count, 1); Lines[i].Stride:=Stride; end; dPhi:=(Sector+1)*pi/(128*Count); SetLength(FVerts, Length(FVerts)+Result.Count*Result.LinesCount); for i:=0 to Count do begin with V do begin X:=Center.X+Radius*Cos(i*dPhi); Y:=Center.Y; Z:=Center.Z+Radius*Sin(i*dPhi); end; for j:=0 to Result.LinesCount-1 do FVerts[Result.Lines[j].Start+i*Result.Lines[j].Stride].Vertex:=V; end; end; procedure TPMBPrimitive.CreateTCLine(FromX, ToX, FromY, ToY: Single; const VertInfo: TVertInfo); var dX, dY: Single; i: Integer; begin {dX:=(ToX-FromX)/Count; dY:=(ToY-FromY)/Count; for i:=0 to Count do with VA[i].TexCoord do begin X:=FromX+i*dX; Y:=FromY+i*dY; end; } end; procedure TPMBPrimitive.CreateTCCircle(CenterX, CenterY, Radius: Single; const VertInfo: TVertInfo); begin end; procedure TPMBPrimitive.CreateStrip(Line1Start, Line1Stride, Line2Start, Line2Stride, Count: Integer; Smooth: Boolean); var i, Start, L1, L2: Integer; begin Start:=Length(FFaces); SetLength(FFaces, Start+2*Count); for i:=0 to Count-1 do begin L1:=Line1Start+i*Line1Stride; L2:=Line2Start+i*Line2Stride; //Quad(Start+i*2, Line1Start+i*Line1Stride end; end; function TPMBPrimitive.WriteChunk(Data: TStream): Boolean; var ChunkType: Byte; ChunkSize: Word; ChunkStart: Integer; begin Result:=false; ChunkStart:=Data.Position; ChunkType:=ChunkObjectPrimitive; Data.Write(ChunkType, SizeOf(ChunkType)); Data.Write(ChunkSize, SizeOf(ChunkSize)); Data.Write(FType, SizeOf(FType)); FTransform.Write(Data); FFlags:=0; if FTexGenUV then FFlags:=FFlags or PMFTexInfo; if FInvertNormals then FFlags:=FFlags or PMFInvertNormals; UpdateFlags; Data.Write(FFlags, SizeOf(FFlags)); DoWriteChunk(Data); ChunkSize:=Data.Position-ChunkStart; Data.Seek(ChunkStart+SizeOf(ChunkType), soFromBeginning); Data.Write(ChunkSize, SizeOf(ChunkSize)); Data.Seek(0, soFromEnd); Result:=true; end; class function TPMBPrimitive.ReadChunk(Obj: TPMBObject; Data: TStream; ChunkSize: Integer): TPMBPrimitive; var ChunkEnd: Integer; PriType: Byte; begin Result:=nil; ChunkEnd:=Data.Position+ChunkSize; Data.Read(PriType, SizeOf(PriType)); case PriType of PrimitiveCube: Result:=TPMBPrimitiveCube.Create(Obj); PrimitiveSphere: Result:=TPMBPrimitiveSphere.Create(Obj); PrimitiveCone: Result:=TPMBPrimitiveCone.Create(Obj); PrimitiveTorus: Result:=TPMBPrimitiveTorus.Create(Obj); PrimitiveTube: Result:=TPMBPrimitiveTube.Create(Obj); else Exit; end; with Result do begin FTransform.Read(Data); Data.Read(FFlags, SizeOf(FFlags)); FTexGenUV:=FFlags and PMFTexInfo <> 0; FInvertNormals:=FFlags and PMFInvertNormals <> 0; DoReadChunk(Data, ChunkEnd-Data.Position); end; if Data.Position<>ChunkEnd then raise Exception.Create(SCannotLoadModelChunkSizeMismatch); end; procedure TPMBPrimitive.Relink(Obj: TPMBObject); begin if Obj=FObj then Exit; FObj.DeletePrimitive(Self); FObj:=Obj; FObj.AddPrimitive(Self); end; procedure TPMBPrimitive.SetSelected(Value: Boolean); begin if Value then FObj.Model.DeselectAll; FSelected:=Value; end; {TPMBPrimitiveCube} constructor TPMBPrimitiveCube.Create(Obj: TPMBObject); begin inherited Create(Obj); FType:=PrimitiveCube; end; function TPMBPrimitiveCube.GetUV(Index: Byte): TPMUVRect; begin if Index<3 then Result:=FTexUV[Index]; end; procedure TPMBPrimitiveCube.SetUV(Index: Byte; Value: TPMUVRect); begin if Index<3 then FTexUV[Index]:=Value; end; function TPMBPrimitiveCube.GetSplitSides(Index: Byte): Boolean; begin if Index<3 then Result:=FTexMergeSides[Index] else Result:=false; end; procedure TPMBPrimitiveCube.SetSplitSides(Index: Byte; Value: Boolean); begin if Index<3 then FTexMergeSides[Index]:=Value; end; function TPMBPrimitiveCube.CreateVerts: Boolean; function Coord(Bit: Integer; Pattern: Byte): Single; begin Result:=((Pattern and (1 shl Bit)) shr Bit); end; const Verts: array[0..23] of Byte = ( $16, $1F, $0B, $02, $30, $39, $2D, $24, $4E, $42, $50, $5C, $6B, $67, $75, $79, $8A, $83, $91, $98, $AF, $A6, $B4, $BD); var MergeInfo: Byte; i, FaceType: Integer; begin Result:=false; SetLength(FVerts, 24); ZeroMemory(@FVerts[0], SizeOf(TVertex)*Length(FVerts)); SetLength(FFaces, 12); MergeInfo:=0; for i:=0 to 2 do if FTexMergeSides[i] then MergeInfo:=MergeInfo or 1 shl i; for i:=0 to High(FVerts) do with FVerts[i] do begin with Vertex do begin X:=Coord(0, Verts[i])-0.5; Y:=Coord(1, Verts[i])-0.5; Z:=Coord(2, Verts[i])-0.5; end; if FTexGenUV then with TexCoord do begin FaceType:=(Verts[i] and $C0) shr 6; X:=FTexUV[FaceType].OrigU/255+Coord(3, Verts[i])*FTexUV[FaceType].SizeU/255; Y:=FTexUV[FaceType].OrigV/255+Coord(4, Verts[i])*FTexUV[FaceType].SizeV/255 +Coord(5, Verts[i])*Coord(FaceType, MergeInfo)*FTexUV[FaceType].SizeV/255; end; end; for i:=0 to 5 do Quad(2*i, 4*i, 4*i+1, 4*i+2, 4*i+3); FTransform.Apply(FVerts); ComputeNormalsTriangles(FVerts, FFaces); Result:=true; end; procedure TPMBPrimitiveCube.UpdateFlags; var i: Byte; begin for i:=0 to 2 do if FTexMergeSides[i] then FFlags:=FFlags or 1 shl i; end; function TPMBPrimitiveCube.DoWriteChunk(Data: TStream): Boolean; begin if FTexGenUV then Data.Write(FTexUV, SizeOf(FTexUV)); Result:=true; end; procedure TPMBPrimitiveCube.DoReadChunk(Data: TStream; ChunkSize: Integer); var i: Integer; begin for i:=0 to 2 do FTexMergeSides[i]:=FFlags and (1 shl i) <> 0; if FTexGenUV then Data.Read(FTexUV, SizeOf(FTexUV)); end; {TPMBPrimitiveSphere} constructor TPMBPrimitiveSphere.Create(Obj: TPMBObject); begin inherited Create(Obj); FType:=PrimitiveSphere; FSmooth:=true; FSlices:=16; FStacks:=8; FSlicesSector:=255; FStacksSector:=255; end; function TPMBPrimitiveSphere.CreateVerts: Boolean; var Slice, Stack, StackLen, VertBase, Start, Start2: Integer; R, H, V, dPhi, dTheta, U0, V0, dU, dV: Single; Vert: TVertex; begin Result:=false; dTheta:=(FStacksSector+1)*pi/(256*FStacks); //dPhi:=2*FSlicesSector*pi/(255*FSlices); U0:=FTexUV.OrigU/255; V0:=FTexUV.OrigV/255; dU:=FTexUV.SizeU/(255*FSlices); dV:=FTexUV.SizeV/(255*FStacks); StackLen:=SelI(FSmooth, FSlices+1, 4*FSlices); VertBase:=SelI(FSmooth, 0, -2*FSlices); VectorClear(Vert.Normal); SetLength(FVerts, SelI(FSmooth, (FSlices+1)*(FStacks+1), 4*FSlices*FStacks)); SetLength(FFaces, 2*FStacks*FSlices); for Stack:=0 to FStacks do begin R:=Sin(Stack*dTheta); if (Stack=0) or ((Stack=FStacks) and (FStacksSector=255)) then R:=0; H:=Cos(Stack*dTheta); V:=V0+Stack*dV; Start:=Stack*StackLen+VertBase; Start2:=Start+StackLen; for Slice:=0 to FSlices do begin with Vert do begin with Vertex do begin X:=R*Cos(Slice*dPhi); Y:=H; Z:=R*Sin(Slice*dPhi); end; if FSmooth then begin Normal:=Vertex; VectorNormalize(Normal); end; if FTexGenUV then with TexCoord do begin X:=U0+Slice*dU; Y:=V; end; end; if FSmooth then FVerts[Start+Slice]:=Vert else begin if Stack>0 then begin if Slice>0 then FVerts[Start+2*Slice-1]:=Vert; if Slice<FSlices then FVerts[Start+2*Slice]:=Vert; end; if Stack<FStacks then begin if Slice>0 then FVerts[Start+2*FSlices+2*Slice-1]:=Vert; if Slice<FSlices then FVerts[Start+2*FSlices+2*Slice]:=Vert; end; end; if (Stack<FStacks) and (Slice<FSlices) then if FSmooth then Quad(2*(Stack*FSlices+Slice), Start+Slice, Start+Slice+1, Start2+Slice+1, Start2+Slice) else Quad(2*(Stack*FSlices+Slice), Start+2*FSlices+2*Slice, Start+2*FSlices+2*Slice+1, Start2+2*Slice+1, Start2+2*Slice); end; end; FTransform.Apply(FVerts); if not FSmooth then ComputeNormalsTriangles(FVerts, FFaces); Result:=true; end; procedure TPMBPrimitiveSphere.UpdateFlags; begin if FSmooth then FFlags:=FFlags or PMFSmooth; end; function TPMBPrimitiveSphere.DoWriteChunk(Data: TStream): Boolean; var Sphere: TPPSphere; begin Result:=false; Sphere.Slices:=FSlices; Sphere.Stacks:=FStacks; Sphere.SlicesSector:=FSlicesSector; Sphere.StacksSector:=FStacksSector; Data.Write(Sphere, SizeOf(Sphere)-SizeOf(Sphere.UV)); Sphere.UV:=FTexUV; if FTexGenUV then Data.Write(Sphere.UV, SizeOf(Sphere.UV)); Result:=true; end; procedure TPMBPrimitiveSphere.DoReadChunk(Data: TStream; ChunkSize: Integer); var Sphere: TPPSphere; begin FSmooth:=FFlags and PMFSmooth <> 0; Data.Read(Sphere, SizeOf(Sphere)-SizeOf(Sphere.UV)); if FTexGenUV then Data.Read(Sphere.UV, SizeOf(Sphere.UV)); FSlices:=Sphere.Slices; FStacks:=Sphere.Stacks; FSlicesSector:=Sphere.SlicesSector; FStacksSector:=Sphere.StacksSector; if FTexGenUV then FTexUV:=Sphere.UV; end; {TPMBPrimitiveCone} constructor TPMBPrimitiveCone.Create(Obj: TPMBObject); begin inherited Create(Obj); FType:=PrimitiveCone; FSmooth:=true; FSlices:=16; FSlicesSector:=255; FRadiusT:=128; FRadiusB:=255; end; function TPMBPrimitiveCone.CreateVerts: Boolean; const Sign: array[0..1] of Integer=(1, -1); var Slice, iY, BaseLen: Integer; dPhi, R, U0, V0, dU, dV: Single; Vert: TVertex; Normal: TVector3D; Radius: array[0..1] of Single; begin Result:=false; dPhi:=2*FSlicesSector*pi/(255*FSlices); U0:=FUVSide.OrigU/255; V0:=FUVSide.OrigV/255; dU:=FUVSide.SizeU/(255*FSlices); dV:=FUVSide.SizeV/255; Radius[0]:=FRadiusB/255; Radius[1]:=FRadiusT/255; VectorClear(Vert.Normal); SetLength(FVerts, SelI(FSmooth, FSlices*4+2, 6*FSlices)); SetLength(FFaces, 4*FSlices-2); BaseLen:=SelI(FSmooth, FSlices+1, 2*FSlices); for iY:=0 to 1 do for Slice:=0 to FSlices do begin with Vert do begin with Vertex do begin X:=Radius[iY]*Cos(Slice*dPhi); Y:=iY-0.5; Z:=Radius[iY]*Sin(Slice*dPhi); end; if FTexGenUV then with TexCoord do begin X:=U0+Slice*dU; Y:=V0+iY*dV; end; end; if FSmooth or (Slice<FSlices) then FVerts[iY*BaseLen+SelI(FSmooth, 1, 2)*Slice]:=Vert; if (Slice>0) and not FSmooth then FVerts[iY*BaseLen+SelI(FSmooth, 1, 2)*Slice-1]:=Vert; if Slice<FSlices then FVerts[2*BaseLen+iY*FSlices+Slice]:=Vert; if (iY=0) and (Slice<FSlices) then if FSmooth then Quad(2*Slice, BaseLen+Slice, BaseLen+Slice+1, Slice+1, Slice) else Quad(2*Slice, BaseLen+2*Slice, BaseLen+2*Slice+1, 2*Slice+1, 2*Slice); if Slice<FSlices-1 then begin with FFaces[2*FSlices+iY*(FSlices-1)+Slice] do begin Vert1:=2*BaseLen+iY*FSlices; Vert2:=2*BaseLen+2*iY*FSlices+Sign[iY]*(Slice+1); Vert3:=2*BaseLen+2*iY*FSlices+Sign[iY]*(Slice+2); end; end; end; FTransform.Apply(FVerts); ComputeNormalsTriangles(FVerts, FFaces); if FSmooth and (FSlicesSector=255) then for iY:=0 to 1 do begin Normal:=VectorAdd(FVerts[iY*BaseLen].Normal, FVerts[iY*BaseLen+BaseLen-1].Normal); VectorNormalize(Normal); FVerts[iY*BaseLen].Normal:=Normal; FVerts[iY*BaseLen+BaseLen-1].Normal:=Normal; end; Result:=true; end; procedure TPMBPrimitiveCone.UpdateFlags; begin if FSmooth then FFlags:=FFlags or PMFSmooth; end; function TPMBPrimitiveCone.DoWriteChunk(Data: TStream): Boolean; var Cone: TPPCone; begin Result:=false; Cone.RadiusT:=FRadiusT; Cone.RadiusB:=FRadiusB; Cone.Slices:=FSlices; Cone.SlicesSector:=FSlicesSector; if FTexGenUV then begin Cone.UVSide:=UVSide; Cone.UVBaseT:=UVBaseT; Cone.UVBaseB:=UVBaseB; end; Data.Write(Cone, SizeOf(Cone)-ConeUVSize); if FTexGenUV then Data.Write(Cone.UVSide, ConeUVSize); Result:=true; end; procedure TPMBPrimitiveCone.DoReadChunk(Data: TStream; ChunkSize: Integer); var Cone: TPPCone; begin FSmooth:=FFlags and PMFSmooth <> 0; Data.Read(Cone, SizeOf(Cone)-ConeUVSize); if FTexGenUV then Data.Read(Cone.UVSide, ConeUVSize); FRadiusT:=Cone.RadiusT; FRadiusB:=Cone.RadiusB; FSlices:=Cone.Slices; FSlicesSector:=Cone.SlicesSector; if FTexGenUV then begin UVSide:=Cone.UVSide; UVBaseT:=Cone.UVBaseT; UVBaseB:=Cone.UVBaseB; end; end; {TPMBPrimitiveTorus} constructor TPMBPrimitiveTorus.Create(Obj: TPMBObject); begin inherited Create(Obj); FType:=PrimitiveTorus; //to do end; destructor TPMBPrimitiveTorus.Destroy; begin //to do inherited Destroy; end; function TPMBPrimitiveTorus.CreateVerts: Boolean; begin Result:=false; end; procedure TPMBPrimitiveTorus.UpdateFlags; begin //to do end; function TPMBPrimitiveTorus.DoWriteChunk(Data: TStream): Boolean; begin //to do end; procedure TPMBPrimitiveTorus.DoReadChunk(Data: TStream; ChunkSize: Integer); begin //to do end; {TPMBPrimitiveTube} constructor TPMBPrimitiveTube.Create(Obj: TPMBObject); begin inherited Create(Obj); FType:=PrimitiveTube; //to do end; destructor TPMBPrimitiveTube.Destroy; begin //to do inherited Destroy; end; function TPMBPrimitiveTube.CreateVerts: Boolean; begin Result:=false; end; procedure TPMBPrimitiveTube.UpdateFlags; begin //to do end; function TPMBPrimitiveTube.DoWriteChunk(Data: TStream): Boolean; begin //to do end; procedure TPMBPrimitiveTube.DoReadChunk(Data: TStream; ChunkSize: Integer); begin //to do end; {TPMBObject} constructor TPMBObject.Create(Model: TPMBModel; Parent: TPMBObject); begin inherited Create; FModel:=Model; FParent:=Parent; if Assigned(FParent) then FParent.AddObject(Self) else FModel.AddObject(Self); FObjects:=TList.Create; FPrimitives:=TList.Create; FTransform:=TPMBTransform.Create; FVisible:=true; end; destructor TPMBObject.Destroy; begin FTransform.Free; if Assigned(FParent) then FParent.DeleteObject(Self) else FModel.DeleteObject(Self); while ObjectsCount>0 do Objects[0].Free; FObjects.Free; while PrimitivesCount>0 do Primitives[0].Free; FPrimitives.Free; inherited Destroy; end; procedure TPMBObject.Draw; var i: Integer; begin glPushMatrix; FTransform.Apply; if FVisible then begin glEnable(GL_NORMALIZE); if Assigned(FMaterial) then FMaterial.Apply; if FSelected then begin glPushAttrib(GL_LIGHTING_BIT or GL_CURRENT_BIT); glColor(0.5, 0.5, 1.0); glEnable(GL_COLOR_MATERIAL); end; if Assigned(FMesh) then FMesh.Draw; for i:=0 to PrimitivesCount-1 do Primitives[i].Draw; if FSelected then glPopAttrib; end; for i:=0 to ObjectsCount-1 do Objects[i].Draw; glPopMatrix; end; procedure TPMBObject.DrawUV; var i: Integer; begin if Assigned(FMaterial) then FMaterial.ApplyUV; try if Assigned(FMesh) then FMesh.DrawUV; for i:=0 to PrimitivesCount-1 do Primitives[i].DrawUV; finally if Assigned(FMaterial) then FMaterial.EndUV; end; end; procedure TPMBObject.SetVisibility(Visibility: Boolean); var i: Integer; begin FVisible:=Visibility; if Assigned(FMesh) then FMesh.Visible:=Visibility; for i:=0 to PrimitivesCount-1 do Primitives[i].Visible:=Visibility; for i:=0 to ObjectsCount-1 do Objects[i].SetVisibility(Visibility); end; function TPMBObject.GetID: string; var i: Integer; IDC: PIDC; begin SetLength(Result, 4); IDC:=@FID; for i:=1 to 4 do if Byte(IDC^[i])<32 then Result[i]:=' ' else Result[i]:=IDC[i]; end; procedure TPMBObject.SetID(const ID: string); var i: Integer; IDC: TIDC; begin for i:=1 to 4 do if i<=Length(ID) then IDC[i]:=ID[i] else IDC[i]:=#32; IID:=Cardinal(IDC); end; procedure TPMBObject.SetIID(IID: Cardinal); begin FID:=IID; end; function TPMBObject.GetObjectsCount: Integer; begin Result:=FObjects.Count; end; function TPMBObject.GetObject(Index: Integer): TPMBObject; begin Result:=nil; if (Index<0) or (Index>FObjects.Count-1) then Exit; Result:=TPMBObject(FObjects[Index]); end; procedure TPMBObject.SetMesh(Mesh: TPMBMesh); begin if Assigned(FMesh) and Assigned(Mesh) then FMesh.Free; FMesh:=Mesh; end; function TPMBObject.GetPrimitivesCount: Integer; begin Result:=FPrimitives.Count; end; function TPMBObject.GetPrimitive(Index: Integer): TPMBPrimitive; begin Result:=nil; if (Index<0) or (Index>FPrimitives.Count-1) then Exit; Result:=TPMBPrimitive(FPrimitives[Index]); end; function TPMBObject.AddObject(Obj: TPMBObject): Integer; begin Result:=FObjects.Add(Obj); end; procedure TPMBObject.DeleteObject(Obj: TPMBObject); begin FObjects.Remove(Obj) end; function TPMBObject.AddPrimitive(Primitive: TPMBPrimitive): Integer; begin Result:=FPrimitives.Add(Primitive); end; procedure TPMBObject.DeletePrimitive(Primitive: TPMBPrimitive); begin FPrimitives.Remove(Primitive); end; procedure TPMBObject.DeselectAll; var i: Integer; begin FSelected:=false; if Assigned(FMesh) then FMesh.FSelected:=false; for i:=0 to PrimitivesCount-1 do Primitives[i].FSelected:=false; for i:=0 to ObjectsCOunt-1 do Objects[i].DeselectAll; end; function TPMBObject.WriteChunk(Data: TStream): Boolean; var ChunkType, MatID: Byte; ChunkSize: Word; ChunkStart: Integer; i: Integer; begin Result:=false; ChunkStart:=Data.Position; ChunkType:=ChunkModelObject; Data.Write(ChunkType, SizeOf(ChunkType)); Data.Write(ChunkSize, SizeOf(ChunkSize)); Data.Write(FID, SizeOf(FID)); FTransform.Write(Data); if Assigned(FMaterial) then MatID:=FMaterial.ID else MatID:=0; Data.Write(MatID, SizeOf(MatID)); if Assigned(FMesh) then if not FMesh.WriteChunk(Data) then Exit; for i:=0 to PrimitivesCount-1 do if not Primitives[i].WriteChunk(Data) then Exit; for i:=0 to ObjectsCount-1 do if not Objects[i].WriteChunk(Data) then Exit; ChunkSize:=Data.Position-ChunkStart; Data.Seek(ChunkStart+SizeOf(ChunkType), soFromBeginning); Data.Write(ChunkSize, SizeOf(ChunkSize)); Data.Seek(0, soFromEnd); Result:=true; end; procedure TPMBObject.ReadChunk(Data: TStream; ChunkSize: Integer); var MaterialID: Byte; begin ChunkSize:=Data.Position+ChunkSize; //ChunkEnd Data.Read(FID, SizeOf(FID)); FTransform.Read(Data); Data.Read(MaterialID, SizeOf(MaterialID)); FMaterial:=TPMBMaterial(Integer(MaterialID)); //needs further resolving while Data.Position<ChunkSize do ReadChunk(Data); if Data.Position<>ChunkSize then raise Exception.Create(SCannotLoadModelChunkSizeMismatch); end; procedure TPMBObject.ReadChunk(Data: TStream); var ChunkID: Byte; ChunkSize: Word; ChunkEnd: Integer; begin ChunkEnd:=Data.Position; Data.Read(ChunkID, SizeOf(ChunkID)); Data.Read(ChunkSize, SizeOf(ChunkSize)); Inc(ChunkEnd, ChunkSize); case ChunkID of ChunkModelObject: TPMBObject.Create(FModel, Self).ReadChunk(Data, ChunkEnd-Data.Position); ChunkObjectPrimitive: TPMBPrimitive.ReadChunk(Self, Data, ChunkEnd-Data.Position); ChunkObjectMesh: begin TPMBMesh.Create(Self); FMesh.ReadChunk(Data, ChunkID, ChunkEnd-Data.Position); end; else raise Exception.CreateFmt(SCannotLoadModelInvalidChunkAt, [ChunkID, ChunkEnd-ChunkSize]); end; while ChunkEnd>Data.Position do ReadChunk(Data); if ChunkEnd<>Data.Position then raise Exception.Create(SCannotLoadModelChunkSizeMismatch); end; procedure TPMBObject.Relink(Obj: TPMBObject); begin if (Obj=Self) or (Obj=FParent) then Exit; if Assigned(FParent) then FParent.DeleteObject(Self) else FModel.DeleteObject(Self); FParent:=Obj; FParent.AddObject(Self); end; procedure TPMBObject.Relink(Model: TPMBModel); begin if not Assigned(FParent) then Exit; if Model<>FModel then raise Exception.Create(SCannotRelinkObjectToAnotherModel); FParent.DeleteObject(Self); FParent:=nil; FModel.AddObject(Self); end; procedure TPMBObject.SetSelected(Value: Boolean); begin if Value then FModel.DeselectAll; FSelected:=Value; end; {TPMBModel} constructor TPMBModel.Create; begin inherited Create; FObjects:=TList.Create; FMaterials:=TList.Create; end; destructor TPMBModel.Destroy; begin while ObjectsCount>0 do Objects[0].Free; while MaterialsCount>0 do Materials[0].Free; FObjects.Free; FMaterials.Free; inherited Destroy; end; procedure TPMBModel.Draw; var i: Integer; begin for i:=0 to ObjectsCount-1 do Objects[i].Draw; end; procedure TPMBModel.SetVisibility(Visibility: Boolean); var i: Integer; begin for i:=0 to ObjectsCount-1 do Objects[i].SetVisibility(Visibility); end; procedure TPMBModel.LoadFromFile(const FileName: string); var F: TFileStream; begin if not FileExists(FileName) then Exit; F:=TFileStream.Create(FileName, fmOpenRead); try LoadFromStream(F); finally F.Free; end; end; procedure TPMBModel.LoadFromStream(Stream: TStream); procedure ProcessObj(Obj: TPMBObject); var i: Integer; begin Obj.Material:=FindMaterial(Byte(Integer(Obj.Material))); for i:=0 to Obj.ObjectsCount-1 do ProcessObj(Obj.Objects[i]); end; var ChunkType: Byte; ChunkSize: Word; i: Integer; begin Stream.Read(ChunkType, SizeOf(ChunkType)); if ChunkType<>ChunkModel then raise Exception.Create(SCannotLoadModelInvalidFirstChunk); while ObjectsCount>0 do Objects[0].Free; while MaterialsCount>0 do Materials[0].Free; Stream.Read(ChunkSize, SizeOf(ChunkSize)); while Stream.Position<ChunkSize do ReadChunk(Stream); for i:=0 to ObjectsCount-1 do ProcessObj(Objects[i]); if Stream.Position<>ChunkSize then raise Exception.Create(SCannotLoadModelChunkSizeMismatch); end; procedure TPMBModel.SaveToFile(const FileName: string); var F: TFileStream; begin if FileExists(FileName) then DeleteFile(FileName); F:=TFileStream.Create(FileName, fmCreate); try SaveToStream(F); finally F.Free; end; end; procedure TPMBModel.SaveToStream(Stream: TStream); var ChunkType: Byte; ChunkSize: Word; i: Integer; begin ChunkType:=ChunkModel; ChunkSize:=0; Stream.Write(ChunkType, SizeOf(ChunkType)); Stream.Write(ChunkSize, SizeOf(ChunkSize)); for i:=0 to ObjectsCount-1 do if not Objects[i].WriteChunk(Stream) then Exit; for i:=0 to MaterialsCount-1 do if not Materials[i].WriteChunk(Stream) then Exit; if Stream.Size>MaxWord then raise Exception.Create(SCannotSaveModelResultingFileSize); ChunkSize:=Stream.Size; Stream.Seek(SizeOf(ChunkType), soFromBeginning); Stream.Write(ChunkSize, SizeOf(ChunkSize)); end; function TPMBModel.FindMaterial(ID: Byte): TPMBMaterial; var i: Integer; begin Result:=nil; for i:=0 to MaterialsCount-1 do if Materials[i].ID=ID then begin Result:=Materials[i]; Exit; end; end; function TPMBModel.GetObjectsCount: Integer; begin Result:=FObjects.Count; end; function TPMBModel.GetObject(Index: Integer): TPMBObject; begin Result:=nil; if (Index<0) or (Index>FObjects.Count-1) then Exit; Result:=TPMBObject(FObjects[Index]); end; function TPMBModel.GetMaterialsCount: Integer; begin Result:=FMaterials.Count; end; function TPMBModel.GetMaterial(Index: Integer): TPMBMaterial; begin Result:=nil; if (Index<0) or (Index>FMaterials.Count-1) then Exit; Result:=TPMBMaterial(FMaterials[Index]); end; function TPMBModel.AddObject(Obj: TPMBObject): Integer; begin Result:=FObjects.Add(Obj); end; procedure TPMBModel.DeleteObject(Obj: TPMBObject); begin FObjects.Remove(Obj); end; function TPMBModel.ObjIDExists(ID: Cardinal): Boolean; function CheckObj(Obj: TPMBObject): Boolean; var i: Integer; begin Result:=Obj.IID=ID; if not Result then for i:=0 to Obj.ObjectsCount-1 do if CheckObj(Obj.Objects[i]) then begin Result:=true; Exit; end; end; var i: Integer; begin Result:=false; for i:=0 to ObjectsCount-1 do if CheckObj(Objects[i]) then begin Result:=true; Exit; end; end; function TPMBModel.AddMaterial(Mat: TPMBMaterial): Integer; begin Result:=FMaterials.Add(Mat); end; procedure TPMBModel.DeleteMaterial(Mat: TPMBMaterial); procedure ProcessObj(Obj: TPMBObject); var i: Integer; begin if Obj.Material=Mat then Obj.Material:=nil; for i:=0 to Obj.ObjectsCount-1 do ProcessObj(Obj.Objects[i]); end; var i: Integer; begin for i:=0 to ObjectsCount-1 do ProcessObj(Objects[i]); FMaterials.Remove(Mat); end; function TPMBModel.GetMaterialID: Byte; var IDs: array[1..255] of Boolean; i: Integer; begin Result:=0; for i:=0 to High(IDs) do IDs[i]:=false; for i:=0 to MaterialsCount-1 do IDs[Materials[i].ID]:=true; for i:=1 to High(IDs) do if not IDs[i] then begin Result:=i; Exit; end; end; function TPMBModel.LoadTexture(const TexName: string): Cardinal; begin if Assigned(FOnLoadTex) and (TexName<>'') then Result:=FOnLoadTex(TexName) else Result:=0; end; procedure TPMBModel.BindTexture(ID: Cardinal); begin if Assigned(FOnBindTex) then FOnBindTex(ID); end; procedure TPMBModel.DeselectAll; var i: Integer; begin for i:=0 to ObjectsCount-1 do Objects[i].DeselectAll; end; procedure TPMBModel.ReadChunk(Data: TStream); var ChunkID: Byte; ChunkSize: Word; ChunkEnd: Integer; begin ChunkEnd:=Data.Position; Data.Read(ChunkID, SizeOf(ChunkID)); Data.Read(ChunkSize, SizeOf(ChunkSize)); Inc(ChunkEnd, ChunkSize); case ChunkID of ChunkModelObject: TPMBObject.Create(Self, nil).ReadChunk(Data, ChunkEnd-Data.Position); ChunkMaterial: TPMBMaterial.Create(Self).ReadChunk(Data, ChunkEnd-Data.Position); else raise Exception.CreateFmt(SCannotLoadModelInvalidChunkAt, [ChunkID, ChunkEnd-ChunkSize]); end; while ChunkEnd>Data.Position do ReadChunk(Data); if ChunkEnd<>Data.Position then raise Exception.Create(SCannotLoadModelChunkSizeMismatch); end; function PriTypeToString(PriType: Byte): string; begin case PriType of PrimitiveCube: Result:='Cube'; PrimitiveSphere: Result:='Sphere'; PrimitiveCone: Result:='Cone'; PrimitiveTorus: Result:='Torus'; PrimitiveTube: Result:='Tube'; else Result:='Unknown'; end; end; end.
{ Subroutine STRING_F_MACADR (S, MACADR) * * Create the standard "dash" string representation of the ethernet MAC * address in MACADR. } module string_f_macadr; define string_f_macadr; %include 'string2.ins.pas'; procedure string_f_macadr ( {make string from ethernet MAC address} in out s: univ string_var_arg_t; {output string} in macadr: sys_macadr_t); {input MAC address} val_param; var i: sys_int_machine_t; {loop counter} tk: string_var16_t; {sratch token} stat: sys_err_t; {completion status} begin tk.max := size_char(tk.str); {init local var string} s.len := 0; {init return string to emtpy} for i := 5 downto 0 do begin {once for each byte in the MAC address} if s.len <> 0 then begin {not first byte ?} string_append1 (s, '-'); {add dash separator after previous byte} end; string_f_int_max_base ( {make HEX string from this byte} tk, {output string} macadr[i], {input integer} 16, {radix} 2, {field width} [ string_fi_leadz_k, {write leading zeros to fill field} string_fi_unsig_k], {input number is unsigned} stat); string_append (s, tk); end; end;
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, RzPanel, StdCtrls, RzLstBox, RzButton, RzCmboBx, RzLabel, RzShellDialogs, Menus, RzStatus, ImgList; type TForm1 = class(TForm) Less_List: TRzListBox; Panel: TRzPanel; btnStart: TRzBitBtn; btnPath: TRzBitBtn; btnQuit: TRzBitBtn; GroupBox: TRzGroupBox; Number: TRzComboBox; RzSelectFolderDialog1: TRzSelectFolderDialog; MainMenu: TMainMenu; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; N4: TMenuItem; N5: TMenuItem; N6: TMenuItem; Path_Status: TRzStatusPane; procedure btnQuitClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure Less_ListClick(Sender: TObject); procedure btnPathClick(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure N6Click(Sender: TObject); procedure N4Click(Sender: TObject); procedure N3Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation Uses DataMod, TestForm, About; {$R *.dfm} procedure TForm1.btnQuitClick(Sender: TObject); begin Close; end; procedure TForm1.FormShow(Sender: TObject); var F: TSearchRec; Path: string; Attr: Integer; begin {Искать все файлы в заданной директории с расширение .abs} Path := ExtractFilePath(Application.ExeName)+'Lessons\*.abs'; Attr := faAnyFile; FindFirst(Path, Attr, F); {Если хотя бы один файл найден, то продолжить поиск} if F.name <> '' then begin Less_List.Items.Add(F.name); {Добавление в TListBox имени найденного файла} while FindNext(F) = 0 do Less_List.Items.Add(F.name); end; FindClose(F); Path_Status.Caption := ExtractFilePath(Application.ExeName)+'Lessons\'; end; procedure TForm1.Less_ListClick(Sender: TObject); var i:integer; begin with DataModule1 do begin ABSDatabase1.DatabaseFileName := Path_Status.Caption+Less_List.Items.Strings[Less_List.ItemIndex]; ABSDatabase1.Connected := true; ABSTable1.Active := true; end; btnStart.Enabled := true; Number.Clear; for i:=1 to DataModule1.ABSTable1.RecordCount do Number.Items.Add(IntToStr(i)); if DataModule1.ABSTable1.RecordCount >= 25 then Number.ItemIndex := 24 else Number.ItemIndex := DataModule1.ABSTable1.RecordCount-1; end; procedure TForm1.btnPathClick(Sender: TObject); var F: TSearchRec; Path: string; Attr: Integer; begin if RzSelectFolderDialog1.Execute then begin Less_List.Clear; DataModule1.ABSTable1.Active := false; DataModule1.ABSDatabase1.Connected := false; btnStart.Enabled := false; Number.Clear; {Искать все файлы в заданной директории с расширение .abs} Path := RzSelectFolderDialog1.SelectedPathName+'\*.abs'; Attr := faAnyFile; FindFirst(Path, Attr, F); {Если хотя бы один файл найден, то продолжить поиск} if F.name <> '' then begin Less_List.Items.Add(F.name); {Добавление в TListBox имени найденного файла} while FindNext(F) = 0 do Less_List.Items.Add(F.name); end; FindClose(F); Path_Status.Caption := RzSelectFolderDialog1.SelectedPathName+'\'; end; end; procedure TForm1.btnStartClick(Sender: TObject); begin Form2.Start; Form2.ShowModal; end; procedure TForm1.N6Click(Sender: TObject); begin Form1.Close; end; procedure TForm1.N4Click(Sender: TObject); begin btnPath.Click; end; procedure TForm1.N3Click(Sender: TObject); begin Form4.ShowModal; end; end.
unit UxlCommDlgs; interface uses Windows, CommDlg, UxlClasses, UxlWinControl, UxlFunctions, ShlObj, UxlStrUtils; type TxlCommDlgSuper = class protected FOwnerHandle: HWND; procedure OnInitialize (); virtual; public constructor Create (AOwner: TxlWinControl = nil); overload; constructor Create (HOwner: HWND); overload; function Execute(): boolean; virtual; abstract; end; type TOpenSaveType = (ostOpen, ostSave); type TxlOpenSaveDialog = class (TxlCommDlgSuper) protected FType: TOpenSaveType; FMultiSelect: boolean; FOverwritePrompt: boolean; FFilter: WideString; FTitle: WideString; FDefaultExt: WideString; FFilterIndex: integer; FFileName: WideString; FPath: WideString; procedure OnInitialize (); override; public property Title: widestring write FTitle; property Path: widestring read Fpath write FPath; // return value ends with '\' property FileName: widestring read FFileName write FFileName; // return value contains no path property Filter: widestring write FFilter; property FilterIndex: integer read FFilterIndex write FFilterIndex; property DefaultExt: widestring read FDefaultExt write FDefaultExt; function Execute(): boolean; override; end; type TxlOpenDialog = class (TxlOpenSaveDialog) protected procedure OnInitialize (); override; public property MultiSelect: boolean write FMultiSelect; end; type TxlSaveDialog = class (TxlOpenSaveDialog) protected procedure OnInitialize (); override; public property OverWritePrompt: boolean write FOverwritePrompt; end; type TxlPathDialog = class (TxlCommDlgSuper) public Path: widestring; Title: widestring; function Execute(): boolean; override; end; type TxlFontDialog = class (TxlCommDlgSuper) private FFont: TxlFont; procedure SetFont (value: TxlFont); public constructor Create (AOwner: TxlWinControl = nil); destructor Destroy (); override; function Execute(): boolean; override; property Font: TxlFont read FFont write SetFont; end; type TxlColorDialog = class (TxlCommDlgSuper) private FColor: TColor; FCustColors: array [0..15] of TColor; public function Execute(): boolean; override; property Color: TColor read FColor write FColor; end; type TxlPrintDialog = class (TxlCommDlgSuper) private FCopies: integer; FPrinter: integer; public function Execute(): boolean; override; property Copies: integer read FCopies write FCopies; property Printer: integer read FPrinter write FPrinter; end; type TMessageType = (mtWarning, mtExclamation, mtInformation, mtQuestion, mtQuestionYesNo, mtQuestion3B, mtError); TMessageResult = (mrOK, mrCancel, mrYes, mrNo); //function BrowseCallbackProc (Wnd: HWND; uMsg: UINT; l_Param, lpData: LPARAM): integer; stdcall; function ShowMessage (const s_msg: widestring; fmMessageType: TMessageType = mtInformation; s_caption: widestring = ''): TMessageResult; overload; procedure ShowMessage (const i_msg: Int64); overload; implementation uses UxlDialog, UxlWindow, UxlWinDef; constructor TxlCommDlgSuper.Create (AOwner: TxlWinControl = nil); begin if AOwner <> nil then FOwnerHandle := AOwner.handle else FOwnerHandle := MainWinHandle; OnInitialize (); end; constructor TxlCommDlgSuper.Create (HOwner: HWND); begin FOwnerHandle := HOwner; OnInitialize (); end; procedure TxlCommDlgSuper.OnInitialize (); begin end; //---------------- function TxlOpenSaveDialog.Execute(): boolean; var ofn: OpenFileNameW; strFile, strFilter: pwidechar; i: integer; b: boolean; const i_maxchar = 1024; begin strFile := AllocMem (i_maxchar * 2); CopyMemory (StrFile, pwidechar(FFileName), length(FFileName) * 2); strFilter := AllocMem (i_maxchar * 2); CopyMemory (StrFilter, pwidechar(FFilter), length(FFilter) * 2); for i := 0 to length(FFilter) - 1 do if strFilter[i] = '|' then strFilter[i] := #0; with ofn do begin lStructSize := sizeof(ofn); hWndOwner := FOwnerHandle; hInstance := system.Maininstance; lpstrFilter := strFilter; lpstrCustomFilter := nil; nMaxCustFilter := 0; nFilterIndex := FFilterIndex; lpstrFile := strFile; nMaxFile := i_maxchar; lpstrFileTitle := nil; nMaxFileTitle:= 0; lpstrInitialDir := pwidechar(FPath); lpstrTitle := PWideChar(FTitle); Flags := OFN_EXPLORER or OFN_NOCHANGEDIR; if FType = ostOpen then begin Flags := Flags or OFN_CREATEPROMPT; if FMultiSelect then Flags := Flags or OFN_ALLOWMULTISELECT; end else if FOverWritePrompt then Flags := FLags or OFN_OVERWRITEPROMPT; nFileOffset:=0; nFileExtension:=0; lpstrDefExt:=pWideChar(FDefaultExt); lCustData:=0; lpfnHook:=nil; lpTemplateName:=''; pvReserved:=nil; dwReserved:=0; FlagsEx:=0; end; if FType = ostOpen then b := GetOpenFileNameW(ofn) else b := GetSaveFileNameW(ofn); if b then begin if FMultiSelect then begin for i := 1 to i_maxchar - 2 do if (strFile[i] = #0) and (strFile[i - 1] <> #0) and (strFile[i + 1] <> #0) then strFile[i] := #9; FFileName := MidStr(strFile, ofn.nFileOffset + 1); FPath := LeftStr (StrFile, ofn.nFileOffset - 1) + '\'; end else begin FFileName := ExtractFileName (strFile); FPath := ExtractFilePath (strFile); end; result := true; end else result := false; FreeMem (strFile, i_maxchar * 2); FreeMem (strFilter, i_maxchar * 2); end; procedure TxlOpenSaveDialog.OnInitialize (); begin FFilter := ''; FFilterIndex := 0; FTitle := ''; FDefaultExt := ''; FFileName := ''; FPath := ''; end; procedure TxlOpenDialog.OnInitialize (); begin FType := ostOpen; FMultiSelect := false; inherited; end; procedure TxlSaveDialog.OnInitialize (); begin FType := ostSave; FOverWritePrompt := true; inherited; end; //--------------------- function TxlPathDialog.Execute(): boolean; var o_binfo: TBROWSEINFOW; p: pwidechar; p2: pointer; begin p := AllocMem (2000); // copymemory (p, pwidechar(Path), length(Path) * 2); with o_binfo do begin hwndOwner := FOwnerHandle; pidlRoot := nil; pszDisplayName := p; lpszTitle := pwidechar(Title); ulFlags := BIF_NEWDIALOGSTYLE; // BIF_VALIDATE; lpfn := nil; //BrowseCallBackProc; lParam := 0; end; p2 := SHBrowseForFolderW (o_binfo); result := (p2 <> nil); if result then begin SHGetPathFromIDListW (p2, p); Path := p; if rightstr(path, 1) <> '\' then path := path + '\'; end; FreeMem (p, 2000); end; //--------------------- function TxlColorDialog.Execute(): boolean; var o_color: TChooseColor; begin with o_color do begin lStructSize := sizeof (o_color); hWndOwner := FOwnerHandle; hInstance := system.Maininstance; rgbResult := FColor; lpCustColors := @FCustColors; Flags := CC_RGBINIT or CC_FULLOPEN; lCustData := 0; lpfnHook := nil; lpTemplateName := nil; end; result := ChooseColor (o_color); if result then FColor := o_color.rgbResult; end; //----------------------- constructor TxlFontDialog.Create (AOwner: TxlWinControl = nil); begin inherited Create (AOwner); FFont := TxlFont.Create; end; destructor TxlFontDialog.Destroy (); begin FFont.Free; inherited; end; procedure TxlFontDialog.SetFont (value: TxlFont); begin FFont.Assign (value); end; function TxlFontDialog.Execute(): boolean; var o_cfont: TChooseFontW; o_lfont: LogFontW; begin o_lfont := FFont.LogFont; with o_cfont do begin lStructSize := sizeof (o_cfont); hWndOwner := FOwnerHandle; hDC := 0; lpLogFont := @o_lfont; iPointSize := 0; Flags := CF_EFFECTS or CF_INITTOLOGFONTSTRUCT or CF_SCREENFONTS or CF_NOSCRIPTSEL; // or CF_USESTYLE rgbColors := FFont.Color; lCustData := 0; lpfnHook := nil; lpTemplateName := nil; hInstance := 0; lpszStyle := nil; nFontType := 0; nSizeMin := 0; nSizeMax := 0; end; result := ChooseFontW (o_cfont); if result then begin FFont.LogFont := o_cfont.lpLogFont^; FFont.Color := o_cfont.rgbColors; end; end; //------------------------- function TxlPrintDialog.Execute(): boolean; //var o_prdlg: LPPrintDlgEx; // hr: HResult; begin // result := false; // hr := PrintDlgEx (o_prdlg); // if not hr = S_OK then exit; // // if o_prdlg.dwResultAction = PD_RESULT_PRINT then // begin result := true; // end; end; //------------------------- function ShowMessage (const s_msg: widestring; fmMessageType: TMessageType = mtInformation; s_caption: widestring = ''): TMessageResult; var i_icon: cardinal; hParent: HWND; begin case fmMessageType of mtExclamation, mtWarning: begin i_icon := MB_OK or MB_ICONExclamation; if s_caption = '' then s_caption := '¾¯¸æ!'; end; mtError: begin i_icon := MB_OK or MB_ICONERROR; if s_caption = '' then s_caption := '´íÎó!'; end; mtQuestion, mtQuestion3B, mtQuestionYesNo: begin if fmMessageType = mtQuestion then i_icon := MB_OKCANCEL else if fmMessageType = mtQuestionYesNo then i_icon := MB_YESNO else i_icon := MB_YESNOCANCEL; i_icon := i_icon or MB_ICONQUESTION; if s_caption = '' then s_caption := '×¢Òâ!'; end; else begin i_icon := MB_OK or MB_ICONInformation; if s_caption = '' then s_caption := 'Ìáʾ!'; end; end; hParent := GetWindow (MainWinHandle, GW_ENABLEDPOPUP); if hParent = 0 then hParent := MainWinHandle; SendMessageW (hParent, WM_DIALOGOPENED, 0, 0); case MessageBoxW (hParent, pwidechar(s_msg), pwidechar(s_caption), i_icon) of IDOK: result := mrOK; IDCancel: result := mrCancel; IDYes: result := mrYes; else result := mrNo; // IDNo end; SendMessageW (hParent, WM_DIALOGCLOSED, 0, 0); end; procedure ShowMessage (const i_msg: Int64); begin ShowMessage (IntToStr(i_msg)); end; end.
unit SimpleParser; {$mode macpas} // Simple parser for general purpose parsing. // Can only handle a few basic types. // Can, unlike the color coder, find numerics. // Scientific syntax (like 15E-2) not supported! // Also supports Pascal-style hex code ($) and C-style (0x) // By Ingemar 160107 // 160111: Added string support. // 16040?: Minus can now be part of an alphanumeric string. (Bad for math expressions, good for file names.) interface const kNoToken = 0; // Nothing found! kOtherToken = 9; // Same number as the ColorCoding unit kAlphaNumericToken = 101; // Outside the current range for the ColorCoding unit kNumericToken = 102; // Outside the current range for the ColorCoding unit kSingleCharToken = 8; // Same number as the ColorCoding unit kHexToken = 103; // Outside the current range for the ColorCoding unit kStringToken = 6; procedure SimpleParserGetToken(data: AnsiString; var pos, tokenStart, tokenEnd, tokenType: Longint; var tokenValue: AnsiString); overload; procedure SimpleParserGetToken(data: AnsiString; var pos, tokenType: Longint; var tokenValue: AnsiString); overload; implementation // Variant that ignores the tokenStart and tokenEnd. procedure SimpleParserGetToken(data: AnsiString; var pos, tokenType: Longint; var tokenValue: AnsiString); overload; var tokenStart, tokenEnd: Longint; begin SimpleParserGetToken(data, pos, tokenStart, tokenEnd, tokenType, tokenValue); end; procedure SimpleParserGetToken(data: AnsiString; var pos, tokenStart, tokenEnd, tokenType: Longint; var tokenValue: AnsiString); overload; var s: AnsiString; bufferLength: Longint; hexFlag: Boolean; const CR = Char(13); LF = Char(10); TAB = Char(9); begin // Set defaults (150111) tokenValue := ''; tokenType := kNoToken; tokenStart := pos; tokenEnd := pos; hexFlag := false; // Guard against bad input if Length(data) = 0 then Exit; if pos > Length(data) then Exit; bufferLength := Length(data); s := ''; while (data[pos] in [CR, LF, TAB, ' ']) and (pos <= bufferLength) do pos := pos + 1; if pos > Length(data) then Exit; tokenStart := pos; // Check for leading minus! Or something else leading! if data[pos] = '-' then begin if pos+1 <= bufferLength then if data[pos+1] in ['0'..'9'] then begin pos := pos + 1; end; end else if data[pos] = '0' then // Can it be a 0x? begin if pos+1 <= bufferLength then if data[pos+1] = 'x' then begin pos := pos + 2; hexFlag := true; end; end else if data[pos] = '$' then // Can it be a 0x? begin pos := pos + 1; hexFlag := true; end else if data[pos] = '"' then begin // Scan until end ", skip \" pos := pos + 1; while not (data[pos] in ['"', CR, LF]) and (pos < bufferLength) do begin if data[pos] = '\' then pos := pos + 1; pos := pos + 1; end; tokenEnd := pos; pos := pos + 1; // Skip " tokenType := kStringToken; tokenStart := tokenStart; // + 1; tokenValue := Copy(data, tokenStart+1, tokenEnd - tokenStart-1); Exit(SimpleParserGetToken); end; // Parse the rest! // Check first character for numeric, alphanumeric or single char special if hexFlag then begin while (data[pos] in ['0'..'9', 'a'..'f', 'A'..'F']) and (pos <= bufferLength) do pos := pos + 1; tokenEnd := pos - 1; s := s + Copy(data, tokenStart, pos - tokenStart); tokenType := kHexToken; tokenValue := s; end else if data[pos] in ['0'..'9'] then begin while (data[pos] in ['0'..'9', '.']) and (pos <= bufferLength) do pos := pos + 1; tokenEnd := pos - 1; s := s + Copy(data, tokenStart, pos - tokenStart); tokenType := kNumericToken; tokenValue := s; end else if data[pos] in ['a'..'z', 'A'..'Z', '0'..'9', '_'] then begin // Change 160403: "-" now allowed as part of a token! Valid for file names. But this is clearly NOT useful for reading math expressions! // Should I make this optional? while (data[pos] in ['a'..'z', 'A'..'Z', '0'..'9', '_', '.', '-']) and (pos <= bufferLength) do pos := pos + 1; tokenEnd := pos - 1; s := Copy(data, tokenStart, pos - tokenStart); tokenType := kAlphaNumericToken; tokenValue := s; end else begin // Otherwise skip the symbol tokenEnd := tokenStart; tokenType := kSingleCharToken; tokenValue := data[pos]; pos := pos + 1; end; end; end.
unit Maze.DistanceDijkstra; interface uses Maze.Grid, Maze.Cell; procedure CalcDijkstraDistance(const Grid : IGrid); procedure CalcDijkstraSolve(const Grid : IGrid); implementation uses Spring.Collections, System.SysUtils; function GetDistances(const Grid : IGrid) : IDictionary<ICell, Integer>; var Distances : IDictionary<ICell, Integer>; Cell, Link : ICell; Frontier, NewFrontier : IList<ICell>; begin Distances := TCollections.CreateDictionary<ICell, Integer>; for Cell in Grid.EachCell do Distances.Add(Cell, -1); Frontier := TCollections.CreateList<ICell>; NewFrontier := TCollections.CreateList<ICell>; // Start cell is always bottom left - arbitrary Cell := Grid.Cells[Grid.Rows-1, 0]; Frontier.Add(Cell); Distances[Cell] := 0; while Frontier.Any do begin NewFrontier.Clear; for Cell in Frontier do begin for Link in Cell.Links do begin if Distances[Link] = -1 then begin Distances.AddOrSetValue(Link, Distances[Cell] + 1); NewFrontier.Add(Link); end; end; end; Frontier.Clear; Frontier.AddRange(NewFrontier); end; Result := Distances; end; procedure CalcDijkstraDistance(const Grid : IGrid); var Distances : IDictionary<ICell, Integer>; Cell : ICell; begin Distances := GetDistances(Grid); for Cell in Distances.Keys do Cell.Distance := Distances[Cell]; end; function FindMaxCell(const Distances : IDictionary<ICell, Integer>) : ICell; var MaxDist : Integer; Cell : ICell; begin Result := nil; MaxDist := -1; for Cell in Distances.Keys do if Cell.Distance > MaxDist then begin MaxDist := Cell.Distance; Result := Cell; end; end; function FindMinLinkedNeighbour(const Cell : ICell; const Distances : IDictionary<ICell, Integer>) : ICell; var MaxDist : Integer; N : ICell; begin Result := nil; MaxDist := Distances[Cell]; for N in Cell.Links do if Distances[N] < MaxDist then begin MaxDist := Distances[N]; Result := N; end; end; procedure CalcDijkstraSolve(const Grid : IGrid); var Distances : IDictionary<ICell, Integer>; Cell, CurrentCell : ICell; begin for Cell in Grid.EachCell do Cell.Distance := -1; Distances := GetDistances(Grid); //CurrentCell := FindMaxCell(Distances); // Always solve to the bottom right - arbitrary CurrentCell := Grid.Cells[Grid.Rows-1, Grid.Columns-1]; // If not found, or it's the starting cell, quit if not Assigned(CurrentCell) or (Distances[CurrentCell] <= 0) then Exit; while Assigned(CurrentCell) do begin CurrentCell.Distance := Distances[CurrentCell]; // Non- -1 CurrentCell := FindMinLinkedNeighbour(CurrentCell, Distances); end; end; end.
unit ALAndroidVKontakteApi; interface uses Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.App; type {*******************} JVKScope = interface; JVKAccessToken = interface; JVKAuthCallback = interface; JVK = interface; JVKUtils = interface; {***********************************} JVKScopeClass = interface(JEnumClass) ['{6D299E22-9E66-4DD9-8556-17C7830134F6}'] {class} function _GetADS: JVKScope; cdecl; {class} function _GetAUDIO: JVKScope; cdecl; {class} function _GetDOCS: JVKScope; cdecl; {class} function _GetEMAIL: JVKScope; cdecl; {class} function _GetFRIENDS: JVKScope; cdecl; {class} function _GetGROUPS: JVKScope; cdecl; {class} function _GetMARKET: JVKScope; cdecl; {class} function _GetMESSAGES: JVKScope; cdecl; {class} function _GetNOTES: JVKScope; cdecl; {class} function _GetNOTIFICATIONS: JVKScope; cdecl; {class} function _GetNOTIFY: JVKScope; cdecl; {class} function _GetOFFLINE: JVKScope; cdecl; {class} function _GetPAGES: JVKScope; cdecl; {class} function _GetPHONE: JVKScope; cdecl; {class} function _GetPHOTOS: JVKScope; cdecl; {class} function _GetSTATS: JVKScope; cdecl; {class} function _GetSTATUS: JVKScope; cdecl; {class} function _GetSTORIES: JVKScope; cdecl; {class} function _GetVIDEO: JVKScope; cdecl; {class} function _GetWALL: JVKScope; cdecl; {class} function valueOf(name: JString): JVKScope; cdecl; {class} function values: TJavaObjectArray<JVKScope>; cdecl; {class} property ADS: JVKScope read _GetADS; {class} property AUDIO: JVKScope read _GetAUDIO; {class} property DOCS: JVKScope read _GetDOCS; {class} property EMAIL: JVKScope read _GetEMAIL; {class} property FRIENDS: JVKScope read _GetFRIENDS; {class} property GROUPS: JVKScope read _GetGROUPS; {class} property MARKET: JVKScope read _GetMARKET; {class} property MESSAGES: JVKScope read _GetMESSAGES; {class} property NOTES: JVKScope read _GetNOTES; {class} property NOTIFICATIONS: JVKScope read _GetNOTIFICATIONS; {class} property NOTIFY: JVKScope read _GetNOTIFY; {class} property OFFLINE: JVKScope read _GetOFFLINE; {class} property PAGES: JVKScope read _GetPAGES; {class} property PHONE: JVKScope read _GetPHONE; {class} property PHOTOS: JVKScope read _GetPHOTOS; {class} property STATS: JVKScope read _GetSTATS; {class} property STATUS: JVKScope read _GetSTATUS; {class} property STORIES: JVKScope read _GetSTORIES; {class} property VIDEO: JVKScope read _GetVIDEO; {class} property WALL: JVKScope read _GetWALL; end; [JavaSignature('com/vk/api/sdk/auth/VKScope')] JVKScope = interface(JEnum) ['{2596E59E-D2E5-457F-B3EE-CA7ADD5FD1C2}'] end; TJVKScope = class(TJavaGenericImport<JVKScopeClass, JVKScope>) end; {*******************************************} JVKAccessTokenClass = interface(JObjectClass) ['{4AA5D139-70EF-4BED-AFCE-6AD11B109F57}'] end; [JavaSignature('com/vk/api/sdk/auth/VKAccessToken')] JVKAccessToken = interface(JObject) ['{B7E0A898-D133-4A4B-A74E-F192D64E28DA}'] function getAccessToken: JString; cdecl; function getCreated: Int64; cdecl; function getEmail: JString; cdecl; function getPhone: JString; cdecl; function getPhoneAccessKey: JString; cdecl; function getSecret: JString; cdecl; function getUserId: Integer; cdecl; function isValid: Boolean; cdecl; end; TJVKAccessToken = class(TJavaGenericImport<JVKAccessTokenClass, JVKAccessToken>) end; {******************************************} JVKAuthCallbackClass = interface(IJavaClass) ['{85991DF5-2CD9-46BD-B3BC-41373EA0850F}'] {class} function _GetAUTH_CANCELED: Integer; cdecl; {class} function _GetUNKNOWN_ERROR: Integer; cdecl; {class} property AUTH_CANCELED: Integer read _GetAUTH_CANCELED; {class} property UNKNOWN_ERROR: Integer read _GetUNKNOWN_ERROR; end; [JavaSignature('com/vk/api/sdk/auth/VKAuthCallback')] JVKAuthCallback = interface(IJavaInstance) ['{682834EF-3C5A-40DA-AD7D-30DE4015C2B5}'] procedure onLogin(token: JVKAccessToken); cdecl; procedure onLoginFailed(errorCode: Integer); cdecl; end; TJVKAuthCallback = class(TJavaGenericImport<JVKAuthCallbackClass, JVKAuthCallback>) end; {********************************} JVKClass = interface(JObjectClass) ['{0450DCD7-E946-43D6-801E-9DAC255B6052}'] //{class} function _GetINSTANCE: JVK; cdecl; //{class} function _GetapiManager: JVKApiManager; cdecl; //{class} procedure addTokenExpiredHandler(handler: JVKTokenExpiredHandler); cdecl; {class} procedure clearAccessToken(context: JContext); cdecl; //{class} procedure execute(request: JApiCommand; callback: JVKApiCallback); cdecl; //{class} function executeSync(cmd: JApiCommand): JObject; cdecl; {class} function getApiVersion: JString; cdecl; {class} function getAppId(context: JContext): Integer; cdecl; {class} function getUserId: Integer; cdecl; {class} procedure initialize(context: JContext); cdecl; {class} function isLoggedIn: Boolean; cdecl; {class} procedure login(activity: JActivity); cdecl; overload; {class} procedure login(activity: JActivity; scopes: JCollection); cdecl; overload; {class} procedure logout; cdecl; {class} function onActivityResult(requestCode: Integer; resultCode: Integer; data: JIntent; callback: JVKAuthCallback): Boolean; cdecl; //{class} procedure removeTokenExpiredHandler(handler: JVKTokenExpiredHandler); cdecl; //{class} procedure saveAccessToken(context: JContext; userId: Integer; accessToken: JString; secret: JString); cdecl; //{class} procedure setConfig(config: JVKApiConfig); cdecl; //{class} procedure setCredentials(context: JContext; userId: Integer; accessToken: JString; secret: JString; saveAccessTokenToStorage: Boolean); cdecl; end; [JavaSignature('com/vk/api/sdk/VK')] JVK = interface(JObject) ['{CBA5C3FA-9F3B-467C-A3D5-0F21093F2CFB}'] end; TJVK = class(TJavaGenericImport<JVKClass, JVK>) end; {*************************************} JVKUtilsClass = interface(JObjectClass) ['{8D1AE62F-18C2-414B-8048-F837494A60B1}'] {class} function explodeQueryString(queryString: JString): JMap; cdecl; {class} function getCertificateFingerprint(Context: JContext; packageName: JString): TJavaObjectArray<JString>; cdecl; {class} function isAppInstalled(context: JContext; packageName: JString): Boolean; cdecl; {class} function isIntentAvailable(context: JContext; action: JString): Boolean; cdecl; end; [JavaSignature('com/vk/api/sdk/utils/VKUtils')] JVKUtils = interface(JObject) ['{4830DA3E-0FC5-4B07-9284-4E9B702DDEF7}'] procedure clearAllCookies(context: JContext); cdecl; function density: Single; cdecl; function dp(dp: Integer): Integer; cdecl; //function getDisplayMetrics: JDisplayMetrics; cdecl; function height(context: JContext): Integer; cdecl; function width(context: JContext): Integer; cdecl; end; TJVKUtils = class(TJavaGenericImport<JVKUtilsClass, JVKUtils>) end; implementation procedure RegisterTypes; begin TRegTypes.RegisterType('ALAndroidVKontakteApi.JVKScope', TypeInfo(ALAndroidVKontakteApi.JVKScope)); TRegTypes.RegisterType('ALAndroidVKontakteApi.JVKAccessToken', TypeInfo(ALAndroidVKontakteApi.JVKAccessToken)); TRegTypes.RegisterType('ALAndroidVKontakteApi.JVKAuthCallback', TypeInfo(ALAndroidVKontakteApi.JVKAuthCallback)); TRegTypes.RegisterType('ALAndroidVKontakteApi.JVK', TypeInfo(ALAndroidVKontakteApi.JVK)); TRegTypes.RegisterType('ALAndroidVKontakteApi.JVKUtils', TypeInfo(ALAndroidVKontakteApi.JVKUtils)); end; initialization RegisterTypes; end.