text
stringlengths
14
6.51M
unit rOrders; {$OPTIMIZATION OFF} interface uses SysUtils, Classes, ORFn, ORNet, uCore, Dialogs, Controls; type TOrder = class public ICD9Code: string; ID: string; DGroup: Integer; OrderTime: TFMDateTime; StartTime: string; StopTime: string; Status: Integer; Signature: Integer; VerNurse: string; VerClerk: string; ChartRev: string; Provider: Int64; ProviderName: string; ProviderDEA: string; ProviderVa: string; DigSigReq: string; XMLText: string; Text: string; DGroupSeq: Integer; DGroupName: string; Flagged: Boolean; Retrieved: Boolean; EditOf: string; ActionOn: string; EventPtr: string; //ptr to #100.2 EventName: string; //Event name in #100.5 OrderLocIEN: string; //imo OrderLocName: string; //imo ParentID : string; LinkObject: TObject; EnteredInError: Integer; //AGP Changes 26.12 PSI-04-053 DCOriginalOrder: boolean; IsOrderPendDC: boolean; IsDelayOrder: boolean; IsControlledSubstance: boolean; IsDetox : boolean; procedure Assign(Source: TOrder); procedure Clear; end; TParentEvent = class public ParentIFN: integer; ParentName: string; ParentType: Char; ParentDlg: string; constructor Create; procedure Assign(AnEvtID: string); end; TOrderDelayEvent = record EventType: Char; // A=admit, T=transfer, D=discharge, C=current TheParent: TParentEvent; // Parent Event EventIFN : Integer; // Pointer to OE/RR EVENTS file (#100.5) EventName: String; // Event name from OR/RR EVENTS file (#100.5) PtEventIFN: Integer; // Patient event IFN ptr to #100.2 Specialty: Integer; // pointer to facility treating specialty file Effective: TFMDateTime; // effective date/time (estimated start time) IsNewEvent: Boolean; // is new event for an patient end; TOrderDialogResolved = record InputID: string; // can be dialog IEN or '#ORIFN' QuickLevel: Integer; // 0=dialog,1=auto,2=verify,8=reject,9=cancel ResponseID: string; // DialogID + ';' + $H DialogIEN: Integer; // pointer to 101.41 for dialog (may be quick order IEN) DialogType: Char; // type of dialog (Q or D) FormID: Integer; // windows form to display DisplayGroup: Integer; // pointer to 100.98, display group for dialog ShowText: string; // text to show for verify or rejection QOKeyVars: string; // from entry action of quick order end; TNextMoveRec = record NextStep: Integer; LastIndex: Integer; end; TOrderMenu = class public IEN: Integer; NumCols: Integer; Title: string; KeyVars: string; MenuItems: TList; {of TOrderMenuItem} end; TOrderMenuItem = class public IEN: Integer; Row: Integer; Col: Integer; DlgType: Char; FormID: Integer; AutoAck: Boolean; ItemText: string; Mnemonic: string; Display: Integer; Selected: Boolean; end; TSelectedOrder = class public Position: Integer; Order: TOrder; end; TOrderRenewFields = class public BaseType: Integer; StartTime: string; StopTime: string; Refills: Integer; Pickup: string; Comments: string; NewText: string; end; TPrintParams = record PromptForChartCopy : char; ChartCopyDevice : string; PromptForLabels : char; LabelDevice : string; PromptForRequisitions : char; RequisitionDevice : string; PromptForWorkCopy : char; WorkCopyDevice : string; AnyPrompts : boolean; // OrdersToPrint : TStringList; {*KCM*} end; TOrderView = class public Changed: Boolean; // true when view has been modified DGroup: Integer; // display group (pointer value) Filter: Integer; // FLGS parameter passed to ORQ InvChrono: Boolean; // true for inverse chronological order ByService: Boolean; // true for grouping orders by service TimeFrom: TFMDateTime; // beginning time for orders in list TimeThru: TFMDateTime; // ending time for orders in list CtxtTime: TFMDateTime; // set by server, context hours begin time TextView: Integer; // set by server, 0 if mult views of same order ViewName: string; // display name for the view EventDelay: TOrderDelayEvent; // fields for event delay view public procedure Assign(Src: TOrderView); end; { Order List functions } function DetailOrder(const ID: string): TStrings; function ResultOrder(const ID: string): TStrings; function ResultOrderHistory(const ID: string): TStrings; function NameOfStatus(IEN: Integer): string; function GetOrderStatus(AnOrderId: string): integer; function ExpiredOrdersStartDT: TFMDateTime; procedure ClearOrders(AList: TList); procedure LoadOrders(Dest: TList; Filter, Groups: Integer); procedure LoadOrdersAbbr(Dest: TList; AView: TOrderView; APtEvtID: string); overload; procedure LoadOrdersAbbr(DestDC,DestRL: TList; AView: TOrderView; APtEvtID: string); overload; procedure LoadOrdersAbbr(Dest:Tlist; AView: TOrderView; AptEvtID: string; AlertID: string); overload; procedure LoadOrderSheets(Dest: TStrings); procedure LoadOrderSheetsED(Dest: TStrings); procedure LoadOrderViewDefault(AView: TOrderView); procedure LoadUnsignedOrders(IDList, HaveList: TStrings); procedure SaveOrderViewDefault(AView: TOrderView); procedure RetrieveOrderFields(OrderList: TList; ATextView: Integer; ACtxtTime: TFMDateTime); procedure SetOrderFields(AnOrder: TOrder; const x, y, z: string); procedure SetOrderFromResults(AnOrder: TOrder); procedure SortOrders(AList: TList; ByGroup, InvChron: Boolean); procedure ConvertOrders(Dest: TList; AView: TOrderView); { Display Group & List functions } function DGroupAll: Integer; function DGroupIEN(AName: string): Integer; procedure ListDGroupAll(Dest: TStrings); procedure ListSpecialties(Dest: TStrings); procedure ListSpecialtiesED(AType: Char; Dest: TStrings); procedure ListOrderFilters(Dest: TStrings); procedure ListOrderFiltersAll(Dest: TStrings); function NameOfDGroup(IEN: Integer): string; function ShortNameOfDGroup(IEN: Integer): string; function SeqOfDGroup(IEN: Integer): Integer; function CheckOrderGroup(AOrderID: string): integer; function CheckQOGroup(AQOId:string): Boolean; { Write Orders } procedure BuildResponses(var ResolvedDialog: TOrderDialogResolved; const KeyVars: string; AnEvent: TOrderDelayEvent; ForIMO: boolean = False); procedure ClearOrderRecall; function CommonLocationForOrders(OrderList: TStringList): Integer; function FormIDForDialog(IEN: Integer): Integer; function DlgIENForName(DlgName: string): Integer; procedure LoadOrderMenu(AnOrderMenu: TOrderMenu; AMenuIEN: Integer); procedure LoadOrderSet(SetItems: TStrings; AnIEN: Integer; var KeyVars, ACaption: string); procedure LoadWriteOrders(Dest: TStrings); procedure LoadWriteOrdersED(Dest: TStrings; EvtID: string); function OrderDisabledMessage(DlgIEN: Integer): string; procedure SendOrders(OrderList: TStringList; const ESCode: string); procedure SendReleaseOrders(OrderList: TStringList); procedure SendAndPrintOrders(OrderList, ErrList: TStrings; const ESCode: string; const DeviceInfo: string); procedure ExecutePrintOrders(SelectedList: TStringList; const DeviceInfo: string); procedure PrintOrdersOnReview(OrderList: TStringList; const DeviceInfo: string; PrintLoc: Integer = 0); {*KCM*} procedure PrintServiceCopies(OrderList: TStringList; PrintLoc: Integer = 0); {*REV*} procedure OrderPrintDeviceInfo(OrderList: TStringList; var PrintParams: TPrintParams; Nature: Char; PrintLoc: Integer = 0); {*KCM*} function UseNewMedDialogs: Boolean; { Order Actions } function DialogForOrder(const ID: string): Integer; procedure LockPatient(var ErrMsg: string); procedure UnlockPatient; procedure LockOrder(OrderID: string; var ErrMsg: string); procedure UnlockOrder(OrderID: string); function FormIDForOrder(const ID: string): Integer; procedure ValidateOrderAction(const ID, Action: string; var ErrMsg: string); procedure ValidateOrderActionNature(const ID, Action, Nature: string; var ErrMsg: string); procedure IsLatestAction(const ID: string; var ErrList: TStringList); procedure ChangeOrder(AnOrder: TOrder; ResponseList: TList); procedure RenewOrder(AnOrder: TOrder; RenewFields: TOrderRenewFields; IsComplex: integer; AnIMOOrderAppt: double; OCList: TStringList); procedure HoldOrder(AnOrder: TOrder); procedure ListDCReasons(Dest: TStrings; var DefaultIEN: Integer); function GetREQReason: Integer; procedure DCOrder(AnOrder: TOrder; AReason: Integer; NewOrder: boolean; var DCType: Integer); procedure ReleaseOrderHold(AnOrder: TOrder); procedure AlertOrder(AnOrder: TOrder; AlertRecip: Int64); procedure FlagOrder(AnOrder: TOrder; const FlagReason: string; AlertRecip: Int64); procedure UnflagOrder(AnOrder: TOrder; const AComment: string); procedure LoadFlagReason(Dest: TStrings; const ID: string); procedure LoadWardComments(Dest: TStrings; const ID: string); procedure PutWardComments(Src: TStrings; const ID: string; var ErrMsg: string); procedure CompleteOrder(AnOrder: TOrder; const ESCode: string); procedure VerifyOrder(AnOrder: TOrder; const ESCode: string); procedure VerifyOrderChartReview(AnOrder: TOrder; const ESCode: string); function GetOrderableIen(AnOrderId:string): integer; procedure StoreDigitalSig(AID, AHash: string; AProvider: Int64; ASig, ACrlUrl, DFN: string; var AError: string); procedure UpdateOrderDGIfNeeded(AnID: string); function CanEditSuchRenewedOrder(AnID: string; IsTxtOrder: integer): boolean; function IsPSOSupplyDlg(DlgID, QODlg: integer): boolean; procedure SaveChangesOnRenewOrder(var AnOrder: TOrder; AnID, TheRefills, ThePickup: string; IsTxtOrder: integer); function DoesOrderStatusMatch(OrderArray: TStringList): boolean; //function GetPromptandDeviceParameters(Location: integer; OrderList: TStringList; Nature: string): TPrintParams; { Order Information } procedure LoadRenewFields(RenewFields: TOrderRenewFields; const ID: string); procedure GetChildrenOfComplexOrder(AnParentID,CurrAct: string; var ChildList: TStringList); //PSI-COMPLEX procedure LESValidationForChangedLabOrder(var RejectedReason: TStringList; AnOrderInfo: string); procedure ValidateComplexOrderAct(AnOrderID: string; var ErrMsg: string); //PSI-COMPLEX function IsRenewableComplexOrder(AnParentID: string): boolean; //PSI-COMPLEX function IsComplexOrder(AnOrderID: string): boolean; //PSI-COMPLEX function GetDlgData(ADlgID: string): string; function OrderIsReleased(const ID: string): Boolean; function TextForOrder(const ID: string): string; function GetConsultOrderNumber(ConsultIEN: string): string; function GetOrderByIFN(const ID: string): TOrder; function GetPackageByOrderID(const OrderID: string): string; function AnyOrdersRequireSignature(OrderList: TStringList): Boolean; function OrderRequiresSignature(const ID: string): Boolean; function OrderRequiresDigitalSignature(const ID: string): Boolean; function GetDrugSchedule(const ID: string): string; function GetExternalText(const ID: string): string; function SetExternalText(const ID: string; ADrugSch: string; AUser: Int64): string; function GetDEA(const ID: string): string; function GetDigitalSignature(const ID: string): string; function GetPKIUse: Boolean; function GetPKISite: Boolean; function DoesOIPIInSigForQO(AnQOID: integer): integer; function GetDispGroupForLES: string; function GetOrderPtEvtID(AnOrderID: string): string; function VerbTelPolicyOrder(AnOrderID: string): boolean; function ForIVandUD(AnOrderID: string): boolean; {Event Delay Enhancement} function DeleteEmptyEvt(APtEvntID: string; var APtEvntName: string; Ask: boolean = True): boolean; function DispOrdersForEvent(AEvtId: string): boolean; function EventInfo(APtEvtID: string): string; // ptr to #100.2 function EventInfo1(AnEvtID: string): string; // ptr to #100.5 function EventExist(APtDFN:string; AEvt: integer): integer; function CompleteEvt(APtEvntID: string; APtEvntName: string; Ask: boolean = True): boolean; function PtEvtEmpty(APtEvtID: string): Boolean; function GetEventIFN(const AEvntID: string): string; function GetEventName(const AEvntID: string): string; function GetEventLoc(const APtEvntID: string): string; function GetEventLoc1(const AnEvntID: string): string; function GetEventDiv(const APtEvntID: string): string; function GetEventDiv1(const AnEvntID: string): string; function GetCurrentSpec(const APtIFN: string): string; function GetDefaultEvt(const AProviderIFN: string): string; function isExistedEvent(const APtDFN: string; const AEvtID: string; var APtEvtID: string): Boolean; function TypeOfExistedEvent(APtDFN: string; AEvtID: Integer): Integer; function isMatchedEvent(const APtDFN: string; const AEvtID: string; var ATs: string): Boolean; function isDCedOrder(const AnOrderID: string): Boolean; function isOnholdMedOrder(AnOrderID: string): Boolean; function SetDefaultEvent(var AErrMsg: string; EvtID: string): Boolean; function GetEventPromptID: integer; function GetDefaultTSForEvt(AnEvtID: integer): string; function GetPromptIDs: string; function GetEventDefaultDlg(AEvtID: integer): string; function CanManualRelease: boolean; function TheParentPtEvt(APtEvt: string): string; function IsCompletedPtEvt(APtEvtID: integer): boolean; function IsPassEvt(APtEvtID: integer; APtEvtType: char): boolean; function IsPassEvt1(AnEvtID: integer; AnEvtType: char): boolean; procedure DeleteDefaultEvt; procedure TerminatePtEvt(APtEvtID: integer); procedure ChangeEvent(AnOrderList: TStringList; APtEvtId: string); procedure DeletePtEvent(APtEvtID: string); procedure SaveEvtForOrder(APtDFN: string; AEvt: integer; AnOrderID: string); procedure SetPtEvtList(Dest: TStrings; APtDFN: string; var ATotal: integer); procedure GetTSListForEvt(Dest: TStrings; AnEvtID:integer); procedure GetChildEvent(var AChildList: TStringList; APtEvtID: string); { Order Checking } function IsMonograph(): Boolean; procedure DeleteMonograph(); procedure GetMonographList(ListOfMonographs: TStringList); procedure GetMonograph(Monograph: TStringList; x: Integer); procedure GetXtraTxt(OCText: TStringList; x: String; y: String); function FillerIDForDialog(IEN: Integer): string; function OrderChecksEnabled: Boolean; function OrderChecksOnDisplay(const FillerID: string): string; procedure OrderChecksOnAccept(ListOfChecks: TStringList; const FillerID, StartDtTm: string; OIList: TStringList; DupORIFN: string; Renewal: string); procedure OrderChecksOnDelay(ListOfChecks: TStringList; const FillerID, StartDtTm: string; OIList: TStringList); procedure OrderChecksForSession(ListOfChecks, OrderList: TStringList); procedure SaveOrderChecksForSession(const AReason: string; ListOfChecks: TStringList); function DeleteCheckedOrder(const OrderID: string): Boolean; function DataForOrderCheck(const OrderID: string): string; { Copay } procedure GetCoPay4Orders; procedure SaveCoPayStatus(AList: TStrings); {IMO: inpatient medication for outpatient} function LocationType(Location: integer): string; function IsValidIMOLoc(LocID: integer; PatientID: string): boolean; //IMO function IsValidIMOLocOrderCom(LocID: integer; PatientID: string): boolean; //IMO function IsIMOOrder(OrderID: string): boolean; function IsInptQO(DlgID: integer): boolean; function IsIVQO(DlgID: integer): boolean; function IsClinicLoc(ALoc: integer): boolean; {None-standard Schedule} //nss function IsValidSchedule(AnOrderID: string): boolean; //NSS function IsValidQOSch(QOID: string): string; //NSS function IsValidSchStr(ASchStr: string): boolean; function IsPendingHold(OrderID: string): boolean; implementation uses Windows, rCore, uConst, TRPCB, ORCtrls, UBAGlobals, UBACore, VAUtils; var uDGroupMap: TStringList; // each string is DGroupIEN=Sequence^TopName^Name uDGroupAll: Integer; uOrderChecksOn: Char; { TOrderView methods } procedure TOrderView.Assign(Src: TOrderView); begin Self.Changed := Src.Changed; Self.DGroup := Src.DGroup; Self.Filter := Src.Filter; Self.InvChrono := Src.InvChrono; Self.ByService := Src.ByService; Self.TimeFrom := Src.TimeFrom; Self.TimeThru := Src.TimeThru; Self.CtxtTime := Src.CtxtTime; Self.TextView := Src.TextView; Self.ViewName := Src.ViewName; Self.EventDelay.EventIFN := Src.EventDelay.EventIFN; Self.EventDelay.EventName := Src.EventDelay.EventName; Self.EventDelay.EventType := Src.EventDelay.EventType; Self.EventDelay.Specialty := Src.EventDelay.Specialty; Self.EventDelay.Effective := Src.EventDelay.Effective; end; { TOrder methods } procedure TOrder.Assign(Source: TOrder); begin ID := Source.ID; DGroup := Source.DGroup; OrderTime := Source.OrderTime; StartTime := Source.StartTime; StopTime := Source.StopTime; Status := Source.Status; Signature := Source.Signature; VerNurse := Source.VerNurse; VerClerk := Source.VerClerk; ChartRev := Source.ChartRev; Provider := Source.Provider; ProviderName := Source.ProviderName; ProviderDEA := Source.ProviderDEA; ProviderVA := Source.ProviderVA; DigSigReq := Source.DigSigReq; XMLText := Source.XMLText; Text := Source.Text; DGroupSeq := Source.DGroupSeq; DGroupName := Source.DGroupName; Flagged := Source.Flagged; Retrieved := Source.Retrieved; EditOf := Source.EditOf; ActionOn := Source.ActionOn; EventPtr := Source.EventPtr; EventName := Source.EventName; OrderLocIEN := Source.OrderLocIEN; OrderLocName := Source.OrderLocName; ParentID := Source.ParentID; LinkObject := Source.LinkObject; IsControlledSubstance := Source.IsControlledSubstance; IsDetox := Source.IsDetox; end; procedure TOrder.Clear; begin ID := ''; DGroup := 0; OrderTime := 0; StartTime := ''; StopTime := ''; Status := 0; Signature := 0; VerNurse := ''; VerClerk := ''; ChartRev := ''; Provider := 0; ProviderName := ''; ProviderDEA := ''; ProviderVA :=''; DigSigReq :=''; XMLText := ''; Text := ''; DGroupSeq := 0; DGroupName := ''; Flagged := False; Retrieved := False; EditOf := ''; ActionOn := ''; OrderLocIEN := ''; //imo OrderLocName := ''; //imo ParentID := ''; LinkObject := nil; IsControlledSubstance := False; IsDetox := False; end; { Order List functions } function DetailOrder(const ID: string): TStrings; begin CallV('ORQOR DETAIL', [ID, Patient.DFN]); Result := RPCBrokerV.Results; end; function ResultOrder(const ID: string): TStrings; begin CallV('ORWOR RESULT', [Patient.DFN,ID,ID]); Result := RPCBrokerV.Results; end; function ResultOrderHistory(const ID: string): TStrings; begin CallV('ORWOR RESULT HISTORY', [Patient.DFN,ID,ID]); Result := RPCBrokerV.Results; end; procedure LoadDGroupMap; begin if uDGroupMap = nil then begin uDGroupMap := TStringList.Create; tCallV(uDGroupMap, 'ORWORDG MAPSEQ', [nil]); end; end; function NameOfStatus(IEN: Integer): string; begin case IEN of 0: Result := 'error'; 1: Result := 'discontinued'; 2: Result := 'complete'; 3: Result := 'hold'; 4: Result := 'flagged'; 5: Result := 'pending'; 6: Result := 'active'; 7: Result := 'expired'; 8: Result := 'scheduled'; 9: Result := 'partial results'; 10: Result := 'delayed'; 11: Result := 'unreleased'; 12: Result := 'dc/edit'; 13: Result := 'cancelled'; 14: Result := 'lapsed'; 15: Result := 'renewed'; 97: Result := ''; { null status, used for 'No Orders Found.' } 98: Result := 'new'; 99: Result := 'no status'; end; end; function GetOrderStatus(AnOrderId: string): integer; begin Result := StrToIntDef(SCallV('OREVNTX1 GETSTS',[AnOrderId]),0); end; function ExpiredOrdersStartDT: TFMDateTime; //Return FM date/time to begin search for expired orders begin Result := MakeFMDateTime(sCallV('ORWOR EXPIRED', [nil])); end; function DispOrdersForEvent(AEvtId: string): boolean; var theResult: integer; begin Result := False; theResult := StrToIntDef(SCallV('OREVNTX1 CPACT',[AEvtId]),0); if theResult > 0 then Result := True; end; function EventInfo(APtEvtID: string): string; begin Result := SCallV('OREVNTX1 GTEVT', [APtEvtID]); end; function EventInfo1(AnEvtID: string): string; begin Result := SCallV('OREVNTX1 GTEVT1', [AnEvtID]); end; function NameOfDGroup(IEN: Integer): string; begin if uDGroupMap = nil then LoadDGroupMap; Result := uDGroupMap.Values[IntToStr(IEN)]; Result := Piece(Result, U, 3); end; function ShortNameOfDGroup(IEN: Integer): string; begin if uDGroupMap = nil then LoadDGroupMap; Result := uDGroupMap.Values[IntToStr(IEN)]; Result := Piece(Result, U, 4); end; function SeqOfDGroup(IEN: Integer): Integer; var x: string; begin if uDGroupMap = nil then LoadDGroupMap; x := uDGroupMap.Values[IntToStr(IEN)]; Result := StrToIntDef(Piece(x, U, 1), 0); end; function CheckOrderGroup(AOrderID: string): integer; begin // Result = 1 Inpatient Medication Display Group; // Result = 2 OutPatient Medication Display Group; // Result = 0 None of In or Out patient display group; Result := StrToInt(SCallV('ORWDPS2 CHKGRP',[AOrderID])); end; function CheckQOGroup(AQOId:string): Boolean; var rst: integer; begin rst := StrToInt(SCallV('ORWDPS2 QOGRP',[AQOId])); Result := False; if rst > 0 then Result := True; end; function TopNameOfDGroup(IEN: Integer): string; begin if uDGroupMap = nil then LoadDGroupMap; Result := uDGroupMap.Values[IntToStr(IEN)]; Result := Piece(Result, U, 2); end; procedure ClearOrders(AList: TList); var i: Integer; begin with AList do for i := 0 to Count - 1 do with TOrder(Items[i]) do Free; AList.Clear; end; procedure SetOrderFields(AnOrder: TOrder; const x, y, z: string); { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 { Pieces: ~IFN^Grp^ActTm^StrtTm^StopTm^Sts^Sig^Nrs^Clk^PrvID^PrvNam^ActDA^Flag^DCType^ChrtRev^DEA#^VA#^DigSig^IMO^DCOrigOrder^ISDCOrder^IsDelayOrder^IsControlledSubstance^IsDetox} begin with AnOrder do begin Clear; ID := Copy(Piece(x, U, 1), 2, Length(Piece(x, U, 1))); DGroup := StrToIntDef(Piece(x, U, 2), 0); OrderTime := MakeFMDateTime(Piece(x, U, 3)); StartTime := Piece(x, U, 4); StopTime := Piece(x, U, 5); Status := StrToIntDef(Piece(x, U, 6), 0); Signature := StrToIntDef(Piece(x, U, 7), 0); VerNurse := Piece(x, U, 8); VerClerk := Piece(x, U, 9); ChartRev := Piece(x, U, 15); Provider := StrToInt64Def(Piece(x, U, 10), 0); ProviderName := Piece(x, U, 11); ProviderDEA := Piece(x, U, 16); ProviderVA := Piece(x, U, 17); DigSigReq := Piece(x, U, 18); Flagged := Piece(x, U, 13) = '1'; Retrieved := True; OrderLocIEN := Piece(Piece(x,U,19),':',2); //imo if Piece(Piece(x,U,19),':',1) = '0;SC(' then OrderLocName := 'Unknown' else OrderLocName := Piece(Piece(x,U,19),':',1); //imo Text := y; XMLText := z; DGroupSeq := SeqOfDGroup(DGroup); DGroupName := TopNameOfDGroup(DGroup); //AGP Changes 26.15 PSI-04-063 if (pos('Entered in error',Text)>0) then AnOrder.EnteredInError := 1 else AnOrder.EnteredInError := 0; //if DGroupName = 'Non-VA Meds' then Text := 'Non-VA ' + Text; if Piece(x,U,20) = '1' then DCOriginalOrder := True else DCOriginalOrder := False; if Piece(X,u,21) = '1' then IsOrderPendDC := True else IsOrderPendDC := False; if Piece(x,u,22) = '1' then IsDelayOrder := True else IsDelayOrder := False; if Piece(x,u,23) = '1' then IsControlledSubstance := True else IsControlledSubstance := False; if Piece(x,u,24) = '1' then IsDetox := True else IsDetox := False; end; end; procedure LoadOrders(Dest: TList; Filter, Groups: Integer); var x, y, z: string; AnOrder: TOrder; begin ClearOrders(Dest); if uDGroupMap = nil then LoadDGroupMap; // to make sure broker not called while looping thru Results CallV('ORWORR GET', [Patient.DFN, Filter, Groups]); with RPCBrokerV do while Results.Count > 0 do begin x := Results[0]; Results.Delete(0); if CharAt(x, 1) <> '~' then Continue; // only happens if out of synch y := ''; while (Results.Count > 0) and (CharAt(Results[0], 1) <> '~') and (CharAt(Results[0], 1) <> '|') do begin y := y + Copy(Results[0], 2, Length(Results[0])) + CRLF; Results.Delete(0); end; if Length(y) > 0 then y := Copy(y, 1, Length(y) - 2); // take off last CRLF z := ''; if (Results.Count > 0) and (Results[0] = '|') then begin Results.Delete(0); while (Results.Count > 0) and (CharAt(Results[0], 1) <> '~') and (CharAt(Results[0], 1) <> '|') do begin z := z + Copy(Results[0], 2, Length(Results[0])); Results.Delete(0); end; end; AnOrder := TOrder.Create; SetOrderFields(AnOrder, x, y, z); Dest.Add(AnOrder); end; end; procedure LoadOrdersAbbr(Dest: TList; AView: TOrderView; APtEvtID: string); //Filter, Specialty, Groups: Integer; var TextView: Integer; // var CtxtTime: TFMDateTime); var FilterTS: string; AlertedUserOnly: boolean; begin ClearOrders(Dest); if uDGroupMap = nil then LoadDGroupMap; // to make sure broker not called while looping thru Results FilterTS := IntToStr(AView.Filter) + U + IntToStr(AView.EventDelay.Specialty); AlertedUserOnly := (Notifications.Active and (AView.Filter = 12)); CallV('ORWORR AGET', [Patient.DFN, FilterTS, AView.DGroup, AView.TimeFrom, AView.TimeThru, APtEvtID, AlertedUserOnly]); if ((Piece(RPCBrokerV.Results[0], U, 1) = '0') or (Piece(RPCBrokerV.Results[0], U, 1) = '')) and (AView.Filter = 5) then // if no expiring orders found display expired orders) begin CallV('ORWORR AGET', [Patient.DFN, '27^0', AView.DGroup, ExpiredOrdersStartDT, FMNow, APtEvtID]); AView.ViewName := 'Recently Expired Orders (No Expiring Orders Found) -' + Piece(AView.ViewName, '-', 2); end; {if (Piece(RPCBrokerV.Results[0], U, 1) = '0') or (Piece(RPCBrokerV.Results[0], U, 1) = '') then // if no orders found (0 element is count) begin AnOrder := TOrder.Create; with AnOrder do begin ID := '0'; DGroup := 0; OrderTime := FMNow; Status := 97; Text := 'No orders found.'; Retrieved := True; end; Dest.Add(AnOrder); Exit; end;} ConvertOrders(Dest, AView); end; procedure LoadOrdersAbbr(Dest: TList; AView: TOrderView; AptEvtID: string; AlertID: string); begin ClearOrders(Dest); if uDGroupMap = nil then LoadDGroupMap; // to make sure broker not called while looping thru Results CallV('ORB FOLLOW-UP ARRAY', [AlertID]); ConvertOrders(Dest, AView); end; procedure ConvertOrders(Dest: TList; AView: TOrderView); var i: Integer; AnOrder: TOrder; begin AView.TextView := StrToIntDef(Piece(RPCBrokerV.Results[0], U, 2), 0); AView.CtxtTime := MakeFMDateTime(Piece(RPCBrokerV.Results[0], U, 3)); with RPCBrokerV do for i := 1 to Results.Count - 1 do // if orders found (skip 0 element) begin if (Piece(RPCBrokerV.Results[i], U, 1) = '0') or (Piece(RPCBrokerV.Results[i], U, 1) = '') then Continue; if (DelimCount(Results[i],U) = 2) then Continue; AnOrder := TOrder.Create; with AnOrder do begin ID := Piece(Results[i], U, 1); DGroup := StrToIntDef(Piece(Results[i], U, 2), 0); OrderTime := MakeFMDateTime(Piece(Results[i], U, 3)); EventPtr := Piece(Results[i],U,4); EventName := Piece(Results[i],U,5); DGroupSeq := SeqOfDGroup(DGroup); end; Dest.Add(AnOrder); end; end; procedure LoadOrdersAbbr(DestDC,DestRL: TList; AView: TOrderView; APtEvtID: string); var i: Integer; AnOrder: TOrder; FilterTS: string; DCStart: boolean; begin DCStart := False; if uDGroupMap = nil then LoadDGroupMap; FilterTS := IntToStr(AView.Filter) + U + IntToStr(AView.EventDelay.Specialty); CallV('ORWORR RGET', [Patient.DFN, FilterTS, AView.DGroup, AView.TimeFrom, AView.TimeThru, APtEvtID]); if RPCBrokerV.Results[0] = '0' then // if no orders found (0 element is count) begin AnOrder := TOrder.Create; with AnOrder do begin ID := '0'; DGroup := 0; OrderTime := FMNow; Status := 97; Text := 'No orders found.'; Retrieved := True; end; DestDC.Add(AnOrder); Exit; end; AView.TextView := StrToIntDef(Piece(RPCBrokerV.Results[0], U, 2), 0); AView.CtxtTime := MakeFMDateTime(Piece(RPCBrokerV.Results[0], U, 3)); with RPCBrokerV do for i := 1 to Results.Count - 1 do // if orders found (skip 0 element) begin if AnsiCompareText('DC START', Results[i]) = 0 then begin DCStart := True; Continue; end; AnOrder := TOrder.Create; with AnOrder do begin ID := Piece(Results[i], U, 1); DGroup := StrToIntDef(Piece(Results[i], U, 2), 0); OrderTime := MakeFMDateTime(Piece(Results[i], U, 3)); EventPtr := Piece(Results[i],U,4); EventName := Piece(Results[i],U,5); DGroupSeq := SeqOfDGroup(DGroup); end; if DCStart then DestDC.Add(AnOrder) else DestRL.Add(AnOrder); end; end; procedure LoadOrderSheets(Dest: TStrings); begin CallV('ORWOR SHEETS', [Patient.DFN]); MixedCaseByPiece(RPCBrokerV.Results, U, 2); FastAssign(RPCBrokerV.Results, Dest); end; procedure LoadOrderSheetsED(Dest: TStrings); var aReturn: TStrings; i: integer; begin aReturn := TStringList.Create; CallVistA('OREVNTX PAT', [Patient.DFN], aReturn); MixedCaseByPiece(aReturn, U, 2); Dest.Add('C;O^Current View'); if aReturn.Count > 1 then begin aReturn.Delete(0); for i := 0 to aReturn.Count - 1 do aReturn[i] := aReturn[i] + ' Orders'; Dest.AddStrings(aReturn); end; end; procedure LoadOrderViewDefault(AView: TOrderView); var x: string; begin x := sCallV('ORWOR VWGET', [nil]); with AView do begin Changed := False; DGroup := StrToIntDef(Piece(x, ';', 4), 0); Filter := StrToIntDef(Piece(x, ';', 3), 0); InvChrono := Piece(x, ';', 6) = 'R'; ByService := Piece(x, ';', 7) = '1'; TimeFrom := StrToFloat(Piece(x, ';', 1)); TimeThru := StrToFloat(Piece(x, ';', 2)); CtxtTime := 0; TextView := 0; ViewName := Piece(x, ';', 8); EventDelay.EventType := 'C'; EventDelay.Specialty := 0; EventDelay.Effective := 0; end; end; procedure LoadUnsignedOrders(IDList, HaveList: TStrings); var i: Integer; begin LockBroker; try with RPCBrokerV do begin ClearParameters := True; RemoteProcedure := 'ORWOR UNSIGN'; Param[0].PType := literal; Param[0].Value := Patient.DFN; Param[1].PType := list; Param[1].Mult['0'] := ''; // (to prevent broker from hanging if empty list) for i := 0 to Pred(HaveList.Count) do Param[1].Mult['"' + HaveList[i] + '"'] := ''; CallBroker; FastAssign(RPCBrokerV.Results,IDList); end; finally UnlockBroker; end; end; procedure RetrieveOrderFields(OrderList: TList; ATextView: Integer; ACtxtTime: TFMDateTime); var i, OrderIndex: Integer; x, y, z: string; AnOrder: TOrder; IDList: TStringList; begin IDList := TStringList.Create; try with OrderList do for i := 0 to Count - 1 do IDList.Add(TOrder(Items[i]).ID); CallV('ORWORR GET4LST', [ATextView, ACtxtTime, IDList]); finally IDList.Free; end; OrderIndex := -1; with RPCBrokerV do while Results.Count > 0 do begin Inc(OrderIndex); if (OrderIndex >= OrderList.Count) then begin Results.Delete(0); Continue; end; AnOrder := TOrder(OrderList.Items[OrderIndex]); x := Results[0]; Results.Delete(0); if CharAt(x, 1) <> '~' then Continue; // only happens if out of synch if Piece(x, U, 1) <> '~' + AnOrder.ID then Continue; // only happens if out of synch y := ''; while (Results.Count > 0) and (CharAt(Results[0], 1) <> '~') and (CharAt(Results[0], 1) <> '|') do begin y := y + Copy(Results[0], 2, Length(Results[0])) + CRLF; Results.Delete(0); end; if Length(y) > 0 then y := Copy(y, 1, Length(y) - 2); // take off last CRLF z := ''; if (Results.Count > 0) and (Results[0] = '|') then begin Results.Delete(0); while (Results.Count > 0) and (CharAt(Results[0], 1) <> '~') and (CharAt(Results[0], 1) <> '|') do begin z := z + Copy(Results[0], 2, Length(Results[0])); Results.Delete(0); end; end; SetOrderFields(AnOrder, x, y, z); end; end; procedure SaveOrderViewDefault(AView: TOrderView); var x: string; begin with AView do begin x := MakeRelativeDateTime(TimeFrom) + ';' + // 1 MakeRelativeDateTime(TimeThru) + ';' + // 2 IntToStr(Filter) + ';' + // 3 IntToStr(DGroup) + ';;'; // 4, skip 5 if InvChrono then x := x + 'R;' else x := x + 'F;'; // 6 if ByService then x := x + '1' else x := x + '0'; // 7 CallV('ORWOR VWSET', [x]); end; end; { MOVE THESE FUNCTIONS INTO UORDERS??? } { < 0 if Item1 is less and Item2, 0 if they are equal and > 0 if Item1 is greater than Item2 } function InverseByGroup(Item1, Item2: Pointer): Integer; var Order1, Order2: TOrder; DSeq1, DSeq2, IFN1, IFN2: Integer; begin Order1 := TOrder(Item1); Order2 := TOrder(Item2); if ( (Piece(Order1.ID, ';', 2) = '1') and (Changes.Exist(CH_ORD, Order1.ID)) ) and ( StrToIntDef(Order1.EventPtr,0) = 0 ) then DSeq1 := 0 else DSeq1 := Order1.DGroupSeq; if ((Piece(Order2.ID, ';', 2) = '1') and (Changes.Exist(CH_ORD, Order2.ID))) and ( StrToIntDef(Order1.EventPtr,0) = 0 ) then DSeq2 := 0 else DSeq2 := Order2.DGroupSeq; if DSeq1 = DSeq2 then begin if Order1.OrderTime > Order2.OrderTime then Result := -1 else if Order1.OrderTime < Order2.OrderTime then Result := 1 else Result := 0; if Result = 0 then begin IFN1 := StrToIntDef(Piece(Order1.ID, ';', 1), 0); IFN2 := StrToIntDef(Piece(Order2.ID, ';', 1), 0); if IFN1 < IFN2 then Result := -1; if IFN1 > IFN2 then Result := 1; end; end else if DSeq1 < DSeq2 then Result := -1 else Result := 1; end; function ForwardByGroup(Item1, Item2: Pointer): Integer; var Order1, Order2: TOrder; DSeq1, DSeq2, IFN1, IFN2: Integer; begin Order1 := TOrder(Item1); Order2 := TOrder(Item2); if (Piece(Order1.ID, ';', 2) = '1') and (Changes.Exist(CH_ORD, Order1.ID)) then DSeq1 := 0 else DSeq1 := Order1.DGroupSeq; if (Piece(Order2.ID, ';', 2) = '1') and (Changes.Exist(CH_ORD, Order2.ID)) then DSeq2 := 0 else DSeq2 := Order2.DGroupSeq; if DSeq1 = DSeq2 then begin if Order1.OrderTime < Order2.OrderTime then Result := -1 else if Order1.OrderTime > Order2.OrderTime then Result := 1 else Result := 0; if Result = 0 then begin IFN1 := StrToIntDef(Piece(Order1.ID, ';', 1), 0); IFN2 := StrToIntDef(Piece(Order2.ID, ';', 1), 0); if IFN1 < IFN2 then Result := -1; if IFN1 > IFN2 then Result := 1; end; end else if DSeq1 < DSeq2 then Result := -1 else Result := 1; end; function InverseChrono(Item1, Item2: Pointer): Integer; var Order1, Order2: TOrder; IFN1, IFN2: Integer; begin Order1 := TOrder(Item1); Order2 := TOrder(Item2); if Order1.OrderTime > Order2.OrderTime then Result := -1 else if Order1.OrderTime < Order2.OrderTime then Result := 1 else Result := 0; if Result = 0 then begin IFN1 := StrToIntDef(Piece(Order1.ID, ';', 1), 0); IFN2 := StrToIntDef(Piece(Order2.ID, ';', 1), 0); if IFN1 < IFN2 then Result := -1; if IFN1 > IFN2 then Result := 1; end; end; function ForwardChrono(Item1, Item2: Pointer): Integer; var Order1, Order2: TOrder; IFN1, IFN2: Integer; begin Order1 := TOrder(Item1); Order2 := TOrder(Item2); if Order1.OrderTime < Order2.OrderTime then Result := -1 else if Order1.OrderTime > Order2.OrderTime then Result := 1 else Result := 0; if Result = 0 then begin IFN1 := StrToIntDef(Piece(Order1.ID, ';', 1), 0); IFN2 := StrToIntDef(Piece(Order2.ID, ';', 1), 0); if IFN1 < IFN2 then Result := -1; if IFN1 > IFN2 then Result := 1; end; end; procedure SortOrders(AList: TList; ByGroup, InvChron: Boolean); begin if ByGroup then begin if InvChron then AList.Sort(InverseByGroup) else AList.Sort(ForwardByGroup); end else begin if InvChron then AList.Sort(InverseChrono) else AList.Sort(ForwardChrono); end; end; function DGroupAll: Integer; var x: string; begin if uDGroupAll = 0 then begin x := sCallV('ORWORDG IEN', ['ALL']); uDGroupAll := StrToIntDef(x, 1); end; Result := uDGroupAll; end; function DGroupIEN(AName: string): Integer; begin Result := StrToIntDef(sCallV('ORWORDG IEN', [AName]), 0); end; procedure ListDGroupAll(Dest: TStrings); begin CallV('ORWORDG ALLTREE', [nil]); FastAssign(RPCBrokerV.Results, Dest); end; procedure ListSpecialties(Dest: TStrings); begin CallV('ORWOR TSALL', [nil]); MixedCaseList(RPCBrokerV.Results); FastAssign(RPCBrokerV.Results, Dest); end; procedure ListSpecialtiesED(AType: Char; Dest: TStrings); var i :integer; Currloc: integer; admitEvts: TStringList; otherEvts: TStringList; commonList: TStringList; IsObservation: boolean; begin if Encounter <> nil then Currloc := Encounter.Location else Currloc := 0; IsObservation := (Piece(GetCurrentSpec(Patient.DFN), U, 3) = '1'); commonList := TStringList.Create; CallV('OREVNTX1 CMEVTS',[Currloc]); //MixedCaseList(RPCBrokerV.Results); if RPCBrokerV.Results.Count > 0 then with RPCBrokerV do for i := 0 to Results.Count - 1 do begin if AType = 'D' then begin if AType = Piece(Results[i],'^',3) then commonList.Add(Results[i]); end else if AType = 'A' then begin if (Piece(Results[i],'^',3) = 'T') or (Piece(Results[i],'^',3) = 'D') then Continue; commonList.Add(Results[i]); end else if IsObservation then begin if (Piece(Results[i],'^',3) = 'T') then Continue; commonList.Add(Results[i]); end else begin if Length(Results[i])> 0 then commonList.Add(Results[i]); end; end; if commonList.Count > 0 then begin Dest.AddStrings(commonList); Dest.Add('^^^^^^^^___________________________________________________________________________________________'); Dest.Add(LLS_SPACE); end; if AType = #0 then begin admitEvts := TStringList.Create; otherEvts := TSTringList.Create; CallV('OREVNTX ACTIVE',['A']); //MixedCaseList(RPCBrokerV.Results); if RPCBrokerV.Results.Count > 0 then begin RPCBrokerV.Results.Delete(0); admitEvts.AddStrings(RPCBrokerV.Results); end; if IsObservation then CallV('OREVNTX ACTIVE',['O^M^D']) else CallV('OREVNTX ACTIVE',['T^O^M^D']); //MixedCaseList(RPCBrokerV.Results); if RPCBrokerV.Results.Count > 0 then begin RPCBrokerV.Results.Delete(0); otherEvts.AddStrings(RPCBrokerV.Results); end; Dest.AddStrings(otherEvts); Dest.Add('^^^^^^^^_____________________________________________________________________________________________'); Dest.Add(LLS_SPACE); Dest.AddStrings(admitEvts); admitEvts.Free; otherEvts.Free; end else if AType = 'A' then begin CallV('OREVNTX ACTIVE',['A^O^M']); //MixedCaseList(RPCBrokerV.Results); if RPCBrokerV.Results.Count > 0 then RPCBrokerV.Results.Delete(0); Dest.AddStrings(RPCBrokerV.Results); end else begin CallV('OREVNTX ACTIVE',[AType]); //MixedCaseList(RPCBrokerV.Results); if RPCBrokerV.Results.Count > 0 then RPCBrokerV.Results.Delete(0); Dest.AddStrings(RPCBrokerV.Results); end; end; procedure ListOrderFilters(Dest: TStrings); begin CallV('ORWORDG REVSTS', [nil]); FastAssign(RPCBrokerV.Results, Dest); end; procedure ListOrderFiltersAll(Dest: TStrings); begin CallV('ORWORDG REVSTS', [nil]); FastAssign(RPCBrokerV.Results, Dest); end; { Write Orders } procedure BuildResponses(var ResolvedDialog: TOrderDialogResolved; const KeyVars: string; AnEvent: TOrderDelayEvent; ForIMO: boolean); const BoolChars: array[Boolean] of Char = ('0', '1'); RESERVED_PIECE = ''; var DelayEvent, x, TheOrder: string; Idx, tmpOrderGroup, PickupIdx, ForIMOResponses: integer; IfUDGrp: Boolean; IfUDGrpForQO: Boolean; temp: string; begin ForIMOResponses := 0; tmpOrderGroup := 0; temp := ''; if ForIMO then ForIMOResponses := 1; PickupIdx := 0; IfUDGrp := False; TheOrder := ResolvedDialog.InputID; IfUDGrpForQO := CheckQOGroup(TheOrder); if CharInSet(CharAt(TheOrder,1), ['C','T']) then begin Delete(TheOrder,1,1); tmpOrderGroup := CheckOrderGroup(TheOrder); if tmpOrderGroup = 1 then IfUDGrp := True else IfUDGrp := False; end; if (not IfUDGrp) and CharInSet(AnEvent.EventType, ['A','T']) then IfUDGrp := True; //FLDS=DFN^LOC^ORNP^INPT^SEX^AGE^EVENT^SC%^^^Key Variables if (Patient.Inpatient = true) and (tmpOrderGroup = 2) then temp := '0'; if temp <> '0' then temp := BoolChars[Patient.Inpatient]; with AnEvent do begin if isNewEvent then DelayEvent := '0;'+ EventType + ';' + IntToStr(Specialty) + ';' + FloatToStr(Effective) else DelayEvent := IntToStr(AnEvent.PtEventIFN) + ';' + EventType + ';' + IntToStr(Specialty) + ';' + FloatToStr(Effective); end; x := Patient.DFN + U + // 1 IntToStr(Encounter.Location) + U + // 2 IntToStr(Encounter.Provider) + U + // 3 BoolChars[Patient.Inpatient] + U + // 4 Patient.Sex + U + // 5 IntToStr(Patient.Age) + U + // 6 DelayEvent + U + // 7 (for OREVENT) IntToStr(Patient.SCPercent) + U + // 8 RESERVED_PIECE + U + // 9 RESERVED_PIECE + U + // 10 KeyVars; CallV('ORWDXM1 BLDQRSP', [ResolvedDialog.InputID, x, ForIMOResponses, Encounter.Location]); // LST(0)=QuickLevel^ResponseID(ORIT;$H)^Dialog^Type^FormID^DGrp with RPCBrokerV do begin x := Results[0]; with ResolvedDialog do begin QuickLevel := StrToIntDef(Piece(x, U, 1), 0); ResponseID := Piece(x, U, 2); DialogIEN := StrToIntDef(Piece(x, U, 3), 0); DialogType := CharAt(Piece(x, U, 4), 1); FormID := StrToIntDef(Piece(x, U, 5), 0); DisplayGroup := StrToIntDef(Piece(x, U, 6), 0); QOKeyVars := Pieces(x, U, 7, 7 + MAX_KEYVARS); Results.Delete(0); if Results.Count > 0 then begin if (IfUDGrp) or (IfUDGrpForQO) then begin for Idx := 0 to Results.Count - 1 do begin if(Pos('PICK UP',UpperCase(Results[idx])) > 0) or (Pos('PICK-UP',UpperCase(Results[idx])) > 0) then begin PickupIdx := Idx; Break; end; end; end; if PickupIdx > 0 then Results.Delete(PickupIdx); SetString(ShowText, Results.GetText, StrLen(Results.GetText)); end; end; end; end; procedure ClearOrderRecall; begin CallV('ORWDXM2 CLRRCL', [nil]); end; function CommonLocationForOrders(OrderList: TStringList): Integer; begin Result := StrToIntDef(sCallV('ORWD1 COMLOC', [OrderList]), 0); end; function FormIDForDialog(IEN: Integer): Integer; begin Result := StrToIntDef(sCallV('ORWDXM FORMID', [IEN]), 0); end; function DlgIENForName(DlgName: string): Integer; begin Result := StrToIntDef(sCallV('OREVNTX1 DLGIEN',[DlgName]),0); end; procedure LoadOrderMenu(AnOrderMenu: TOrderMenu; AMenuIEN: Integer); var OrderMenuItem: TOrderMenuItem; i: Integer; OrderTitle: String; begin CallV('ORWDXM MENU', [AMenuIEN]); with RPCBrokerV do if Results.Count > 0 then begin // Results[0] = Name^Cols^PathSwitch^^^LRFZX^LRFSAMP^LRFSPEC^LRFDATE^LRFURG^LRFSCH^PSJNPOC^ // GMRCNOPD^GMRCNOAT^GMRCREAF^^^^^ OrderTitle := Piece(Results[0], U, 1); if (Pos('&', OrderTitle) > 0) and (Copy(OrderTitle, Pos('&', OrderTitle) + 1, 1) <> '&') then OrderTitle := Copy(OrderTitle, 1, Pos('&', OrderTitle)) + '&' + Copy(OrderTitle, Pos('&', OrderTitle) + 1, Length(OrderTitle)); AnOrderMenu.Title := OrderTitle; AnOrderMenu.NumCols := StrToIntDef(Piece(Results[0], U, 2), 1); AnOrderMenu.KeyVars := Pieces(Results[0], U, 6, 6 + MAX_KEYVARS); for i := 1 to Results.Count - 1 do begin OrderMenuItem := TOrderMenuItem.Create; with OrderMenuItem do begin Col := StrToIntDef(Piece(Results[i], U, 1), 0) - 1; Row := StrToIntDef(Piece(Results[i], U, 2), 0) - 1; DlgType := CharAt(Piece(Results[i], U, 3), 1); IEN := StrToIntDef(Piece(Results[i], U, 4), 0); FormID := StrToIntDef(Piece(Results[i], U, 5), 0); AutoAck := Piece(Results[i], U, 6) = '1'; ItemText := Piece(Results[i], U, 7); Mnemonic := Piece(Results[i], U, 8); Display := StrToIntDef(Piece(Results[i], U, 9), 0); end; {with OrderItem} AnOrderMenu.MenuItems.Add(OrderMenuItem); end; {for i} end; {with RPCBrokerV} end; procedure LoadOrderSet(SetItems: TStrings; AnIEN: Integer; var KeyVars, ACaption: string); var x: string; begin CallV('ORWDXM LOADSET', [AnIEN]); KeyVars := ''; ACaption := ''; if RPCBrokerV.Results.Count > 0 then begin x := RPCBrokerV.Results[0]; ACaption := Piece(x, U, 1); KeyVars := Copy(x, Pos(U, x) + 1, Length(x)); RPCBrokerV.Results.Delete(0); end; FastAssign(RPCBrokerV.Results, SetItems); end; procedure LoadWriteOrders(Dest: TStrings); begin CallV('ORWDX WRLST', [Encounter.Location]); FastAssign(RPCBrokerV.Results, Dest); end; procedure LoadWriteOrdersED(Dest: TStrings; EvtID: string); begin CallV('OREVNTX1 WRLSTED', [Encounter.Location,EvtID]); if RPCBrokerV.Results.count > 0 then begin Dest.Clear; FastAssign(RPCBrokerV.Results, Dest); end end; function OrderDisabledMessage(DlgIEN: Integer): string; begin Result := sCallV('ORWDX DISMSG', [DlgIEN]); end; procedure SendOrders(OrderList: TStringList; const ESCode: string); var i: Integer; begin { prepending the space to ESCode is temporary way to keep broker from crashing } CallV('ORWDX SEND', [Patient.DFN, Encounter.Provider, Encounter.Location, ' ' + ESCode, OrderList]); { this is a stop gap way to prevent an undesired error message when user chooses not to sign } with RPCBrokerV do for i := 0 to Results.Count - 1 do if Piece(Results[i], U, 4) = 'This order requires a signature.' then Results[i] := Piece(Results[i], U, 1); OrderList.Clear; FastAssign(RPCBrokerV.Results, OrderList); end; procedure SendReleaseOrders(OrderList: TStringList); var loc: string; CurrTS: Integer; PtTS: string; begin PtTS := Piece(GetCurrentSpec(Patient.DFN),'^',2); CurrTS := StrToIntDef(PtTS,0); Loc := IntToStr(Encounter.Location); CallV('ORWDX SENDED',[OrderList,CurrTS,Loc]); OrderList.Clear; FastAssign(RPCBrokerV.Results, OrderList); end; procedure SendAndPrintOrders(OrderList, ErrList: TStrings; const ESCode: string; const DeviceInfo: string); var i: Integer; begin { prepending the space to ESCode is temporary way to keep broker from crashing } CallV('ORWDX SENDP', [Patient.DFN, Encounter.Provider, Encounter.Location, ' ' + ESCode, DeviceInfo, OrderList]); { this is a stop gap way to prevent an undesired error message when user chooses not to sign } with RPCBrokerV do for i := 0 to Results.Count - 1 do if Piece(Results[i], U, 3) <> 'This order requires a signature.' then ErrList.Add(Results[i]); end; procedure PrintOrdersOnReview(OrderList: TStringList; const DeviceInfo: string; PrintLoc: Integer = 0); var Loc: Integer; begin if (PrintLoc > 0) and (PrintLoc <> Encounter.Location) then Loc := PrintLoc else Loc := Encounter.Location; CallV('ORWD1 RVPRINT', [Loc, DeviceInfo, OrderList]); end; procedure PrintServiceCopies(OrderList: TStringList; PrintLoc: Integer = 0); {*REV*} var Loc: Integer; begin if (PrintLoc > 0) and (PrintLoc <> Encounter.Location) then Loc := PrintLoc else Loc := Encounter.Location; CallV('ORWD1 SVONLY', [Loc, OrderList]); end; procedure ExecutePrintOrders(SelectedList: TStringList; const DeviceInfo: string); begin CallV('ORWD1 PRINTGUI', [Encounter.Location, DeviceInfo, SelectedList]); end; { Order Actions } function DialogForOrder(const ID: string): Integer; begin Result := StrToIntDef(sCallV('ORWDX DLGID', [ID]), 0); end; function FormIDForOrder(const ID: string): Integer; begin Result := StrToIntDef(sCallV('ORWDX FORMID', [ID]), 0); end; procedure SetOrderFromResults(AnOrder: TOrder); var x, y, z: string; begin with RPCBrokerV do while Results.Count > 0 do begin x := Results[0]; Results.Delete(0); if CharAt(x, 1) <> '~' then Continue; // only happens if out of synch y := ''; while (Results.Count > 0) and (CharAt(Results[0], 1) <> '~') and (CharAt(Results[0], 1) <> '|') do begin y := y + Copy(Results[0], 2, Length(Results[0])) + CRLF; Results.Delete(0); end; if Length(y) > 0 then y := Copy(y, 1, Length(y) - 2); // take off last CRLF z := ''; if (Results.Count > 0) and (Results[0] = '|') then begin Results.Delete(0); while (Results.Count > 0) and (CharAt(Results[0], 1) <> '~') and (CharAt(Results[0], 1) <> '|') do begin z := z + Copy(Results[0], 2, Length(Results[0])); //PKI Change Results.Delete(0); end; end; SetOrderFields(AnOrder, x, y, z); end; end; procedure LockPatient(var ErrMsg: string); begin ErrMsg := sCallV('ORWDX LOCK', [Patient.DFN]); if Piece(ErrMsg, U, 1) = '1' then ErrMsg := '' else ErrMsg := Piece(ErrMsg, U, 2); end; procedure UnlockPatient; begin sCallV('ORWDX UNLOCK', [Patient.DFN]); end; procedure LockOrder(OrderID: string; var ErrMsg: string); begin ErrMsg := sCallV('ORWDX LOCK ORDER', [OrderID]); if Piece(ErrMsg, U, 1) = '1' then ErrMsg := '' else ErrMsg := Piece(ErrMsg, U, 2); end; procedure UnlockOrder(OrderID: string); begin sCallV('ORWDX UNLOCK ORDER', [OrderID]); end; procedure ValidateOrderAction(const ID, Action: string; var ErrMsg: string); begin if Action = OA_SIGN then ErrMsg := sCallV('ORWDXA VALID', [ID, Action, User.DUZ]) else ErrMsg := sCallV('ORWDXA VALID', [ID, Action, Encounter.Provider]); end; procedure ValidateOrderActionNature(const ID, Action, Nature: string; var ErrMsg: string); begin ErrMsg := sCallV('ORWDXA VALID', [ID, Action, Encounter.Provider, Nature]); end; procedure IsLatestAction(const ID: string; var ErrList: TStringList); begin CallV('ORWOR ACTION TEXT',[ID]); if RPCBrokerV.Results.Count > 0 then FastAssign(RPCBrokerV.Results, Errlist); end; procedure ChangeOrder(AnOrder: TOrder; ResponseList: TList); begin end; procedure RenewOrder(AnOrder: TOrder; RenewFields: TOrderRenewFields; IsComplex: integer; AnIMOOrderAppt: double; OCList: TStringList); { put RenewFields into tmplst[0]=BaseType^Start^Stop^Refills^Pickup, tmplst[n]=comments } var tmplst: TStringList; i: integer; y: string; begin tmplst := TStringList.Create; {Begin Billing Aware} UBAGlobals.SourceOrderID := AnOrder.ID; {End Billing Aware} try with RenewFields do begin tmplst.SetText(PChar(Comments)); tmplst.Insert(0, IntToStr(BaseType) + U + StartTime + U + StopTime + U + IntToStr(Refills) + U + Pickup); end; with RPCBrokerV do begin LockBroker; try ClearParameters := True; RemoteProcedure := 'ORWDXR RENEW'; Param[0].PType := literal; Param[0].Value := AnOrder.ID; Param[1].PType := literal; Param[1].Value := Patient.DFN; Param[2].PType := literal; Param[2].Value := IntToStr(Encounter.Provider); Param[3].PType := literal; Param[3].Value := IntToStr(Encounter.Location); Param[4].PType := list; for i := 0 to tmplst.Count - 1 do Param[4].Mult[IntToStr(i + 1)] := tmplst[i]; Param[4].Mult['"ORCHECK"'] := IntToStr(OCList.Count); for i := 0 to OCList.Count - 1 do begin // put quotes around everything to prevent broker from choking y := '"ORCHECK","' + Piece(OCList[i], U, 1) + '","' + Piece(OCList[i], U, 3) + '","' + IntToStr(i + 1) + '"'; Param[4].Mult[y] := Pieces(OCList[i], U, 2, 4); end; Param[5].PType := literal; Param[5].Value := IntToStr(IsComplex); Param[6].PType := literal; Param[6].Value := FloatToStr(AnIMOOrderAppt); CallBroker; SetOrderFromResults(AnOrder); finally UnlockBroker; end; { Begin Billing Aware } UBAGlobals.TargetOrderID := AnOrder.ID; // the ID of the renewed order UBAGlobals.CopyTreatmentFactorsDxsToRenewedOrder; { End Billing Aware } end; finally tmplst.Free; end; end; procedure HoldOrder(AnOrder: TOrder); begin CallV('ORWDXA HOLD', [AnOrder.ID, Encounter.Provider]); SetOrderFromResults(AnOrder); end; procedure ReleaseOrderHold(AnOrder: TOrder); begin CallV('ORWDXA UNHOLD', [AnOrder.ID, Encounter.Provider]); SetOrderFromResults(AnOrder); end; procedure ListDCReasons(Dest: TStrings; var DefaultIEN: Integer); begin CallV('ORWDX2 DCREASON', [nil]); ExtractItems(Dest, RPCBrokerV.Results, 'DCReason'); //AGP Change 26.15 for PSI-04-63 //DefaultIEN := StrToIntDef(Piece(ExtractDefault(RPCBrokerV.Results, 'DCReason'), U, 1), 0); end; function GetREQReason: Integer; begin Result := StrToIntDef(sCallV('ORWDXA DCREQIEN', [nil]), 0); end; procedure DCOrder(AnOrder: TOrder; AReason: Integer; NewOrder: boolean; var DCType: Integer); var AParentID, DCOrigOrder: string; begin AParentID := AnOrder.ParentID; if AnOrder.DCOriginalOrder = true then DCOrigOrder := '1' else DCOrigOrder := '0'; CallV('ORWDXA DC', [AnOrder.ID, Encounter.Provider, Encounter.Location, AReason, DCOrigOrder, NewOrder]); UBACore.DeleteDCOrdersFromCopiedList(AnOrder.ID); DCType := StrToIntDef(Piece(RPCBrokerV.Results[0], U, 14), 0); SetOrderFromResults(AnOrder); AnOrder.ParentID := AParentID; end; procedure AlertOrder(AnOrder: TOrder; AlertRecip: Int64); begin CallV('ORWDXA ALERT', [AnOrder.ID, AlertRecip]); // don't worry about results end; procedure FlagOrder(AnOrder: TOrder; const FlagReason: string; AlertRecip: Int64); begin CallV('ORWDXA FLAG', [AnOrder.ID, FlagReason, AlertRecip]); SetOrderFromResults(AnOrder); end; procedure LoadFlagReason(Dest: TStrings; const ID: string); begin CallV('ORWDXA FLAGTXT', [ID]); FastAssign(RPCBrokerV.Results, Dest); end; procedure UnflagOrder(AnOrder: TOrder; const AComment: string); begin CallV('ORWDXA UNFLAG', [AnOrder.ID, AComment]); SetOrderFromResults(AnOrder); end; procedure LoadWardComments(Dest: TStrings; const ID: string); begin CallV('ORWDXA WCGET', [ID]); FastAssign(RPCBrokerV.Results, Dest); end; procedure PutWardComments(Src: TStrings; const ID: string; var ErrMsg: string); begin ErrMsg := sCallV('ORWDXA WCPUT', [ID, Src]); end; procedure CompleteOrder(AnOrder: TOrder; const ESCode: string); begin CallV('ORWDXA COMPLETE', [AnOrder.ID, ESCode]); SetOrderFromResults(AnOrder); end; procedure VerifyOrder(AnOrder: TOrder; const ESCode: string); begin CallV('ORWDXA VERIFY', [AnOrder.ID, ESCode]); SetOrderFromResults(AnOrder); end; procedure VerifyOrderChartReview(AnOrder: TOrder; const ESCode: string); begin CallV('ORWDXA VERIFY', [AnOrder.ID, ESCode, 'R']); SetOrderFromResults(AnOrder); end; function GetOrderableIen(AnOrderId:string): integer; begin Result := StrToIntDef(sCallV('ORWDXR GTORITM', [AnOrderId]),0); end; procedure StoreDigitalSig(AID, AHash: string; AProvider: Int64; ASig, ACrlUrl, DFN: string; var AError: string); var len, ix: integer; ASigAray: TStringList; begin ASigAray := TStringList.Create; ix := 1; len := length(ASig); while len >= ix do begin ASigAray.Add(copy(ASig, ix, 240)); inc(ix, 240); end; //while try CallV('ORWOR1 SIG', [AID, AHash, len, '100', AProvider, ASigAray, ACrlUrl, DFN]); with RPCBrokerV do if piece(Results[0],'^',1) = '-1' then begin ShowMsg('Storage of Digital Signature FAILED: ' + piece(Results[0],'^',2) + CRLF + CRLF + 'This error will prevent this order from being sent to the service for processing. Please cancel the order and try again.' + CRLF + CRLF + 'If this problem persists, then there is a problem in the CPRS PKI interface, and it needs to be reported through the proper channels, to the developer Cary Malmrose.'); AError := '1'; end; finally ASigAray.Free; end; end; procedure UpdateOrderDGIfNeeded(AnID: string); var NeedUpdate: boolean; tmpDFN: string; begin tmpDFN := Patient.DFN; Patient.Clear; Patient.DFN := tmpDFN; NeedUpdate := SCallV('ORWDPS4 IPOD4OP', [AnID]) = '1'; if Patient.Inpatient and needUpdate then SCallV('ORWDPS4 UPDTDG',[AnID]); end; function CanEditSuchRenewedOrder(AnID: string; IsTxtOrder: integer): boolean; begin Result := SCallV('ORWDXR01 CANCHG',[AnID,IsTxtOrder]) = '1'; end; function IsPSOSupplyDlg(DlgID, QODlg: integer): boolean; begin Result := SCallV('ORWDXR01 ISSPLY',[DlgID,QODlg])='1'; end; procedure SaveChangesOnRenewOrder(var AnOrder: TOrder; AnID, TheRefills, ThePickup: string; IsTxtOrder: integer); begin SCallV('ORWDXR01 SAVCHG',[AnID,TheRefills,ThePickup,IsTxtOrder]); SetOrderFromResults(AnOrder); end; function DoesOrderStatusMatch(OrderArray: TStringList): boolean; begin Result := StrtoIntDef(SCallV('ORWDX1 ORDMATCH',[Patient.DFN, OrderArray]),0)=1; end; { Order Information } function OrderIsReleased(const ID: string): Boolean; begin Result := sCallV('ORWDXR ISREL', [ID]) = '1'; end; procedure LoadRenewFields(RenewFields: TOrderRenewFields; const ID: string); var i: Integer; begin CallV('ORWDXR RNWFLDS', [ID]); with RPCBrokerV, RenewFields do begin BaseType := StrToIntDef(Piece(Results[0], U, 1), 0); StartTime := Piece(Results[0], U, 2); StopTime := Piece(Results[0], U, 3); Refills := StrToIntDef(Piece(Results[0], U, 4), 0); Pickup := Piece(Results[0], U, 5); Comments := ''; for i := 1 to Results.Count - 1 do Comments := Comments + CRLF + Results[i]; if Copy(Comments, 1, 2) = CRLF then Delete(Comments, 1, 2); end; end; procedure GetChildrenOfComplexOrder(AnParentID,CurrAct: string; var ChildList: TStringList); //PSI-COMPLEX var i: integer; begin CallV('ORWDXR ORCPLX',[AnParentID,CurrAct]); if RPCBrokerV.Results.Count = 0 then Exit; With RPCBrokerV do begin for i := 0 to Results.Count - 1 do begin if (Piece(Results[i],'^',1) <> 'E') and (Length(Results[i])>0) then ChildList.Add(Results[i]); end; end; end; procedure LESValidationForChangedLabOrder(var RejectedReason: TStringList; AnOrderInfo: string); begin CallV('ORWDPS5 LESAPI',[AnOrderInfo]); if RPCBrokerV.Results.Count > 0 then FastAssign(RPCBrokerV.Results, RejectedReason); end; procedure ChangeEvent(AnOrderList: TStringList; APtEvtId: string); begin SCallV('OREVNTX1 CHGEVT', [APtEvtId,AnOrderList]); end; procedure DeletePtEvent(APtEvtID: string); begin SCallV('OREVNTX1 DELPTEVT',[APtEvtID]); end; function IsRenewableComplexOrder(AnParentID: string): boolean; //PSI-COMPLEX var rst: integer; begin Result := False; rst := StrToIntDef(SCallV('ORWDXR CANRN',[AnParentID]),0); if rst>0 then Result := True; end; function IsComplexOrder(AnOrderID: string): boolean; //PSI-COMPLEX var rst: integer; begin Result := False; rst := StrToIntDef(SCallV('ORWDXR ISCPLX',[AnOrderID]),0); if rst > 0 then Result := True; end; procedure ValidateComplexOrderAct(AnOrderID: string; var ErrMsg: string); //PSI-COMPLEX begin ErrMsg := SCallV('ORWDXA OFCPLX',[AnOrderID]); end; function GetDlgData(ADlgID: string): string; begin Result := SCallV('OREVNTX1 GETDLG',[ADlgID]); end; function PtEvtEmpty(APtEvtID: string): Boolean; begin Result := False; if StrToIntDef(SCallV('OREVNTX1 EMPTY',[APtEvtID]),0)>0 then Result := True; end; function TextForOrder(const ID: string): string; begin CallV('ORWORR GETTXT', [ID]); Result := RPCBrokerV.Results.Text; end; function GetConsultOrderNumber(ConsultIEN: string): string; begin Result := sCallv('ORQQCN GET ORDER NUMBER',[ConsultIEN]); end; function GetOrderByIFN(const ID: string): TOrder; var x, y, z: string; AnOrder: TOrder; begin AnOrder := TOrder.Create; CallV('ORWORR GETBYIFN', [ID]); with RPCBrokerV do while Results.Count > 0 do begin x := Results[0]; Results.Delete(0); if CharAt(x, 1) <> '~' then Continue; // only happens if out of synch y := ''; while (Results.Count > 0) and (CharAt(Results[0], 1) <> '~') and (CharAt(Results[0], 1) <> '|') do begin y := y + Copy(Results[0], 2, Length(Results[0])) + CRLF; Results.Delete(0); end; if Length(y) > 0 then y := Copy(y, 1, Length(y) - 2); // take off last CRLF z := ''; if (Results.Count > 0) and (Results[0] = '|') then begin Results.Delete(0); while (Results.Count > 0) and (CharAt(Results[0], 1) <> '~') and (CharAt(Results[0], 1) <> '|') do begin z := z + Copy(Results[0], 2, Length(Results[0])); //PKI Change Results.Delete(0); end; end; SetOrderFields(AnOrder, x, y, z); end; Result := AnOrder; end; function GetPackageByOrderID(const OrderID: string): string; begin Result := SCallV('ORWDXR GETPKG',[OrderID]); end; function AnyOrdersRequireSignature(OrderList: TStringList): Boolean; begin Result := sCallV('ORWD1 SIG4ANY', [OrderList]) = '1'; end; function OrderRequiresSignature(const ID: string): Boolean; begin Result := sCallV('ORWD1 SIG4ONE', [ID]) = '1'; end; function OrderRequiresDigitalSignature(const ID: string): Boolean; begin Result := sCallV('ORWOR1 CHKDIG', [ID]) = '1'; end; function GetDrugSchedule(const ID: string): string; begin Result := sCallV('ORWOR1 GETDSCH', [ID]); end; function GetExternalText(const ID: string): string; var x,y: string; begin CallV('ORWOR1 GETDTEXT', [ID]); y := ''; with RPCBrokerV do while Results.Count > 0 do begin x := Results[0]; Results.Delete(0); y := y + x; end; Result := y; end; function SetExternalText(const ID: string; ADrugSch: string; AUser: Int64): string; var x,y: string; begin CallV('ORWOR1 SETDTEXT', [ID, ADrugSch, AUser]); y := ''; with RPCBrokerV do while Results.Count > 0 do begin x := Results[0]; Results.Delete(0); y := y + x; end; Result := y; end; function GetDigitalSignature(const ID: string): string; begin CallV('ORWORR GETDSIG', [ID]); Result := RPCBrokerV.Results.Text; end; function GetDEA(const ID: string): string; begin CallV('ORWORR GETDEA', [ID]); Result := RPCBrokerV.Results.Text; end; function GetPKISite: Boolean; begin Result := sCallV('ORWOR PKISITE', [nil]) = '1'; end; function GetPKIUse: Boolean; begin Result := sCallV('ORWOR PKIUSE', [nil]) = '1'; end; function DoesOIPIInSigForQO(AnQOID: integer): integer; begin Result := StrToIntDef(SCallV('ORWDPS1 HASOIPI',[AnQOID]),0); end; function GetDispGroupForLES: string; begin Result := SCallV('ORWDPS5 LESGRP',[nil]); end; function GetOrderPtEvtID(AnOrderID: string): string; begin Result := SCallV('OREVNTX1 ODPTEVID',[AnOrderID]); end; function VerbTelPolicyOrder(AnOrderID: string): boolean; begin Result := SCallV('ORWDPS5 ISVTP',[AnOrderID]) = '1'; end; function ForIVandUD(AnOrderID: string): boolean; begin Result := SCallV('ORWDPS4 ISUDIV',[AnOrderID]) = '1'; end; function GetEventIFN(const AEvntID: string): string; begin Result := sCallV('OREVNTX1 EVT',[AEvntID]); end; function GetEventName(const AEvntID: string): string; begin Result := sCallV('OREVNTX1 NAME',[AEvntID]); end; function GetEventLoc(const APtEvntID: string): string; begin Result := SCallV('OREVNTX1 LOC', [APtEvntID]); end; function GetEventLoc1(const AnEvntID: string): string; begin Result := SCallV('OREVNTX1 LOC1', [AnEvntID]); end; function GetEventDiv(const APtEvntID: string): string; begin Result := SCallV('OREVNTX1 DIV',[APtEvntID]); end; function GetEventDiv1(const AnEvntID: string): string; begin Result := SCallV('OREVNTX1 DIV1',[AnEvntID]); end; function GetCurrentSpec(const APtIFN: string): string; begin Result := SCallV('OREVNTX1 CURSPE', [APtIFN]); end; function GetDefaultEvt(const AProviderIFN: string): string; begin Result := SCallV('OREVNTX1 DFLTEVT',[AProviderIFN]); end; procedure DeleteDefaultEvt; begin SCallV('OREVNTX1 DELDFLT',[User.DUZ]); end; function isExistedEvent(const APtDFN: string; const AEvtID: string; var APtEvtID: string): Boolean; begin Result := False; APtEvtID := SCallV('OREVNTX1 EXISTS', [APtDFN,AEvtID]); if StrToIntDef(APtEvtID,0) > 0 then Result := True; end; function TypeOfExistedEvent(APtDFN: string; AEvtID: Integer): Integer; begin Result := StrToIntDef(SCallV('OREVNTX1 TYPEXT', [APtDFN,AEvtID]),0); end; function isMatchedEvent(const APtDFN: string; const AEvtID: string; var ATs:string): Boolean; var rst: string; begin Result := False; rst := SCallV('OREVNTX1 MATCH',[APtDFN,AEvtID]); if StrToIntDef(Piece(rst,'^',1),0)>0 then begin ATs := Piece(rst,'^',2); Result := True; end; end; function isDCedOrder(const AnOrderID: string): Boolean; var rst: string; begin Result := False; rst := SCAllV('OREVNTX1 ISDCOD',[AnOrderID]); if STrToIntDef(rst,0)>0 then Result := True; end; function isOnholdMedOrder(AnOrderID: string): Boolean; var rst: string; begin Result := False; rst := SCAllV('OREVNTX1 ISHDORD',[AnOrderID]); if StrToIntDef(rst,0)>0 then Result := True; end; function SetDefaultEvent(var AErrMsg: string; EvtID: string): Boolean; begin AErrMsg := SCallV('OREVNTX1 SETDFLT',[EvtID]); Result := True; end; function GetEventPromptID: integer; var evtPrompt: string; begin evtPrompt := SCallV('OREVNTX1 PRMPTID',[nil]); Result := StrToIntDef(evtPrompt,0); end; function GetDefaultTSForEvt(AnEvtID: integer): string; begin Result := SCallV('OREVNTX1 DEFLTS',[AnEvtID]); end; function GetPromptIDs: string; begin Result := SCallV('OREVNTX1 PROMPT IDS',[nil]); end; function GetEventDefaultDlg(AEvtID: integer): string; begin Result := SCallV('OREVNTX1 DFLTDLG',[AEvtID]); end; function CanManualRelease: boolean; var rst: integer; begin Result := False; rst := StrToIntDef(SCallV('OREVNTX1 AUTHMREL',[nil]),0); if rst > 0 then Result := True; end; function TheParentPtEvt(APtEvt: string): string; begin Result := SCallV('OREVNTX1 HAVEPRT',[APtEvt]); end; function IsCompletedPtEvt(APtEvtID: integer): boolean; var rst : integer; begin Result := False; rst := StrToIntDef(SCallV('OREVNTX1 COMP',[APtEvtID]),0); if rst > 0 then Result := True; end; function IsPassEvt(APtEvtID: integer; APtEvtType: char): boolean; var rst: integer; begin Result := False; rst := StrToIntDef(SCallV('OREVNTX1 ISPASS',[APtEvtID, APtEvtType]),0); if rst = 1 then Result := True; end; function IsPassEvt1(AnEvtID: integer; AnEvtType: char): boolean; var rst: integer; begin Result := False; rst := StrToIntDef(SCallV('OREVNTX1 ISPASS1',[AnEvtID, AnEvtType]),0); if rst = 1 then Result := True; end; procedure TerminatePtEvt(APtEvtID: integer); begin SCallV('OREVNTX1 DONE',[APtEvtID]); end; procedure SetPtEvtList(Dest: TStrings; APtDFN: string; var ATotal: Integer); begin CallV('OREVNTX LIST',[APtDFN]); if RPCBrokerV.Results.Count > 0 then begin ATotal := StrToIntDef(RPCBrokerV.Results[0],0); if ATotal > 0 then begin MixedCaseList( RPCBrokerV.Results ); RPCBrokerV.Results.Delete(0); FastAssign(RPCBrokerV.Results, Dest); end; end; end; procedure GetTSListForEvt(Dest: TStrings; AnEvtID:integer); begin CallV('OREVNTX1 MULTS',[AnEvtID]); if RPCBrokerV.Results.Count > 0 then begin SortByPiece(TStringList(RPCBrokerV.Results),'^',2); FastAssign(RPCBrokerV.Results, Dest); end; end; procedure GetChildEvent(var AChildList: TStringList; APtEvtID: string); begin // end; function DeleteEmptyEvt(APtEvntID: string; var APtEvntName: string; Ask: boolean): boolean; const TX_EVTDEL1 = 'There are no orders tied to '; TX_EVTDEL2 = ', Would you like to cancel it?'; begin Result := false; if APtEvntID = '0' then begin Result := True; Exit; end; if PtEvtEmpty(APtEvntID) then begin if Length(APtEvntName)=0 then APtEvntName := GetEventName(APtEvntID); if Ask then begin if InfoBox(TX_EVTDEL1 + APtEvntName + TX_EVTDEL2, 'Confirmation', MB_YESNO or MB_ICONQUESTION) = IDYES then begin DeletePtEvent(APtEvntID); Result := True; end; end; if not Ask then begin DeletePtEvent(APtEvntID); Result := True; end; end; end; function CompleteEvt(APtEvntID: string; APtEvntName: string; Ask: boolean): boolean; const TX_EVTFIN1 = 'All of the orders tied to '; TX_EVTFIN2 = ' have been released to a service, ' + #13 + 'Would you like to terminate this event?'; var ThePtEvtName: string; begin Result := false; if APtEvntID = '0' then begin Result := True; Exit; end; if PtEvtEmpty(APtEvntID) then begin if Length(APtEvntName)=0 then ThePtEvtName := GetEventName(APtEvntID) else ThePtEvtName := APtEvntName; if Ask then begin if InfoBox(TX_EVTFIN1 + ThePtEvtName + TX_EVTFIN2, 'Confirmation', MB_OKCANCEL or MB_ICONQUESTION) = IDOK then begin SCallV('OREVNTX1 DONE',[APtEvntID]); Result := True; end; end else begin SCallV('OREVNTX1 DONE',[APtEvntID]); Result := True; end; end; end; { Order Checking } function FillerIDForDialog(IEN: Integer): string; begin Result := sCallV('ORWDXC FILLID', [IEN]); end; function IsMonograph(): Boolean; var ret: string; begin ret := CharAt(sCallV('ORCHECK ISMONO', [nil]), 1); Result := ret = '1'; end; procedure GetMonographList(ListOfMonographs: TStringList); begin CallV('ORCHECK GETMONOL', []); FastAssign(RPCBrokerV.Results, ListOfMonographs); end; procedure GetMonograph(Monograph: TStringList; x: Integer); begin CallV('ORCHECK GETMONO', [x]); FastAssign(RPCBrokerV.Results, Monograph); end; procedure DeleteMonograph(); begin CallV('ORCHECK DELMONO', []); end; procedure GetXtraTxt(OCText: TStringList; x: String; y: String); begin CallV('ORCHECK GETXTRA', [x,y]); FastAssign(RPCBrokerV.Results, OCText); end; function OrderChecksEnabled: Boolean; begin if uOrderChecksOn = #0 then uOrderChecksOn := CharAt(sCallV('ORWDXC ON', [nil]), 1); Result := uOrderChecksOn = 'E'; end; function OrderChecksOnDisplay(const FillerID: string): string; begin CallV('ORWDXC DISPLAY', [Patient.DFN, FillerID]); with RPCBrokerV.Results do SetString(Result, GetText, Length(Text)); end; procedure OrderChecksOnAccept(ListOfChecks: TStringList; const FillerID, StartDtTm: string; OIList: TStringList; DupORIFN: string; Renewal: string); begin // don't pass OIList if no items, since broker pauses 5 seconds per order if OIList.Count > 0 then CallV('ORWDXC ACCEPT', [Patient.DFN, FillerID, StartDtTm, Encounter.Location, OIList, DupORIFN, Renewal]) else CallV('ORWDXC ACCEPT', [Patient.DFN, FillerID, StartDtTm, Encounter.Location]); FastAssign(RPCBrokerV.Results, ListOfChecks); end; procedure OrderChecksOnDelay(ListOfChecks: TStringList; const FillerID, StartDtTm: string; OIList: TStringList); begin // don't pass OIList if no items, since broker pauses 5 seconds per order if OIList.Count > 0 then CallV('ORWDXC DELAY', [Patient.DFN, FillerID, StartDtTm, Encounter.Location, OIList]) else CallV('ORWDXC DELAY', [Patient.DFN, FillerID, StartDtTm, Encounter.Location]); FastAssign(RPCBrokerV.Results, ListOfChecks); end; procedure OrderChecksForSession(ListOfChecks, OrderList: TStringList); begin CallV('ORWDXC SESSION', [Patient.DFN, OrderList]); FastAssign(RPCBrokerV.Results, ListOfChecks); end; procedure SaveOrderChecksForSession(const AReason: string; ListOfChecks: TStringList); var i, inc, len, numLoop, remain: integer; OCStr, TmpStr: string; begin LockBroker; try //CallV('ORWDXC SAVECHK', [Patient.DFN, AReason, ListOfChecks]); { no result used currently } RPCBrokerV.ClearParameters := True; RPCBrokerV.RemoteProcedure := 'ORWDXC SAVECHK'; RPCBrokerV.Param[0].PType := literal; RPCBrokerV.Param[0].Value := Patient.DFN; //*DFN* RPCBrokerV.Param[1].PType := literal; RPCBrokerV.Param[1].Value := AReason; RPCBrokerV.Param[2].PType := list; RPCBrokerV.Param[2].Mult['"ORCHECKS"'] := IntToStr(ListOfChecks.count); for i := 0 to ListOfChecks.Count - 1 do begin OCStr := ListofChecks.Strings[i]; len := Length(OCStr); if len > 255 then begin numLoop := len div 255; remain := len mod 255; inc := 0; while inc <= numLoop do begin tmpStr := Copy(OCStr, 1, 255); OCStr := Copy(OCStr, 256, Length(OcStr)); RPCBrokerV.Param[2].Mult['"ORCHECKS",' + InttoStr(i) + ',' + InttoStr(inc)] := tmpStr; inc := inc +1; end; if remain > 0 then RPCBrokerV.Param[2].Mult['"ORCHECKS",' + InttoStr(i) + ',' + inttoStr(inc)] := OCStr; end else RPCBrokerV.Param[2].Mult['"ORCHECKS",' + InttoStr(i)] := OCStr; end; CallBroker; finally UnlockBroker; end; end; function DeleteCheckedOrder(const OrderID: string): Boolean; begin Result := sCallV('ORWDXC DELORD', [OrderID]) = '1'; end; function DataForOrderCheck(const OrderID: string): string; begin Result := sCallV('ORWDXR01 OXDATA',[OrderID]); end; (* TEMPORARILY COMMENTED OUT WHILE TESTING function GetPromptandDeviceParameters(Location: integer; OrderList: TStringList; Nature: string): TPrintParams; var TempParams: TPrintParams; x: string; begin tempParams.OrdersToPrint := TStringList.Create; try CallV('ORWD1 PARAM', [Location, Nature, OrderList]); x := RPCBrokerV.Results[0]; with TempParams do begin PromptForChartCopy := CharAt(Piece(x, U, 1),1); if Piece(x, U, 5) <> '' then ChartCopyDevice := Piece(Piece(x, U, 5),';',1) + '^' + Piece(Piece(x, U, 5),';',2); PromptForLabels := CharAt(Piece(x, U, 2),1); if Piece(x, U, 6) <> '' then LabelDevice := Piece(Piece(x, U, 6),';',1) + '^' + Piece(Piece(x, U, 6),';',2); PromptForRequisitions := CharAt(Piece(x, U, 3),1); if Piece(x, U, 7) <> '' then RequisitionDevice := Piece(Piece(x, U, 7),';',1) + '^' + Piece(Piece(x, U, 7),';',2); PromptForWorkCopy := CharAt(Piece(x, U, 4),1); if Piece(x, U, 8) <> '' then WorkCopyDevice := Piece(Piece(x, U, 8),';',1) + '^' + Piece(Piece(x, U, 8),';',2); AnyPrompts := ((PromptForChartCopy in ['1','2']) or (PromptForLabels in ['1','2']) or (PromptForRequisitions in ['1','2']) or (PromptForWorkCopy in ['1','2'])); RPCBrokerV.Results.Delete(0); FastAssign(RPCBrokerV.Results, OrdersToPrint); end; Result := TempParams; finally tempParams.OrdersToPrint.Free; end; end; *) procedure OrderPrintDeviceInfo(OrderList: TStringList; var PrintParams: TPrintParams; Nature: Char; PrintLoc: Integer = 0); var x: string; begin if Nature <> #0 then begin if PrintLoc > 0 then CallV('ORWD2 DEVINFO', [PrintLoc, Nature, OrderList]) else CallV('ORWD2 DEVINFO', [Encounter.Location, Nature, OrderList]); end else begin if PrintLoc > 0 then CallV('ORWD2 MANUAL', [PrintLoc, OrderList]) else CallV('ORWD2 MANUAL', [Encounter.Location, OrderList]); end; x := RPCBrokerV.Results[0]; FillChar(PrintParams, SizeOf(PrintParams), #0); with PrintParams do begin PromptForChartCopy := CharAt(Piece(x, U, 1),1); if Piece(x, U, 5) <> '' then ChartCopyDevice := Piece(Piece(x, U, 5),';',1) + '^' + Piece(Piece(x, U, 5),';',2); PromptForLabels := CharAt(Piece(x, U, 2),1); if Piece(x, U, 6) <> '' then LabelDevice := Piece(Piece(x, U, 6),';',1) + '^' + Piece(Piece(x, U, 6),';',2); PromptForRequisitions := CharAt(Piece(x, U, 3),1); if Piece(x, U, 7) <> '' then RequisitionDevice := Piece(Piece(x, U, 7),';',1) + '^' + Piece(Piece(x, U, 7),';',2); PromptForWorkCopy := CharAt(Piece(x, U, 4),1); if Piece(x, U, 8) <> '' then WorkCopyDevice := Piece(Piece(x, U, 8),';',1) + '^' + Piece(Piece(x, U, 8),';',2); AnyPrompts := (CharInSet(PromptForChartCopy, ['1','2']) or CharInSet(PromptForLabels, ['1','2']) or CharInSet(PromptForRequisitions, ['1','2']) or CharInSet(PromptForWorkCopy, ['1','2'])); end; if Nature <> #0 then begin RPCBrokerV.Results.Delete(0); OrderList.Clear; FastAssign(RPCBrokerV.Results, OrderList); end; end; procedure SaveEvtForOrder(APtDFN: string; AEvt: integer; AnOrderID: string); var TheEventID: string; begin TheEventID := SCallV('OREVNTX1 PUTEVNT',[APtDFN,IntToStr(AEvt),AnOrderID]); end; function EventExist(APtDFN:string; AEvt: integer): integer; var AOutCome: string; begin AOutCome := SCallV('OREVNTX1 EXISTS', [APtDFN,IntToStr(AEvt)]); if AOutCome = '' then Result := 0 else Result := StrToInt(AOutCome); end; function UseNewMedDialogs: Boolean; begin Result := sCallV('ORWDPS1 CHK94', [nil]) = '1'; end; { Copay } procedure GetCoPay4Orders; begin LockBroker; try RPCBrokerV.RemoteProcedure := 'ORWDPS4 CPLST'; RPCBrokerV.Param[0].PType := literal; RPCBrokerV.Param[0].Value := Patient.DFN; CallBroker; finally UnlockBroker; end; end; procedure SaveCoPayStatus(AList: TStrings); var i: integer; begin if AList.Count > 0 then begin LockBroker; try RPCBrokerV.ClearParameters := True; RPCBrokerV.RemoteProcedure := 'ORWDPS4 CPINFO'; RPCBrokerV.Param[0].PType := list; for i := 0 to AList.Count-1 do RPCBrokerV.Param[0].Mult[IntToStr(i+1)] := AList[i]; CallBroker; finally UnlockBroker; end; end; end; function LocationType(Location: integer): string; begin Result := sCallV('ORWDRA32 LOCTYPE',[Location]); end; function IsValidIMOLoc(LocID: integer; PatientID: string): boolean; //IMO var rst: string; begin // Result := IsCliniCloc(LocID); rst := SCallV('ORIMO IMOLOC',[LocID, PatientID]); Result := StrToIntDef(rst,-1) > -1; end; function IsValidIMOLocOrderCom(LocID: integer; PatientID: string): boolean; //IMO var rst: string; begin // Result := IsCliniCloc(LocID); rst := SCallV('ORIMO IMOLOC',[LocID, PatientID, 1]); Result := StrToIntDef(rst,-1) > -1; end; function IsIMOOrder(OrderID: string): boolean; //IMO begin Result := SCallV('ORIMO IMOOD',[OrderId])='1'; end; function IsInptQO(DlgID: integer): boolean; begin Result := SCallV('ORWDXM3 ISUDQO', [DlgID]) = '1'; end; function IsIVQO(DlgID: integer): boolean; begin Result := SCallV('ORIMO ISIVQO', [DlgID]) = '1'; end; function IsClinicLoc(ALoc: integer): boolean; begin Result := SCallV('ORIMO ISCLOC', [ALoc]) = '1'; end; function IsValidSchedule(AnOrderID: string): boolean; //nss begin result := SCallV('ORWNSS VALSCH', [AnOrderID]) = '1'; end; function IsValidQOSch(QOID: string): string; //nss begin Result := SCallV('ORWNSS QOSCH',[QOID]); end; function IsValidSchStr(ASchStr: string): boolean; begin Result := SCallV('ORWNSS CHKSCH',[ASchStr]) = '1'; end; function IsPendingHold(OrderID: string): boolean; var ret: string; begin ret := sCallV('ORDEA PNDHLD', [OrderID]); if ret = '1' then Result := True else Result := False; end; { TParentEvent } procedure TParentEvent.Assign(AnEvtID: string); var evtInfo: string; begin // ORY = EVTTYPE_U_EVT_U_EVTNAME_U_EVTDISP_U_EVTDLG evtInfo := EventInfo1(AnEvtID); ParentIFN := StrToInt(AnEvtID); if Length(Piece(evtInfo,'^',4)) < 1 then ParentName := Piece(evtInfo,'^',3) else ParentName := Piece(evtInfo,'^',4); ParentType := CharAt(Piece(evtInfo,'^',1),1); ParentDlg := Piece(evtInfo,'^',5); end; constructor TParentEvent.Create; begin ParentIFN := 0; ParentName := ''; ParentType := #0; ParentDlg := '0'; end; initialization uDGroupAll := 0; uOrderChecksOn := #0; finalization if uDGroupMap <> nil then uDGroupMap.Free; end.
// Copyright 2021 Darian Miller, Licensed under Apache-2.0 // SPDX-License-Identifier: Apache-2.0 // More info: www.radprogrammer.com unit radRTL.Base32Encoding.Tests; interface uses TestFramework; type TBase32Test = class(TTestCase) published procedure TestEncodingRFCVectors; procedure TestDecodingRFCVectors; procedure TestDecoding_SkippedCharacters; procedure TestLongerInput_LoremIpsum; procedure TestEncodingDelphi; procedure TestDecodingDelphi; end; implementation uses radRTL.Base32Encoding; // test vectors as specified in RFC // https://datatracker.ietf.org/doc/html/rfc4648.html procedure TBase32Test.TestEncodingRFCVectors; begin CheckEquals('', TBase32.Encode('')); CheckEquals('MY======', TBase32.Encode('f')); CheckEquals('MZXQ====', TBase32.Encode('fo')); CheckEquals('MZXW6===', TBase32.Encode('foo')); CheckEquals('MZXW6YQ=', TBase32.Encode('foob')); CheckEquals('MZXW6YTB', TBase32.Encode('fooba')); CheckEquals('MZXW6YTBOI======', TBase32.Encode('foobar')); end; procedure TBase32Test.TestDecodingRFCVectors; begin CheckEquals('', TBase32.Decode('')); CheckEquals('f', TBase32.Decode('MY======')); CheckEquals('fo', TBase32.Decode('MZXQ====')); CheckEquals('foo', TBase32.Decode('MZXW6===')); CheckEquals('foob', TBase32.Decode('MZXW6YQ=')); CheckEquals('fooba', TBase32.Decode('MZXW6YTB')); CheckEquals('foobar', TBase32.Decode('MZXW6YTBOI======')); end; procedure TBase32Test.TestDecoding_SkippedCharacters; begin //Unhandled characters are simply skipped in the current implementation CheckEquals('', TBase32.Decode('=1890abcdefghijklmnopqrstuvwxyz,[]()~!@#$%^&*()_+')); end; procedure TBase32Test.TestLongerInput_LoremIpsum; const LOREM_TEXT = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ' + 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ' + 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. ' + 'Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'; //manually verified from a few online decoders LOREM_BASE32 = 'JRXXEZLNEBUXA43VNUQGI33MN5ZCA43JOQQGC3LFOQWCAY3PNZZWKY3UMV2HK4RAMFSGS4DJONRWS3THEBSWY2LUFQQHGZLEEBSG6IDFNF2X' + 'G3LPMQQHIZLNOBXXEIDJNZRWSZDJMR2W45BAOV2CA3DBMJXXEZJAMV2CAZDPNRXXEZJANVQWO3TBEBQWY2LROVQS4ICVOQQGK3TJNUQGCZ' + 'BANVUW42LNEB3GK3TJMFWSYIDROVUXGIDON5ZXI4TVMQQGK6DFOJRWS5DBORUW63RAOVWGYYLNMNXSA3DBMJXXE2LTEBXGS43JEB2XIIDB' + 'NRUXC5LJOAQGK6BAMVQSAY3PNVWW6ZDPEBRW63TTMVYXKYLUFYQEI5LJOMQGC5LUMUQGS4TVOJSSAZDPNRXXEIDJNYQHEZLQOJSWQZLOMR' + 'SXE2LUEBUW4IDWN5WHK4DUMF2GKIDWMVWGS5BAMVZXGZJAMNUWY3DVNUQGI33MN5ZGKIDFOUQGM5LHNFQXIIDOOVWGYYJAOBQXE2LBOR2X' + 'ELRAIV4GGZLQORSXK4RAONUW45BAN5RWGYLFMNQXIIDDOVYGSZDBORQXIIDON5XCA4DSN5UWIZLOOQWCA43VNZ2CA2LOEBRXK3DQMEQHC5' + 'LJEBXWMZTJMNUWCIDEMVZWK4TVNZ2CA3LPNRWGS5BAMFXGS3JANFSCAZLTOQQGYYLCN5ZHK3JO'; begin CheckEquals(LOREM_BASE32, TBase32.Encode(LOREM_TEXT)); CheckEquals(LOREM_TEXT, TBase32.Decode(LOREM_BASE32)); //note: an extra unused byte may be discarded depending on padding..in this specific case 1 surplus trailing character is safely discarded CheckEquals(LOREM_TEXT, TBase32.Decode(LOREM_BASE32+'L')); //note: two extra bytes should fail... CheckNotEquals(LOREM_TEXT, TBase32.Decode(LOREM_BASE32+'LL')); end; procedure TBase32Test.TestEncodingDelphi; begin CheckEquals('IRSWY4DINE======', TBase32.Encode('Delphi')); end; procedure TBase32Test.TestDecodingDelphi; begin CheckEquals('Delphi', TBase32.Decode('IRSWY4DINE======')); end; initialization RegisterTest(TBase32Test.Suite); end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Spin, rxclock; type { TForm1 } TForm1 = class(TForm) CheckBox1: TCheckBox; Label2: TLabel; Label3: TLabel; Label4: TLabel; RxClock1: TRxClock; SpinEdit1: TSpinEdit; SpinEdit2: TSpinEdit; SpinEdit3: TSpinEdit; procedure CheckBox1Change(Sender: TObject); procedure FormCreate(Sender: TObject); procedure RxClock1Alarm(Sender: TObject); private public end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.RxClock1Alarm(Sender: TObject); begin ShowMessage('Alarm!'); CheckBox1.Checked:=false; end; procedure TForm1.CheckBox1Change(Sender: TObject); begin RxClock1.AlarmEnabled:=CheckBox1.Checked; if CheckBox1.Checked then begin RxClock1.AlarmHour:=SpinEdit1.Value; RxClock1.AlarmMinute:=SpinEdit2.Value; RxClock1.AlarmSecond:=SpinEdit3.Value; end; SpinEdit1.Enabled:=not CheckBox1.Checked; SpinEdit2.Enabled:=SpinEdit1.Enabled; SpinEdit3.Enabled:=SpinEdit1.Enabled; Label2.Enabled:=SpinEdit1.Enabled; Label3.Enabled:=SpinEdit1.Enabled; Label4.Enabled:=SpinEdit1.Enabled; end; procedure TForm1.FormCreate(Sender: TObject); var H, M, S, MS: word; begin DecodeTime(Now, H, M, S, MS); SpinEdit1.Value:=H; SpinEdit2.Value:=M; end; end.
unit StoreHouseInfoView; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMemo, cxDBEdit, cxLabel, Vcl.ExtCtrls, Data.DB, cxMaskEdit, cxSpinEdit, StoreHouseListQuery, dxSkinsCore, dxSkinsDefaultPainters, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue; type TViewStorehouseInfo = class(TFrame) lblTitle: TcxLabel; lblExternalId: TcxLabel; lblResponsible: TcxLabel; lblAddress: TcxLabel; cxTeResponsible: TcxDBTextEdit; cxdbmAddress: TcxDBMemo; cxdbteAbbreviation: TcxDBTextEdit; cxdbmTitle: TcxDBMemo; private FqStoreHouseList: TQueryStoreHouseList; procedure SetqStoreHouseList(const Value: TQueryStoreHouseList); protected public property qStoreHouseList: TQueryStoreHouseList read FqStoreHouseList write SetqStoreHouseList; end; implementation {$R *.dfm} procedure TViewStorehouseInfo.SetqStoreHouseList(const Value : TQueryStoreHouseList); begin if FqStoreHouseList <> Value then begin FqStoreHouseList := Value; if FqStoreHouseList <> nil then begin cxdbmTitle.DataBinding.DataSource := FqStoreHouseList.W.DataSource; cxdbmTitle.DataBinding.DataField := FqStoreHouseList.W.Title.FieldName; cxdbteAbbreviation.DataBinding.DataSource := FqStoreHouseList.W.DataSource; cxdbteAbbreviation.DataBinding.DataField := FqStoreHouseList.W.Abbreviation.FieldName; cxTeResponsible.DataBinding.DataSource := FqStoreHouseList.W.DataSource; cxTeResponsible.DataBinding.DataField := FqStoreHouseList.W.Responsible.FieldName; cxdbmAddress.DataBinding.DataSource := FqStoreHouseList.W.DataSource; cxdbmAddress.DataBinding.DataField := FqStoreHouseList.W.Address.FieldName; end else begin cxdbmTitle.DataBinding.DataSource := nil; cxdbteAbbreviation.DataBinding.DataSource := nil; cxTeResponsible.DataBinding.DataSource := nil; cxdbmAddress.DataBinding.DataSource := nil; end; end; end; end.
unit LTUtils; interface uses SysUtils; function CreateGuestID: string; implementation function CreateGuestID: string; var Guid: TGUID; begin CreateGuid(Guid); Result := GuidToString(Guid); end; end.
unit TreeNTRegister; // Registration file for TTreeNT and its editors. // Dipl. Ing. Mike Lischke // public@lischke-online.com {$I DFS.inc} interface uses DsgnIntf, TreeNT, TNTEditor, Dialogs, Forms, SysUtils; type TTreeNTNodesProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; TTreeNTEditor = class(TDefaultEditor) public procedure Edit; override; function GetVerbCount: Integer; override; function GetVerb(Index: Integer): string; override; procedure ExecuteVerb(Index: Integer); override; end; procedure Register; //------------------------------------------------------------------------------ implementation uses Classes, Graphics; //----------------- TTreeNTNodesProperty --------------------------------------- procedure TTreeNTNodesProperty.Edit; begin if EditTreeViewItems(TTreeNTNodes(GetOrdValue)) then Modified; end; //------------------------------------------------------------------------------ function TTreeNTNodesProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paReadOnly]; end; //----------------- TTreeNTEditor ---------------------------------------------- const VerbCount = 7; var Verbs : array[0..VerbCount-1] of String = ('Edit tree nodes ...', 'Load from file ...', 'Save to tree file ...', 'Save to text file ...', 'Save to bitmap file ...', 'Print tree...', 'Clear tree'); SaveDir1 : String = ''; SaveDir2 : String = ''; procedure TTreeNTEditor.Edit; begin ExecuteVerb(0); end; //------------------------------------------------------------------------------ function TTreeNTEditor.GetVerbCount: Integer; begin Result := VerbCount; end; //------------------------------------------------------------------------------ function TTreeNTEditor.GetVerb(Index: Integer): string; begin Result := Verbs[Index]; end; //------------------------------------------------------------------------------ procedure TTreeNTEditor.ExecuteVerb(Index: Integer); var OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; PrintDialog: TPrintDialog; Bitmap: TBitmap; begin case Index of 0: if EditTreeViewItems(TTreeNT(Component).Items) then Designer.Modified; 1: begin OpenDialog := TOpenDialog.Create(Application); with OpenDialog do begin Filter := 'TreeNT files (*.tnt)|*.tnt|All Files (*.*)|*.*'; DefaultExt := 'tnt'; InitialDir := SaveDir1; Options := [ofHideReadOnly, ofPathMustExist, ofFileMustExist]; try if OpenDialog.Execute then begin TTreeNT(Component).LoadFromFile(FileName); Designer.Modified; end; finally SaveDir1 := ExtractFileDir(FileName); Free; end; end; end; 2, 3: begin SaveDialog := TSaveDialog.Create(Application); with SaveDialog do begin Filter := 'TreeNT files (*.tnt)|*.tnt|Text files (*.txt)|*.txt|All Files (*.*)|*.*'; DefaultExt := 'txt'; InitialDir := SaveDir2; Options := [ofPathMustExist, ofOverwritePrompt]; try if SaveDialog.Execute then TTreeNT(Component).SaveToFile(FileName,Index = 2); finally SaveDir2 := ExtractFileDir(FileName); Free; end; end; end; 4: begin SaveDialog := TSaveDialog.Create(Application); with SaveDialog do begin Filter := 'Bitmaps (*.bmp)|*.bmp|All Files (*.*)|*.*'; DefaultExt := 'bmp'; InitialDir := SaveDir2; Options := [ofPathMustExist, ofOverwritePrompt]; try if SaveDialog.Execute then begin Bitmap := TBitmap.Create; try // capture screen output {$ifdef DFS_COMPILER_3_UP} Bitmap.PixelFormat := pf24Bit; {$endif} Bitmap.Width := TTreeNT(Component).TreeWidth; Bitmap.Height := TTreeNT(Component).Treeheight; // draw the tree to our bitmap TTreeNT(Component).DrawTo(Bitmap.Canvas); Bitmap.SaveToFile(FileName); finally Bitmap.Free; end; end; finally SaveDir2 := ExtractFileDir(FileName); Free; end; end; end; 5: begin PrintDialog := TPrintDialog.Create(Application); try if PrintDialog.Execute then TTreeNT(Component).Print(0, 0, 100); finally PrintDialog.Free; end; end; 6: begin TTreeNT(Component).Items.Clear; Designer.Modified; end; end; end; //------------------------------------------------------------------------------ procedure Register; begin RegisterComponents('Samples', [TTreeNT]); RegisterPropertyEditor(TypeInfo(TTreeNTNodes), nil, '', TTreeNTNodesProperty); RegisterComponentEditor(TTreeNT, TTreeNTEditor); end; //------------------------------------------------------------------------------ end.
{ ---------------------------------------------------------------------------- } { HeightMapGenerator MB3D } { Copyright (C) 2017 Andreas Maschke } { ---------------------------------------------------------------------------- } unit ShaderUtil; interface uses SysUtils, Classes, dglOpenGL; // from https://github.com/neslib/DelphiLearnOpenGL/blob/master/Tutorials/Common/Sample.Classes.pas type { Encapsulates an OpenGL shader program consisting of a vertex shader and fragment shader. Implemented in the TShader class. } IShader = interface ['{6389D101-5FD2-4AEA-817A-A4AF21C7189D}'] {$REGION 'Internal Declarations'} function _GetHandle: GLuint; {$ENDREGION 'Internal Declarations'} { Uses (activates) the shader for rendering } procedure Use; { Retrieves the location of a "uniform" (global variable) in the shader. Parameters: AName: the name of the uniform to retrieve Returns: The location of the uniform. Raises an exception if the AName is not found in the shader. } function GetUniformLocation(const AName: RawByteString): Integer; function GetUniformLocationUnicode(const AName: String): Integer; { Low level OpenGL handle of the shader. } property Handle: GLuint read _GetHandle; end; type { Implements IShader } TShader = class(TInterfacedObject, IShader) {$REGION 'Internal Declarations'} private FProgram: GLuint; private class function CreateShader(const AShaderCode: String; const AShaderType: GLenum): GLuint; static; protected { IShader } function _GetHandle: GLuint; function GetUniformLocation(const AName: RawByteString): Integer; function GetUniformLocationUnicode(const AName: String): Integer; {$ENDREGION 'Internal Declarations'} public constructor Create(const AVertexShaderCode, AFragmentShaderCode: String); overload; constructor Create(const AFragmentShaderCode: String); overload; destructor Destroy; override; procedure Use; end; implementation const R_TRUE = 1; R_FALSE = 0; {$IFDEF DEBUG} procedure glErrorCheck; var Error: GLenum; begin Error := glGetError; if (Error <> GL_NO_ERROR) then raise Exception.CreateFmt('OpenGL Error: $%.4x', [Error]); end; {$ELSE} procedure glErrorCheck; inline; begin { Nothing } end; {$ENDIF} constructor TShader.Create(const AVertexShaderCode, AFragmentShaderCode: String); var Status, LogLength: GLint; VertexShader, FragmentShader: GLuint; Log: TBytes; Msg: String; begin inherited Create; FragmentShader := 0; VertexShader := CreateShader(AVertexShaderCode, GL_VERTEX_SHADER); try FragmentShader := CreateShader(AFragmentShaderCode, GL_FRAGMENT_SHADER); FProgram := glCreateProgram; glAttachShader(FProgram, VertexShader); glErrorCheck; glAttachShader(FProgram, FragmentShader); glErrorCheck; glLinkProgram(FProgram); glGetProgramiv(FProgram, GL_LINK_STATUS, @Status); if (Status <> R_TRUE) then begin glGetProgramiv(FProgram, GL_INFO_LOG_LENGTH, @LogLength); if (LogLength > 0) then begin SetLength(Log, LogLength); glGetProgramInfoLog(FProgram, LogLength, @LogLength, @Log[0]); Msg := TEncoding.ANSI.GetString(Log); raise Exception.Create(Msg); end; end; glErrorCheck; finally if (FragmentShader <> 0) then glDeleteShader(FragmentShader); if (VertexShader <> 0) then glDeleteShader(VertexShader); end; end; constructor TShader.Create(const AFragmentShaderCode: String); var Status, LogLength: GLint; FragmentShader: GLuint; Log: TBytes; Msg: String; begin inherited Create; FragmentShader := CreateShader(AFragmentShaderCode, GL_FRAGMENT_SHADER); try FProgram := glCreateProgram; glAttachShader(FProgram, FragmentShader); glErrorCheck; glLinkProgram(FProgram); glGetProgramiv(FProgram, GL_LINK_STATUS, @Status); if (Status <> R_TRUE) then begin glGetProgramiv(FProgram, GL_INFO_LOG_LENGTH, @LogLength); if (LogLength > 0) then begin SetLength(Log, LogLength); glGetProgramInfoLog(FProgram, LogLength, @LogLength, @Log[0]); Msg := TEncoding.ANSI.GetString(Log); raise Exception.Create(Msg); end; end; glErrorCheck; finally if (FragmentShader <> 0) then glDeleteShader(FragmentShader); end; end; class function TShader.CreateShader(const AShaderCode: String; const AShaderType: GLenum): GLuint; var Source: RawByteString; SourcePtr: MarshaledAString; Status, LogLength: GLint; Log: TBytes; Msg: String; begin Result := glCreateShader(AShaderType); Assert(Result <> 0); glErrorCheck; Source := AShaderCode; {$IFNDEF MOBILE} { Desktop OpenGL doesn't recognize precision specifiers } if (AShaderType = GL_FRAGMENT_SHADER) then Source := '#define lowp'#10+ '#define mediump'#10+ '#define highp'#10+ Source; {$ENDIF} SourcePtr := MarshaledAString(Source); glShaderSource(Result, 1, @SourcePtr, nil); glErrorCheck; glCompileShader(Result); glErrorCheck; Status := R_FALSE; glGetShaderiv(Result, GL_COMPILE_STATUS, @Status); if (Status <> R_TRUE) then begin glGetShaderiv(Result, GL_INFO_LOG_LENGTH, @LogLength); if (LogLength > 0) then begin SetLength(Log, LogLength); glGetShaderInfoLog(Result, LogLength, @LogLength, @Log[0]); Msg := TEncoding.ANSI.GetString(Log); raise Exception.Create(Msg); end; end; end; destructor TShader.Destroy; begin glUseProgram(0); if (FProgram <> 0) then glDeleteProgram(FProgram); inherited; end; function TShader.GetUniformLocation(const AName: RawByteString): Integer; begin Result := glGetUniformLocation(FProgram, MarshaledAString(AName)); if (Result < 0) then raise Exception.CreateFmt('Uniform "%s" not found in shader', [AName]); end; function TShader.GetUniformLocationUnicode(const AName: String): Integer; begin Result := GetUniformLocation(RawByteString(AName)); end; procedure TShader.Use; begin glUseProgram(FProgram); end; function TShader._GetHandle: GLuint; begin Result := FProgram; end; end.
unit RN_DetourTileCache; interface uses RN_DetourStatus; typedef unsigned int dtObstacleRef; typedef unsigned int dtCompressedTileRef; /// Flags for addTile enum dtCompressedTileFlags { DT_COMPRESSEDTILE_FREE_DATA = 0x01, ///< Navmesh owns the tile memory and should free it. }; struct dtCompressedTile { unsigned int salt; ///< Counter describing modifications to the tile. struct dtTileCacheLayerHeader* header; unsigned char* compressed; int compressedSize; unsigned char* data; int dataSize; unsigned int flags; dtCompressedTile* next; }; enum ObstacleState { DT_OBSTACLE_EMPTY, DT_OBSTACLE_PROCESSING, DT_OBSTACLE_PROCESSED, DT_OBSTACLE_REMOVING, }; static const int DT_MAX_TOUCHED_TILES = 8; struct dtTileCacheObstacle { float pos[3], radius, height; dtCompressedTileRef touched[DT_MAX_TOUCHED_TILES]; dtCompressedTileRef pending[DT_MAX_TOUCHED_TILES]; unsigned short salt; unsigned char state; unsigned char ntouched; unsigned char npending; dtTileCacheObstacle* next; }; struct dtTileCacheParams { float orig[3]; float cs, ch; int width, height; float walkableHeight; float walkableRadius; float walkableClimb; float maxSimplificationError; int maxTiles; int maxObstacles; }; struct dtTileCacheMeshProcess { virtual ~dtTileCacheMeshProcess() { } virtual void process(struct dtNavMeshCreateParams* params, unsigned char* polyAreas, unsigned short* polyFlags) = 0; }; class dtTileCache { public: dtTileCache(); ~dtTileCache(); struct dtTileCacheAlloc* getAlloc() { return m_talloc; } struct dtTileCacheCompressor* getCompressor() { return m_tcomp; } const dtTileCacheParams* getParams() const { return &m_params; } inline int getTileCount() const { return m_params.maxTiles; } inline const dtCompressedTile* getTile(const int i) const { return &m_tiles[i]; } inline int getObstacleCount() const { return m_params.maxObstacles; } inline const dtTileCacheObstacle* getObstacle(const int i) const { return &m_obstacles[i]; } const dtTileCacheObstacle* getObstacleByRef(dtObstacleRef ref); dtObstacleRef getObstacleRef(const dtTileCacheObstacle* obmin) const; dtStatus init(const dtTileCacheParams* params, struct dtTileCacheAlloc* talloc, struct dtTileCacheCompressor* tcomp, struct dtTileCacheMeshProcess* tmproc); int getTilesAt(const int tx, const int ty, dtCompressedTileRef* tiles, const int maxTiles) const ; dtCompressedTile* getTileAt(const int tx, const int ty, const int tlayer); dtCompressedTileRef getTileRef(const dtCompressedTile* tile) const; const dtCompressedTile* getTileByRef(dtCompressedTileRef ref) const; dtStatus addTile(unsigned char* data, const int dataSize, unsigned char flags, dtCompressedTileRef* result); dtStatus removeTile(dtCompressedTileRef ref, unsigned char** data, int* dataSize); dtStatus addObstacle(const float* pos, const float radius, const float height, dtObstacleRef* result); dtStatus removeObstacle(const dtObstacleRef ref); dtStatus queryTiles(const float* bmin, const float* bmax, dtCompressedTileRef* results, int* resultCount, const int maxResults) const; dtStatus update(const float /*dt*/, class dtNavMesh* navmesh); dtStatus buildNavMeshTilesAt(const int tx, const int ty, class dtNavMesh* navmesh); dtStatus buildNavMeshTile(const dtCompressedTileRef ref, class dtNavMesh* navmesh); void calcTightTileBounds(const struct dtTileCacheLayerHeader* header, float* bmin, float* bmax) const; void getObstacleBounds(const struct dtTileCacheObstacle* ob, float* bmin, float* bmax) const; /// Encodes a tile id. inline dtCompressedTileRef encodeTileId(unsigned int salt, unsigned int it) const { return ((dtCompressedTileRef)salt << m_tileBits) | (dtCompressedTileRef)it; } /// Decodes a tile salt. inline unsigned int decodeTileIdSalt(dtCompressedTileRef ref) const { const dtCompressedTileRef saltMask = ((dtCompressedTileRef)1<<m_saltBits)-1; return (unsigned int)((ref >> m_tileBits) & saltMask); } /// Decodes a tile id. inline unsigned int decodeTileIdTile(dtCompressedTileRef ref) const { const dtCompressedTileRef tileMask = ((dtCompressedTileRef)1<<m_tileBits)-1; return (unsigned int)(ref & tileMask); } /// Encodes an obstacle id. inline dtObstacleRef encodeObstacleId(unsigned int salt, unsigned int it) const { return ((dtObstacleRef)salt << 16) | (dtObstacleRef)it; } /// Decodes an obstacle salt. inline unsigned int decodeObstacleIdSalt(dtObstacleRef ref) const { const dtObstacleRef saltMask = ((dtObstacleRef)1<<16)-1; return (unsigned int)((ref >> 16) & saltMask); } /// Decodes an obstacle id. inline unsigned int decodeObstacleIdObstacle(dtObstacleRef ref) const { const dtObstacleRef tileMask = ((dtObstacleRef)1<<16)-1; return (unsigned int)(ref & tileMask); } private: enum ObstacleRequestAction { REQUEST_ADD, REQUEST_REMOVE, }; struct ObstacleRequest { int action; dtObstacleRef ref; }; int m_tileLutSize; ///< Tile hash lookup size (must be pot). int m_tileLutMask; ///< Tile hash lookup mask. dtCompressedTile** m_posLookup; ///< Tile hash lookup. dtCompressedTile* m_nextFreeTile; ///< Freelist of tiles. dtCompressedTile* m_tiles; ///< List of tiles. unsigned int m_saltBits; ///< Number of salt bits in the tile ID. unsigned int m_tileBits; ///< Number of tile bits in the tile ID. dtTileCacheParams m_params; dtTileCacheAlloc* m_talloc; dtTileCacheCompressor* m_tcomp; dtTileCacheMeshProcess* m_tmproc; dtTileCacheObstacle* m_obstacles; dtTileCacheObstacle* m_nextFreeObstacle; static const int MAX_REQUESTS = 64; ObstacleRequest m_reqs[MAX_REQUESTS]; int m_nreqs; static const int MAX_UPDATE = 64; dtCompressedTileRef m_update[MAX_UPDATE]; int m_nupdate; }; dtTileCache* dtAllocTileCache(); void dtFreeTileCache(dtTileCache* tc); #endif #include "DetourTileCache.h" #include "DetourTileCacheBuilder.h" #include "DetourNavMeshBuilder.h" #include "DetourNavMesh.h" #include "DetourCommon.h" #include "DetourMath.h" #include "DetourAlloc.h" #include "DetourAssert.h" #include <string.h> #include <new> dtTileCache* dtAllocTileCache() { void* mem = dtAlloc(sizeof(dtTileCache), DT_ALLOC_PERM); if (!mem) return 0; return new(mem) dtTileCache; } void dtFreeTileCache(dtTileCache* tc) { if (!tc) return; tc->~dtTileCache(); dtFree(tc); } static bool contains(const dtCompressedTileRef* a, const int n, const dtCompressedTileRef v) { for (int i = 0; i < n; ++i) if (a[i] == v) return true; return false; } inline int computeTileHash(int x, int y, const int mask) { const unsigned int h1 = 0x8da6b343; // Large multiplicative constants; const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes unsigned int n = h1 * x + h2 * y; return (int)(n & mask); } struct BuildContext { inline BuildContext(struct dtTileCacheAlloc* a) : layer(0), lcset(0), lmesh(0), alloc(a) {} inline ~BuildContext() { purge(); } void purge() { dtFreeTileCacheLayer(alloc, layer); layer = 0; dtFreeTileCacheContourSet(alloc, lcset); lcset = 0; dtFreeTileCachePolyMesh(alloc, lmesh); lmesh = 0; } struct dtTileCacheLayer* layer; struct dtTileCacheContourSet* lcset; struct dtTileCachePolyMesh* lmesh; struct dtTileCacheAlloc* alloc; }; dtTileCache::dtTileCache() : m_tileLutSize(0), m_tileLutMask(0), m_posLookup(0), m_nextFreeTile(0), m_tiles(0), m_saltBits(0), m_tileBits(0), m_talloc(0), m_tcomp(0), m_tmproc(0), m_obstacles(0), m_nextFreeObstacle(0), m_nreqs(0), m_nupdate(0) { memset(&m_params, 0, sizeof(m_params)); } dtTileCache::~dtTileCache() { for (int i = 0; i < m_params.maxTiles; ++i) { if (m_tiles[i].flags & DT_COMPRESSEDTILE_FREE_DATA) { dtFree(m_tiles[i].data); m_tiles[i].data = 0; } } dtFree(m_obstacles); m_obstacles = 0; dtFree(m_posLookup); m_posLookup = 0; dtFree(m_tiles); m_tiles = 0; m_nreqs = 0; m_nupdate = 0; } const dtCompressedTile* dtTileCache::getTileByRef(dtCompressedTileRef ref) const { if (!ref) return 0; unsigned int tileIndex = decodeTileIdTile(ref); unsigned int tileSalt = decodeTileIdSalt(ref); if ((int)tileIndex >= m_params.maxTiles) return 0; const dtCompressedTile* tile = &m_tiles[tileIndex]; if (tile->salt != tileSalt) return 0; return tile; } dtStatus dtTileCache::init(const dtTileCacheParams* params, dtTileCacheAlloc* talloc, dtTileCacheCompressor* tcomp, dtTileCacheMeshProcess* tmproc) { m_talloc = talloc; m_tcomp = tcomp; m_tmproc = tmproc; m_nreqs = 0; memcpy(&m_params, params, sizeof(m_params)); // Alloc space for obstacles. m_obstacles = (dtTileCacheObstacle*)dtAlloc(sizeof(dtTileCacheObstacle)*m_params.maxObstacles, DT_ALLOC_PERM); if (!m_obstacles) return DT_FAILURE | DT_OUT_OF_MEMORY; memset(m_obstacles, 0, sizeof(dtTileCacheObstacle)*m_params.maxObstacles); m_nextFreeObstacle = 0; for (int i = m_params.maxObstacles-1; i >= 0; --i) { m_obstacles[i].salt = 1; m_obstacles[i].next = m_nextFreeObstacle; m_nextFreeObstacle = &m_obstacles[i]; } // Init tiles m_tileLutSize = dtNextPow2(m_params.maxTiles/4); if (!m_tileLutSize) m_tileLutSize = 1; m_tileLutMask = m_tileLutSize-1; m_tiles = (dtCompressedTile*)dtAlloc(sizeof(dtCompressedTile)*m_params.maxTiles, DT_ALLOC_PERM); if (!m_tiles) return DT_FAILURE | DT_OUT_OF_MEMORY; m_posLookup = (dtCompressedTile**)dtAlloc(sizeof(dtCompressedTile*)*m_tileLutSize, DT_ALLOC_PERM); if (!m_posLookup) return DT_FAILURE | DT_OUT_OF_MEMORY; memset(m_tiles, 0, sizeof(dtCompressedTile)*m_params.maxTiles); memset(m_posLookup, 0, sizeof(dtCompressedTile*)*m_tileLutSize); m_nextFreeTile = 0; for (int i = m_params.maxTiles-1; i >= 0; --i) { m_tiles[i].salt = 1; m_tiles[i].next = m_nextFreeTile; m_nextFreeTile = &m_tiles[i]; } // Init ID generator values. m_tileBits = dtIlog2(dtNextPow2((unsigned int)m_params.maxTiles)); // Only allow 31 salt bits, since the salt mask is calculated using 32bit uint and it will overflow. m_saltBits = dtMin((unsigned int)31, 32 - m_tileBits); if (m_saltBits < 10) return DT_FAILURE | DT_INVALID_PARAM; return DT_SUCCESS; } int dtTileCache::getTilesAt(const int tx, const int ty, dtCompressedTileRef* tiles, const int maxTiles) const { int n = 0; // Find tile based on hash. int h = computeTileHash(tx,ty,m_tileLutMask); dtCompressedTile* tile = m_posLookup[h]; while (tile) { if (tile->header && tile->header->tx == tx && tile->header->ty == ty) { if (n < maxTiles) tiles[n++] = getTileRef(tile); } tile = tile->next; } return n; } dtCompressedTile* dtTileCache::getTileAt(const int tx, const int ty, const int tlayer) { // Find tile based on hash. int h = computeTileHash(tx,ty,m_tileLutMask); dtCompressedTile* tile = m_posLookup[h]; while (tile) { if (tile->header && tile->header->tx == tx && tile->header->ty == ty && tile->header->tlayer == tlayer) { return tile; } tile = tile->next; } return 0; } dtCompressedTileRef dtTileCache::getTileRef(const dtCompressedTile* tile) const { if (!tile) return 0; const unsigned int it = (unsigned int)(tile - m_tiles); return (dtCompressedTileRef)encodeTileId(tile->salt, it); } dtObstacleRef dtTileCache::getObstacleRef(const dtTileCacheObstacle* ob) const { if (!ob) return 0; const unsigned int idx = (unsigned int)(ob - m_obstacles); return encodeObstacleId(ob->salt, idx); } const dtTileCacheObstacle* dtTileCache::getObstacleByRef(dtObstacleRef ref) { if (!ref) return 0; unsigned int idx = decodeObstacleIdObstacle(ref); if ((int)idx >= m_params.maxObstacles) return 0; const dtTileCacheObstacle* ob = &m_obstacles[idx]; unsigned int salt = decodeObstacleIdSalt(ref); if (ob->salt != salt) return 0; return ob; } dtStatus dtTileCache::addTile(unsigned char* data, const int dataSize, unsigned char flags, dtCompressedTileRef* result) { // Make sure the data is in right format. dtTileCacheLayerHeader* header = (dtTileCacheLayerHeader*)data; if (header->magic != DT_TILECACHE_MAGIC) return DT_FAILURE | DT_WRONG_MAGIC; if (header->version != DT_TILECACHE_VERSION) return DT_FAILURE | DT_WRONG_VERSION; // Make sure the location is free. if (getTileAt(header->tx, header->ty, header->tlayer)) return DT_FAILURE; // Allocate a tile. dtCompressedTile* tile = 0; if (m_nextFreeTile) { tile = m_nextFreeTile; m_nextFreeTile = tile->next; tile->next = 0; } // Make sure we could allocate a tile. if (!tile) return DT_FAILURE | DT_OUT_OF_MEMORY; // Insert tile into the position lut. int h = computeTileHash(header->tx, header->ty, m_tileLutMask); tile->next = m_posLookup[h]; m_posLookup[h] = tile; // Init tile. const int headerSize = dtAlign4(sizeof(dtTileCacheLayerHeader)); tile->header = (dtTileCacheLayerHeader*)data; tile->data = data; tile->dataSize = dataSize; tile->compressed = tile->data + headerSize; tile->compressedSize = tile->dataSize - headerSize; tile->flags = flags; if (result) *result = getTileRef(tile); return DT_SUCCESS; } dtStatus dtTileCache::removeTile(dtCompressedTileRef ref, unsigned char** data, int* dataSize) { if (!ref) return DT_FAILURE | DT_INVALID_PARAM; unsigned int tileIndex = decodeTileIdTile(ref); unsigned int tileSalt = decodeTileIdSalt(ref); if ((int)tileIndex >= m_params.maxTiles) return DT_FAILURE | DT_INVALID_PARAM; dtCompressedTile* tile = &m_tiles[tileIndex]; if (tile->salt != tileSalt) return DT_FAILURE | DT_INVALID_PARAM; // Remove tile from hash lookup. const int h = computeTileHash(tile->header->tx,tile->header->ty,m_tileLutMask); dtCompressedTile* prev = 0; dtCompressedTile* cur = m_posLookup[h]; while (cur) { if (cur == tile) { if (prev) prev->next = cur->next; else m_posLookup[h] = cur->next; break; } prev = cur; cur = cur->next; } // Reset tile. if (tile->flags & DT_COMPRESSEDTILE_FREE_DATA) { // Owns data dtFree(tile->data); tile->data = 0; tile->dataSize = 0; if (data) *data = 0; if (dataSize) *dataSize = 0; } else { if (data) *data = tile->data; if (dataSize) *dataSize = tile->dataSize; } tile->header = 0; tile->data = 0; tile->dataSize = 0; tile->compressed = 0; tile->compressedSize = 0; tile->flags = 0; // Update salt, salt should never be zero. tile->salt = (tile->salt+1) & ((1<<m_saltBits)-1); if (tile->salt == 0) tile->salt++; // Add to free list. tile->next = m_nextFreeTile; m_nextFreeTile = tile; return DT_SUCCESS; } dtObstacleRef dtTileCache::addObstacle(const float* pos, const float radius, const float height, dtObstacleRef* result) { if (m_nreqs >= MAX_REQUESTS) return DT_FAILURE | DT_BUFFER_TOO_SMALL; dtTileCacheObstacle* ob = 0; if (m_nextFreeObstacle) { ob = m_nextFreeObstacle; m_nextFreeObstacle = ob->next; ob->next = 0; } if (!ob) return DT_FAILURE | DT_OUT_OF_MEMORY; unsigned short salt = ob->salt; memset(ob, 0, sizeof(dtTileCacheObstacle)); ob->salt = salt; ob->state = DT_OBSTACLE_PROCESSING; dtVcopy(ob->pos, pos); ob->radius = radius; ob->height = height; ObstacleRequest* req = &m_reqs[m_nreqs++]; memset(req, 0, sizeof(ObstacleRequest)); req->action = REQUEST_ADD; req->ref = getObstacleRef(ob); if (result) *result = req->ref; return DT_SUCCESS; } dtObstacleRef dtTileCache::removeObstacle(const dtObstacleRef ref) { if (!ref) return DT_SUCCESS; if (m_nreqs >= MAX_REQUESTS) return DT_FAILURE | DT_BUFFER_TOO_SMALL; ObstacleRequest* req = &m_reqs[m_nreqs++]; memset(req, 0, sizeof(ObstacleRequest)); req->action = REQUEST_REMOVE; req->ref = ref; return DT_SUCCESS; } dtStatus dtTileCache::queryTiles(const float* bmin, const float* bmax, dtCompressedTileRef* results, int* resultCount, const int maxResults) const { const int MAX_TILES = 32; dtCompressedTileRef tiles[MAX_TILES]; int n = 0; const float tw = m_params.width * m_params.cs; const float th = m_params.height * m_params.cs; const int tx0 = (int)dtMathFloorf((bmin[0]-m_params.orig[0]) / tw); const int tx1 = (int)dtMathFloorf((bmax[0]-m_params.orig[0]) / tw); const int ty0 = (int)dtMathFloorf((bmin[2]-m_params.orig[2]) / th); const int ty1 = (int)dtMathFloorf((bmax[2]-m_params.orig[2]) / th); for (int ty = ty0; ty <= ty1; ++ty) { for (int tx = tx0; tx <= tx1; ++tx) { const int ntiles = getTilesAt(tx,ty,tiles,MAX_TILES); for (int i = 0; i < ntiles; ++i) { const dtCompressedTile* tile = &m_tiles[decodeTileIdTile(tiles[i])]; float tbmin[3], tbmax[3]; calcTightTileBounds(tile->header, tbmin, tbmax); if (dtOverlapBounds(bmin,bmax, tbmin,tbmax)) { if (n < maxResults) results[n++] = tiles[i]; } } } } *resultCount = n; return DT_SUCCESS; } dtStatus dtTileCache::update(const float /*dt*/, dtNavMesh* navmesh) { if (m_nupdate == 0) { // Process requests. for (int i = 0; i < m_nreqs; ++i) { ObstacleRequest* req = &m_reqs[i]; unsigned int idx = decodeObstacleIdObstacle(req->ref); if ((int)idx >= m_params.maxObstacles) continue; dtTileCacheObstacle* ob = &m_obstacles[idx]; unsigned int salt = decodeObstacleIdSalt(req->ref); if (ob->salt != salt) continue; if (req->action == REQUEST_ADD) { // Find touched tiles. float bmin[3], bmax[3]; getObstacleBounds(ob, bmin, bmax); int ntouched = 0; queryTiles(bmin, bmax, ob->touched, &ntouched, DT_MAX_TOUCHED_TILES); ob->ntouched = (unsigned char)ntouched; // Add tiles to update list. ob->npending = 0; for (int j = 0; j < ob->ntouched; ++j) { if (m_nupdate < MAX_UPDATE) { if (!contains(m_update, m_nupdate, ob->touched[j])) m_update[m_nupdate++] = ob->touched[j]; ob->pending[ob->npending++] = ob->touched[j]; } } } else if (req->action == REQUEST_REMOVE) { // Prepare to remove obstacle. ob->state = DT_OBSTACLE_REMOVING; // Add tiles to update list. ob->npending = 0; for (int j = 0; j < ob->ntouched; ++j) { if (m_nupdate < MAX_UPDATE) { if (!contains(m_update, m_nupdate, ob->touched[j])) m_update[m_nupdate++] = ob->touched[j]; ob->pending[ob->npending++] = ob->touched[j]; } } } } m_nreqs = 0; } // Process updates if (m_nupdate) { // Build mesh const dtCompressedTileRef ref = m_update[0]; dtStatus status = buildNavMeshTile(ref, navmesh); m_nupdate--; if (m_nupdate > 0) memmove(m_update, m_update+1, m_nupdate*sizeof(dtCompressedTileRef)); // Update obstacle states. for (int i = 0; i < m_params.maxObstacles; ++i) { dtTileCacheObstacle* ob = &m_obstacles[i]; if (ob->state == DT_OBSTACLE_PROCESSING || ob->state == DT_OBSTACLE_REMOVING) { // Remove handled tile from pending list. for (int j = 0; j < (int)ob->npending; j++) { if (ob->pending[j] == ref) { ob->pending[j] = ob->pending[(int)ob->npending-1]; ob->npending--; break; } } // If all pending tiles processed, change state. if (ob->npending == 0) { if (ob->state == DT_OBSTACLE_PROCESSING) { ob->state = DT_OBSTACLE_PROCESSED; } else if (ob->state == DT_OBSTACLE_REMOVING) { ob->state = DT_OBSTACLE_EMPTY; // Update salt, salt should never be zero. ob->salt = (ob->salt+1) & ((1<<16)-1); if (ob->salt == 0) ob->salt++; // Return obstacle to free list. ob->next = m_nextFreeObstacle; m_nextFreeObstacle = ob; } } } } if (dtStatusFailed(status)) return status; } return DT_SUCCESS; } dtStatus dtTileCache::buildNavMeshTilesAt(const int tx, const int ty, dtNavMesh* navmesh) { const int MAX_TILES = 32; dtCompressedTileRef tiles[MAX_TILES]; const int ntiles = getTilesAt(tx,ty,tiles,MAX_TILES); for (int i = 0; i < ntiles; ++i) { dtStatus status = buildNavMeshTile(tiles[i], navmesh); if (dtStatusFailed(status)) return status; } return DT_SUCCESS; } dtStatus dtTileCache::buildNavMeshTile(const dtCompressedTileRef ref, dtNavMesh* navmesh) { dtAssert(m_talloc); dtAssert(m_tcomp); unsigned int idx = decodeTileIdTile(ref); if (idx > (unsigned int)m_params.maxTiles) return DT_FAILURE | DT_INVALID_PARAM; const dtCompressedTile* tile = &m_tiles[idx]; unsigned int salt = decodeTileIdSalt(ref); if (tile->salt != salt) return DT_FAILURE | DT_INVALID_PARAM; m_talloc->reset(); BuildContext bc(m_talloc); const int walkableClimbVx = (int)(m_params.walkableClimb / m_params.ch); dtStatus status; // Decompress tile layer data. status = dtDecompressTileCacheLayer(m_talloc, m_tcomp, tile->data, tile->dataSize, &bc.layer); if (dtStatusFailed(status)) return status; // Rasterize obstacles. for (int i = 0; i < m_params.maxObstacles; ++i) { const dtTileCacheObstacle* ob = &m_obstacles[i]; if (ob->state == DT_OBSTACLE_EMPTY || ob->state == DT_OBSTACLE_REMOVING) continue; if (contains(ob->touched, ob->ntouched, ref)) { dtMarkCylinderArea(*bc.layer, tile->header->bmin, m_params.cs, m_params.ch, ob->pos, ob->radius, ob->height, 0); } } // Build navmesh status = dtBuildTileCacheRegions(m_talloc, *bc.layer, walkableClimbVx); if (dtStatusFailed(status)) return status; bc.lcset = dtAllocTileCacheContourSet(m_talloc); if (!bc.lcset) return status; status = dtBuildTileCacheContours(m_talloc, *bc.layer, walkableClimbVx, m_params.maxSimplificationError, *bc.lcset); if (dtStatusFailed(status)) return status; bc.lmesh = dtAllocTileCachePolyMesh(m_talloc); if (!bc.lmesh) return status; status = dtBuildTileCachePolyMesh(m_talloc, *bc.lcset, *bc.lmesh); if (dtStatusFailed(status)) return status; // Early out if the mesh tile is empty. if (!bc.lmesh->npolys) return DT_SUCCESS; dtNavMeshCreateParams params; memset(&params, 0, sizeof(params)); params.verts = bc.lmesh->verts; params.vertCount = bc.lmesh->nverts; params.polys = bc.lmesh->polys; params.polyAreas = bc.lmesh->areas; params.polyFlags = bc.lmesh->flags; params.polyCount = bc.lmesh->npolys; params.nvp = DT_VERTS_PER_POLYGON; params.walkableHeight = m_params.walkableHeight; params.walkableRadius = m_params.walkableRadius; params.walkableClimb = m_params.walkableClimb; params.tileX = tile->header->tx; params.tileY = tile->header->ty; params.tileLayer = tile->header->tlayer; params.cs = m_params.cs; params.ch = m_params.ch; params.buildBvTree = false; dtVcopy(params.bmin, tile->header->bmin); dtVcopy(params.bmax, tile->header->bmax); if (m_tmproc) { m_tmproc->process(&params, bc.lmesh->areas, bc.lmesh->flags); } unsigned char* navData = 0; int navDataSize = 0; if (!dtCreateNavMeshData(&params, &navData, &navDataSize)) return DT_FAILURE; // Remove existing tile. navmesh->removeTile(navmesh->getTileRefAt(tile->header->tx,tile->header->ty,tile->header->tlayer),0,0); // Add new tile, or leave the location empty. if (navData) { // Let the navmesh own the data. status = navmesh->addTile(navData,navDataSize,DT_TILE_FREE_DATA,0,0); if (dtStatusFailed(status)) { dtFree(navData); return status; } } return DT_SUCCESS; } void dtTileCache::calcTightTileBounds(const dtTileCacheLayerHeader* header, float* bmin, float* bmax) const { const float cs = m_params.cs; bmin[0] = header->bmin[0] + header->minx*cs; bmin[1] = header->bmin[1]; bmin[2] = header->bmin[2] + header->miny*cs; bmax[0] = header->bmin[0] + (header->maxx+1)*cs; bmax[1] = header->bmax[1]; bmax[2] = header->bmin[2] + (header->maxy+1)*cs; } void dtTileCache::getObstacleBounds(const struct dtTileCacheObstacle* ob, float* bmin, float* bmax) const { bmin[0] = ob->pos[0] - ob->radius; bmin[1] = ob->pos[1]; bmin[2] = ob->pos[2] - ob->radius; bmax[0] = ob->pos[0] + ob->radius; bmax[1] = ob->pos[1] + ob->height; bmax[2] = ob->pos[2] + ob->radius; }
{ Rubbermade: Create new colour TextureSets darkconsole http://darkconsole.tumblr.com } Unit UserScript; Const TemplateTxst = $d62; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// Function DccCreateForm(TemplateID: Integer; Plugin: IInterface): IInterface; Var FormID: Integer; Begin AddMessage('Load Order ' + IntToStr(GetLoadOrder(Plugin))); FormID := (GetLoadOrder(Plugin) shl 24) + TemplateID; AddMessage('Creating Form From Template: ' + IntToHex(FormID,8)); Result := wbCopyElementToFile( DccGetForm(FormID), Plugin, True, True ); End; Function DccGetForm(FormID: Integer): IInterface; Begin Result := RecordByFormID( FileByLoadOrder(FormID shr 24), LoadOrderFormIDtoFileFormID( FileByLoadOrder(FormID shr 24), FormID ), True ); End; Procedure DccSetEditorID(Form: IInterface; EditorID: String); Begin SetElementEditValues(Form,'EDID - Editor ID',EditorID); End; Procedure DccSetTextureDiffuse(Form: IInterface; Filename: String); Begin SetElementEditValues(Form,'Textures (RGB/A)\TX00 - Difuse',Filename); End; Procedure DccSetTextureNormal(Form: IInterface; FileName: String); Begin SetElementEditValues(Form,'Textures (RGB/A)\TX01 - Normal/Gloss',Filename); End; Procedure DccSetTextureEnv(Form: IInterface; FileName: String); Begin SetElementEditValues(Form,'Textures (RGB/A)\TX05 - Environment',Filename); End; Function DccFirstCase(StrIn: string): String; Var StrOut: String; Iter: Int; Begin Iter := 1; StrOut := ''; While Iter <= Length(StrIn) Do Begin If(Iter = 1) Then Begin StrOut := StrOut + UpperCase(Copy(StrIn,Iter,1)); End Else Begin StrOut := StrOut + LowerCase(Copy(StrIn,Iter,1)); End; Inc(Iter) End; Result := StrOut; End; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// Procedure DccCreateTxst(Plugin: IInterface; ColourName: String; ColourFile: String; FinishKey: String; SolidKey: String); Var Form: IInterface; EditorID: String; DiffuseFile: String; NormalFile: String; FinishFile: String; Begin if(LowerCase(FinishKey) = 's') Then Begin FinishFile := 'e.shine.dds'; End Else Begin FinishFile := 'e.matte.dds'; End; DiffuseFile := 'd.' + LowerCase(SolidKey) + '-' + LowerCase(ColourFile) + '.dds'; NormalFile := 'n.' + LowerCase(SolidKey) + '.dds'; EditorID := 'dcc_latex_Tex' + DccFirstCase(ColourFile) + '' + UpperCase(FinishKey) + UpperCase(SolidKey); AddMessage(EditorID + ': ' + DiffuseFile + ', ' + NormalFile + ', ' + FinishFile); Form := DccCreateForm(TemplateTxst,Plugin); DccSetEditorID(Form,EditorID); DccSetTextureDiffuse(Form,('dcc-rubbermade\common\' + DiffuseFile)); DccSetTextureNormal(Form,('dcc-rubbermade\common\' + NormalFile)); DccSetTextureEnv(Form,('dcc-rubbermade\common\' + FinishFile)); End; Procedure DccCreateTxstSolidShiny(Plugin: IInterface; ColourName: String; ColourFile: String); Begin DccCreateTxst(Plugin,ColourName,ColourFile,'s','s'); End; Procedure DccCreateTxstTransparentShiny(Plugin: IInterface; ColourName: String; ColourFile: String); Begin DccCreateTxst(Plugin,ColourName,ColourFile,'s','t1'); End; Procedure DccCreateTxstTranslucentShiny(Plugin: IInterface; ColourName: String; ColourFile: String); Begin DccCreateTxst(Plugin,ColourName,ColourFile,'s','t2'); End; Procedure DccCreateTxstSolidMatte(Plugin: IInterface; ColourName: String; ColourFile: String); Begin DccCreateTxst(Plugin,ColourName,ColourFile,'m','s'); End; Procedure DccCreateTxstTransparentMatte(Plugin: IInterface; ColourName: String; ColourFile: String); Begin DccCreateTxst(Plugin,ColourName,ColourFile,'m','t1'); End; Procedure DccCreateTxstTranslucentMatte(Plugin: IInterface; ColourName: String; ColourFile: String); Begin DccCreateTxst(Plugin,ColourName,ColourFile,'m','t2'); End; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// Procedure DccCreateTextureSet(Plugin: IInterface); Var ColourName: String; // input ColourFile: String; // input TempString: String; InputResult: Boolean; FormNewTxst: IInterface; Begin AddMessage('Creating new Texture Set Set in ' + Name(Plugin)); //////// //////// InputResult := TRUE; While InputResult Do Begin ColourName := NULL; ColourFile := NULL; InputResult := InputQuery( 'Enter Colour Name', 'Type it as you would want it displayed, with caps etc.', ColourName ); If(InputResult = FALSE) Then Begin Exit; End; InputResult := InputQuery( 'Enter Colour File', 'Type it as it appears in the filenames. Note your files should follow the file naming system.', ColourFile ); If(InputResult = FALSE) Then Begin Exit; End; //////// //////// DccCreateTxstSolidShiny(Plugin,ColourName,ColourFile); DccCreateTxstTransparentShiny(Plugin,ColourName,ColourFile); DccCreateTxstTranslucentShiny(Plugin,ColourName,ColourFile); DccCreateTxstSolidMatte(Plugin,ColourName,ColourFile); DccCreateTxstTransparentMatte(Plugin,ColourName,ColourFile); DccCreateTxstTranslucentMatte(Plugin,ColourName,ColourFile); End; //////// //////// End; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// Function Initialize: Integer; Var Iter: Integer; Plugin: IInterface; Begin For Iter := 0 To FileCount - 1 Do Begin Plugin := FileByIndex(Iter); AddMessage('-- ' + IntToStr(Iter) + ' ' + Name(Plugin)); If(CompareText(GetFileName(Plugin),'dcc-rubbermade.esm') = 0) Then Begin DccCreateTextureSet(Plugin); End; End; End; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// End.
unit Options; {$mode objfpc}{$H+} interface uses Classes, SysUtils, CustomXML; const KeyCount = 32; type pBool= ^boolean; eGraphicsOptions = (grDrawFrame, grWireFrame); { TODO 2 -cFeature : variant array with enumerators for every option } ePlayerAction = (aEsc = -2, aNone = -1, aLeft, aRight, aForward, aBackward, aUpward, aDownward, aPitchDown, aPitchUp, aYawLeft, aYawRight, aRollLeft, aRollRight); {$INCLUDE keys.inc} type rGraphicsOptions = record XRes, YRes: longword; //FOV DrawFrame, WireFrame: boolean; end; rGamePlayOptions = record MouseSensitivity: single; end; rSystemOptions = record KeepLog: boolean; PrintToConsole: boolean; end; {rControlScheme = record m: array[0..KeyCount - 1] of pBool; end; } { tOptions } tOptions = class CS: array[low(eScanCode)..high(eScanCode)] of ePlayerAction; // Control Scheme Graphics: rGraphicsOptions; GamePlay: rGamePlayOptions; System: rSystemOptions; function Load(FileName: string): integer; function Save(FileName: string): integer; function WriteDefault(FileName: string): integer; end; implementation uses SDL2, Utility; { tOptions } function tOptions.Load(FileName: string): integer; var F: tXMLFile; a: ePlayerAction; KeyCode: eScanCode; e: integer; s: string; begin F:= tXMLFile.Open(FileName); if F = nil then begin WriteLog('Failed to load config'); exit(-1); end; for KeyCode:= low(eScanCode) to high(eScanCode) do begin CS[KeyCode]:= aNone; end; F.FindNode('keybindings'); while F.IterateNodesWithName('keyb') do begin s:= F.GetValue('action'); WriteLog('Read string ' + s); val(s, a, e); if e <> 0 then continue; s:= F.GetValue('keyprim'); { TODO : make all these into enums } WriteLog('Read string ' + s); val(s, KeyCode, e); if e = 0 then CS[KeyCode]:= a; end; CS[scESCAPE]:= aEsc; F.BackToRoot; F.FindNode('graphicssettings'); while F.IterateNodesWithName('grs') do begin s:= F.GetValue('name'); case s of 'xres': Graphics.XRes:= F.GetValue('value'); 'yres': Graphics.YRes:= F.GetValue('value'); else Writelog('Warning: unrecognised setting name in ' + FileName + ': ' + s); end; end; F.BackToRoot; F.FindNode('gameplaysettings'); while F.IterateNodesWithName('gms') do begin s:= F.GetValue('name'); writelog(s); case s of 'mousesens': GamePlay.MouseSensitivity:= F.GetValue('value'); else Writelog('Warning: unrecognised setting name in ' + FileName + ': ' + s); end; end; F.Free; end; function tOptions.Save(FileName: string): integer; var F: tXMLFile; a, v: string; KeyCode: eScanCode; begin F:= tXMLFile.CreateNew(FileName, true); if F = nil then begin WriteLog('Failed to save config'); exit(-1); end; F.AddNode('keybindings'); for KeyCode:= low(eScanCode) to high(eScanCode) do begin if CS[KeyCode] <> aNone then begin str(CS[KeyCode], a); str(KeyCode, v); F.AddNode('keyb'); F.SetValue('action', a); F.SetValue('keyprim', v); F.Back; end; end; F.Back; F.AddNode('graphicssettings'); F.AddNode('grs'); F.SetValue('name', 'xres'); F.SetValue('value', Graphics.XRes); F.Back; F.AddNode('grs'); F.SetValue('name', 'yres'); F.SetValue('value', Graphics.YRes); F.Back; F.Back; F.AddNode('gameplaysettings'); F.AddNode('gms'); F.SetValue('name', 'mousesens'); F.SetValue('value', GamePlay.MouseSensitivity); F.Back; F.Back; F.Free; Result:= 0; end; function tOptions.WriteDefault(FileName: string): integer; var F: tXMLFile; i: ePlayerAction; a, v: string; begin GamePlay.MouseSensitivity:= 0.8; Graphics.XRes:= 1000; Graphics.YRes:= 1000; System.KeepLog:= true; WriteLog('Writing default config to ' + Filename); F:= tXMLFile.CreateNew(FileName); if F = nil then begin WriteLog('Failed to create default config'); exit(-1); end; F.AddNode('keybindings'); for i:= aLeft to high(ePlayerAction) do //Has to start from aLeft, low(..) is -1! begin str(i, a); str(DefaultBinds[i], v); F.AddNode('keyb'); F.SetValue('action', a); F.SetValue('keyprim', v); F.Back; end; F.Back; F.AddNode('graphicssettings'); F.AddNode('grs'); F.SetValue('name', 'xres'); F.SetValue('value', Graphics.XRes); F.Back; F.AddNode('grs'); F.SetValue('name', 'yres'); F.SetValue('value', Graphics.YRes); F.Back; F.Back; F.AddNode('gameplaysettings'); F.AddNode('gms'); F.SetValue('name', 'mousesens'); F.SetValue('value', GamePlay.MouseSensitivity); F.Back; F.Back; F.Free; Result:= 0; end; end.
{ Copyright (C) Miguel A. Risco-Castillo FPC-markdown is a fork of Grahame Grieve <grahameg@gmail.com> Delphi-markdown https://github.com/grahamegrieve/delphi-markdown 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 MarkdownDaringFireball; {$mode objfpc}{$H+} interface uses SysUtils, Classes, TypInfo, MarkdownProcessor, MarkdownUtils, MarkdownTables; type TMarkdownDaringFireball = class(TMarkdownProcessor) private Femitter: TEmitter; FuseExtensions: boolean; function readLines(reader : TReader): TBlock; procedure initListBlock(root: TBlock); procedure recurse(root: TBlock; listMode: boolean); protected function GetUnSafe: boolean; override; procedure SetUnSafe(const value: boolean); override; public Constructor Create; Destructor Destroy; override; function process(source: String): String; override; end; implementation { TMarkdownDaringFireball } constructor TMarkdownDaringFireball.Create; begin inherited Create; Config := TConfiguration.Create(true); Femitter := TEmitter.Create(config); TTable.Emitter:=Femitter; end; destructor TMarkdownDaringFireball.Destroy; begin Femitter.Free; Config.Free; inherited; end; function TMarkdownDaringFireball.GetUnSafe: boolean; begin result := not Config.safeMode; end; procedure TMarkdownDaringFireball.initListBlock(root: TBlock); var line: TLine; t: TLineType; begin line := root.lines; line := line.next; while (line <> nil) do begin t := line.getLineType(Config); if ((t = ltOLIST) or (t = ltULIST) or (not line.isEmpty and (line.prevEmpty and (line.leading = 0) and not((t = ltOLIST) or (t = ltULIST))))) then root.split(line.previous).type_ := btLIST_ITEM; line := line.next; end; root.split(root.lineTail).type_ := btLIST_ITEM; end; function TMarkdownDaringFireball.process(source: String): String; var out_: TStringBuilder; parent, block: TBlock; rdr : TReader; begin FuseExtensions := Config.isDialect([mdTxtMark,mdCommonMark]); rdr := TReader.Create(source); try out_ := TStringBuilder.Create; try parent := readLines(rdr); try parent.removeSurroundingEmptyLines; recurse(parent, false); block := parent.blocks; while (block <> nil) do begin Femitter.emit(out_, block); block := block.next; end; result := out_.ToString; finally parent.Free; end; finally out_.Free; end; finally rdr.Free; end; end; function TMarkdownDaringFireball.readLines(reader : TReader): TBlock; var block: TBlock; sb: TStringBuilder; c, ch: char; position, np: integer; eol, isLinkRef, lineAdded: boolean; lastLinkRef, lr: TLinkRef; line: TLine; id, link, comment: String; begin block := TBlock.Create; sb := TStringBuilder.Create; try c := reader.read(); lastLinkRef := nil; while (c <> #0) do begin sb.Clear; position := 0; eol := false; while (not eol) do begin case c of #0: eol := true; #10: begin c := reader.read(); if (c = #13) then c := reader.read(); eol := true; end; #13: begin c := reader.read(); if (c = #10) then c := reader.read(); eol := true; end; #9: begin np := position + (4 - (position and 3)); while (position < np) do begin sb.append(' '); inc(position); end; c := reader.read(); end; else if (c <> '<') or (not Config.panicMode) then begin inc(position); sb.append(c); end else begin inc(position, 4); sb.append('&lt;'); end; c := reader.read(); end; end; lineAdded := false; line := TLine.Create; try line.value := sb.ToString(); line.Init(); // Check for link definitions isLinkRef := false; id := ''; link := ''; comment := ''; if (not line.isEmpty) and (line.leading < 4) and (line.value[1 + line.leading] = '[') then begin line.position := line.leading + 1; // Read ID up to ']' id := line.readUntil([']']); // Is ID valid and are there any more characters? if (id <> '') and ((line.position + 2) < Length(line.value)) then begin // Check for ':' ([...]:...) if (line.value[1 + line.position + 1] = ':') then begin line.position := line.position + 2; if line.skipSpaces() then begin // Check for link syntax if (line.value[1 + line.position] = '<') then begin line.position := line.position + 1; link := line.readUntil(['>']); line.position := line.position + 1; end else link := line.readUntil([' ', #10]); // Is link valid? if (link <> '') then begin // Any non-whitespace characters following? if (line.skipSpaces()) then begin ch := line.value[1 + line.position]; // Read comment if (ch = '"') or (ch = '''') or (ch = '(') then begin line.position := line.position + 1; if ch = '(' then comment := line.readUntil([')']) else comment := line.readUntil([ch]); // Valid linkRef only if comment is valid if (comment <> '') then isLinkRef := true; end; end else isLinkRef := true; end; end; end; end; end; if (isLinkRef) then begin if (LowerCase(id) = '$profile$') then begin if LowerCase(link) = 'extended' then begin FuseExtensions:=true; Config.Dialect:=mdTxtMark; end; lastLinkRef := nil; end else begin // Store linkRef and skip line lr := TLinkRef.Create(link, comment, (comment <> '') and (Length(link) = 1) and (link[1] = '*')); Femitter.addLinkRef(id, lr); if (comment = '') then lastLinkRef := lr; end; end else begin comment := ''; // Check for multi-line linkRef if (not line.isEmpty and (lastLinkRef <> nil)) then begin line.position := line.leading; ch := line.value[1 + line.position]; if (ch = '"') or (ch = '''') or (ch = '(') then begin line.position := line.position + 1; if ch = '(' then comment := line.readUntil([')']) else comment := line.readUntil([ch]); end; if (comment <> '') then lastLinkRef.title := comment; lastLinkRef := nil; end; // No multi-line linkRef, store line if (comment = '') then begin line.position := 0; block.AppendLine(line); lineAdded := true; end; end; finally if not lineAdded then line.Free; end; end; result := block; finally sb.Free; end; end; procedure TMarkdownDaringFireball.recurse(root: TBlock; listMode: boolean); var block, list: TBlock; line: TLine; type_, t: TLineType; wasEmpty: boolean; bt: TBlockType; begin line := root.lines; if (listMode) then begin root.removeListIndent(Config); if (Config.isDialect([mdTxtMark,mdCommonMark]) and (root.lines <> nil) and (root.lines.getLineType(Config) <> ltCODE)) then root.id := root.lines.stripID(); end; while (line <> nil) and line.isEmpty do line := line.next; if (line = nil) then exit; while (line <> nil) do begin type_ := line.getLineType(Config); case type_ of ltOTHER: begin wasEmpty := line.prevEmpty; while (line <> nil) and (not line.isEmpty) do begin t := line.getLineType(Config); if (listMode or FuseExtensions) and (t in [ltOLIST, ltULIST]) then break; if (FuseExtensions and (t in [ltCODE, ltFENCED_CODE])) then break; if (t in [ltHEADLINE, ltHEADLINE1, ltHEADLINE2, ltHR, ltBQUOTE, ltXML, ltTABLE]) then break; line := line.next; end; if (line <> nil) and not line.isEmpty then begin if (listMode and not wasEmpty) then bt := btNONE else bt := btPARAGRAPH; if line = nil then root.split(root.lineTail).type_ := bt else root.split(line.previous).type_ := bt; root.removeLeadingEmptyLines(); end else begin if (listMode and ((line = nil) or (not line.isEmpty)) and not wasEmpty) then bt := btNONE else bt := btPARAGRAPH; root.removeLeadingEmptyLines(); if (line <> nil) then root.split(line.previous).type_ := bt else root.split(root.lineTail).type_ := bt; end; line := root.lines; end; ltCODE: begin while (line <> nil) and (line.isEmpty or (line.leading > 3)) do line := line.next; if (line <> nil) then block := root.split(line.previous) else block := root.split(root.lineTail); block.type_ := btCODE; block.removeSurroundingEmptyLines(); end; ltXML: begin if (line.previous <> nil) then // FIXME ... this looks wrong root.split(line.previous); root.split(line.xmlEndLine).type_ := btXML; root.removeLeadingEmptyLines(); line := root.lines; end; ltBQUOTE: begin while (line <> nil) do begin if (not line.isEmpty and (line.prevEmpty and (line.leading = 0) and (line.getLineType(Config) <> ltBQUOTE))) then break; line := line.next; end; if line <> nil then block := root.split(line.previous) else block := root.split(root.lineTail); block.type_ := btBLOCKQUOTE; block.removeSurroundingEmptyLines(); block.removeBlockQuotePrefix(); recurse(block, false); line := root.lines; end; ltHR: begin if (line.previous <> nil) then // FIXME ... this looks wrong root.split(line.previous); root.split(line).type_ := btRULER; root.removeLeadingEmptyLines(); line := root.lines; end; ltFENCED_CODE: begin line := line.next; while (line <> nil) do begin if (line.getLineType(Config) = ltFENCED_CODE) then break; line := line.next; end; if (line <> nil) then line := line.next; //skip close fenced code if line <> nil then block := root.split(line.previous) // end of fenced code else block := root.split(root.lineTail); // end of the block block.removeSurroundingEmptyLines(); // trim block block.type_ := btFENCED_CODE; block.meta := TUtils.getMetaFromFence(block.lines.value); block.lines.setEmpty(); // blank first fenced code if (block.lineTail.getLineType(Config) = ltFENCED_CODE) then block.lineTail.setEmpty(); // blank last fenced code block.removeSurroundingEmptyLines(); //trim block end; ltHEADLINE, ltHEADLINE1, ltHEADLINE2: begin if (line.previous <> nil) then root.split(line.previous); if (type_ <> ltHEADLINE) then line.next.setEmpty(); block := root.split(line); block.type_ := btHEADLINE; if (type_ <> ltHEADLINE) then if type_ = ltHEADLINE1 then block.hlDepth := 1 else block.hlDepth := 2; if Config.isDialect([mdTxtMark,mdCommonMark]) then block.id := block.lines.stripID(); block.transfromHeadline(); root.removeLeadingEmptyLines(); line := root.lines; end; ltOLIST, ltULIST: begin while (line <> nil) do begin t := line.getLineType(Config); if (not line.isEmpty and (line.prevEmpty and (line.leading = 0) and (not(t = type_)))) then break; line := line.next; end; if line <> nil then list := root.split(line.previous) else list := root.split(root.lineTail); if type_ = ltOLIST then list.type_ := btORDERED_LIST else list.type_ := btUNORDERED_LIST; list.lines.prevEmpty := false; list.lineTail.nextEmpty := false; list.removeSurroundingEmptyLines(); list.lineTail.nextEmpty := false; list.lines.prevEmpty := list.lineTail.nextEmpty; initListBlock(list); block := list.blocks; while (block <> nil) do begin recurse(block, true); block := block.next; end; list.expandListParagraphs(); end; ltTABLE: begin while (line <> nil) do begin if not TTable.isRow(line) then break; line := line.next; end; if line <> nil then block := root.split(line.previous) else block := root.split(root.lineTail); block.removeSurroundingEmptyLines(); block.type_ := btTABLE end; else line := line.next; end; end; end; procedure TMarkdownDaringFireball.SetUnSafe(const value: boolean); begin Config.safeMode := not value; end; end.
unit crc8_1; interface implementation type Byte = UInt8; PByte = ^UInt8; TCRC8PolyTable = array [0..255] of Byte; PCRC8PolyTable = ^TCRC8PolyTable; const Crc8TableP0x31: TCRC8PolyTable = ( $00, $31, $62, $53, $C4, $F5, $A6, $97, $B9, $88, $DB, $EA, $7D, $4C, $1F, $2E, $43, $72, $21, $10, $87, $B6, $E5, $D4, $FA, $CB, $98, $A9, $3E, $0F, $5C, $6D, $86, $B7, $E4, $D5, $42, $73, $20, $11, $3F, $0E, $5D, $6C, $FB, $CA, $99, $A8, $C5, $F4, $A7, $96, $01, $30, $63, $52, $7C, $4D, $1E, $2F, $B8, $89, $DA, $EB, $3D, $0C, $5F, $6E, $F9, $C8, $9B, $AA, $84, $B5, $E6, $D7, $40, $71, $22, $13, $7E, $4F, $1C, $2D, $BA, $8B, $D8, $E9, $C7, $F6, $A5, $94, $03, $32, $61, $50, $BB, $8A, $D9, $E8, $7F, $4E, $1D, $2C, $02, $33, $60, $51, $C6, $F7, $A4, $95, $F8, $C9, $9A, $AB, $3C, $0D, $5E, $6F, $41, $70, $23, $12, $85, $B4, $E7, $D6, $7A, $4B, $18, $29, $BE, $8F, $DC, $ED, $C3, $F2, $A1, $90, $07, $36, $65, $54, $39, $08, $5B, $6A, $FD, $CC, $9F, $AE, $80, $B1, $E2, $D3, $44, $75, $26, $17, $FC, $CD, $9E, $AF, $38, $09, $5A, $6B, $45, $74, $27, $16, $81, $B0, $E3, $D2, $BF, $8E, $DD, $EC, $7B, $4A, $19, $28, $06, $37, $64, $55, $C2, $F3, $A0, $91, $47, $76, $25, $14, $83, $B2, $E1, $D0, $FE, $CF, $9C, $AD, $3A, $0B, $58, $69, $04, $35, $66, $57, $C0, $F1, $A2, $93, $BD, $8C, $DF, $EE, $79, $48, $1B, $2A, $C1, $F0, $A3, $92, $05, $34, $67, $56, $78, $49, $1A, $2B, $BC, $8D, $DE, $EF, $82, $B3, $E0, $D1, $46, $77, $24, $15, $3B, $0A, $59, $68, $FF, $CE, $9D, $AC); function _crc8(aTable: PCRC8PolyTable; BaseCRC: byte; Data: PByte; Length: Byte): byte; overload; var Idx: Byte; begin Result := BaseCRC; while (Length > 0) do begin Idx := (Result xor Data^); Result := aTable[Idx]; Inc(Data); Dec(Length); end; end; function Crc8(BaseCRC: byte; Data: PByte; Length: Byte): byte; overload; begin Result := _crc8(@Crc8TableP0x31, BaseCRC, Data, Length); end; function Crc8(Data: PByte; Length: Byte): byte; overload; begin Result := Crc8($FF, Data, Length); end; var Data: UInt64 = $AABBCCDDEEFF9988; CRC: Byte; procedure Test; begin CRC := Crc8(PByte(@Data), 8); end; initialization Test(); finalization Assert(CRC = 80); end.
(* MPI: MM, 2020-04-29 *) (* ------ *) (* MiniPascal Interpreter. *) (* ========================================================================= *) PROGRAM MPI; USES MPL, MPP; VAR inputFilePath: STRING; BEGIN (* MPI *) IF (ParamCount = 1) THEN BEGIN inputFilePath := ParamStr(1); END ELSE BEGIN Write('MiniPascal source file > '); ReadLn(inputFilePath); END; (* IF *) InitLex(inputFilePath); S; IF (success) THEN BEGIN WriteLn('parsing complete: success'); END ELSE BEGIN WriteLn('parsing failed.'); END; (* IF *) END. (* MPI *)
unit HelpersPadrao; interface uses Data.Win.ADODB, Winapi.OleDB, Winapi.ADOInt; Type TADOConnectionHelper = Class Helper for TADOConnection published Function Attributes(Value: TXactAttributes):TADOConnection; public Function GetAttributes: TXactAttributes; End; Const XactAttributeValues: array[TXactAttribute] of TOleEnum = (adXactCommitRetaining, adXactAbortRetaining); implementation {$Region 'TADOConnectionHelper'} function TADOConnectionHelper.Attributes( Value: TXactAttributes): TADOConnection; var Attributes: LongWord; Xa: TXactAttribute; begin Attributes := 0; if Value <> [] then for Xa := Low(TXactAttribute) to High(TXactAttribute) do if Xa in Value then Attributes := Attributes + XactAttributeValues[Xa]; ConnectionObject.Attributes := Attributes; Result := Self; end; function TADOConnectionHelper.GetAttributes: TXactAttributes; var Attributes: Integer; Xa: TXactAttribute; begin Result := []; Attributes := ConnectionObject.Attributes; if Attributes <> 0 then for Xa := Low(TXactAttribute) to High(TXactAttribute) do if (XactAttributeValues[Xa] and Attributes) <> 0 then Include(Result, Xa); end; {$EndRegion} end.
unit JvImageTransformForm; { The images of this demo are taken from the Lazarus mushroom database example in folder (lazarus)/examples/database/image_mushrooms } {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, JvImageTransform; type { TMainForm } TMainForm = class(TForm) Bevel1: TBevel; btnTransform: TButton; ComboBox1: TComboBox; Image1: TImage; Image2: TImage; Image3: TImage; JvImageTransform1: TJvImageTransform; Label1: TLabel; Panel1: TPanel; Panel2: TPanel; procedure btnTransformClick(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure FormCreate(Sender: TObject); private FCurrImage: Integer; public end; var MainForm: TMainForm; implementation {$R *.lfm} { TMainForm } procedure TMainForm.btnTransformClick(Sender: TObject); var pic: TPicture; begin // Execute the transformation JvImageTransform1.Transform; // Load next image FCurrImage := (FCurrImage + 1) mod 3; case FCurrImage of 0: pic := Image1.Picture; 1: pic := Image2.Picture; 2: pic := Image3.Picture; end; if JvImageTransform1.ImageShown = 1 then JvImageTransform1.Picture2.Assign(pic) else JvImageTransform1.Picture1.Assign(pic); end; procedure TMainForm.ComboBox1Change(Sender: TObject); begin JvImageTransform1.TransformType := TJvTransformationKind(ComboBox1.ItemIndex); end; procedure TMainForm.FormCreate(Sender: TObject); begin JvImageTransform1.Picture1.Assign(Image1.Picture); JvImageTransform1.Picture2.Assign(Image2.Picture); end; end.
{ Iniquity Programming Language - Global Constants } const cTitle = 'Iniquity Programming Language'; cProgram = 'Iniquity/PL [executable file]'; cVersion = 'v1.00a'; idLength = 40; idVersion = 30; extSource = '.ips'; extExecute = '.ipx'; maxFile = 20; maxVar = 500; maxIdentLen = 30; maxVarDeclare = 30; maxParam = 40; maxProc = 2; maxArray = 3; maxGoto = 100; chDigit = ['0'..'9']; chNumber = ['0'..'9','.']; chAny = [#0..#255]; chIdent1 = ['a'..'z','A'..'Z','_']; chIdent2 = ['a'..'z','A'..'Z','0'..'9','_']; errUeEndOfFile = 1; errFileNotfound = 2; errFileRecurse = 3; errOutputFile = 4; errExpected = 5; errUnknownIdent = 6; errInStatement = 7; errIdentTooLong = 8; errExpIdentifier = 9; errTooManyVars = 10; errDupIdent = 11; errOverMaxDec = 12; errTypeMismatch = 13; errSyntaxError = 14; errStringNotClosed = 15; errStringTooLong = 16; errTooManyParams = 17; errBadProcRef = 18; errNumExpected = 19; errToOrDowntoExp = 20; errExpOperator = 21; errOverArrayDim = 22; errNoInitArray = 23; errTooManyGotos = 24; errDupLabel = 25; errLabelNotFound = 26; xrrUeEndOfFile = 1; xrrFileNotFound = 2; xrrInvalidFile = 3; xrrVerMismatch = 4; xrrUnknownOp = 5; xrrTooManyVars = 6; xrrMultiInit = 7; xrrDivisionByZero = 8; xrrMathematical = 9; type tIqVar = (vNone,vStr,vByte,vShort,vWord,vInt,vLong,vReal,vBool); tIqWord = (wOpenBlock,wCloseBlock,wCmtStartBlock,wCmtEndBlock, wCommentLine,wCmtNumberSign,wVarDeclare,wVarSep,wSetVar, wOpenBrack,wCloseBrack,wOpenString,wCloseString,wStrAdd, wCharPrefix,wProcDef,wOpenParam,wCloseParam,wParamVar, wParamSpec,wFuncSpec,wParamSep,wFor,wTo,wDownto,wDo,wTrue, wFalse,wOpEqual,wOpNotEqual,wOpGreater,wOpLess,wOpEqGreat, wOpEqLess,wIf,wThen,wElse,wWhile,wRepeat,wUntil,wNot,wAnd, wOr,wStrCh,wOpenArr,wCloseArr,wArrSep,wVarDef,wOpenStrLen, wCloseStrLen,wGoto,wLabel); tIqOp = (oOpenBlock,oCloseBlock,oVarDeclare,oStr,oByte,oShort,oWord, oInt,oLong,oReal,oBool,oSetVar,oOpenBrack,oCloseBrack, oVariable,oOpenString,oCloseString,oProcDef,oProcExec, oParamSep,oFor,oTo,oDownto,oTrue,oFalse,oOpEqual, oOpNotEqual,oOpGreater,oOpLess,oOpEqGreat,oOpEqLess, oStrAdd,oProcType,oIf,oElse,oWhile,oOpenNum,oCloseNum, oRepeat,oNot,oAnd,oOr,oStrCh,oArrDef,oVarDef,oStrLen, oVarNormal,oGoto); const iqv : array[tIqVar] of String[maxIdentLen] = ('none','str','byte','short','word','int','long','real','bool'); iqw : array[tIqWord] of String[maxIdentLen] = ('{','}','|','|','%','#','@',',','=','(',')','"','"','+','#','proc', '[',']','+',';',':',',','for','to','downto','do','true','false','=', '<>','>','<','>=','<=','if','then','else','while','repeat','until', 'not','and','or','.','(',')',',','=','<','>','goto',':'); iqo : array[tIqOp] of Char = ('[',']','+','s','b','h','w','i','l','r','o','-','(',')','v','"','"', '%','ø','/','#','Ü','ß','t','f','=','!','>','<','}','{','&',':','?', '*','|','`','''','é','ï','î','þ','~',#0,'ä','\','í','Û'); vnums : set of tIqVar = [vByte,vShort,vWord,vInt,vLong,vReal]; {$IFDEF ipx} type pData = ^tData; tData = array[1..65535] of Byte; tArray = array[1..maxArray] of Word; pVar = ^tVar; tVar = record id : Word; vtype : tIqVar; param : array[1..maxParam] of Char; numPar : Byte; proc : Boolean; pid : array[1..maxParam] of Word; ppos : LongInt; dsize : Word; size : Word; data : pData; kill : Boolean; arr : Byte; arrdim : tArray; end; tVars = array[1..maxVar] of pVar; {$ELSE} type pVar = ^tVar; tVar = record id : Word; ident : String[maxIdentLen]; vtype : tIqVar; param : array[1..maxParam] of Char; numPar : Byte; proc : Boolean; inproc : Boolean; arr : Byte; end; tVars = array[1..maxVar] of pVar; pGoto = ^tGoto; tGoto = record ident : String[maxIdentLen]; xPos : LongInt; stat : Byte; end; var cVar : tVars; cVars : Word; cID : Word; cGoto : array[1..maxGoto] of pGoto; cGotos : Word; {$ENDIF} var xUstart : Word; function cVarType(c : Char) : tIqVar; begin c := upCase(c); case c of 'S' : cVarType := vStr; 'B' : cVarType := vByte; 'H' : cVarType := vShort; 'W' : cVarType := vWord; 'I' : cVarType := vInt; 'L' : cVarType := vLong; 'R' : cVarType := vReal; 'O' : cVarType := vBool; else cVarType := vNone; end; end; function xVarSize(t : tIqVar) : Word; begin case t of vNone : xVarSize := 0; vStr : xVarSize := 256; vByte : xVarSize := 1; vShort : xVarSize := 1; vWord : xVarSize := 2; vInt : xVarSize := 2; vLong : xVarSize := 4; vReal : xVarSize := 6; vBool : xVarSize := 1; end; end; procedure cInitProcs(var cV : tVars; var x : Word; var iw : Word); procedure ip(i : String; p : String; t : tIqVar); begin Inc(x); New(cV[x]); with cV[x]^ do begin id := iw; Inc(iw); vtype := t; Move(p[1],param,Ord(p[0])); numPar := Ord(p[0]); proc := True; {$IFDEF ipx} size := 0; dsize := 0; data := nil; FillChar(pid,SizeOf(pid),0); ppos := 0; kill := True; {$ELSE} ident := i; inproc := False; {$ENDIF} arr := 0; {arrdim} end; end; procedure is(i : String; t : tIqVar; si : Word); begin Inc(x); New(cV[x]); with cV[x]^ do begin id := iw; Inc(iw); vtype := t; {param} numPar := 0; proc := False; {$IFDEF ipx} size := si+1; dsize := size; GetMem(data,dsize); FillChar(data^,dsize,0); FillChar(pid,SizeOf(pid),0); ppos := 0; kill := True; {$ELSE} ident := i; inproc := False; {$ENDIF} arr := 0; {arrdim} end; end; procedure iv(i : String; t : tIqVar); begin is(i,t,xVarSize(t)-1); end; procedure ivp(i : String; t : tIqVar; si : Word; pd : Pointer); begin Inc(x); New(cV[x]); with cV[x]^ do begin id := iw; Inc(iw); vtype := t; {param} numPar := 0; proc := False; {$IFDEF ipx} if t = vStr then size := si+1 else size := si; dsize := size; data := pd; { GetMem(data,dsize); FillChar(data^,dsize,0);} FillChar(pid,SizeOf(pid),0); ppos := 0; kill := False; {$ELSE} ident := i; inproc := False; {$ENDIF} arr := 0; {arrdim} end; end; begin iw := 0; { output routines } ip('out', 's', vNone); ip('outln', 's', vNone); ip('clrscr', '', vNone); ip('clreol', '', vNone); ip('beep', '', vNone); ip('cout', 's', vNone); ip('coutln', 's', vNone); ip('dnln', 'b', vNone); ip('gotoxy', 'bb', vNone); ip('posup', 'b', vNone); ip('posdown', 'b', vNone); ip('posleft', 'b', vNone); ip('posright', 'b', vNone); ip('posx', 'b', vNone); ip('posy', 'b', vNone); ip('setback', 'b', vNone); ip('setfore', 'b', vNone); ip('setblink', 'o', vNone); ip('setcolor', 'bb', vNone); ip('sout', 's', vNone); ip('soutln', 's', vNone); ip('strout', 'w', vNone); ip('stroutln', 'w', vNone); ip('xout', 's', vNone); ip('xoutln', 's', vNone); ip('aout', 's', vNone); ip('showtext', 's', vBool); ip('showfile', 's', vBool); ip('fline', '', vNone); ip('wherex', '', vByte); ip('wherey', '', vByte); iw := 40; { input routines } ip('inkey', '', vStr); ip('instr', 'ssssb', vStr); ip('instrf', 'ssssbb', vStr); ip('keypressed', '', vBool); ip('indate', 's', vStr); ip('intime', 's', vStr); ip('inphone', 's', vStr); ip('inpostal', '', vStr); ip('inzipcode', '', vStr); ip('inyesno', 'o', vBool); iw := 60; { string funtions } ip('strup', 's', vStr); ip('strlow', 's', vStr); ip('stryesno', 'o', vStr); ip('strpos', 'ss', vByte); ip('strtrim', 's', vStr); ip('strmixed', 's', vStr); ip('strnocol', 's', vStr); ip('strsize', 'sb', vStr); ip('strsizenc', 'sb', vStr); ip('strsizer', 'sb', vStr); ip('strint', 'l', vStr); ip('strreal', 'rbb', vStr); ip('strintc', 'l', vStr); ip('strsquish', 'sb', vStr); ip('strreplace', 'sss', vStr); ip('strcopy', 'sbb', vStr); ip('strdel', 'sbb', vStr); ip('strrepeat', 'sb', vStr); iw := 80; { ipl-related routines } ip('iplver', '', vStr); ip('iplname', '', vStr); ip('iplpar', 'b', vStr); ip('iplnumpar', '', vByte); { user manipulation } iw := 90; ip('userget', '', vNone); ip('userput', '', vNone); ip('userload', 'w', vNone); ip('usersave', '', vNone); iw := 200; { user-record variables } xUstart := x+1; iv('unumber', vInt); is('uhandle', vStr, 36); is('urealname', vStr, 36); is('upassword', vStr, 20); is('uphone', vStr, 13); is('ubdate', vStr, 8); is('ulocation', vStr, 40); is('uaddress', vStr, 36); is('unote', vStr, 40); is('usex', vStr, 1); iv('usl', vByte); iv('udsl', vByte); iv('ubaud', vLong); iv('ucalls', vWord); iv('umsgarea', vWord); iv('ufilearea', vWord); { acflag !! } { colors!! } is('ulastcall', vStr, 8); iv('upagelen', vWord); iv('uemail', vWord); is('ulevel', vStr, 1); iv('usiglines', vByte); is('uautosig', vStr, maxSigLines*81-1); cV[x]^.arr := 1; {$IFDEF ipx} cV[x]^.size := 81; cV[x]^.arrdim[1] := maxSigLines; {$ENDIF} iv('umsgconf', vByte); iv('ufileconf', vByte); is('ufirstcall', vStr, 8); is('ustartmenu', vStr, 8); is('usysopnote', vStr, 40); iv('uposts', vWord); iv('uemail', vWord); iv('uuploads', vWord); iv('udownloads', vWord); iv('uuploadkb', vWord); iv('udownloadkb', vWord); iv('ucallst', vWord); { flags!! } iv('ufilepts', vWord); iv('udownloadt', vWord); iv('udlkbt', vWord); iv('utextlib', vByte); is('uzipcode', vStr, 10); iv('uvoteyes', vByte); iv('uvoteno', vByte); iw := 250; { internal variables - non-killable } ivp('remoteout', vBool, 1, @RemoteOut); ivp('remotein', vBool, 1, @RemoteIn); ivp('localio', vBool, 1, @LocalIO); ivp('modemio', vBool, 1, @ModemIO); ivp('useron', vBool, 1, @UserOn); ivp('loggedin', vBool, 1, @LoggedIn); ivp('screenoff', vBool, 1, @ScreenOff); ivp('tempsysop', vBool, 1, @TempSysOp); ivp('quitafter', vBool, 1, @QuitAfter); ivp('keylocal', vBool, 1, @LocKey); ivp('usetag', vBool, 1, @useTag); ivp('timecheck', vBool, 1, @timeCheck); ivp('asdoor', vBool, 1, @asDoor); ivp('mconfall', vBool, 1, @mandMsg); ivp('fconfall', vBool, 1, @fConfAll); ivp('node', vByte, 1, @Node); ivp('numbatch', vByte, 1, @numBatch); ivp('chatreason', vStr, 255, @ChatReason); ivp('inputstring',vStr, 255, @inputString); ivp('numevent', vWord, 2, @numEvent); ivp('nummarea', vWord, 2, @numMsgArea); ivp('numfarea', vWord, 2, @numFileArea); ivp('numusers', vWord, 2, @numUsers); ivp('nummconf', vWord, 2, @numMsgConf); ivp('numfconf', vWord, 2, @numFileConf); ivp('numtlib', vWord, 2, @numLib); ivp('numiform', vWord, 2, @numInfo); ivp('emailtag', vWord, 2, @emailTag); ivp('readtag', vWord, 2, @readTag); iw := 300; end;
{*! * Fano Web Framework (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano * @copyright Copyright (c) 2018 Zamrony P. Juhara * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) *} unit TemplateStrViewImpl; interface {$MODE OBJFPC} {$H+} uses HeadersIntf, ResponseIntf, ViewParametersIntf, ViewIntf, OutputBufferIntf, TemplateViewImpl, TemplateParserIntf; type (*!------------------------------------------------ * View that can render from a HTML template in * pascal variable/const/resource string * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-------------------------------------------------*) TTemplateStrFileView = class(TTemplateView) protected (*!------------------------------------------------ * Build template *------------------------------------------------- * @return HTML template *-------------------------------------------------*) function buildTemplateStr(): string; virtual; abstract; public constructor create( const hdrs : IHeaders; const outputBufferInst : IOutputBuffer; const templateParserInst : ITemplateParser ); end; implementation constructor TTemplateStrFileView.create( const hdrs : IHeaders; const outputBufferInst : IOutputBuffer; const templateParserInst : ITemplateParser ); begin inherited create( hdrs, outputBufferInst, templateParserInst, buildTemplateStr() ); end; end.
{$MODE OBJFPC} { -*- delphi -*- } {$INCLUDE settings.inc} unit world; interface uses plasticarrays, genericutils, provinces, players; type TPerilDataFeatures = (pdfProvinces, pdfPlayers, pdfTurnNumber); TPerilDataFeaturesSet = set of TPerilDataFeatures; TPerilWorld = class abstract protected type TPlayerArray = specialize PlasticArray <TPlayer, TObjectUtils>; protected FProvinces: TProvinceHashTable; FPlayers: TPlayerIDHashTable; FTurnNumber: Cardinal; function CountProvinces(): Cardinal; procedure AddProvince(const Province: TProvince); function CountPlayers(): Cardinal; function Serialise(const Player: TPlayer = nil): UTF8String; // outputs JSON of the world public constructor Create(); destructor Destroy(); override; procedure LoadData(const FileName: AnsiString; const Features: TPerilDataFeaturesSet); procedure SaveData(const Directory: AnsiString); property PlayerCount: Cardinal read CountPlayers; property ProvinceCount: Cardinal read CountProvinces; end; TPerilWorldCreator = class(TPerilWorld) public procedure DistributePlayers(); procedure RandomiseIDs(); end; TPerilWorldTurn = class(TPerilWorld) protected type TMoveAction = record Player: TPlayer; Source, Dest: TProvince; Count: Cardinal; end; TActionArray = specialize PlasticArray <TMoveAction, specialize IncomparableUtils <TMoveAction>>; protected FInstructions: TActionArray; public procedure LoadInstructions(const Directory: AnsiString); procedure ExecuteInstructions(); end; implementation uses sysutils, fileutils, arrayutils, exceptions, json, stringrecorder; constructor TPerilWorld.Create(); begin FProvinces := TProvinceHashTable.Create(); FPlayers := TPlayerIDHashTable.Create(); end; destructor TPerilWorld.Destroy(); var Province: TProvince; Player: TPlayer; begin try for Province in FProvinces.Values do // $R- begin Assert(Assigned(Province)); Province.Free(); end; except Writeln('Failure during TPerilWorld.Destroy(), freeing provinces:'); ReportCurrentException(); end; try FProvinces.Free(); except Writeln('Failure during TPerilWorld.Destroy(), freeing provinces hash table:'); ReportCurrentException(); end; try for Player in FPlayers.Values do // $R- begin Assert(Assigned(Player)); Player.Free(); end; except Writeln('Failure during TPerilWorld.Destroy(), freeing players:'); ReportCurrentException(); end; try FPlayers.Free(); except Writeln('Failure during TPerilWorld.Destroy(), freeing players hash table:'); ReportCurrentException(); end; end; procedure TPerilWorld.LoadData(const FileName: AnsiString; const Features: TPerilDataFeaturesSet); function IsValidPlayerID(PlayerID: UTF8String): Boolean; var Index: Cardinal; begin Result := False; if (Length(PlayerID) > 10) then exit; if (Length(PlayerID) < 1) then exit; for Index := 1 to Length(PlayerID) do // $R- if (not (PlayerID[Index] in ['a'..'z'])) then exit; Result := True; end; var ParsedData, ProvinceData, NeighbourData, PlayerData: TJSON; Owner: TPlayer; ProvinceIndex, NeighbourIndex: Cardinal; ID, Troops: Cardinal; OwnerID, PlayerID, PlayerName: UTF8String; begin ParsedData := ParseJSON(ReadTextFile(FileName)); try if (pdfPlayers in Features) then begin Assert(FPlayers.Count = 0); if (Assigned(ParsedData['Players'])) then begin for PlayerData in ParsedData['Players'] do begin if (not Assigned(PlayerData['ID'])) then raise Exception.Create('syntax error: missing player ID'); PlayerID := PlayerData['ID']; if (not IsValidPlayerID(PlayerID)) then raise Exception.Create('syntax error: invalid player ID'); if (FPlayers.Has(PlayerID)) then raise Exception.Create('syntax error: duplicate player ID'); if (Assigned(PlayerData['Name'])) then PlayerName := PlayerData['Name'] else PlayerName := ''; FPlayers[PlayerID] := TPlayer.Create(PlayerName, PlayerID); end; end; end; if (pdfProvinces in Features) then begin Assert(FProvinces.Count = 0); if (Assigned(ParsedData['Provinces'])) then begin for ProvinceData in ParsedData['Provinces'] do begin if (Assigned(ProvinceData['ID'])) then ID := ProvinceData['ID'] else ID := FProvinces.Count; Owner := nil; if (Assigned(ProvinceData['Owner'])) then begin OwnerID := ProvinceData['Owner']; if ((not IsValidPlayerID(OwnerID)) or (not FPlayers.Has(OwnerID))) then raise Exception.Create('syntax error: reference to undeclared player'); Owner := FPlayers[OwnerID]; end; Troops := 0; if (Assigned(Owner) and Assigned(ProvinceData['Troops'])) then Troops := ProvinceData['Troops']; AddProvince(TProvince.Create(ProvinceData['Name'], ID, Owner, Troops)); end; ProvinceIndex := 0; for ProvinceData in ParsedData['Provinces'] do begin if (Assigned(ProvinceData['ID'])) then ID := ProvinceData['ID'] else ID := ProvinceIndex; Assert(FProvinces.Has(ID)); for NeighbourData in ProvinceData['Neighbours'] do begin NeighbourIndex := NeighbourData; if (not FProvinces.Has(NeighbourIndex)) then raise Exception.Create('syntax error: unknown neighbour ID'); FProvinces[ID].AddNeighbour(FProvinces[NeighbourIndex]); end; Inc(ProvinceIndex); end; end; end; if (pdfTurnNumber in Features) then begin if (Assigned(ParsedData['Turn'])) then FTurnNumber := ParsedData['Turn']; end; finally ParsedData.Free(); end; end; procedure TPerilWorld.AddProvince(const Province: TProvince); begin FProvinces[Province.ID] := Province; end; function TPerilWorld.Serialise(const Player: TPlayer = nil): UTF8String; var Province, Neighbour: TProvince; CurrentPlayer: TPlayer; Neighbours: TProvince.TReadOnlyArray; Writer: TJSONWriter; Index, SubIndex: Cardinal; Recorder: TStringRecorderForStrings; begin // XXX this is very inefficient Writer := TJSONWriter.Create(); Writer['Turn'].SetValue(FTurnNumber); if (Assigned(Player)) then Writer['Player'].SetValue(Player.ID); Index := 0; for Province in FProvinces.Values do // $R- begin if (Assigned(Player) and not Province.CanBeSeenBy(Player)) then continue; Writer['Provinces'][Index]['ID'].SetValue(Province.ID); Writer['Provinces'][Index]['Name'].SetValue(Province.Name); if (Assigned(Province.Owner)) then begin Writer['Provinces'][Index]['Owner'].SetValue(Province.Owner.ID); Writer['Provinces'][Index]['Troops'].SetValue(Province.ResidentTroopPopulation); end; if (not Assigned(Player) or Province.NeighboursCanBeSeenBy(Player)) then begin Neighbours := Province.GetNeighbours(); try SubIndex := 0; for Neighbour in Neighbours do // $R- begin Writer['Provinces'][Index]['Neighbours'][SubIndex].SetValue(Neighbour.ID); Inc(SubIndex); end; finally Neighbours.Free(); end; end; Inc(Index); end; Index := 0; for CurrentPlayer in FPlayers.Values do // $R- begin Writer['Players'][Index]['Name'].SetValue(CurrentPlayer.Name); Writer['Players'][Index]['ID'].SetValue(CurrentPlayer.ID); Inc(Index); end; Recorder := TStringRecorderForStrings.Create(); Writer.Serialise(Recorder); Result := Recorder.Value; Recorder.Free(); Writer.Free(); end; procedure TPerilWorld.SaveData(const Directory: AnsiString); var Player: TPlayer; begin WriteTextFile(Directory + '/server.json', Serialise()); for Player in FPlayers.Values do // $R- WriteTextFile(Directory + '/state-for-player-' + Player.ID + '.json', Serialise(Player)); end; function TPerilWorld.CountProvinces(): Cardinal; begin Result := FProvinces.Count; end; function TPerilWorld.CountPlayers(): Cardinal; begin Result := FPlayers.Count; end; procedure TPerilWorldCreator.DistributePlayers(); var Index: Cardinal; ProvinceList: array of TProvince; Province: TProvince; Player: TPlayer; begin Assert(FProvinces.Count > 0); Assert(FPlayers.Count > 0); Assert(FPlayers.Count < FProvinces.Count); SetLength(ProvinceList, FProvinces.Count); Index := 0; for Province in FProvinces.Values do begin ProvinceList[Index] := Province; Inc(Index); end; // randomly assign players to provinces FisherYatesShuffle(ProvinceList[0], Length(ProvinceList), SizeOf(TProvince)); // $R- Index := 0; for Player in FPlayers.Values do // $R- begin ProvinceList[Index].AssignInitialPlayer(Player); Inc(Index); end; FTurnNumber := 1; end; procedure TPerilWorldCreator.RandomiseIDs(); var Province: TProvince; NewTable: TProvinceHashTable; begin NewTable := TProvinceHashTable.Create(); for Province in FProvinces.Values do // $R- begin Province.SetID(NewTable.GetNewID()); NewTable.Add(Province.ID, Province); end; FProvinces.Free(); FProvinces := NewTable; end; procedure TPerilWorldTurn.LoadInstructions(const Directory: AnsiString); var Player: TPlayer; ParsedData, ParsedAction: TJSON; Action: TMoveAction; begin for Player in FPlayers.Values do // $R- begin try ParsedData := ParseJSON(ReadTextFile(Directory + '/actions-for-player-' + Player.ID + '.json')); try if (Assigned(ParsedData['Actions'])) then begin for ParsedAction in ParsedData['Actions'] do begin try if (ParsedAction['Action'] = 'move') then begin Action.Player := Player; Action.Source := FProvinces[ParsedAction['From']]; if (not (Assigned(Action.Source))) then raise ESyntaxError.Create('unknown "from"'); if (Action.Source.Owner <> Player) then raise ESyntaxError.Create('unknown "from"'); if (not Action.Source.CanBeSeenBy(Player)) then raise ESyntaxError.Create('unknown "from"'); Action.Dest := FProvinces[ParsedAction['To']]; if (not Assigned(Action.Dest)) then raise ESyntaxError.Create('unknown "to"'); if (not Action.Source.HasNeighbour(Action.Dest)) then raise ESyntaxError.Create('unknown "to"'); if (not Action.Dest.CanBeSeenBy(Player)) then raise ESyntaxError.Create('unknown "to"'); if (Action.Source = Action.Dest) then raise ESyntaxError.Create('"from" and "to" are the same'); Action.Count := ParsedAction['Count']; if (not Action.Source.CommitTroops(Action.Count, Player)) then raise ESyntaxError.Create('overcommited troops'); FInstructions.Push(Action); end else begin // Ignore this action, it's an unsupported or bogus type raise ESyntaxError.Create('unknown "action"'); end; except on E: Exception do begin Writeln('Failed to parse action in instructions from ', Player.Name); ReportCurrentException(); end; end; end; end; finally ParsedData.Free(); end; except on E: Exception do begin Writeln('Failed to parse instructions from ', Player.Name); ReportCurrentException(); end; end; end; end; procedure TPerilWorldTurn.ExecuteInstructions(); var Action: TMoveAction; Province: TProvince; begin Inc(FTurnNumber); for Action in FInstructions do Action.Dest.ReceiveTroops(Action.Count, Action.Player); for Province in FProvinces.Values do Province.ResolveBattles(); for Province in FProvinces.Values do Province.EndTurn(); end; end.
unit untEasyDesignerGridPopuMenuReg; {$I cxGridUtils.inc} interface uses Windows, Messages, SysUtils, Classes; procedure DesignerGridPopuMenuRegRegister; implementation uses {$IFDEF DELPHI6} Types, DesignIntf, DesignEditors, {$ELSE} DsgnIntf, {$ENDIF} cxGridPopupMenu, cxGridCustomPopUpMenu, cxGridReg, TypInfo, Dialogs; type TcxGridPopupMenuEditor = class(TComponentEditor) public function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TcxGridPopupMenuProperty = class(TComponentProperty) private FGetValuesStrProc: TGetStrProc; protected procedure ReceiveComponentNames(const S: string); public procedure GetValues(Proc: TGetStrProc); override; end; procedure DesignerGridPopuMenuRegRegister; begin RegisterPropertyEditor(TypeInfo(TComponent), TcxPopupMenuInfo, 'PopupMenu', TcxGridPopupMenuProperty); RegisterComponentEditor(TcxGridPopupMenu, TcxGridPopupMenuEditor); RegisterComponents('Easy Grid', [TcxGridPopupMenu]); end; { TcxGridPopupMenuEditor } function TcxGridPopupMenuEditor.GetVerb(Index: Integer): string; begin case Index of 0: Result := 'ExpressQuantumGrid Suite v' + cxGridVersion; 1: Result := 'www.devexpress.com'; end; end; function TcxGridPopupMenuEditor.GetVerbCount: Integer; begin Result := 2; end; { TcxGridPopupMenuProperty } procedure TcxGridPopupMenuProperty.GetValues(Proc: TGetStrProc); begin FGetValuesStrProc := Proc; try Designer.GetComponentNames(GetTypeData(GetPropType), ReceiveComponentNames); finally FGetValuesStrProc := nil; end; end; procedure TcxGridPopupMenuProperty.ReceiveComponentNames(const S: string); var AComponent: TComponent; Intf: IUnknown; begin AComponent := Designer.GetComponent(S); if Assigned(FGetValuesStrProc) and Assigned(AComponent) and ( {$IFDEF DELPHI5} Supports(AComponent, IDoPopup, Intf) {$ELSE} (AComponent.GetInterface(IDoPopup, Intf) and (Intf <> nil)) {$ENDIF} or (AComponent.ClassName = 'TPopupMenu') or (AComponent.ClassName = 'TdxBarPopupMenu')) then FGetValuesStrProc(S); end; initialization DesignerGridPopuMenuRegRegister; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Objects {$IFDEF ANDROID} , Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes, Androidapi.Helpers, Androidapi.JNI.Net, FMX.Surfaces, System.IOUtils, xPlat.OpenPDF, FMX.Helpers.Android {$ENDIF} ; type TForm1 = class(TForm) ToolBar1: TToolBar; Button1: TButton; Image1: TImage; procedure Button1Click(Sender: TObject); private {$IFDEF ANDROID} function FileNameToURI(const Filename: string): Jnet_Uri; function CMToPixel(const ACentimeter: Double): Double; {$ENDIF} { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} {$IFDEF ANDROID} function TForm1.FileNameToURI(const Filename: string): Jnet_Uri; var JavaFile : JFile; begin JavaFile := TJFile.JavaClass.init(StringToJString(FileName)); Result := TJnet_Uri.JavaClass.fromFile(JavaFile); end; function TForm1.CMToPixel(const ACentimeter: Double): Double; var iPPI : Double; begin iPPI := TDeviceDisplayMetrics.Default.PixelsPerInch / 2.54; Result := Round(iPPI * ACentimeter); end; {$ENDIF} procedure TForm1.Button1Click(Sender: TObject); {$IFDEF ANDROID} var Documento : JPdfDocument; PageInfo : JPdfDocument_PageInfo; Page : JPdfDocument_Page; Canvas : JCanvas; Paint : JPaint; Recto : JRect; Rect : JRect; Filename : string; OutputStream : JFileOutputStream; Intent : JIntent; NativeBitmap : JBitmap; sBitmap : TBitmapSurface; begin Documento := TJPdfDocument.JavaClass.init; try //Página 1 PageInfo := TJPageInfo_Builder.JavaClass.init(595, 842, 1).Create; Page := Documento.startPage(PageInfo); Canvas := Page.getCanvas; Paint := TJPaint.JavaClass.init; Paint.setARGB($FF, 0, 0, $FF); Canvas.drawText(StringToJString('Texto 1') , CMToPixel(2), CMToPixel(2), Paint); Canvas.drawText(StringToJString('Texto 2') , CMToPixel(3), CMToPixel(3), Paint); Canvas.drawText(StringToJString('Texto 3') , CMToPixel(4), CMToPixel(4), Paint); Canvas.drawText(StringToJString('Texto 4'), CMToPixel(10), CMToPixel(10), Paint); Documento.finishPage(Page); //Página 2 PageInfo := TJPageInfo_Builder.JavaClass.init(595, 842, 2).Create; Page := Documento.startPage(PageInfo); Canvas := Page.getCanvas; Paint := TJPaint.JavaClass.init; //Linha 1 Paint.setARGB($FF, $FF, 0, 0); Canvas.drawLine(10, 10, 90, 10, Paint); //Linha 2 Paint.setStrokeWidth(1); Paint.setARGB($FF, 0, $FF, 0); Canvas.drawLine(10, 20, 90, 20, Paint); Paint.setStrokeWidth(2); Paint.setARGB($FF, 0, 0, $FF); Canvas.drawLine(10, 30, 90, 30, Paint); Paint.setARGB($FF, $FF, $FF, 0); Canvas.drawRect(10, 40, 90, 60, Paint); Rect := TJRect.JavaClass.init; Rect.&set(15, 50, 65, 100); Recto := TJRect.JavaClass.init; Recto.&set(0, 0, Image1.Bitmap.Width, Image1.Bitmap.Height); Paint.setARGB($FF, $FF, 0, $FF); NativeBitmap := TJBitmap.JavaClass.createBitmap(Image1.Bitmap.Width, Image1.Bitmap.Height, TJBitmap_Config.JavaClass.ARGB_8888); sBitMap := TBitmapSurface.create; sBitMap.Assign(Image1.Bitmap); SurfaceToJBitmap(sBitMap, NativeBitmap); Canvas.drawBitmap(NativeBitmap, Recto, Rect, Paint); Documento.finishPage(Page); Filename := TPath.Combine(TPath.GetSharedDocumentsPath, 'Demo.pdf'); OutputStream := TJFileOutputStream.JavaClass.init(StringToJString(Filename)); try Documento.writeTo(OutputStream); finally OutputStream.close; end; finally Documento.close; end; Intent := TJIntent.JavaClass.init; Intent.setAction(TJIntent.JavaClass.ACTION_VIEW); Intent.setDataAndType(FileNameToUri(FileName), StringToJString('application/pdf')); Intent.setFlags(TJIntent.JavaClass.FLAG_ACTIVITY_NO_HISTORY or TJIntent.JavaClass.FLAG_ACTIVITY_CLEAR_TOP); SharedActivity.StartActivity(Intent); {$ELSE} ShowMessage('Função funciona somente em Android'); {$ENDIF} end; end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit Unit1; interface uses Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Controls, SysUtils, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private hrc: HGLRC; Pixel : Array [0..50, 0..50, 0..2] of GLUbyte; end; var frmGL: TfrmGL; implementation {$R *.DFM} {======================================================================= Перерисовка окна} procedure TfrmGL.FormPaint(Sender: TObject); var i : 1..30000; begin wglMakeCurrent(Canvas.Handle, hrc); glViewPort (0, 0, ClientWidth, ClientHeight); // область вывода glClear (GL_COLOR_BUFFER_BIT); // очистка буфера цвета glColor3f (1.0, 1.0, 1.0); For i := 1 to 30000 do begin glPointSize (random * 3); glBegin (GL_POINTS); glVertex2f (random * 4 - 2, random * 4 - 2); glVertex2f (random * 4 - 2, random * 4 - 2); glEnd; end; glReadPixels(round(ClientWidth / 2), round(ClientHeight / 2), 50, 50, GL_RGB, GL_UNSIGNED_BYTE, @Pixel); glRasterPos2f (-0.5, 0.0); glDrawPixels(50, 50, GL_RGB, GL_UNSIGNED_BYTE, @Pixel); glRasterPos2f (-0.25, 0.0); glDrawPixels(50, 50, GL_RGB, GL_UNSIGNED_BYTE, @Pixel); glRasterPos2f (0.0, 0.0); glDrawPixels(50, 50, GL_RGB, GL_UNSIGNED_BYTE, @Pixel); glRasterPos2f (0.25, 0.0); glDrawPixels(50, 50, GL_RGB, GL_UNSIGNED_BYTE, @Pixel); glRasterPos2f (-0.5, -0.25); glDrawPixels(50, 50, GL_RGB, GL_UNSIGNED_BYTE, @Pixel); glRasterPos2f (-0.25, -0.25); glDrawPixels(50, 50, GL_RGB, GL_UNSIGNED_BYTE, @Pixel); glRasterPos2f (0.0, -0.25); glDrawPixels(50, 50, GL_RGB, GL_UNSIGNED_BYTE, @Pixel); glRasterPos2f (0.25, -0.25); glDrawPixels(50, 50, GL_RGB, GL_UNSIGNED_BYTE, @Pixel); SwapBuffers(Canvas.Handle); // содержимое буфера - на экран wglMakeCurrent(0, 0); end; {======================================================================= Формат пикселя} procedure SetDCPixelFormat (hdc : HDC); var pfd : TPixelFormatDescriptor; nPixelFormat : Integer; begin FillChar (pfd, SizeOf (pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat (hdc, @pfd); SetPixelFormat (hdc, nPixelFormat, @pfd); end; {======================================================================= Создание формы} procedure TfrmGL.FormCreate(Sender: TObject); begin Randomize; SetDCPixelFormat(Canvas.Handle); hrc := wglCreateContext(Canvas.Handle); end; {======================================================================= Конец работы приложения} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglDeleteContext(hrc); end; procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close; If Key = VK_SPACE then Refresh; end; end.
namespace RemObjects.SDK.CodeGen4; interface uses RemObjects.Elements.RTL; type RodlCodeGen = public abstract class protected CodeGenTypes: Dictionary<String, CGTypeReference>:= new Dictionary<String, CGTypeReference>; ReaderFunctions: Dictionary<String, String>:= new Dictionary<String, String>; ReservedWords: List<String> := new List<String>; PredefinedTypes: Dictionary<CGPredefinedTypeKind, CGTypeReference>:= new Dictionary<CGPredefinedTypeKind, CGTypeReference>; property targetNamespace: String; {$REGION support methods} method ResolveDataTypeToTypeRef(library: RodlLibrary; dataType: String): CGTypeReference; method ResolveStdtypes(&type: CGPredefinedTypeReference; isNullable: Boolean := false; isNotNullable: Boolean := false): CGTypeReference; method EntityNeedsCodeGen(entity: RodlEntity): Boolean; method PascalCase(name:String):String; method isStruct(library: RodlLibrary; dataType: String): Boolean; method isEnum(library: RodlLibrary; dataType: String): Boolean; method isArray(library: RodlLibrary; dataType: String): Boolean; method isException(library: RodlLibrary; dataType: String): Boolean; method isComplex(library: RodlLibrary; dataType: String): Boolean; virtual; method isBinary(dataType: String): Boolean; method IsAnsiString(dataType: String): Boolean; method IsUTF8String(dataType: String): Boolean; method FindEnum(&library: RodlLibrary; dataType: String): nullable RodlEnum; method SafeIdentifier(aValue: String): String; method EscapeString(aString:String):String; method Operation_GetAttributes(library: RodlLibrary; operation: RodlOperation): Dictionary<String,String>; method GenerateEnumMemberName(library: RodlLibrary; entity: RodlEnum; member: RodlEnumValue): String; method CleanedWsdlName(aName: String): String; {$ENDREGION} method GenerateDocumentation(entity: RodlEntity; aGenerateOperationMembersDoc: Boolean := False): CGCommentStatement; method DoGenerateInterfaceFile(library: RodlLibrary; aTargetNamespace: String; aUnitName: String := nil): CGCodeUnit; virtual; method AddUsedNamespaces(file: CGCodeUnit; library: RodlLibrary);virtual; empty; method AddGlobalConstants(file: CGCodeUnit; library: RodlLibrary);virtual; empty; method GenerateEnum(file: CGCodeUnit; library: RodlLibrary; entity: RodlEnum); virtual; method GenerateStruct(file: CGCodeUnit; library: RodlLibrary; entity: RodlStruct);virtual; empty; method GenerateArray(file: CGCodeUnit; library: RodlLibrary; entity: RodlArray);virtual; empty; method GenerateException(file: CGCodeUnit; library: RodlLibrary; entity: RodlException);virtual; empty; method GenerateService(file: CGCodeUnit; library: RodlLibrary; entity: RodlService);virtual; empty; method GenerateEventSink(file: CGCodeUnit; library: RodlLibrary; entity: RodlEventSink);virtual; empty; method GenerateUnitComment(isImpl: Boolean): CGCommentStatement; virtual; method GetNamespace(library: RodlLibrary): String; virtual; method GetIncludesNamespace(library: RodlLibrary): String; virtual; empty; method GetGlobalName(library: RodlLibrary): String; abstract; property EnumBaseType: CGTypeReference read ResolveStdtypes(CGPredefinedTypeReference.UInt32); virtual; public class property KnownRODLPaths: Dictionary<String,String> := new Dictionary<String,String>; property Generator: CGCodeGenerator; virtual; property DontPrefixEnumValues: Boolean := True; virtual; property CodeUnitSupport: Boolean := True; virtual; property RodlFileName: String :=''; method GenerateInterfaceCodeUnit(library: RodlLibrary; aTargetNamespace: String; aUnitName: String := nil): CGCodeUnit; virtual; method GenerateInvokerCodeUnit(library: RodlLibrary; aTargetNamespace: String; aUnitName: String := nil): CGCodeUnit; virtual; method GenerateImplementationCodeUnit(library: RodlLibrary; aTargetNamespace: String; aServiceName: String): CGCodeUnit; virtual; method GenerateInterfaceFile(library: RodlLibrary; aTargetNamespace: String; aUnitName: String := nil): not nullable String; virtual; method GenerateInterfaceFiles(library: RodlLibrary; aTargetNamespace: String): not nullable Dictionary<String,String>; virtual; method GenerateInvokerFile(library: RodlLibrary; aTargetNamespace: String; aUnitName: String := nil): not nullable String; virtual; method GenerateImplementationFiles(library: RodlLibrary; aTargetNamespace: String; aServiceName: String): not nullable Dictionary<String,String>;virtual; method GenerateImplementationFiles(file: CGCodeUnit; library: RodlLibrary; aServiceName: String): not nullable Dictionary<String,String>;virtual; end; CompareFunc<T,U> = method(Value:T):U; extension method List<T>.Sort_OrdinalIgnoreCase(cond: CompareFunc<T,String>): List<T>;assembly; implementation extension method List<T>.Sort_OrdinalIgnoreCase(cond: CompareFunc<T,String>): List<T>; begin var r:= new List<T>; r.Add(Self); r.Sort((x,y)-> begin var x1 := cond(x); var y1 := cond(y); if (x1 = nil) and (y1 = nil) then exit 0; if (x1 = nil) then exit -1; if (y1 = nil) then exit 1; x1 := x1.ToUpperInvariant; y1 := y1.ToUpperInvariant; var min_length := iif(x1.Length > y1.Length, y1.Length, x1.Length); for i: Integer :=0 to min_length-1 do begin if x1[i] > y1[i] then exit 1; if x1[i] < y1[i] then exit -1; end; exit x1.Length - y1.Length; end); exit r; end; method RodlCodeGen.GenerateInterfaceFile(&library: RodlLibrary; aTargetNamespace: String; aUnitName: String := nil): not nullable String; begin exit Generator.GenerateUnit(GenerateInterfaceCodeUnit(library, aTargetNamespace, aUnitName)); end; method RodlCodeGen.GenerateInterfaceFiles(library: RodlLibrary; aTargetNamespace: String): not nullable Dictionary<String,String>; begin raise new Exception("not supported"); { var lunit := DoGenerateInterfaceFile(library, aTargetNamespace); result := new Dictionary<String,String>; result.Add(lunit.FileName, Generator.GenerateUnit(lunit)); } end; {$REGION support methods} method RodlCodeGen.EntityNeedsCodeGen(entity: RodlEntity): Boolean; begin if entity.DontCodegen then exit false; Result := not (entity.IsFromUsedRodl or (entity.FromUsedRodlId ≠ Guid.Empty)); if (not Result) then begin Result := (entity.FromUsedRodl = nil); if (not Result) then Result := not entity.FromUsedRodl.DontApplyCodeGen; end; end; method RodlCodeGen.PascalCase(name: String): String; begin case name:Length of 0: Result := ''; 1: Result := name.ToUpperInvariant; else Result := name.Substring(0,1).ToUpperInvariant + name.Substring(1); end; end; method RodlCodeGen.isStruct(&library: RodlLibrary; dataType: String): Boolean; begin var lEntity: RodlEntity := library.FindEntity(dataType); exit assigned(lEntity) and (lEntity is RodlStruct); end; method RodlCodeGen.isEnum(&library: RodlLibrary; dataType: String): Boolean; begin var lEntity: RodlEntity := library.FindEntity(dataType); exit assigned(lEntity) and (lEntity is RodlEnum); end; method RodlCodeGen.FindEnum(&library: RodlLibrary; dataType: String): nullable RodlEnum; begin var lEntity: RodlEntity := library.FindEntity(dataType); result := RodlEnum(lEntity); end; method RodlCodeGen.isArray(&library: RodlLibrary; dataType: String): Boolean; begin var lEntity: RodlEntity := library.FindEntity(dataType); exit (assigned(lEntity) and (lEntity is RodlArray)) or dataType.ToLowerInvariant.EndsWith("array"); end; method RodlCodeGen.isException(&library: RodlLibrary; dataType: String): Boolean; begin var lEntity: RodlEntity := library.FindEntity(dataType); exit assigned(lEntity) and (lEntity is RodlException); end; method RodlCodeGen.isComplex(&library: RodlLibrary; dataType: String): Boolean; begin if not assigned(library) then exit false; var lEntity: RodlEntity := library.FindEntity(dataType); exit assigned(lEntity) and ( (lEntity is RodlStruct) or (lEntity is RodlArray) or (lEntity is RodlException) or (lEntity is RodlService) or (lEntity is RodlEventSink) ); end; method RodlCodeGen.SafeIdentifier(aValue: String): String; begin exit iif(ReservedWords.IndexOf(aValue) < 0, aValue , '_' + aValue); end; method RodlCodeGen.EscapeString(aString: String): String; begin exit aString.Replace('\','\\').Replace('"','\"'); end; method RodlCodeGen.ResolveStdtypes(&type: CGPredefinedTypeReference; isNullable: Boolean := false; isNotNullable: Boolean := false): CGTypeReference; begin if PredefinedTypes.ContainsKey(&type.Kind) then exit PredefinedTypes[&type.Kind] else if isNullable then exit &type.NullableNotUnwrapped else if isNotNullable then exit &type.NotNullable else exit &type end; method RodlCodeGen.ResolveDataTypeToTypeRef(&library: RodlLibrary; dataType: String): CGTypeReference; begin var lLower := dataType.ToLowerInvariant(); if CodeGenTypes.ContainsKey(lLower) then exit CodeGenTypes[lLower] else exit dataType.AsTypeReference(not isEnum(library, dataType)); end; method RodlCodeGen.Operation_GetAttributes(&library: RodlLibrary; operation: RodlOperation): Dictionary<String, String>; begin result := new Dictionary<String,String>; for k: String in operation.CustomAttributes.Keys do result[k] := operation.CustomAttributes[k]; for k: String in operation.Owner.Owner.CustomAttributes.Keys do result[k] := operation.Owner.Owner.CustomAttributes[k]; for k: String in library.CustomAttributes.Keys do result[k] := library.CustomAttributes[k]; end; method RodlCodeGen.isBinary(dataType: String): Boolean; begin exit dataType.EqualsIgnoringCaseInvariant('binary'); end; method RodlCodeGen.IsAnsiString(dataType: String): Boolean; begin exit dataType.EqualsIgnoringCaseInvariant('AnsiString'); end; method RodlCodeGen.IsUTF8String(dataType: String): Boolean; begin exit dataType.EqualsIgnoringCaseInvariant('UTF8String'); end; method RodlCodeGen.CleanedWsdlName(aName: String): String; begin if aName.StartsWith('___') then aName := aName.Substring(3); result := aName; end; {$ENDREGION} method RodlCodeGen.GenerateEnum(file: CGCodeUnit; &library: RodlLibrary; entity: RodlEnum); begin var lenum := new CGEnumTypeDefinition(SafeIdentifier(entity.Name), Visibility := CGTypeVisibilityKind.Public, BaseType := EnumBaseType); lenum.Comment := GenerateDocumentation(entity); file.Types.Add(lenum); for enummember: RodlEnumValue in entity.Items index i do begin var lname := GenerateEnumMemberName(library, entity, enummember); var lenummember :=new CGEnumValueDefinition(lname, i.AsLiteralExpression); lenummember.Comment := GenerateDocumentation(enummember); lenum.Members.Add(lenummember); end; end; method RodlCodeGen.GenerateUnitComment(isImpl: Boolean): CGCommentStatement; begin var list:= New List<String>; if isImpl then begin list.Add("----------------------------------------------------------------------"); list.Add(" This file was automatically generated by Remoting SDK from a"); list.Add(" RODL file downloaded from a server or associated with this project."); list.Add(""); list.Add(" This is where you are supposed to code the implementation of your objects."); list.Add("----------------------------------------------------------------------"); end else begin list.Add("----------------------------------------------------------------------"); list.Add(" This file was automatically generated by Remoting SDK from a"); list.Add(" RODL file downloaded from a server or associated with this project."); list.Add(""); list.Add(" Do not modify this file manually, or your changes will be lost when"); list.Add(" it is regenerated the next time you update your RODL."); list.Add("----------------------------------------------------------------------"); end; exit new CGCommentStatement(list); end; method RodlCodeGen.GenerateInvokerFile(&library: RodlLibrary; aTargetNamespace: String; aUnitName: String := nil): not nullable String; begin exit Generator.GenerateUnit(GenerateInvokerCodeUnit(library, aTargetNamespace, aUnitName)); end; method RodlCodeGen.GenerateImplementationFiles(library: RodlLibrary; aTargetNamespace: String; aServiceName: String): not nullable Dictionary<String, String>; begin var lunit := GenerateImplementationCodeUnit(library, aTargetNamespace, aServiceName); exit GenerateImplementationFiles(lunit, library, aServiceName); end; method RodlCodeGen.GenerateEnumMemberName(&library: RodlLibrary; entity: RodlEnum; member: RodlEnumValue): String; begin if DontPrefixEnumValues then exit SafeIdentifier(member.Name) else exit SafeIdentifier(iif(entity.PrefixEnumValues,entity.Name+'_','')+ member.Name); end; method RodlCodeGen.DoGenerateInterfaceFile(library: RodlLibrary; aTargetNamespace: String; aUnitName: String := nil): CGCodeUnit; begin targetNamespace := coalesce(GetIncludesNamespace(library), aTargetNamespace, GetNamespace(library)); result := new CGCodeUnit(); result.Namespace := new CGNamespaceReference(targetNamespace); result.HeaderComment := GenerateUnitComment(False); result.FileName := aUnitName; AddUsedNamespaces(result, &library); AddGlobalConstants(result, &library); {$region Collect custom attributes on the rodl level} var lLibraryCustomAttributes := new Dictionary<String, String>(); for key: String in library.CustomAttributes.Keys do lLibraryCustomAttributes.Add(key, library.CustomAttributes[key]); {$endregion} {$region Generate Enums} for entity: RodlEnum in library.Enums.Items.OrderBy(b->b.Name) do begin if not EntityNeedsCodeGen(entity) then Continue; GenerateEnum(result, &library, entity); end; {$endregion} {$region Generate Structs} for entity: RodlStruct in library.Structs.SortedByAncestor do begin if not EntityNeedsCodeGen(entity) then Continue; GenerateStruct(result, &library, entity); end; {$endregion} {$region Generate Arrays} for entity: RodlArray in library.Arrays.Items.OrderBy(b->b.Name) do begin if not EntityNeedsCodeGen(entity) then Continue; GenerateArray(result, &library, entity); end; {$endregion} {$region Generate Exception} for entity: RodlException in library.Exceptions.SortedByAncestor do begin if not EntityNeedsCodeGen(entity) then Continue; GenerateException(result, &library, entity); end; {$endregion} {$region Generate Services} for entity: RodlService in library.Services.SortedByAncestor do begin if not EntityNeedsCodeGen(entity) then Continue; GenerateService(result, &library, entity); end; {$endregion} {$region Generate EventSinks} for entity: RodlEventSink in library.EventSinks.Items.OrderBy(b->b.Name) do begin if not EntityNeedsCodeGen(entity) then Continue; GenerateEventSink(result, &library, entity); end; {$endregion} end; method RodlCodeGen.GetNamespace(library: RodlLibrary): String; begin result := library.Namespace; if String.IsNullOrWhiteSpace(result) then result := library.Name; end; method RodlCodeGen.GenerateInterfaceCodeUnit(library: RodlLibrary; aTargetNamespace: String; aUnitName: String): CGCodeUnit; begin exit DoGenerateInterfaceFile(library, coalesce(GetIncludesNamespace(library), aTargetNamespace, GetNamespace(library)), aUnitName); end; method RodlCodeGen.GenerateInvokerCodeUnit(library: RodlLibrary; aTargetNamespace: String; aUnitName: String): CGCodeUnit; begin raise new Exception("not supported"); end; method RodlCodeGen.GenerateImplementationCodeUnit(library: RodlLibrary; aTargetNamespace: String; aServiceName: String): CGCodeUnit; begin raise new Exception("not supported"); end; method RodlCodeGen.GenerateImplementationFiles(file: CGCodeUnit; library: RodlLibrary; aServiceName: String): not nullable Dictionary<String,String>; begin raise new Exception("not supported"); end; method RodlCodeGen.GenerateDocumentation(entity: RodlEntity; aGenerateOperationMembersDoc: Boolean := false): CGCommentStatement; begin var lDoc := entity.Documentation; if aGenerateOperationMembersDoc and (entity is RodlOperation) then begin var lDoc1:= Environment.LineBreak+'Parameters:'; var ldocPresent: Boolean := false; for op in RodlOperation(entity).Items do begin lDoc1 := lDoc1 + Environment.LineBreak + op.Name+':'; if not String.IsNullOrEmpty(op.Documentation) then begin ldocPresent := true; lDoc1 := lDoc1 + ' '+op.Documentation; end; end; if ldocPresent then lDoc := lDoc + lDoc1; end; if not String.IsNullOrEmpty(lDoc) then exit new CGCommentStatement( 'Description:'+Environment.LineBreak + lDoc) else exit nil; end; end.
unit sNIF.params; { ******************************************************* sNIF Utilidad para buscar ficheros ofimáticos con cadenas de caracteres coincidentes con NIF/NIE. ******************************************************* 2012-2018 Ángel Fernández Pineda. Madrid. Spain. This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. ******************************************************* } interface uses System.Classes; type { PROPOSITO: Contiene los parámetros de búsqueda y exploración. No deben modificarse una vez se ha iniciado la exploración porque no hay sincronización. } TsNIFParametros = class private FCarpetas: TStrings; FExts: TStrings; FMaxNIF: cardinal; FMaxSinNIF: integer; FMinBytes: int64; FMinDiasCreado: integer; FNumHilos: integer; FFicheroSalida: string; FIncluirErrores: boolean; FGenerarResumen: boolean; procedure setMaxSinNif(const porcentaje: integer); procedure setNumHilos(const valor: integer); procedure setMinBytes(const valor: int64); procedure setMaxNIF(const valor: cardinal); procedure setMinDiasCreado(const valor: integer); function getFicheroResumen: string; public // Constructor/Destructor constructor Create; destructor Destroy; override; procedure Limpiar; // Indica si falta algun parámetro imprescindible function esCompleto: boolean; // Comprobar que los parametros son coherentes y corregirlos procedure comprobarCoherencia; // Carpetas a explorar property Carpetas: TStrings read FCarpetas; // Extensiones de los ficheros a explorar (sin punto) property Extensiones: TStrings read FExts; // No seguir buscando si se alcanza MaxNIF property MaxNIF: cardinal read FMaxNIF write setMaxNIF; // No seguir buscando si no se encuentran NIF tras buscar // en el % inicial del fichero establecido en MaxSinNIF property MaxSinNIF: integer read FMaxSinNIF write setMaxSinNif; // Tamaño mínimo de los ficheros a explorar en bytes property MinBytes: int64 read FMinBytes write setMinBytes; // Número mínimo de días transcurridos desde que el fichero se // creó para que sea elegido para exploración property MinDiasCreado: integer read FMinDiasCreado write setMinDiasCreado; // Número de hilos para explorar el contenido de los ficheros property NumHilos: integer read FNumHilos write setNumHilos; // Fichero con los resultados property FicheroSalida: string read FFicheroSalida write FFicheroSalida; // Fichero con el resumen de los resultados property FicheroResumen: string read getFicheroResumen; // true para incluir los errores de lectura en el fichero de salida property IncluirErrores: boolean read FIncluirErrores write FIncluirErrores; // true para generar el fichero con el resumen de los resultados. false // para no generarlo property GenerarResumen: boolean read FGenerarResumen write FGenerarResumen; end; const EXTENSIONES_POR_DEFECTO = 'xls xlsx accdb mdb csv txt xlsxm xlsxb mdx ' + 'accda mde accde ade db dbf prn dif tab adp'; MAXIMO_HILOS = 10; implementation uses sNIF.params.DEF, IOUtils, IOUtilsFix, System.SysUtils; // ---------------------------------------------------------------------------- // TsNIFParametros // ---------------------------------------------------------------------------- constructor TsNIFParametros.Create; begin inherited Create; FCarpetas := TStringList.Create; FExts := TStringList.Create; FExts.Delimiter := ' '; FExts.StrictDelimiter := true; Limpiar; end; procedure TsNIFParametros.Limpiar; begin FCarpetas.Clear; FExts.Clear; FMaxNIF := 1000; FMaxSinNIF := 50; FFicheroSalida := ''; FIncluirErrores := true; FGenerarResumen := true; FNumHilos := 6; {$IFDEF DEBUG} FMinBytes := 0; FMinDiasCreado := 0; FExts.DelimitedText := '*'; {$ELSE} FMinBytes := 3145728; // = 3 MB FMinDiasCreado := 365; FExts.DelimitedText := 'xls accd? md? csv txt xlsx* db* prn ' + 'dif tab adp gdb ib jet odb sbf sqlite* xml'; {$ENDIF} end; destructor TsNIFParametros.Destroy; begin FCarpetas.Free; FExts.Free; inherited Destroy; end; procedure TsNIFParametros.comprobarCoherencia; var i, j: integer; begin // Comprobar que solo hay rutas de carpeta bien formadas i := 0; while i < FCarpetas.Count do if (not TPath.isWellFormed(FCarpetas.Strings[i], true, false)) then FCarpetas.Delete(i) else inc(i); // Excluir subcarpetas si ya está incluida la raiz y // quitar carpetas duplicadas. Comprobar que es una ruta válida // (hacia adelante) for i := 0 to FCarpetas.Count - 1 do begin j := i + 1; while j < FCarpetas.Count do if (TPath.isContainerOf(FCarpetas.Strings[i], FCarpetas.Strings[j])) or (CompareText(FCarpetas.Strings[i], FCarpetas.Strings[j]) = 0) then FCarpetas.Delete(j) else inc(j); end; // (hacia atrás) i := FCarpetas.Count - 1; while (i >= 0) do begin j := i - 1; while (j >= 0) do if (TPath.isContainerOf(FCarpetas.Strings[i], FCarpetas.Strings[j])) or (CompareText(FCarpetas.Strings[i], FCarpetas.Strings[j]) = 0) then begin FCarpetas.Delete(j); dec(j); dec(i); end else dec(j); dec(i); end; // Si no hay extensiones, buscar todas if (FExts.Count = 0) then FExts.Add('*'); end; function TsNIFParametros.getFicheroResumen: string; begin if (Length(FFicheroSalida) > 0) then Result := TPath.ReplaceFileName(FFicheroSalida, FFicheroSalida + '.log') else Result := ''; end; function TsNIFParametros.esCompleto: boolean; begin Result := (Length(FFicheroSalida) > 0) and (FExts.Count > 0) and (FCarpetas.Count > 0); end; procedure TsNIFParametros.setMaxNIF(const valor: cardinal); begin if (valor >= 20) then FMaxNIF := valor else raise EArgumentOutOfRangeException.Create ('Valor fuera de rango en parámetro ' + PARAM_MAXNIF); end; procedure TsNIFParametros.setMinBytes(const valor: int64); begin if (valor >= 0) then FMinBytes := valor else raise EArgumentOutOfRangeException.Create ('Valor fuera de rango en parámetro ' + PARAM_MINBYTES); end; procedure TsNIFParametros.setMinDiasCreado(const valor: integer); begin if (valor >= 0) then FMinDiasCreado := valor else raise EArgumentOutOfRangeException.Create ('Valor fuera de rango en parámetro ' + PARAM_MINDIAS); end; procedure TsNIFParametros.setMaxSinNif(const porcentaje: integer); begin if (porcentaje >= 40) and (porcentaje <= 100) then FMaxSinNIF := porcentaje else raise EArgumentOutOfRangeException.Create ('Valor fuera de rango en parámetro ' + PARAM_MAXSINNIF); end; procedure TsNIFParametros.setNumHilos(const valor: integer); begin if (valor > 0) and (valor <= MAXIMO_HILOS) then FNumHilos := valor else raise EArgumentOutOfRangeException.Create ('Valor fuera de rango en parámetro ' + PARAM_HILOS); end; // ---------------------------------------------------------------------------- end.
unit Vigilante.Infra.Build.Repositorio.Impl; interface uses System.JSON, Vigilante.Build.Repositorio, Vigilante.Build.Model; type TBuildRepositorio = class(TInterfacedObject, IBuildRepositorio) private function BuscarJSON(const AURL: string): TJSONObject; function TratarURL(const AURL: string): string; public function BuscarBuild(const AURL: string): IBuildModel; end; implementation uses System.SysUtils, ContainerDI, Vigilante.Infra.Build.Builder, Vigilante.Conexao.JSON; function TBuildRepositorio.BuscarBuild(const AURL: string): IBuildModel; var _json: TJSONObject; _buildBuilder: IBuildBuilder; begin Result := nil; _json := BuscarJSON(AURL); if not Assigned(_json) then Exit; try _buildBuilder := CDI.Resolve<IBuildBuilder>([_json]); Result := _buildBuilder.PegarBuild; finally FreeAndNil(_json); end; end; function TBuildRepositorio.BuscarJSON(const AURL: string): TJSONObject; var _conexaoJSON: IConexaoJSON; _url: string; begin _url := TratarURL(AURL); _conexaoJSON := CDI.Resolve<IConexaoJSON>([_url]); Result := _conexaoJSON.PegarBuild; end; function TBuildRepositorio.TratarURL(const AURL: string): string; begin Result := AURL; if not AURL.EndsWith('api/json', True) then Result := AURL + '/api/json'; end; end.
unit DMCommon; interface uses System.Classes, dxLayoutLookAndFeels, System.ImageList, Vcl.ImgList, Vcl.Controls, cxGraphics, WUpdate, cxLookAndFeels, dxSkinsForm, cxClasses, cxLocalization, RemoteDB.Client.Dataset, RemoteDB.Client.Database, gmClientDataset, cxGridDBDataDefinitions, cxRichEdit, cxProgressBar, cxGridDBTableView, Vcl.ExtCtrls, cxCustomData, Generics.Collections, cxGridCustomView, Winapi.Windows, Data.DB, CustomDataSetParams; type TFDMCommon = class; TDataSetParams = class(TCustomDataSetParams) private FParams: TFDMCommon; // DataModule where the dataset is located public function DataSet: TDataSet; override; function CompanyField: TField; override; function UserField: TField; override; function BlobField: TBlobField; override; function NameField: TField; override; function ValueField: TField; override; procedure Open; override; end; TFDMCommon = class(TDataModule) cxLocalizer1: TcxLocalizer; dxSkinController: TdxSkinController; WebUpdate1: TWebUpdate; cxImageFlatMenu: TcxImageList; cxImageNavigator16: TcxImageList; dxLayoutLookAndFeelList: TdxLayoutLookAndFeelList; dxLayoutSkinLookAndFeel1: TdxLayoutSkinLookAndFeel; gmDatabase: TgmDatabase; qParamDataset: TgmClientDataset; qParamDatasetNAME: TStringField; qParamDatasetVALUE: TStringField; qParamDatasetCOMPANY_ID: TStringField; qParamDatasetUSER_ID: TStringField; qParamDatasetDATA: TBlobField; qReportId: TgmClientDataset; qReportIditem_id: TAutoIncField; cxImageNavigator32: TcxImageList; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure WebUpdate1AppDoClose(Sender: TObject); procedure WebUpdate1AppRestart(Sender: TObject; var Allow: Boolean); procedure WebUpdate1FileProgress(Sender: TObject; FileName: string; Pos, Size: Integer); procedure WebUpdate1Status(Sender: TObject; StatusStr: string; StatusCode, ErrCode: Integer); procedure WebUpdate1Success(Sender: TObject); procedure WebUpdate1Progress(Sender: TObject; Action: string); private { Private declarations } // FIniFile: TIniFile; FIsConnected: boolean; FSkinSelected: string; // FmMenu: TfrmBaseMainMenu; FDataController: TcxGridDBDataController; // FManager: TObjectManager; FpnlUpgrade: TPanel; FreUpgrade: TcxRichEdit; FcxProgressUpdate: TcxProgressBar; // FBaseController: TdmTabelleBaseController; // FBaseControllerLoaded: boolean; FImgList: TcxImageList; procedure GetSelectedKeyValues(ADataController: TcxGridDBDataController); procedure AddKeyFieldValueToList(ARowIndex: Integer; ARowInfo: TcxRowInfo); function CheckConnect: boolean; procedure Connect; public { Public declarations } FKeyFieldList: TList<string>; // TStringList; procedure GetSelectedIDs(Grid: TcxGridDBTableView); function GetRealDragSourceGridView(const aSource: TObject): TcxGridDBTableView; function GetDragSourceGridView(const aSource: TObject): TcxGridDBTableView; function vLocate(Grid: TcxGridDBTableView; pkKey: Integer): boolean; function GetMasterRecordID(AView: TcxCustomGridView): Integer; procedure Update; procedure SelectSkin(pSkin: integer); function VarIsNumericZero(const AValue: Variant): Boolean; function GetReportId(const repName: string): string; function VarToInt(const AVariant: Variant): integer; // property Manager: TObjectManager read FManager; property pnlUpgrade: TPanel read FpnlUpgrade write FpnlUpgrade; property reUpgrade: TcxRichEdit read FreUpgrade write FreUpgrade; property cxProgressUpdate: TcxProgressBar read FcxProgressUpdate write FcxProgressUpdate; // property BaseController: TdmTabelleBaseController read FBaseController write FBaseController; // property BaseControllerLoaded: boolean read FBaseControllerLoaded write FBaseControllerLoaded; // property mMenu: TfrmBaseMainMenu read FmMenu write FmMenu; property SkinSelected: string read FSkinSelected write FSkinSelected; property IsConnected: boolean read FIsConnected; property ImgList: TcxImageList read FImgList; end; var FDMCommon: TFDMCommon; procedure PostKeyEx( hWindow: HWnd; key: Word; Const shift: TShiftState; specialkey: Boolean ); function StrToWord(const Value: String): Word; function IIfThen(AValue: Boolean; const ATrue: string; const AFalse: string = ''): string; //overload; resourcestring RS_AV = 'Si è verificato un problema.'#13'L''applicazione verrà chiusa'; nfsCancellaDDT = 'Confermi la cancellazione del D.D.T. ?'; nfsPswdErrata = 'Password errata !'; nfsPswdScaduta = 'Password scaduta !'; DB_ErroreUnicita = 'E''già stato registrato un altro record con lo stesso valore'; DB_ErroreForeign = 'La cancellazione non e'' possibile. Esistono delle registrazioni nella tabella %s'; DB_ServerNonDisponibile = 'Il collegamento non e'' attualmente disponibile. Riprovare più tardi.(SY003)'; implementation uses Variants, System.Threading, cxControls, cxDBData, Forms, Dialogs, Metropolis_GM, MetropolisDark, VSoft.CommandLine.Parser, VSoft.CommandLIne.Options, uCMDLineOptions, System.UITypes, DBConnection, ParamManager, {$IFDEF EUREKALOG} EEvents, EException, ETypes, {$ENDIF} {$IFDEF MADEXCEPT} madExcept, madTypes, madStrings, {$ENDIF} cxEdit, //Mask, Winapi.Messages, SysUtils, Sparkle.WinHttp.Api; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} {$R grid6_ita.RES} procedure TFDMCommon.Connect; begin try TDBConnection.CreateConnection( gmDatabase ); FIsConnected := True; except on E: Exception do begin MessageDlg(format('Collegamento a %s non disponibile'#13#10'%s',[TCMDLineOptions.Server,E.Message]),mtError,[mbOK],0); FIsConnected := False; end; end; end; procedure TFDMCommon.DataModuleCreate(Sender: TObject); //var // skin: string; begin // FBaseControllerLoaded := false; cxLocalizer1.Active:= True; cxLocalizer1.Locale:= 1040; if (Screen.PixelsPerInch>96) then FImgList := cxImageNavigator32 else FImgList := cxImageNavigator16; // FManager := TDBConnection.GetInstance.CreateObjectManager; FKeyFieldList := TList<string>.Create; dxSkinController.NativeStyle := False; dxLayoutSkinLookAndFeel1.LookAndFeel.NativeStyle := False; {$IFDEF VIRTUALUIx} dxSkinController1.UseImageSet := imsAlternate; {$ENDIF} SelectSkin(0); CheckConnect; end; procedure TFDMCommon.DataModuleDestroy(Sender: TObject); begin // FManager.Free; FKeyFieldList.Free; // FBaseController.Free; end; function TFDMCommon.CheckConnect: boolean; begin result := TCMDLineOptions.ReadCMDParameters; // pnlUpgrade.Visible := TCMDLineOptions.Debug; if result then begin Connect; end; end; procedure TFDMCommon.GetSelectedIDs(Grid: TcxGridDBTableView); //var // I: Integer; // sWhere: string; begin // sWhere := ''; FKeyFieldList.Clear; try //screen.Cursor := crHourglass; Grid.DataController.DataSource.DataSet.DisableControls; GetSelectedKeyValues(Grid.DataController); { if (FKeyFieldList.Count > 0) then begin sWhere := ''''; //Iterate selected records for I := 0 to FKeyFieldList.Count - 1 do begin if (i < (FKeyFieldList.Count - 1)) then sWhere := sWhere + string(FKeyFieldList[i]) + ''',''' else sWhere := sWhere + string(FKeyFieldList[i]) + ''''; end; end; } finally Grid.DataController.DataSource.DataSet.EnableControls; end; end; procedure TFDMCommon.GetSelectedKeyValues(ADataController: TcxGridDBDataController); begin FDataController := ADataController; ADataController.ForEachRow(True, AddKeyFieldValueToList); end; procedure TFDMCommon.AddKeyFieldValueToList(ARowIndex: Integer; ARowInfo: TcxRowInfo); var AKeyFieldValue: Variant; begin with FDataController do begin //test whether a row is a data record if ARowInfo.Level = Groups.GroupingItemCount then begin AKeyFieldValue := GetRecordId(ARowInfo.RecordIndex); if not varisnull(AKeyFieldValue) then FKeyFieldList.Add(string(AKeyFieldValue)); end; end; end; function TFDMCommon.GetRealDragSourceGridView(const aSource: TObject): TcxGridDBTableView; begin result := nil; if (TcxDragControlObject (aSource).Control is TcxGridSite) then begin result := TcxGridSite (TcxDragControlObject (aSource).Control).GridView as TcxGridDBTableView; end; end; function TFDMCommon.GetDragSourceGridView(const aSource: TObject): TcxGridDBTableView; begin result := GetRealDragSourceGridView (aSource); if (result<>nil) and result.IsDetail then result := result.PatternGridView as TcxGridDBTableView; end; function TFDMCommon.vLocate(Grid: TcxGridDBTableView; pkKey: Integer): boolean; var RecIdx: integer; begin if (Grid=nil) then result := false else if not Grid.DataController.DataModeController.SyncMode then result := Grid.DataController.LocateByKey(pkKey) else begin result := Grid.DataController.LocateByKey(pkKey); if result then begin RecIdx := Grid.DataController.FindRecordIndexByKey(pkKey); if RecIdx<>-1 then begin if Grid.OptionsSelection.MultiSelect then Grid.DataController.ClearSelection; Grid.DataController.FocusedRecordIndex := RecIdx; Grid.Controller.FocusedRecord.Selected := true; end; end; end; end; procedure TFDMCommon.WebUpdate1AppDoClose(Sender: TObject); begin Application.Terminate; end; procedure TFDMCommon.WebUpdate1AppRestart(Sender: TObject; var Allow: Boolean); begin // Allow := MessageDlg('Confermi la chiusura del programma per effettuare l''aggiornamento ?',mtConfirmation,[mbYes,mbNo],0)=mrYes; Allow := True; end; procedure TFDMCommon.WebUpdate1FileProgress(Sender: TObject; FileName: string; Pos, Size: Integer); begin if cxProgressUpdate<>nil then begin cxProgressUpdate.Properties.Max := size; cxProgressUpdate.Position := pos; end; end; procedure TFDMCommon.WebUpdate1Progress(Sender: TObject; Action: string); begin // end; procedure TFDMCommon.WebUpdate1Status(Sender: TObject; StatusStr: string; StatusCode, ErrCode: Integer); begin if (FpnlUpgrade<>nil) {and FpnlUpgrade.Visible} then case StatusCode of WebUpdateNoNewVersion: FreUpgrade.Lines.Add( 'Nessuna nuova versione disponibile' ); WebUpdateNotFound: FreUpgrade.Lines.Add( 'Sito di aggiornamento non disponibile' ); else FreUpgrade.Lines.Add( StatusStr ); end; end; procedure TFDMCommon.WebUpdate1Success(Sender: TObject); begin // end; function TFDMCommon.GetMasterRecordID(AView: TcxCustomGridView): Integer; begin Result := TcxDBDataRelation(AView.DataController.GetMasterRelation).GetMasterRecordID(AView.MasterGridRecordIndex); end; procedure TFDMCommon.Update; var VerInfo: TOSVersionInfo; OSVersion: string; begin pnlUpgrade.Visible := True; try VerInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo); GetVersionEx(verinfo); OSVersion := IntToStr(verinfo.dwMajorVersion)+':'+IntToStr(verinfo.dwMinorVersion); { ??? WebUpdate1.PostUpdateInfo.Data := WebUpdate1.PostUpdateInfo.Data + '&TIME='+FormatDateTime('dd/mm/yyyy@hh:nn',Now)+'&OS='+OSVersion; } if TCMDLineOptions.UrlUpd<>'' then begin WebUpdate1.URL := TCMDLineOptions.UrlUpd + '/'+ChangeFileExt(ExtractFileName(paramstr(0)),'.inf'); // WebUpdate1.DoThreadupdate WebUpdate1.DoUpdate; if (pnlUpgrade<>nil) then pnlUpgrade.Visible := False; end else begin if (FpnlUpgrade<>nil) {and FpnlUpgrade.Visible} then FreUpgrade.Lines.Add( 'Sito di aggiornamento non definito' ); end; finally // pnlUpgrade.Visible := TCMDLineOptions.Debug; end; end; procedure TFDMCommon.SelectSkin(pSkin: integer); const SkinNames: array[0..1] of string = ('Metropolis', 'MetropolisDark'); // 'MetroWhite.skinres', begin FSkinSelected := SkinNames[pSkin]; dxSkinController.Kind := lfUltraFlat; dxSkinController.NativeStyle := False; dxSkinController.SkinName := FSkinSelected; dxSkinController.UseSkins := True; dxLayoutSkinLookAndFeel1.LookAndFeel.Kind := lfUltraFlat; dxLayoutSkinLookAndFeel1.LookAndFeel.NativeStyle := False; dxLayoutSkinLookAndFeel1.LookAndFeel.SkinName := FSkinSelected; end; function TFDMCommon.VarIsNumericZero(const AValue: Variant): Boolean; begin Result := VarIsNull(AValue) or (AValue=0); end; function TFDMCommon.GetReportId(const repName: string): string; begin qReportId.Close; qReportId.ParamByName('item_name').AsString := repName; qReportId.Open; result := qReportIditem_id.AsString; end; function TFDMCommon.VarToInt(const AVariant: Variant): integer; begin Result := StrToIntDef(Trim(VarToStr(AVariant)), 0); end; function StrToWord(const Value: String): Word; inline; begin // if Length(Value) > 1 then begin {$IFDEF STRING_IS_UNICODE} Result := TwoCharToWord(Value[1], Value[2]); {$ELSE} Result := PWord(Pointer(Value))^; {$ENDIF} // end else begin // Result := 0; // end; end; {************************************************* *********** * Procedure PostKeyEx * * Parameters: * hWindow: target window to be send the keystroke * key : virtual keycode of the key to send. For printable * keys this is simply the ANSI code (Ord(character)). * shift : state of the modifier keys. This is a set, so you * can set several of these keys (shift, control, alt, * mouse buttons) in tandem. The TShiftState type is * declared in the Classes Unit. * specialkey: normally this should be False. Set it to True to * specify a key on the numeric keypad, for example. * If this parameter is true, bit 24 of the lparam for * the posted WM_KEY* messages will be set. * Description: * This procedure sets up Windows key state array to correctly * reflect the requested pattern of modifier keys and then posts * a WM_KEYDOWN/WM_KEYUP message pair to the target window. Then * Application.ProcessMessages is called to process the messages * before the keyboard state is restored. * Error Conditions: * May fail due to lack of memory for the two key state buffers. * Will raise an exception in this case. * NOTE: * Setting the keyboard state will not work across applications * running in different memory spaces on Win32 unless AttachThreadInput * is used to connect to the target thread first. *Created: 02/21/96 16:39:00 by P. Below ************************************************** **********} Procedure PostKeyEx( hWindow: HWnd; key: Word; Const shift: TShiftState; specialkey: Boolean ); Type TBuffers = Array [0..1] of TKeyboardState; Var pKeyBuffers : ^TBuffers; lparam: LongInt; Begin (* check if the target window exists *) If IsWindow(hWindow) Then Begin (* set local variables to default values *) // pKeyBuffers := Nil; lparam := MakeLong(0, MapVirtualKey(key, 0)); (* modify lparam if special key requested *) If specialkey Then lparam := lparam or $1000000; (* allocate space for the key state buffers *) New(pKeyBuffers); try (* Fill buffer 1 with current state so we can later restore it. Null out buffer 0 to get a "no key pressed" state. *) GetKeyboardState( pKeyBuffers^[1] ); FillChar(pKeyBuffers^[0], Sizeof(TKeyboardState), 0); (* set the requested modifier keys to "down" state in the buffer *) If ssShift In shift Then pKeyBuffers^[0][VK_SHIFT] := $80; If ssAlt In shift Then Begin (* Alt needs special treatment since a bit in lparam needs also be set *) pKeyBuffers^[0][VK_MENU] := $80; lparam := lparam or $20000000; End; If ssCtrl In shift Then pKeyBuffers^[0][VK_CONTROL] := $80; If ssLeft In shift Then pKeyBuffers^[0][VK_LBUTTON] := $80; If ssRight In shift Then pKeyBuffers^[0][VK_RBUTTON] := $80; If ssMiddle In shift Then pKeyBuffers^[0][VK_MBUTTON] := $80; (* make out new key state array the active key state map *) SetKeyboardState( pKeyBuffers^[0] ); (* post the key messages *) If ssAlt In Shift Then Begin PostMessage( hWindow, WM_SYSKEYDOWN, key, lparam); PostMessage( hWindow, WM_SYSKEYUP, key, lparam or $C0000000); End Else Begin PostMessage( hWindow, WM_KEYDOWN, key, lparam); PostMessage( hWindow, WM_KEYUP, key, lparam or $C0000000); End; (* process the messages *) Application.ProcessMessages; (* restore the old key state map *) SetKeyboardState( pKeyBuffers^[1] ); finally (* free the memory for the key state buffers *) If pKeyBuffers <> Nil Then Dispose( pKeyBuffers ); End; { If } End; End; { PostKeyEx } function IIfThen(AValue: Boolean; const ATrue: string; const AFalse: string = ''): string; //overload; begin if AValue then Result := ATrue else Result := AFalse; end; { TDataSetParams } function TDataSetParams.BlobField: TBlobField; begin Result := FParams.qParamDatasetDATA; end; function TDataSetParams.CompanyField: TField; begin Result := FParams.qParamDatasetCOMPANY_ID; // Required for company scoped params end; function TDataSetParams.DataSet: TDataSet; begin Result := FParams.qParamDataset; end; function TDataSetParams.NameField: TField; begin Result := FParams.qParamDatasetNAME; end; procedure TDataSetParams.Open; begin inherited; if FParams = nil then FParams := FDMCommon; FParams.qParamDataset.Open; end; function TDataSetParams.UserField: TField; begin Result := FParams.qParamDatasetUSER_ID; //Required for company scoped params end; function TDataSetParams.ValueField: TField; begin Result := FParams.qParamDatasetVALUE; end; {$IFDEF EUREKALOG} // Your handler for OnExceptionNotify event procedure MyHandler(const ACustom: Pointer; AExceptionInfo: TEurekaExceptionInfo; var AHandle: Boolean; var ACallNextHandler: Boolean); var dove: integer; ExceptionMessage: string; vShow: integer; // -- 0= no show; 1=show locale; 2=show handler vContinue,vLog: boolean; begin ExceptionMessage := AExceptionInfo.ExceptionMessage; if (AExceptionInfo.ExceptionClass = 'EDatabaseError') or (AExceptionInfo.ExceptionClass = 'EAstaProtocolError') then begin vShow := 2; vLog := True; dove := Pos('ORA-20001',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,dove+11,Length(ExceptionMessage)-(dove+10)); dove := Pos(#10,ExceptionMessage); if dove>0 then ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vLog := false; vShow := 1; end; dove := Pos('ORA-20002',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,dove+11,Length(ExceptionMessage)-(dove+10)); dove := Pos(#10,ExceptionMessage); if dove>0 then ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vLog := true; vShow := 1; end; dove := Pos('ORA-00001',ExceptionMessage); if dove>0 then begin ExceptionMessage := DB_ErroreUnicita; vLog := false; vShow := 1; end; dove := Pos('ORA-02292',ExceptionMessage); if dove>0 then begin dove := Pos('(',ExceptionMessage); ExceptionMessage := Copy(ExceptionMessage,dove+1,Length(ExceptionMessage)-dove); dove := Pos(')',ExceptionMessage); ExceptionMessage := Copy(ExceptionMessage,1,dove-1); ExceptionMessage := format(DB_ErroreForeign,[ExceptionMessage]); vLog := false; vShow := 1; end; dove := Pos('(SY002)',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vContinue := false; vShow := 4; end; dove := Pos('(SY003)',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vContinue := false; vShow := 4; end; if (vShow=2) and ((Pos('ORA-03114',ExceptionMessage)>0) or (Pos('Not logged on',ExceptionMessage)>0) or ((Pos('ORA-03113',ExceptionMessage)>0) and not (Pos('ORA-02050',ExceptionMessage)>0)) or (Pos('ORA-12535',ExceptionMessage)>0) or (Pos('ORA-12500',ExceptionMessage)>0) or (Pos('ORA-12203',ExceptionMessage)>0) or (Pos('ORA-01089',ExceptionMessage)>0) or (Pos('ORA-01033',ExceptionMessage)>0) or (Pos('ORA-01034',ExceptionMessage)>0) or (Pos('ORA-01012',ExceptionMessage)>0) or (Pos('ORA-12570',ExceptionMessage)>0) or (Pos('ORA-12571',ExceptionMessage)>0)) then begin ExceptionMessage := DB_ServerNonDisponibile; vContinue := false; vShow := 4; end; AExceptionInfo.Options.ExceptionDialogType := edtMessageBox; AExceptionInfo.Options.SaveLogFile := vLog; AExceptionInfo.Options.edoSendErrorReportChecked := vLog; AExceptionInfo.ExceptionMessage := ExceptionMessage; end else begin AExceptionInfo.Options.edoSendErrorReportChecked := not TCMDLineOptions.Debug; end; end; {$ENDIF} {$IFDEF MADEXCEPT} procedure ExceptionFilter(const exceptIntf : IMEException; var handled : boolean); var dove: integer; ExceptionMessage: string; vShow: integer; // -- 0= no show; 1=show locale; 2=show handler vContinue,vLog: boolean; begin (* exceptIntf.BeginUpdate; exceptIntf.BugReportHeader.Insert(0,'*** inizio errore ***', '***'); exceptIntf.BugReportHeader.Insert(1,'utente: ', gblNomeUtente + ' ('+IntToStr(gblCodUtente)+')'); exceptIntf.BugReportSections.Add('*** fine errore ***','***'); exceptIntf.EndUpdate; *) if (exceptIntf.ExceptType=etFrozen) then begin AutoSaveBugReport(exceptIntf.bugReport); exit; end; if (exceptIntf.exceptObject = nil) then exit; ExceptionMessage := MadException(exceptIntf.exceptObject).Message; vShow := 1; vLog := true; vContinue := true; if (exceptIntf.exceptObject is EAccessViolation) or (exceptIntf.exceptObject is EInvalidPointer) or (exceptIntf.exceptObject is EAbstractError) or (exceptIntf.exceptObject is EcxInvalidDataControllerOperation) then begin if TCMDLineOptions.Debug then vShow := 2 // 3=reset applicazione 2=rimane dentro; else vShow := 4; // 4=chiudi applicazione 2=rimane dentro; end; if //(exceptIntf.exceptObject is EDBEditError) or (exceptIntf.exceptObject is EcxEditValidationError) then begin vLog := false; end; if (exceptIntf.exceptObject is EWinHttpClientException) and ((Pos('Error: (12002)',ExceptionMessage)>0) or (Pos('Error: (12007)',ExceptionMessage)>0) ) then begin vShow := 1; vLog := false; ExceptionMessage := 'Il server non è raggiungibile'; end; (* --- ToDo: fare gestione dipendente dal tipo di connessione e di DB if (exceptIntf.exceptObject is ESocketError) then begin vContinue := gbldebugmode; // false; ExceptionMessage := format(ExceptionMessage+' (%s %s)',[FDMCommon.AstaClientSocket.Address,FDMCommon.AstaClientSocket.Address]); end; if (Pos('List index out of bounds',ExceptionMessage)>0) then vShow := 0 {JRT 5488: eliminato else if (exceptIntf.exceptObject is RefVocException) then vShow := 0 } else if ((exceptIntf.exceptObject is EDataBaseError) or (exceptIntf.exceptObject is EAstaProtocolError)) then begin vShow := 2; dove := Pos('ORA-20001',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,dove+11,Length(ExceptionMessage)-(dove+10)); dove := Pos(#10,ExceptionMessage); if dove>0 then ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vLog := false; vShow := 1; end; dove := Pos('ORA-20002',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,dove+11,Length(ExceptionMessage)-(dove+10)); dove := Pos(#10,ExceptionMessage); if dove>0 then ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vLog := true; vShow := 1; end; dove := Pos('ORA-00001',ExceptionMessage); if dove>0 then begin ExceptionMessage := RIS_ErroreUnicita; vLog := false; vShow := 1; end; dove := Pos('ORA-02292',ExceptionMessage); if dove>0 then begin dove := Pos('(',ExceptionMessage); ExceptionMessage := Copy(ExceptionMessage,dove+1,Length(ExceptionMessage)-dove); dove := Pos(')',ExceptionMessage); ExceptionMessage := Copy(ExceptionMessage,1,dove-1); ExceptionMessage := format(RIS_ErroreForeign,[ExceptionMessage]); vLog := false; vShow := 1; end; dove := Pos('(SY001)',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vContinue := false; vShow := 3; end; dove := Pos('(SY002)',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vContinue := false; vShow := 4; end; dove := Pos('(SY003)',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vContinue := false; vShow := 4; end; if (vShow=2) and ((Pos('ORA-03114',ExceptionMessage)>0) or (Pos('Not logged on',ExceptionMessage)>0) or ((Pos('ORA-03113',ExceptionMessage)>0) and not (Pos('ORA-02050',exceptIntf.bugReport)>0)) or (Pos('ORA-12535',ExceptionMessage)>0) or (Pos('ORA-12500',ExceptionMessage)>0) or (Pos('ORA-12203',ExceptionMessage)>0) or (Pos('ORA-01089',ExceptionMessage)>0) or (Pos('ORA-01033',ExceptionMessage)>0) or (Pos('ORA-01034',ExceptionMessage)>0) or (Pos('ORA-01012',ExceptionMessage)>0) or (Pos('ORA-12570',ExceptionMessage)>0) or (Pos('ORA-12571',ExceptionMessage)>0)) then begin ExceptionMessage := RS_ServerNonDisponibile; vContinue := false; vShow := 4; end; end; *) MadException(exceptIntf.exceptObject).Message := ExceptionMessage; if vLog then begin // AutoSaveBugReport(exceptIntf.bugReport,exceptIntf); AutoSendBugReport(exceptIntf.bugReport,exceptIntf.ScreenShot); end; case vShow of 0:begin handled := true; end; 1,2:begin handled := true; if not (GetCurrentThreadID = MainThreadID) then MessageBox(0, pchar(ExceptionMessage), 'Errore...', MB_ICONERROR) else MessageDlg(ExceptionMessage, mtError, [mbOk], 0); end; 3:begin handled := true; if not (GetCurrentThreadID = MainThreadID) then MessageBox(0, pchar(ExceptionMessage), 'Errore...', MB_ICONERROR) else if MessageDlg(ExceptionMessage, mtError, [mbYes,mbNo], 0, mbYes)=mrNo then vShow := 4; end; 4:begin handled := true; // if not (GetCurrentThreadID = MainThreadID) then MessageBox(0, pchar(RS_AV), 'Errore...', MB_ICONERROR) // else // MsgDlg(RS_AV, '', ktError, [kbOk], dfFirst); end; end; exceptIntf.canContinue := vContinue; if TCMDLineOptions.Debug then exceptIntf.AutoClose := 1 else exceptIntf.AutoClose := 0; exceptIntf.AutoShowBugReport := TCMDLineOptions.Debug; case vShow of 3: RestartApplication; 4: CloseApplication; end; end; {$ENDIF} initialization TParamManager.RemoteParamsClass := TDataSetParams; {$IFDEF EUREKALOG} RegisterEventExceptionNotify(nil, MyHandler); {$ENDIF} {$IFDEF MADEXCEPT} RegisterExceptionHandler(ExceptionFilter,stTrySyncCallAlways); {$ENDIF} end.
UNIT BaseDeDatos; (******************************************************************************* La presente unidad tiene como objetivo realizar la conexión a la base de datos del sistema y retornar datos desde ella. La base de datos tendrá por nombre la cadena dada por la constante DATABASE_NAME y deberá estar almacenada en el mismo directorio donde del proyecto, y por ende, del ejecutable del sistema. *******************************************************************************) {$mode objfpc}{$H+} INTERFACE USES Classes, SysUtils, sqldb, sqlite3conn, Utilidades, DT_Especie, DT_TipoElemental; CONST DATABASE_NAME= 'PKMNPas.db'; CONNECTION_TYPE= 'SQLite3'; VAR //Interface Conn: TSQLConnector; //Conector de la base de datos. Trans: TSQLTransaction;//Transacción o 'Statement' Query: TSQLQuery; //Consultor de la base de datos. FUNCTION GetConnection(): TSQLConnector; //Retorna la conección. FUNCTION GetTransaction(): TSQLTransaction;//Retorna la transacción. FUNCTION GetQuery(): TSQLQuery; //Retorna la consulta. (****************************************************************************) (* OPERACIONES PARA LECTURA DE DATOS *) (****************************************************************************) (*Crea todas las especies pokemon y las asigna a 'l' a partir de los datos almacenados en la base de datos. La lista resultante estará ordenada según los números usados en la pokedex de los videojuegos. La lista original será sobreescrita.*) PROCEDURE CargarListaEspecies(VAR l: ListaEspecies); (*Crea un listado con todos los tipos elementales del juego y lo asigna a 'l'. La lista resultante estará ordenada alfabéticamente. La lista original será sobreescrita.*) PROCEDURE CargarListaTiposElementales(VAR l: ListaTiposElementales); IMPLEMENTATION FUNCTION GetConnection(): TSQLConnector; Begin GetConnection:= Conn; End; //GetConnection FUNCTION GetTransaction(): TSQLTransaction; Begin GetTransaction:= Trans; End; //GetTrasaction FUNCTION GetQuery(): TSQLQuery; Begin GetQuery:= Query; End; //GetQuery (****************************************************************************) (* OPERACIONES PARA LECTURA DE DATOS *) (****************************************************************************) (*Crea todas las especies pokemon y las asigna a 'l' a partir de los datos almacenados en la base de datos. La lista resultante estará ordenada según los números usados en la pokedex de los videojuegos.*) PROCEDURE CargarListaEspecies(VAR l: ListaEspecies); VAR e: Especie; //Especie auxiliar. Begin IniciarListaEspecies(l); Query.SQL.Text:= 'SELECT Especies.*, TiposDeCrecimiento.Nombre NombreCrecimiento FROM Especies, TiposDeCrecimiento WHERE Especies.TipoCrecimiento=TiposDeCrecimiento.TIPOS_DE_CRECIMIENTO_ID ORDER BY Especies.ESPECIE_ID'; Query.Open; WHILE NOT Query.EOF DO Begin WITH e DO begin id:= Query.FieldByName('ESPECIE_ID').AsInteger; Numero:= Query.FieldByName('Numero').AsString; Nombre:= Query.FieldByName('Nombre').AsString; PS_Base:= Query.FieldByName('PS_Base').AsInteger; ATK_Base:= Query.FieldByName('ATK_Base').AsInteger; DEF_Base:= Query.FieldByName('DEF_Base').AsInteger; ATKSp_Base:= Query.FieldByName('ATKSp_Base').AsInteger; DEFSp_Base:= Query.FieldByName('DEFSp_Base').AsInteger; VEL_Base:= Query.FieldByName('VEL_Base').AsInteger; AMISTAD_Base:= Query.FieldByName('AMISTAD_Base').AsInteger; EXP_Base:= Query.FieldByName('EXP_Base').AsInteger; PS_Esfuerzo:= Query.FieldByName('PS_Esfuerzo').AsInteger; ATK_Esfuerzo:= Query.FieldByName('ATK_Esfuerzo').AsInteger; DEF_Esfuerzo:= Query.FieldByName('DEF_Esfuerzo').AsInteger; VEL_Esfuerzo:= Query.FieldByName('VEL_Esfuerzo').AsInteger; ATKSp_Esfuerzo:= Query.FieldByName('ATKSp_Esfuerzo').AsInteger; DEFSp_Esfuerzo:= Query.FieldByName('DEFSp_Esfuerzo').AsInteger; Crecimiento:= Query.FieldByName('NombreCrecimiento').AsString; Tipo1:= Query.FieldByName('Tipo1').AsInteger; Tipo2:= Query.FieldByName('Tipo2').AsInteger; RatioCaptura:= Query.FieldByName('RatioCaptura').AsInteger; end; AgregarEspecieListaEspecies(e,l); Query.Next; end; Query.Close; End; (*Crea un listado con todos los tipos elementales del juego y lo asigna a 'l'. La lista resultante estará ordenada alfabéticamente. La lista original será sobreescrita.*) PROCEDURE CargarListaTiposElementales(VAR l: ListaTiposElementales); VAR t: TipoElemental; //TipoElemental auxiliar. Begin IniciarListaTiposElementales(l); Query.SQL.Text:= 'SELECT * FROM TiposElementales'; Query.Open; WHILE NOT Query.EOF DO Begin WITH t DO begin id:= Query.FieldByName('TYPE_ID').AsInteger; nombre:= Query.FieldByName('Nombre').AsString; end; AgregarTipoListaTiposElementales(t,l); Query.Next; end; Query.Close; end; BEGIN //MAIN Código de inicialización ****************************************** Conn := TSQLConnector.Create(nil); with Conn do begin ConnectorType := CONNECTION_TYPE; HostName := ''; // not important DatabaseName := DATABASE_NAME; UserName := ''; // not important Password := ''; // not important end; Trans := TSQLTransaction.Create(nil); Conn.Transaction := Trans; Query := TSQLQuery.Create(nil); Query.DataBase := Conn; END.//**************************************************************************
unit CustListFormU; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, DBGrids; type TCustListForm = class(TForm) Button1: TButton; Button2: TButton; DBGrid2: TDBGrid; procedure FormShow(Sender: TObject); procedure FormHide(Sender: TObject); private FSaveSync: Boolean; function GetCustNo: Integer; { Private declarations } public { Public declarations } property CustNo: Integer read GetCustNo; end; implementation uses ClientDataModuleU; {$R *.DFM} { TForm1 } function TCustListForm.GetCustNo: Integer; begin Result := ClientDataModule.CustomerListDataSet.FieldByName('CustNo').AsInteger; end; procedure TCustListForm.FormShow(Sender: TObject); begin FSaveSync := ClientDataModule.SyncToCustomerNumber; ClientDataModule.SyncToCustomerNumber := False; end; procedure TCustListForm.FormHide(Sender: TObject); begin ClientDataModule.SyncToCustomerNumber := FSaveSync; end; end.
unit UniDBC; interface uses SysUtils, Variants, Classes, Dialogs, UniProvider, OracleUniProvider, Uni, SQLServerUniProvider; type TConnCfg = record ProviderName, Server: string; Port: Word; Database, Username, Password: string; IsDirect: Boolean; end; TDBCtl = class(TComponent) private FSQLServerPrv: TSQLServerUniProvider; FOraclePrv: TOracleUniProvider; FConn: TUniConnection; FTrans: TUniTransaction; FLastErrInfo: string; function _ConnDB(const ProviderName, Server: string; const Port: Word; const Database, Username, Password: string; const IsDirect: Boolean): Boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function ConnDB(const ConnCfg: TConnCfg): Boolean; function ReConnDB(): Boolean; function IsConn(): Boolean; procedure StartTrans; procedure CommitTrans; procedure RollbackTrans; function GetQuery(var Qry: TUniQuery; const Sql: string; Pv: array of Variant): boolean; function ExecCmd(const Sql: string; Pv: array of Variant): Integer; //第一个字段值 function GetFistFieldValue(const Sql: string; Pv: array of Variant; var Value: Variant): Integer; //服务器时间,可以覆盖 function GetSvrDateTime(var dt: TDateTime): Boolean; virtual; property Conn: TUniConnection read FConn; property LastErrInfo: string read FLastErrInfo; end; implementation procedure TDBCtl.StartTrans(); begin FTrans.StartTransaction; end; procedure TDBCtl.CommitTrans(); begin FTrans.Commit; end; procedure TDBCtl.RollbackTrans(); begin FTrans.Rollback; end; function TDBCtl.GetQuery(var Qry: TUniQuery; const Sql: string; Pv: array of Variant): boolean; var i: Integer; begin Result := False; if Qry = nil then Exit; try Qry.Close; Qry.Connection := FConn; Qry.Sql.Text := Sql; for i := low(Pv) to high(Pv) do Qry.Params[i].Value := Pv[i]; Qry.Open(); Result := True; except on Ex: Exception do FLastErrInfo := Ex.Message; end; end; function TDBCtl.GetSvrDateTime(var dt: TDateTime): Boolean; begin dt := Now(); Result := True; end; function TDBCtl.ExecCmd(const Sql: string; Pv: array of Variant): Integer; var Qry: TUniQuery; i: Integer; begin Result := -1; Qry := TUniQuery.Create(Self); try Qry.Close; Qry.Connection := FConn; Qry.Sql.Text := Sql; for i := low(Pv) to high(Pv) do Qry.Params[i].Value := Pv[i]; Qry.Execute; Result := Qry.RowsAffected; except on Ex: Exception do FLastErrInfo := Ex.Message; end; end; function TDBCtl.GetFistFieldValue(const Sql: string; Pv: array of Variant; var Value: Variant): Integer; var Qry: TUniQuery; i: Integer; begin Result := -1; Qry := TUniQuery.Create(Self); try Qry.Close; Qry.Connection := FConn; Qry.Sql.Text := Sql; for i := low(Pv) to high(Pv) do Qry.Params[i].Value := Pv[i]; Qry.Open; if not Qry.IsEmpty then Value := Qry.Fields[0].Value; Result := Qry.RecordCount; except on Ex: Exception do FLastErrInfo := Ex.Message; end; end; function TDBCtl._ConnDB(const ProviderName, Server: string; const Port: Word; const Database, Username, Password: string; const IsDirect: Boolean): Boolean; begin Result := False; try //建立连接 FConn.Close; FConn.ProviderName := ProviderName; if IsDirect then begin //Oracle 直连 if UpperCase(ProviderName) = UpperCase('Oracle') then FConn.SpecificOptions.Values['Direct'] := 'True'; end; FConn.Server := Server; FConn.Port := Port; FConn.Database := Database; FConn.Username := Username; FConn.Password := Password; FConn.LoginPrompt := False; FConn.Connect; Result := FConn.Connected; except on Ex: Exception do FLastErrInfo := Ex.Message; end; end; function TDBCtl.ConnDB(const ConnCfg: TConnCfg): Boolean; begin Result := _ConnDB(ConnCfg.ProviderName, ConnCfg.Server, ConnCfg.Port, ConnCfg.Database, ConnCfg.Username, ConnCfg.Password, ConnCfg.IsDirect); end; constructor TDBCtl.Create(AOwner: TComponent); begin inherited; FSQLServerPrv := TSQLServerUniProvider.Create(Self); FOraclePrv := TOracleUniProvider.Create(Self); FConn := TUniConnection.Create(Self); FTrans := TUniTransaction.Create(Self); //建立事务连接 FTrans.DefaultConnection := FConn; end; destructor TDBCtl.Destroy; begin FTrans.Free; if FConn.Connected then FConn.Close; FConn.Free; FOraclePrv.Free; FSQLServerPrv.Free; inherited; end; function TDBCtl.IsConn: Boolean; begin Result := FConn.Connected; end; function TDBCtl.ReConnDB: Boolean; begin Result := False; try FConn.Close; FConn.Connect; Result := FConn.Connected; except on Ex: Exception do FLastErrInfo := Ex.Message; end; end; end.
unit P_Insa; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.ToolWin, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Mask, Vcl.DBCtrls, Vcl.Buttons, Vcl.WinXCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TInsa = class(TForm) Panel1: TPanel; ToolBar1: TToolBar; Panel2: TPanel; InsaDBGrid: TDBGrid; First: TSpeedButton; Prior: TSpeedButton; Next: TSpeedButton; Last: TSpeedButton; Label1: TLabel; Label2: TLabel; Insert: TButton; Modify: TButton; Cancel: TButton; Delete: TButton; Inquiry: TButton; Save: TButton; Refresh: TButton; InsaSearchBox: TSearchBox; DBEdit1: TDBEdit; DBEdit2: TDBEdit; Label3: TLabel; DBLookupComboBox1: TDBLookupComboBox; FDQuery1: TFDQuery; DataSource1: TDataSource; FDQuery1M_ID: TIntegerField; FDQuery1M_NAME: TWideStringField; FDQuery1M_TEAM: TStringField; FDQuery1M_PHONE: TWideStringField; procedure InsertClick(Sender: TObject); procedure ModifyClick(Sender: TObject); procedure CancelClick(Sender: TObject); procedure DeleteClick(Sender: TObject); procedure SaveClick(Sender: TObject); procedure RefreshClick(Sender: TObject); procedure InquiryClick(Sender: TObject); procedure InsaSearchBoxChange(Sender: TObject); procedure FirstClick(Sender: TObject); procedure PriorClick(Sender: TObject); procedure NextClick(Sender: TObject); procedure LastClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure DBEdit1Change(Sender: TObject); procedure DBEdit2Change(Sender: TObject); procedure DBEdit1KeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var Insa: TInsa; implementation {$R *.dfm} uses P_DataModule, P_Main, P_ProjectInfo, P_Department, P_ProjectMember; var SaveInsa : Boolean; procedure TInsa.InsertClick(Sender: TObject); begin TDataModule.InsaTable.Insert; Insa.DBEdit1.SetFocus; end; procedure TInsa.ModifyClick(Sender: TObject); begin TDataModule.InsaTable.Edit; if MessageDlg('정말 수정하시겠습니까?', mtConfirmation, [mbYes, mbNo],0) = mrYes then try TDataModule.InsaTable.Edit; except on e:Exception do ShowMessage(e.Message); end; end; procedure TInsa.DeleteClick(Sender: TObject); begin if MessageDlg('정말 삭제하시겠습니까?', mtConfirmation, [mbYes, mbNo],0) = mrYes then try TDataModule.InsaTable.Delete; except on e:Exception do ShowMessage(e.Message); end; end; procedure TInsa.InquiryClick(Sender: TObject); begin InsaDBGrid.DataSource := DataSource1; Fdquery1.Refresh; end; procedure TInsa.RefreshClick(Sender: TObject); begin TDataModule.InsaTable.Refresh; end; procedure TInsa.CancelClick(Sender: TObject); begin TDataModule.InsaTable.Cancel; end; procedure TInsa.SaveClick(Sender: TObject); begin if SaveInsa then TDataModule.InsaTable.Post; end; procedure TInsa.DBEdit1Change(Sender: TObject); begin if (DBEdit1.Text <> '') then SaveInsa := True; end; procedure TInsa.DBEdit1KeyPress(Sender: TObject; var Key: Char); begin if key = #13 then SelectNext(ActiveControl, true, true); end; procedure TInsa.DBEdit2Change(Sender: TObject); begin if (DBEdit2.Text <> '') then SaveInsa := True; end; procedure TInsa.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; Insa := nil; end; procedure TInsa.FormShow(Sender: TObject); begin DBEdit1.Text := ''; DBEdit2.Text := ''; DBLookupComboBox1.KeyValue := ''; SaveInsa := False; end; procedure TInsa.InsaSearchBoxChange(Sender: TObject); begin TDataModule.InsaTable.IndexFieldNames := 'M_ID'; TDataModule.InsaTable.IndexFieldNames := 'M_NAME'; TDataModule.InsaTable.IndexFieldNames := 'M_TEAM'; TDataModule.InsaTable.IndexFieldNames := 'M_PHONE'; TDataModule.InsaTable.FindNearest([InsaSearchBox.Text]); end; procedure TInsa.FirstClick(Sender: TObject); begin FDQuery1.First; TDataModule.InsaTable.First; end; procedure TInsa.PriorClick(Sender: TObject); begin if Not FDQuery1.Bof then FDQuery1.Prior; if Not TDataModule.InsaTable.Bof then TDataModule.InsaTable.Prior; end; procedure TInsa.NextClick(Sender: TObject); begin if Not FDQuery1.Eof then FDQuery1.Next; if Not TDataModule.InsaTable.Eof then TDataModule.InsaTable.Next; end; procedure TInsa.LastClick(Sender: TObject); begin FDQuery1.Last; TDataModule.InsaTable.Last; end; end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------ //单元说明: // 本单元是工程数据集窗体的基本单元 // //主要实现: //-----------------------------------------------------------------------------} unit untEasyPlateDBForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, untEasyPlateDBBaseForm, DB, DBClient, ImgList, untEasyToolBar, untEasyToolBarStylers, untReconcileError, ExtCtrls, untEasyGroupBox, DBGrids, untEasyPageControl, Buttons, Grids, ComCtrls, StdCtrls, DBCtrls, dbcgrids, Tabs; type //浏览 编辑(插入) 无记录 不可用状态 TEasyDataState = (edsBrowse, edsInsert, edsEdit, edsNoRecord, edsInactive); TfrmEasyPlateDBForm = class(TfrmEasyPlateDBBaseForm) dkpDBForm: TEasyDockPanel; tlbDBForm: TEasyToolBar; tlbStyDBForm: TEasyToolBarOfficeStyler; btnNew: TEasyToolBarButton; imgTlbDBForm: TImageList; btnEdit: TEasyToolBarButton; btnCancel: TEasyToolBarButton; btnDelete: TEasyToolBarButton; btnCopy: TEasyToolBarButton; btnFind: TEasyToolBarButton; btnPrint: TEasyToolBarButton; btnExit: TEasyToolBarButton; btnRefresh: TEasyToolBarButton; btnSave: TEasyToolBarButton; cdsMain: TClientDataSet; pnlContainer: TEasyPanel; pgcContainer: TEasyPageControl; dsMain: TDataSource; procedure btnExitClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnNewClick(Sender: TObject); procedure btnEditClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnCopyClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnRefreshClick(Sender: TObject); procedure btnFindClick(Sender: TObject); procedure btnPrintClick(Sender: TObject); procedure cdsMainReconcileError(DataSet: TCustomClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction); procedure __ReconcileError(DataSet: TCustomClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure dsMainStateChange(Sender: TObject); private { Private declarations } FMainClientDataSet: TClientDataSet; //绑定数据的ClientDataSet FMainDataSource : TDataSource; FMainSQL : string; //窗体初始化时执行的SQL语句 FDeleteMark: String; //删除标志 FISSaveSuccessMsg : Boolean; //当保存成功时是否提示信息 FISDeleteSuccessMsg : Boolean; //当删除时提示信息 FISBtnNotVisibleHotKey: Boolean; //按钮在非可视状态下是否接收快捷键 FISCanHotKey : Boolean; FEasyDataState : TEasyDataState; //数据集状态 FNotNullFieldList : TStrings; //非空和非复制字段列表 FNotCopyFieldList : TStrings; FNotNullFieldColor : TColor; //非空字段颜色 FDFMList : TStrings; FNotNullControlList : TList; //设置非空字段的颜色的过程 procedure SetEasyMainClientDataSet(const Value: TClientDataSet); function GetEasyMainClientDataSet: TClientDataSet; procedure DoShow; override; //加载模块的配置界面所需要的函数 procedure BindRoot(Form: TComponent; AFileName: string); procedure ReadError(Reader: TReader; const Message: string; var Handled: Boolean); function GetMainDataSource: TDataSource; procedure SetMainDataSource(const Value: TDataSource); // function GetMainGrid: TcxGrid; // procedure SetMainGrid(const Value: TcxGrid); protected { protected declarations } //改变按钮输入状态的过程 procedure SetAllControlStatus; virtual; //当数据集无记录时 procedure SetBtnStatus_NoRecord; virtual; procedure SetSQL(AValue: string); procedure DoSetSQL(const Value: string); virtual; procedure DoSave(sender : TObject); function Append: Boolean; virtual; function Edit: Boolean; virtual; function Save: Boolean; virtual; function Cancel: Boolean; virtual; function Copy: Boolean; virtual; function Print: Boolean;virtual; //Save function BeforeSave(DataSet: TDataSet): Boolean; virtual; function AfterSave(DataSet: TDataSet): Boolean; virtual; function SaveError(DataSet: TDataSet): Boolean; virtual; // 删除数据的过程,含状态控制 ,包含Delete function DeleteClick(DataSet: TDataSet):Boolean;virtual; // 删除数据的过程,不含状态控制 function Delete(AClientDataSet: TClientDataSet; ShowHint: Boolean): Boolean; virtual; function BeforeDelete(DataSet: TDataSet): Boolean; virtual; function ExecuteDelete(AClientDataSet: TClientDataSet): Boolean; virtual; function AfterDelete(DataSet: TDataSet): Boolean; virtual; function SetDeleteMark(AClientDataSet: TClientDataSet): Boolean; virtual; function GetMainClientDataSet: TClientDataSet; procedure SetClientDataSet(const Value: TClientDataSet); function GetMainSQL: string; procedure SetMainSQL(const Value: string); function GetNotNullFieldColor: TColor; procedure SetNullFieldColor(const Value: TColor); function GetMainDeleteMark: string; procedure SetMainDeleteMark(const Value: string); //复制操作相关 function BuildCopyList(AClientDataSet: TClientDataSet; ANotCopyFieldList: TStrings): TStrings; procedure CopyDataFromList(AClientDataSet: TClientDataSet; ACopyFieldList: TStrings); function GetEasyDataState: TEasyDataState; procedure SetEasyDataState(const Value: TEasyDataState); procedure SetNotNullFieldColor(const Value: TColor); //设置非空字段的控件颜色 procedure SetNotNullFieldsControlColor; virtual; //保存之前检查必填字段是否有空 function CheckNotNullFields: Boolean; virtual; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; //非空和非复制字段处理 procedure AddNotNullField(FieldName: string); procedure AddNotNullFields(FieldList: array of string); procedure AddNotCopyField(FieldName: string); procedure AddNotCopyFields(FieldList: array of string); procedure AddDFMFile(FieldName: string); procedure AddDFMFiles(FieldList: array of string); //加载配置DFM文件 procedure LoadEasyDFM(DFMFile: string); //非空字段的颜色 property NotNullFieldColor: TColor read GetNotNullFieldColor write SetNotNullFieldColor default clBlue; //必须指定EasyMainClientDataSet property EasyMainClientDataSet: TClientDataSet read GetEasyMainClientDataSet write SetEasyMainClientDataSet; //操作提示 property ISSaveSuccessMsg : Boolean read FISSaveSuccessMsg write FISSaveSuccessMsg; property ISDeleteSuccessMsg : Boolean read FISDeleteSuccessMsg write FISDeleteSuccessMsg; property ISBtnNotVisibleHotKey : Boolean read FISBtnNotVisibleHotKey write FISBtnNotVisibleHotKey; property ISCanHotKey : Boolean read FISCanHotKey write FISCanHotKey; //数据删除标志 property MainDeleteMark: string read GetMainDeleteMark write SetMainDeleteMark; property EasyDataState: TEasyDataState read GetEasyDataState write SetEasyDataState; //初始化数据集信息 property MainClientDataSet: TClientDataSet read GetMainClientDataSet write SetClientDataSet; property MainDataSource: TDataSource read GetMainDataSource write SetMainDataSource; // property MainGrid: TcxGrid read GetMainGrid write SetMainGrid; property MainSQL: string read GetMainSQL write SetMainSQL; end; var frmEasyPlateDBForm: TfrmEasyPlateDBForm; implementation {$R *.dfm} uses untEasyUtilMethod, untEasyDBConnection, untEasyBaseConst, TypInfo, untEasyIODFM, untEasyStdCmpsReg, untEasyPlateBaseForm; { TfrmEasyPlateDBForm } procedure TfrmEasyPlateDBForm.AddNotCopyField(FieldName: string); begin if not Assigned(FNotCopyFieldList) then FNotCopyFieldList := TStringList.Create; if FNotCopyFieldList.IndexOf(UpperCase(FieldName)) < 0 then FNotCopyFieldList.Add(UpperCase(FieldName)); end; procedure TfrmEasyPlateDBForm.AddNotCopyFields(FieldList: array of string); var I: Integer; begin for I := Low(FieldList) to High(FieldList) do AddNotCopyField(FieldList[I]); end; procedure TfrmEasyPlateDBForm.AddNotNullField(FieldName: string); begin if not Assigned(FNotNullFieldList) then FNotNullFieldList := TStringList.Create; if FNotNullFieldList.IndexOf(FieldName) < 0 then FNotNullFieldList.Add(FieldName); end; procedure TfrmEasyPlateDBForm.AddNotNullFields(FieldList: array of string); var I: Integer; begin for I := Low(FieldList) to High(FieldList) do AddNotNullField(FieldList[I]); end; function TfrmEasyPlateDBForm.AfterDelete(DataSet: TDataSet): Boolean; begin Result := True; end; function TfrmEasyPlateDBForm.AfterSave(DataSet: TDataSet): Boolean; begin Result := True; end; function TfrmEasyPlateDBForm.Append: Boolean; begin Result := False; MainClientDataSet.ReadOnly := False; if Assigned(MainClientDataSet) then begin MainClientDataSet.Append; //添加时间 //用户权限控制 Result := True; end; end; function TfrmEasyPlateDBForm.BeforeDelete(DataSet: TDataSet): Boolean; begin Result := True; end; function TfrmEasyPlateDBForm.BeforeSave(DataSet: TDataSet): Boolean; begin Result := True; end; function TfrmEasyPlateDBForm.Cancel: Boolean; begin Result := False; if Assigned(MainClientDataSet) then begin MainClientDataSet.CancelUpdates; Result := True; end; end; function TfrmEasyPlateDBForm.Copy: Boolean; var CopyList : TStrings; bCanContinue: Boolean; begin Result := False; if Assigned(MainClientDataSet) then begin bCanContinue := True; if not GetUserRight then begin bCanContinue := False; EasyErrorHint(EasyErrorHint_NRight); end; if bCanContinue then begin CopyList := TStringList.Create; if not Assigned(FNotCopyFieldList) then FNotCopyFieldList := TStringList.Create; //获取此表的主键字段和不可复制字段 // if FNotCopyFieldList.Count <= 0 then // FNotCopyFieldList.AddStrings(GetUniqueKeys(GetTableName(FClientDataSet), Self.Connection, [ikPrimary, ikUnique])); try CopyList := BuildCopyList(MainClientDataSet, FNotCopyFieldList); if Append then begin CopyDataFromList(MainClientDataSet, CopyList); Result := True; end; finally CopyList.Free; end; end; end; end; constructor TfrmEasyPlateDBForm.Create(AOwner: TComponent); begin inherited Create(AOwner); FEasyDataState := edsInactive; if not Assigned(FNotNullFieldList) then FNotNullFieldList := TStringList.Create; if not Assigned(FNotCopyFieldList) then FNotCopyFieldList := TStringList.Create; if not Assigned(FDFMList) then FDFMList := TStringList.Create; //打开数据集 if MainSQL <> '' then begin if DMEasyDBConnection.EasyAppType = 'CAS' then begin if MainClientDataSet <> nil then begin if EasyRDMDisp = nil then EasyErrorHint(EasyErrorHint_RDMDispNIL) else begin MainClientDataSet.Data := EasyRDMDisp.EasyGetRDMData(MainSQL); if MainClientDataSet.RecordCount > 0 then EasyDataState := edsBrowse else SetBtnStatus_NoRecord; end; end; end; end; end; function TfrmEasyPlateDBForm.Delete(AClientDataSet: TClientDataSet; ShowHint: Boolean): Boolean; var bCanContinue : Boolean; begin Result := False; bCanContinue := True; //判断当前用户的操作权限 if not GetUserRight then begin bCanContinue := False; EasyErrorHint(EasyErrorHint_NRight); Exit; end else begin if bCanContinue then begin if BeforeDelete(AClientDataSet) then begin //如果执行成功提示 和 显示信息 if ISDeleteSuccessMsg and ShowHint then begin if MessageDlg(EasyHint_ConfirmDelete, mtWarning, [mbYes, mbNo], 0) = mrYes then begin if Trim(MainDeleteMark) <> '' then Result := SetDeleteMark(MainClientDataSet) else Result := ExecuteDelete(MainClientDataSet); end; end else begin if Trim(MainDeleteMark) <> '' then Result := SetDeleteMark(MainClientDataSet) else Result := ExecuteDelete(MainClientDataSet); end; end; end; end; if Result then AfterDelete(MainClientDataSet); end; function TfrmEasyPlateDBForm.DeleteClick(DataSet: TDataSet): Boolean; begin Result := False; if Delete(MainClientDataSet, True) then begin if MainClientDataSet.RecordCount > 0 then EasyDataState := edsBrowse else SetBtnStatus_NoRecord; Result := True; end; end; destructor TfrmEasyPlateDBForm.Destroy; begin if Assigned(FNotNullFieldList) then FNotNullFieldList.Free; if Assigned(FNotCopyFieldList) then FNotCopyFieldList.Free; if Assigned(MainClientDataSet) then MainClientDataSet.Free; if Assigned(FDFMList) then FDFMList.Free; inherited Destroy; end; procedure TfrmEasyPlateDBForm.DoSave(sender: TObject); begin Self.Save; end; procedure TfrmEasyPlateDBForm.DoSetSQL(const Value: string); begin end; procedure TfrmEasyPlateDBForm.DoShow; begin inherited; SetNotNullFieldsControlColor; end; function TfrmEasyPlateDBForm.Edit: Boolean; var bCanContinues : Boolean; begin Result := False; //检查是否指定数据集 if Assigned(MainClientDataSet) then begin if not MainClientDataSet.Active then MainClientDataSet.Open; bCanContinues := True; //检查用户权限 if not GetUserRight then begin bCanContinues := false; EasyErrorHint(EasyErrorHint_NRight); end; //有用户权限 进入Edit if bCanContinues then begin MainClientDataSet.Edit; Result := True; end else EasyErrorHint(EasyEditHint_Edit); end; end; function TfrmEasyPlateDBForm.ExecuteDelete( AClientDataSet: TClientDataSet): Boolean; begin Result := True; end; function TfrmEasyPlateDBForm.GetEasyMainClientDataSet: TClientDataSet; begin Result := FMainClientDataSet; end; function TfrmEasyPlateDBForm.Print: Boolean; begin Result := True; if Assigned(MainClientDataSet) then begin if not MainClientDataSet.Active then MainClientDataSet.Open; if not GetUserRight then begin EasyErrorHint(EasyErrorHint_NRight); Result := False end else Result := True; end; end; function TfrmEasyPlateDBForm.Save: Boolean; begin Result := False; //在保存之前检查是否还NOT NULL字段未填,是否指定数据集 if not CheckNotNullFields and Assigned(MainClientDataSet) then begin if DMEasyDBConnection.EasyAppType = 'CS' then begin end else if DMEasyDBConnection.EasyAppType = 'CAS' then begin end; end; end; function TfrmEasyPlateDBForm.SaveError(DataSet: TDataSet): Boolean; begin Result := True; end; procedure TfrmEasyPlateDBForm.SetAllControlStatus; //设置Grid的编辑状态 {procedure SetDBTableViewState(AState: Boolean); var I: Integer; begin if MainGrid <> nil then begin for I := 0 to MainGrid.ViewCount - 1 do begin if MainGrid.Views[I] is TcxGridDBTableView then begin // ShowMessage(TcxGridDBTableView(MainGrid.Views[I]).Name); TcxGridDBTableView(MainGrid.Views[I]).OptionsData.Editing := AState; end; end; end; end; } //编辑状态 procedure SetEditButtons; begin btnNew.Enabled := False; btnEdit.Enabled := False; btnDelete.Enabled := False; btnCancel.Enabled := True; btnSave.Enabled := True; btnCopy.Enabled := False; btnFind.Enabled := False; btnRefresh.Enabled := False; btnPrint.Enabled := False; // SetDBTableViewState(True); //新增操作之前设置 // MainClientDataSet.ReadOnly := false; end; procedure SetBrowseButtons; begin btnNew.Enabled := True; btnEdit.Enabled := True; btnDelete.Enabled := True; btnCancel.Enabled := False; btnSave.Enabled := False; btnCopy.Enabled := True; btnFind.Enabled := True; btnRefresh.Enabled := True; btnPrint.Enabled := True; // SetDBTableViewState(False); MainClientDataSet.ReadOnly := True; end; procedure SetInactiveButtons; begin btnNew.Enabled := False; btnEdit.Enabled := False; btnDelete.Enabled := False; btnCancel.Enabled := False; btnSave.Enabled := False; btnCopy.Enabled := False; btnFind.Enabled := True; btnRefresh.Enabled := False; btnPrint.Enabled := False; // SetDBTableViewState(False); MainClientDataSet.ReadOnly := True; end; procedure SetNoRecordButtons; begin btnNew.Enabled := True; btnEdit.Enabled := False; btnDelete.Enabled := False; btnCancel.Enabled := False; btnSave.Enabled := False; btnCopy.Enabled := False; btnFind.Enabled := False; btnRefresh.Enabled := False; btnPrint.Enabled := False; // SetDBTableViewState(False); MainClientDataSet.ReadOnly := True; end; procedure SetUserModuleButtonAuth; var iAuth: string; begin iAuth := getUserModuleRight(FormId, DMEasyDBConnection.EasyCurrLoginUserID); if iAuth[1] = '1' then btnNew.Enabled := True else btnNew.Enabled := False; if iAuth[2] = '1' then btnEdit.Enabled := True else btnEdit.Enabled := False; if iAuth[3] = '1' then btnDelete.Enabled := True else btnDelete.Enabled := False; if iAuth[4] = '1' then btnCopy.Enabled := True else btnCopy.Enabled := False; if iAuth[5] = '1' then btnFind.Enabled := True else btnFind.Enabled := False; if iAuth[6] = '1' then btnPrint.Enabled := True else btnPrint.Enabled := False; end; begin case EasyDataState of edsEdit, edsInsert: begin SetEditButtons; end; edsBrowse: begin SetBrowseButtons; end; edsInactive: begin SetInactiveButtons; end; edsNoRecord: begin SetNoRecordButtons; end; end; // SetUserModuleButtonAuth; end; procedure TfrmEasyPlateDBForm.SetBtnStatus_NoRecord; begin if MainClientDataSet.RecordCount = 0 then begin btnNew.Enabled := True; btnEdit.Enabled := False; btnDelete.Enabled := False; btnSave.Enabled := False; btnCopy.Enabled := False; btnFind.Enabled := False; end; end; function TfrmEasyPlateDBForm.SetDeleteMark( AClientDataSet: TClientDataSet): Boolean; begin { try // SetHhfDeleteMark(AClientDataSet,DeleteMark); FHhfRelateUpdates.RunUpdate(ukModify, AClientDataSet); // SetCttRefreshDeleteMark(AClientDataSet); Result := True; except on E:Exception do begin SysErrorBox(NDeleteMark); Result := False; end; end; } end; procedure TfrmEasyPlateDBForm.SetEasyDataState(const Value: TEasyDataState); begin FEasyDataState := Value; //重置按钮状态 SetAllControlStatus; end; procedure TfrmEasyPlateDBForm.SetEasyMainClientDataSet( const Value: TClientDataSet); begin FMainClientDataSet := Value; end; procedure TfrmEasyPlateDBForm.btnExitClick(Sender: TObject); begin inherited; Close; end; procedure TfrmEasyPlateDBForm.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; if MainClientDataSet.ChangeCount > 0 then begin case EasySelectHint('') of ID_YES: begin DoSave(Sender); Action := caFree; end; ID_NO: Action := caFree; ID_CANCEL: begin Action := caNone; end; end; end; end; procedure TfrmEasyPlateDBForm.FormCreate(Sender: TObject); begin inherited; FISSaveSuccessMsg := True; FISDeleteSuccessMsg := True; FISBtnNotVisibleHotKey:=False; FISCanHotKey:=True; //KeyPreview IsKeyPreView := True; FMainClientDataSet := cdsMain; FMainDataSource := dsMain; //非空字段颜色默认为蓝色 clBlue FNotNullFieldColor := clBlue; FNotNullControlList := TList.Create; end; procedure TfrmEasyPlateDBForm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); function GetState(Value : TEasyToolBarButton): Boolean; begin Result := Value.Enabled ; if not FISBtnNotVisibleHotKey then Result:=(Result and Value.Visible); end; begin inherited; if FISCanHotKey then case Key of 112: if GetState(btnNew) then btnNewClick(Sender); 113: if GetState(btnEdit) then btnEditClick(Sender); 114: if GetState(btnDelete) then btnDeleteClick(Sender); 115: if GetState(btnSave) then DoSave(Sender); 116: if GetState(btnCancel) then btnCancelClick(Sender); 117: if GetState(btnCopy) then btnCopyClick(Sender); 118: if GetState(btnFind) then btnFindClick(Sender); 119: if GetState(btnPrint) then btnPrintClick(Sender); 120: if GetState(btnExit) then btnExitClick(Sender); end; end; procedure TfrmEasyPlateDBForm.btnNewClick(Sender: TObject); begin inherited; if Append then EasyDataState := edsInsert; end; procedure TfrmEasyPlateDBForm.btnEditClick(Sender: TObject); begin inherited; if Edit then EasyDataState := edsEdit; end; procedure TfrmEasyPlateDBForm.btnDeleteClick(Sender: TObject); begin inherited; DeleteClick(MainClientDataSet); end; procedure TfrmEasyPlateDBForm.btnCancelClick(Sender: TObject); begin inherited; if Cancel then begin if MainClientDataSet.RecordCount > 0 then EasyDataState := edsBrowse else EasyDataState := edsNoRecord; end; end; procedure TfrmEasyPlateDBForm.btnCopyClick(Sender: TObject); begin inherited; if Copy then EasyDataState := edsInsert; end; procedure TfrmEasyPlateDBForm.btnSaveClick(Sender: TObject); begin inherited; DoSave(Sender); end; procedure TfrmEasyPlateDBForm.btnRefreshClick(Sender: TObject); begin inherited; if EasyDataState in [edsInsert, edsEdit] then begin if MessageDlg(EasyRefreshHint_Save, mtWarning, [mbYes, mbNo], 0) = mrYes then begin if Save then EasyDataState := edsBrowse; end; end; end; procedure TfrmEasyPlateDBForm.btnFindClick(Sender: TObject); begin inherited; if EasyDataState in [edsInsert, edsEdit] then begin if MessageDlg(EasyFindHint_Save, mtWarning, [mbYes, mbNo], 0) = mrYes then begin if Save then EasyDataState := edsBrowse; end; end; end; procedure TfrmEasyPlateDBForm.btnPrintClick(Sender: TObject); begin inherited; if not Print then Exit; end; function TfrmEasyPlateDBForm.GetMainClientDataSet: TClientDataSet; begin Result := FMainClientDataSet; end; procedure TfrmEasyPlateDBForm.SetClientDataSet( const Value: TClientDataSet); begin FMainClientDataSet := Value; end; function TfrmEasyPlateDBForm.GetMainSQL: string; begin Result := FMainSQL; end; procedure TfrmEasyPlateDBForm.SetMainSQL(const Value: string); begin FMainSQL := Value; end; function TfrmEasyPlateDBForm.GetNotNullFieldColor: TColor; begin Result := FNotNullFieldColor; end; procedure TfrmEasyPlateDBForm.SetNullFieldColor(const Value: TColor); begin FNotNullFieldColor := Value; end; function TfrmEasyPlateDBForm.GetMainDeleteMark: string; begin Result := FDeleteMark; end; procedure TfrmEasyPlateDBForm.SetMainDeleteMark(const Value: string); begin FDeleteMark := Value; end; procedure TfrmEasyPlateDBForm.cdsMainReconcileError( DataSet: TCustomClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction); begin inherited; __ReconcileError(DataSet, E, UpdateKind, Action); end; procedure TfrmEasyPlateDBForm.__ReconcileError( DataSet: TCustomClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction); begin HandleReconcileError(DataSet, UpdateKind, E); end; function TfrmEasyPlateDBForm.BuildCopyList(AClientDataSet: TClientDataSet; ANotCopyFieldList: TStrings): TStrings; begin end; procedure TfrmEasyPlateDBForm.CopyDataFromList( AClientDataSet: TClientDataSet; ACopyFieldList: TStrings); begin end; function TfrmEasyPlateDBForm.GetEasyDataState: TEasyDataState; begin Result := FEasyDataState; end; procedure TfrmEasyPlateDBForm.SetNotNullFieldColor(const Value: TColor); begin FNotNullFieldColor := Value; end; function TfrmEasyPlateDBForm.CheckNotNullFields: Boolean; var I, J: Integer; TmpComponent: TComponent; TmpFieldName, ACaption : string; begin Result := False; if FDFMList.Count = 0 then Exit; if FDFMList.Count <= 1 then begin //1 为EasyPageControl 2 为后附加的窗体 if pnlContainer.ControlCount = 2 then begin for I := 0 to TForm(pnlContainer.Controls[1]).ComponentCount - 1 do begin TmpComponent := TForm(pnlContainer.Controls[1]).Components[I]; //如果是非空字段或Tag = 100的非空字段标识 if (FNotNullFieldList.IndexOf(GetDBDataBinding(TmpComponent, ACaption)) <> -1) or (TmpComponent.Tag = 100) then //获取字段名字 TmpFieldName := GetDBDataBinding(TmpComponent, ACaption); if VarToStrDef(MainClientDataSet.FieldByName(TmpFieldName).Value, '') = '' then begin Result := True; EasyHint('【' + ACaption +'】' + EasyNotNullField_Hint); Exit; // Break; end; end; end; end else begin if pgcContainer.PageCount > 0 then pgcContainer.ActivePageIndex := 0; for I := 0 to pgcContainer.PageCount - 1 do begin if pgcContainer.ActivePage.ControlCount = 1 then begin for J := 0 to TForm(pgcContainer.Pages[I].Controls[0]).ComponentCount - 1 do begin TmpComponent := TForm(pgcContainer.Pages[I].Controls[0]).Components[J]; //如果是非空字段或Tag = 100的非空字段标识 if (FNotNullFieldList.IndexOf(GetDBDataBinding(TmpComponent, ACaption)) <> -1) or (TmpComponent.Tag = 100) then //获取字段名字 TmpFieldName := GetDBDataBinding(TmpComponent, ACaption); if VarToStrDef(MainClientDataSet.FieldByName(TmpFieldName).Value, '') = '' then begin Result := True; EasyHint('【' + ACaption +'】' + EasyNotNullField_Hint); Exit; // Break; end; end; end; pgcContainer.ActivePageIndex := pgcContainer.ActivePageIndex + 1; end; if pgcContainer.PageCount > 0 then pgcContainer.ActivePageIndex := 0; end; end; procedure TfrmEasyPlateDBForm.SetSQL(AValue: string); begin end; procedure TfrmEasyPlateDBForm.SetNotNullFieldsControlColor; var I, J : Integer; TmpComponent: TComponent; ACaption : string; begin if FDFMList.Count = 0 then Exit; if FDFMList.Count <= 1 then begin //1 为EasyPageControl 2 为后附加的窗体 if pnlContainer.ControlCount = 2 then begin for I := 0 to TForm(pnlContainer.Controls[1]).ComponentCount - 1 do begin TmpComponent := TForm(pnlContainer.Controls[1]).Components[I]; //绑定数据源 if MainDataSource <> nil then SetEditDataSource(TmpComponent, MainDataSource); //设置非空字段颜色 if (FNotNullFieldList.IndexOf(GetDBDataBinding(TmpComponent, ACaption)) <> -1) or (TmpComponent.Tag = 100) then SetEditLabelColor(TmpComponent, NotNullFieldColor); end; end; end else begin if pgcContainer.PageCount > 0 then pgcContainer.ActivePageIndex := 0; for I := 0 to pgcContainer.PageCount - 1 do begin if pgcContainer.ActivePage.ControlCount = 1 then begin for J := 0 to TForm(pgcContainer.Pages[I].Controls[0]).ComponentCount - 1 do begin TmpComponent := TForm(pgcContainer.Pages[I].Controls[0]).Components[J]; //绑定数据源 if MainDataSource <> nil then SetEditDataSource(TmpComponent, MainDataSource); //设置非空字段颜色 if (FNotNullFieldList.IndexOf(GetDBDataBinding(TmpComponent, ACaption)) <> -1) or (TmpComponent.Tag = 100) then SetEditLabelColor(TmpComponent, NotNullFieldColor); end; end; pgcContainer.ActivePageIndex := pgcContainer.ActivePageIndex + 1; end; if pgcContainer.PageCount > 0 then pgcContainer.ActivePageIndex := 0; end; end; procedure TfrmEasyPlateDBForm.FormDestroy(Sender: TObject); var I: Integer; begin for I := FNotNullControlList.Count - 1 downto 0 do TObject(FNotNullControlList[I]).Free; if pgcContainer.Visible then begin while pgcContainer.PageCount > 0 do FreeComponent_Child(pgcContainer.Pages[0]); end else FreeComponent_NoChild(pnlContainer); inherited; end; procedure TfrmEasyPlateDBForm.BindRoot(Form: TComponent; AFileName: string); var Page: TEasyTabSheet; begin if FDFMList.Count <= 1 then begin if Form is TForm then // 只有Form窗体才能挂靠 begin with TForm(Form) do begin Parent := pnlContainer; pnlContainer.Height := TForm(Form).Height; BorderStyle := bsNone; Align := alClient; Show; end; end; end else begin if Form is TForm then // 只有Form窗体才能挂靠 begin Page := TEasyTabSheet.Create(Self); Page.Caption := TForm(Form).Caption; Page.PageControl := pgcContainer; if pgcContainer.Height > TForm(Form).Height then pgcContainer.Height := TForm(Form).Height; with TForm(Form) do begin Parent := Page; BorderStyle := bsNone; Align := alClient; Show; end; pgcContainer.ActivePageIndex := 0; end; end; end; procedure TfrmEasyPlateDBForm.LoadEasyDFM(DFMFile: string); var fm: TForm; begin if FDFMList.Count = 0 then Exit; if FDFMList.Count = 1 then pgcContainer.Visible := False; fm := TForm.Create(nil); try EasyReadForm(fm, DFMFile); except on e: Exception do begin EasyErrorHint(e.Message); fm.Free; end; end; BindRoot(fm, DFMFile); end; procedure TfrmEasyPlateDBForm.ReadError(Reader: TReader; const Message: string; var Handled: Boolean); begin Handled := True; end; procedure TfrmEasyPlateDBForm.AddDFMFile(FieldName: string); begin if not Assigned(FDFMList) then FDFMList := TStringList.Create; if FDFMList.IndexOf(FieldName) = -1 then FDFMList.Add(FieldName); end; procedure TfrmEasyPlateDBForm.AddDFMFiles(FieldList: array of string); var I: Integer; begin for I := Low(FieldList) to High(FieldList) do AddDFMFile(FieldList[I]); end; procedure TfrmEasyPlateDBForm.FormShow(Sender: TObject); var I: Integer; begin inherited; if not DirectoryExists(EasyPlugPath + 'dfm') then begin try CreateDir(EasyPlugPath + 'dfm'); except on e:Exception do EasyErrorHint(EasyErrorHint_DirCreate + e.Message); end; end; for I := 0 to FDFMList.Count - 1 do begin if FileExists(EasyPlugPath + 'dfm\' + FDFMList.Strings[I]) then LoadEasyDFM(EasyPlugPath + 'dfm\' + FDFMList.Strings[I]) else EasyErrorHint(FDFMList.Strings[I] + EasyErrorHint_NotFile); end; end; function TfrmEasyPlateDBForm.GetMainDataSource: TDataSource; begin Result := FMainDataSource; end; procedure TfrmEasyPlateDBForm.SetMainDataSource(const Value: TDataSource); begin FMainDataSource := Value; end; //function TfrmEasyPlateDBForm.GetMainGrid: TcxGrid; //begin // Result := FMainGrid; //end; // //procedure TfrmEasyPlateDBForm.SetMainGrid(const Value: TcxGrid); //begin // FMainGrid := Value; //end; procedure TfrmEasyPlateDBForm.dsMainStateChange(Sender: TObject); begin inherited; case dsMain.State of dsEdit: EasyDataState := edsEdit; dsInsert: EasyDataState := edsInsert; dsInactive: EasyDataState := edsInactive; dsBrowse: begin if cdsMain.RecordCount <= 0 then EasyDataState := edsInactive else EasyDataState := edsBrowse; end; end; end; end.
PROGRAM SarahRevere(INPUT, OUTPUT); VAR Ch1, Ch2, Ch3, Ch4: CHAR; Looking, Land, Sea: BOOLEAN; PROCEDURE CheckSeaLand(VAR Ch1, Ch2, Ch3, Ch4: CHAR; VAR Land, Sea, Looking: BOOLEAN); BEGIN WHILE ((Looking) AND NOT(Land OR Sea)) DO BEGIN {проверка окна на land} Land := ((Ch1 = 'l') AND (Ch2 = 'a') AND (Ch3 = 'n') AND (Ch4 = 'd')); {проверка окна на sea} Sea := ((Ch1 = 's') AND (Ch2 = 'e') AND (Ch3 = 'a')); {проверка окна на Looking} Looking := (NOT EOLN); {движение окна} IF Looking THEN BEGIN Ch1 := Ch2; Ch2 := Ch3; Ch3 := Ch4; READ(Ch4) END END; END; PROCEDURE MessageFromSarah(VAR Land, Sea: BOOLEAN); BEGIN {создание сообщения Sarah} IF Land THEN WRITELN('The British are coming by land.') ELSE IF Sea THEN WRITELN('The British coming by sea.') ELSE WRITELN('Sarah didn''t say') END; BEGIN {SarahRevere} {Инициализация} Looking := TRUE; Land := FALSE; Sea := FALSE; IF NOT EOLN THEN READ(Ch1); IF NOT EOLN THEN READ(Ch2); IF NOT EOLN THEN READ(Ch3); IF NOT EOLN THEN READ(Ch4); CheckSeaLand(Ch1, Ch2, Ch3, Ch4, Land, Sea, Looking); MessageFromSarah(Land, Sea) END. {SarahRevere}
unit engine; interface uses sysutils; const MAX_SIZE = 100; type position = ^positionDescription; positionDescription = record x : Integer; y : Integer; end; type field = ^fieldDescription; fieldDescription = record pos : position; kind : Integer; {1 - normalny , 2 - woda, 3 - góry} end; type army = ^armyDescription; armyDescription = record kind : Integer; {1 - 6} pos : field; health : Integer; prevArmy : army; nextArmy : army; end; type board = array[1..MAX_SIZE, 1..MAX_SIZE] of field; type fieldListElement = ^fieldListElementDescription; fieldListElementDescription = record x : field; prev : fieldListElement; next : fieldListElement; end; type fieldDoubleEndedQueue = ^fieldDoubleEndedQueueDescription; fieldDoubleEndedQueueDescription = record front : fieldListElement; back : fieldListElement; end; type boardElements = ^boardDescription; boardDescription = record firstArmies : army; secondArmies : army; boardHeight : Integer; boardWidth : Integer; terrain : board; end; type orderKind = (SKIP, MOVE, ATTACK); type order = ^orderDescription; orderDescription = record kind : orderKind; destPos : field; armyToAttack : army; end; type commandKind = (READBOARD, SHOWBOARD, PLAY, QUIT, GENMOVE); type userCommand = ^commandDescription; commandDescription = record kind : commandKind; destPos : position; { = nil if SKIP} newBoard : boardElements; end; type getArmyPair = ^getArmyPairElements; getArmyPairElements = record arm : army; firstArmy : boolean; end; procedure dealDamage(attackingArmyIndex: Integer; isFirstMoving: boolean; var defendingArmy: army; gameBoard: boardElements); procedure moveTo(movingArmyIndex : Integer; isFirstMoving: boolean; destPos : field; gameBoard: boardElements); procedure skipMove(); function canMoveTo(movingArmyIndex: Integer; isFirstMoving: boolean; destPos: field; gameBoard: boardElements) : boolean; function canAttackArmy(attackingArmyIndex: Integer; isFirstMoving: boolean; armyToAttack: army; gameBoard: boardElements) : boolean; function canAttackArmy(attackingArmy: army; defendingArmy: army): boolean; function readCommand() : userCommand; procedure drawBoard(gameBoard: boardElements); function getOrder(gameBoard : boardElements; destPos: position; isFirstMoving : boolean) : order; procedure wrongMove(); procedure drawGeneratedMove(generatedOrder: order); function getArmyByPosition(gameBoard: boardElements; pos: position) : getArmyPair; function computeDamage(attackingArmy: army; defendingArmy: army): Integer; procedure sweepBoard(var board: boardElements); procedure sweepCommand(command: userCommand); function oppositeArmies(a : army; isFirstMoving: boolean; f: field; b: boardElements): boolean; const zr: Array [1..6] of Integer = (2, 1, 3, 3, 5, 5); { zasięg ruchu } zmi: Array [1..6] of Integer = (1, 1, 3, 3, 1, 1); { minimalny zasięg strzału } zma: Array [1..6] of Integer = (1, 3, 5, 7, 7, 3); { maksymalny zasięg strzału } sn: Array [1..6] of Integer = (1, 2, 3, 3, 2, 5); { siła ataku z terenu normalnego } sg: Array [1..6] of Integer = (2, 1, 0, 0, 2, 5); { siła ataku z gór } sw: Array [1..6] of Integer = (0, 0, 0, 0, 3, 6); { siła ataku z wody } p: Array [1..6] of Integer = (0, 0, 4, 3, 2, 1); { wartość pancerza } compatible: Array [1..3] of Array [1..6] of boolean = { na polu może znaleźć się jednostka } ((true, true, true, true, true, true), { teren normalny } (false, false, false, false, true, true), { woda } (true, true, false, false, true, true)); { góry } implementation function getArmyByPosition(gameBoard: boardElements; pos: position) : getArmyPair; { Jeśli na danej pozycji na danej planszy znajduje się jakaś jednostka zwraca parę: jednostka i wartość logiczna mówiąca, czy jednostka należy do pierwszej armii. Jeśli na danej pozycji nie ma jednostki zwraca nil. } var fa, sa : army; { zmienne pomocnicze } fapos, sapos : position; { zmienne pomocnicze } begin assert((gameBoard <> nil) and (pos <> nil)); getArmyByPosition := nil; fa := gameBoard^.firstArmies; sa := gameBoard^.secondArmies; while fa <> nil do begin fapos := fa^.pos^.pos; if (fapos^.x = pos^.x) and (fapos^.y = pos^.y) then begin new(getArmyByPosition); getArmyByPosition^.arm := fa; getArmyByPosition^.firstArmy := true; end; fa := fa^.nextArmy; end; while sa <> nil do begin sapos := sa^.pos^.pos; if (sapos^.x = pos^.x) and (sapos^.y = pos^.y) then begin new(getArmyByPosition); getArmyByPosition^.arm := sa; getArmyByPosition^.firstArmy := false; end; sa := sa^.nextArmy; end; end; function getArmyByIndex(armyIndex : Integer; fromFirstArmy: boolean; gameBoard : boardElements) : army; { Zwraca jednostkę o danym indeksie w danej armii. } var i : Integer; begin assert(gameboard <> nil); if fromFirstArmy then getArmyByIndex := gameBoard^.firstArmies else getArmyByIndex := gameBoard^.secondArmies; for i := 1 to armyIndex - 1 do begin getArmyByIndex := getArmyByIndex^.nextArmy; end; end; procedure setArmies(gameBoard: boardElements; firstArmies: boolean; newArmies: army); { Ustawia wskaźnik pierwszej lub drugiej armii w gameBoard na podany } begin assert(gameBoard <> nil); if firstArmies then gameBoard^.firstArmies := newArmies else gameBoard^.secondArmies := newArmies; end; function computeDamage(attackingArmy: army; defendingArmy: army): Integer; { Oblicza jakie obrażenia odniosłaby defendingArmy zaatakowana przez attackingArmy } begin computeDamage := 0; case attackingArmy^.pos^.kind of 1 : computeDamage := computeDamage + sn[attackingArmy^.kind]; { teren normalny } 2 : computeDamage := computeDamage + sw[attackingArmy^.kind]; { woda } 3 : computeDamage := computeDamage + sg[attackingArmy^.kind]; { góry } end; computeDamage := computeDamage - p[defendingArmy^.kind]; if computeDamage < 0 then computeDamage := 0; end; procedure dealDamage(attackingArmyIndex: Integer; isFirstMoving: boolean; var defendingArmy: army; gameBoard: boardElements); { Zadaje obrażenia, jeśli atakowana jednostka zginie usuwa ją z armii. } var attackingArmy : army; begin assert((defendingArmy <> nil) and (gameBoard <> nil)); assert(canAttackArmy(attackingArmyIndex, isFirstMoving, defendingArmy, gameBoard)); attackingArmy := getArmyByIndex(attackingArmyIndex, isFirstMoving, gameBoard); defendingArmy^.health := defendingArmy^.health - computeDamage(attackingArmy, defendingArmy); if defendingArmy^.health <= 0 then begin { atakowana jednostka była jedyna w armii } if (defendingArmy^.prevArmy = nil) and (defendingArmy^.nextArmy = nil) then begin dispose(defendingArmy); setArmies(gameBoard, (not isFirstMoving), nil); { atakowana jednostka była pierwsza w armii } end else if defendingArmy^.prevArmy = nil then begin setArmies(gameBoard, (not isFirstMoving), defendingArmy^.nextarmy); defendingArmy^.nextArmy^.prevArmy := nil; dispose(defendingArmy); { atakowana jednostka była ostatnia w armii } end else if defendingArmy^.nextArmy = nil then begin defendingArmy^.prevArmy^.nextArmy := nil; dispose(defendingArmy); { atakowana jednostka była pomiędzy innymi w armii } end else begin defendingArmy^.prevArmy^.nextArmy := defendingArmy^.nextArmy; defendingArmy^.nextArmy^.prevArmy := defendingArmy^.prevArmy; dispose(defendingArmy); end; end; writeLn('='); writeLn(); end; procedure moveTo(movingArmyIndex: Integer; isFirstMoving: boolean; destPos: field; gameBoard: boardElements); { Wykonuje ruch jednostki na dane pole. } var movingArmy : army; begin assert(destPos <> nil); assert(gameBoard <> nil); assert(canMoveTo(movingArmyIndex, isFirstMoving, destPos, gameBoard)); movingArmy := getArmyByIndex(movingArmyIndex, isFirstMoving, gameBoard); movingArmy^.pos := destPos; writeLn('='); writeLn(); end; procedure skipMove(); begin writeLn('='); writeLn(); end; function initFieldDoubleEndedQueue(): fieldDoubleEndedQueue; { inicjalizuje dwustronną kolejkę fieldów } begin new(initFieldDoubleEndedQueue); initFieldDoubleEndedQueue^.front := nil; initFieldDoubleEndedQueue^.back := nil; end; function isEmpty(q: fieldDoubleEndedQueue): boolean; { sprawdza, czy kolejka jest pusta } begin isEmpty := (q^.front = nil) and (q^.back = nil); end; procedure pushFront(x: field; q: fieldDoubleEndedQueue); { umieszcza element na początku kolejki } var newElement : fieldListElement; begin new(newElement); newElement^.x := x; newElement^.prev := nil; newElement^.next := nil; if isEmpty(q) then q^.back := newElement else begin q^.front^.prev := newElement; newElement^.next := q^.front; end; q^.front := newElement; end; procedure pushBack(x: field; q: fieldDoubleEndedQueue); { umieszcza element na końcu kolejki } var newElement : fieldListElement; begin new(newElement); newElement^.x := x; newElement^.prev := nil; newElement^.next := nil; if isEmpty(q) then q^.front := newElement else begin q^.back^.next := newElement; newElement^.prev := q^.back; end; q^.back := newElement; end; function popFront(q: fieldDoubleEndedQueue) : field; { Zdejmuje element z początku kolejki i go zwraca } begin assert(not isEmpty(q)); popFront := q^.front^.x; if q^.front = q^.back then begin dispose(q^.front); q^.front := nil; q^.back := nil; end else begin q^.front := q^.front^.next; dispose(q^.front^.prev); q^.front^.prev := nil; end; end; function popBack(q: fieldDoubleEndedQueue) : field; { Zdejmuje element z końca kolejki } begin assert(not isEmpty(q)); popBack := q^.back^.x; if q^.front = q^.back then begin dispose(q^.back); q^.front := nil; q^.back := nil; end else begin q^.back := q^.back^.prev; dispose(q^.back^.next); q^.back^.next := nil; end; end; function member(x: field; q: fieldDoubleEndedQueue) : boolean; { sprawdza, czy w kolejce jest pole o takich współrzędnych jak pole dane } var ptr : fieldListElement; begin ptr := q^.front; member := false; while (ptr <> nil) and (not member) do begin if (x^.pos^.x = ptr^.x^.pos^.x) and (x^.pos^.y = ptr^.x^.pos^.y) then member := true; ptr := ptr^.next; end; end; function oppositeArmies(a : army; isFirstMoving: boolean; f: field; b: boardElements): boolean; { Sprawdza, czy dana jednostka i jednostka, która stoi na danym polu są w różnych armiach, jeśli pole jest puste zwraca false. } var getArmyResult : getArmyPair; begin getArmyResult := getArmyByPosition(b, f^.pos); if getArmyResult <> nil then begin oppositeArmies := ((not isFirstMoving) and (getArmyResult^.firstArmy)) or ((isFirstMoving) and (not getArmyResult^.firstArmy)); dispose(getArmyResult); end else oppositeArmies := false; end; function canMoveTo(movingArmyIndex : Integer; isFirstMoving: boolean; destPos: field; gameBoard: boardElements) : boolean; { Sprawdza, czy jednostka może przejść na dane pole } const { Pomocnicza tablica - sąsiednie pola } neighbours: Array [1..4] of Array[1..2] of Integer = ((-1, 0), (0, -1), (1, 0), (0, 1)); var getArmyResult : getArmyPair; movingArmy : army; fieldQueue, visitedFields : fieldDoubleEndedQueue; currentField, newField : field; currentDistance : Integer; i, j : Integer; cx, cy, nx, ny : Integer; { zmienne pomocnicze } reachable : boolean; currentDistanceCount, nextDistanceCount : Integer; { liczba elementów w odległości obecnej/większej o 1 } begin assert(destPos <> nil); assert(gameBoard <> nil); movingArmy := getArmyByIndex(movingArmyIndex, isFirstMoving, gameBoard); { BFS, który sprawdza, czy na pole da się dojść z zachowaniem reguł w liczbie ruchów, jakimi dysponuje jednostka i zapisuje wynik w reachable } fieldQueue := initFieldDoubleEndedQueue(); { jako FIFO } visitedFields := initFieldDoubleEndedQueue(); { jako LIFO } pushFront(movingArmy^.pos, fieldQueue); pushFront(movingArmy^.pos, visitedFields); reachable := false; currentDistance := 0; currentDistanceCount := 1; nextDistanceCount := 0; while (not isEmpty(fieldQueue)) and (not reachable) do begin { przed j-tym obrotem pętli przeszukane jest j-1 spośród pól znajdujących się w odległości currentDistance od początkowego } for j := 1 to currentDistanceCount do begin currentField := popBack(fieldQueue); cx := currentField^.pos^.x; cy := currentField^.pos^.y; { pole jest w zasięgu } if (destPos^.pos^.x = cx) and (destPos^.pos^.y = cy) then reachable := true { po i-tym obrocie pętli do kolejki wrzucony jest i-ty sąsiad pod warunkiem, że jest w zasięgu, nie ma go jeszcze w kolejce i jest "zgodny" z jednostką } else for i := 1 to 4 do begin { nx, ny to współrzędne jednego z sąsiednich pól } nx := cx + neighbours[i][1]; ny := cy + neighbours[i][2]; { sprawdzenie, czy takie pole rzeczywiście leży na planszy,... } if (1 <= nx) and (nx <= gameBoard^.boardWidth) and (1 <= ny) and (ny <= gameBoard^.boardHeight) then begin newField := gameBoard^.terrain[nx][ny]; { ...można przejść przez pole,... } if compatible[newField^.kind][movingArmy^.kind] and (not oppositeArmies(movingArmy, isFirstMoving, newField, gameBoard)) and { ...czy nie zostało już wcześniej odwiedzone... } (not member(gameBoard^.terrain[nx][ny], visitedFields)) and { i czy znajduje się w zasięgu ruchu jednostki } (currentDistance + 1 <= zr[movingArmy^.kind]) then begin pushFront(gameBoard^.terrain[nx][ny], fieldQueue); pushFront(newField, visitedFields); inc(nextDistanceCount); end; end; end; end; inc(currentDistance); currentDistanceCount := nextDistanceCount; nextDistanceCount := 0; end; { opróżnienie kolejek } while not isEmpty(fieldQueue) do popBack(fieldQueue); while not isEmpty(visitedFields) do popBack(visitedFields); getArmyResult := getArmyByPosition(gameBoard, destPos^.pos); { jeśli pole jest w zasięgu i nie jest zajęte to można do niego dojść } canMoveTo := reachable and (getArmyResult = nil); if getArmyResult <> nil then dispose(getArmyResult); dispose(visitedFields); dispose(fieldQueue); end; function getDistanceBetweenFields(a: field; b: field): Integer; { oblicza odległość w metryce miejskiej pomiędzy dwoma polami } begin getDistanceBetweenFields := abs(a^.pos^.x - b^.pos^.x) + abs(a^.pos^.y - b^.pos^.y); end; function canAttackArmy(attackingArmy: army; defendingArmy: army): boolean; { sprawdza, czy daną jednostkę można zaatakować } var distance: Integer; begin assert(attackingArmy <> nil); assert(defendingArmy <> nil); distance := getDistanceBetweenFields(attackingArmy^.pos, defendingArmy^.pos); { jednostkę można zaatakować gdy jest w zasięgu } canAttackArmy := (zmi[attackingArmy^.kind] <= distance) and (distance <= zma[attackingArmy^.kind]); end; function canAttackArmy(attackingArmyIndex: Integer; isFirstMoving: boolean; armyToAttack: army; gameBoard: boardElements) : boolean; { sprawdza, czy daną jednostkę można zaatakować } var attackingArmy: army; begin assert(armyToAttack <> nil); assert(gameBoard <> nil); attackingArmy := getArmyByIndex(attackingArmyIndex, isFirstMoving, gameBoard); canAttackArmy := canAttackArmy(attackingArmy, armyToAttack); end; procedure splitByFirstSpace(input: string; var part1: string; var part2: string); { rozdziela string na dwie części: do pierwszej spacji i po pierwszej spacji } var firstSpace : integer = 0; i : integer; begin for i := 1 to length(input) do begin if input[i] = ' ' then begin firstSpace := i; end; end; if firstSpace <> 0 then begin part1 := copy(input, 1, firstSpace - 1); part2 := copy(input, firstSpace + 1, length(input)); end else part1 := input; end; function newArmy(kind: integer; pos: field; health: integer; prevArmy: army; nextArmy: army) : army; { Tworzy nową jednostkę. } begin new(newArmy); newArmy^.kind := kind; newArmy^.pos := pos; newArmy^.health := health; newArmy^.prevArmy := prevArmy; newArmy^.nextArmy := nextArmy; end; function readNewBoard() : boardElements; { Wczytuje nową planszę. } var gameBoard : boardElements; x, y : Integer; line : string; newField : field; lastFirstArmy, lastSecondArmy : ^army; dummyFirstArmy, dummySecondArmy : army; index, kind, health : integer; { zmienne pomocnicze } begin new(gameBoard); new(dummyFirstArmy); new(dummySecondArmy); lastFirstArmy := @(dummyFirstArmy); lastSecondArmy := @(dummySecondArmy); readLn(gameBoard^.boardHeight); readLn(gameBoard^.boardWidth); for y := 1 to gameBoard^.boardHeight do begin { wczytaj y-tą linię } readLn(line); for x := 1 to gameBoard^.boardWidth do { wczytaj x-tą jednostkę w y-tej linii } begin index := 4*(x-1) + 1; new(newField); new(newField^.pos); newField^.pos^.x := x; newField^.pos^.y := y; case line[index] of 'a' .. 'f': begin kind := ord(line[index]) - ord('a') + 1; health := ord(line[index + 2]) - ord('0'); lastFirstArmy^^.nextArmy := newArmy(kind, newField, health, lastFirstArmy^, nil); lastFirstArmy := @(lastFirstArmy^^.nextArmy); end; 'A' .. 'F': begin kind := ord(line[index]) - ord('A') + 1; health := ord(line[index + 2]) - ord('0'); lastSecondArmy^^.nextArmy := newArmy(kind, newField, health, lastSecondArmy^, nil); lastSecondArmy := @(lastSecondArmy^^.nextArmy); end; end; case line[index + 1] of '.': newField^.kind := 1; '=' : newField^.kind := 2; '^' : newField^.kind := 3; end; {set position (x, y) in 'gameBoard'} gameBoard^.terrain[x][y] := newField; newField := nil; end; end; { poprawienie wskaźników } gameBoard^.firstArmies := dummyFirstArmy^.nextArmy; gameBoard^.firstArmies^.prevArmy := nil; gameBoard^.secondArmies := dummySecondArmy^.nextArmy; gameBoard^.secondArmies^.prevArmy := nil; readNewBoard := gameBoard; dispose(dummyFirstArmy); dispose(dummySecondArmy); writeln('='); writeln(); end; function readCommand() : userCommand; { funkcja wczytująca polecenie użytkownika } var currentCommand : userCommand; commandLine, command, arguments : string; destPos : position; begin new(currentCommand); currentCommand^.destPos := nil; readLn(commandLine); splitByFirstSpace(commandLine, command, arguments); if command = 'readboard' then begin currentCommand^.kind := READBOARD; currentCommand^.newBoard := readNewBoard(); end else if command = 'showboard' then currentCommand^.kind := SHOWBOARD else if command = 'play' then begin currentCommand^.kind := PLAY; if not (arguments = 'skip') then begin new(destPos); destPos^.x := ord(arguments[1]) - ord('a') + 1; if length(arguments) = 2 then destPos^.y := ord(arguments[2]) - ord('0') else destPos^.y := 10 * (ord(arguments[2]) - ord('0')) + (ord(arguments[3]) - ord('0')); currentCommand^.destPos := destPos; end; end else if command = 'genmove' then currentCommand^.kind := GENMOVE else if command = 'quit' then begin currentCommand^.kind := QUIT; writeLn('='); writeLn(); end; readCommand := currentCommand; end; function describeField(fld: field; board: boardElements): string; { zwraca opis pola w formacie potrzebnym przy wypisywaniu planszy } var armyKind : char = '.'; armyHealth : char = '.'; fieldType : char; getArmyResult : getArmyPair; begin getArmyResult := getArmyByPosition(board, fld^.pos); if getArmyResult <> nil then begin if getArmyResult^.firstArmy then armyKind := chr(ord('a') + getArmyResult^.arm^.kind - 1) else armyKind := chr(ord('A') + getArmyResult^.arm^.kind - 1); armyHealth := chr(ord('0') + getArmyResult^.arm^.health); dispose(getArmyResult); end; case fld^.kind of 1 : fieldType := '.'; 2 : fieldType := '='; 3 : fieldType := '^'; end; describeField := ''; describeField := describeField + armyKind; describeField := describeField + fieldType; describeField := describeField + armyHealth; end; procedure drawBoard(gameBoard: boardElements); { wypisuje planszę } var x, y : integer; begin writeLn('='); for y := 1 to gameBoard^.boardHeight do begin for x := 1 to (gameBoard^.boardWidth - 1) do begin write(describeField(gameBoard^.terrain[x][y], gameBoard)); write(' '); end; writeln(describeField(gameBoard^.terrain[gameBoard^.boardWidth][y], gameBoard)); end; writeLn(); end; function getOrder(gameBoard: boardElements; destPos: position; isFirstMoving : boolean) : order; { sprawdza, czy 'destPos' jest zajęte przez wrogą armię, jeśli tak to zwraca odpowieni rozkaz typu ATTACK, jeśli nie, odpowiedni rozkaz typu MOVE a jeśli 'destPos' jest nilem zwraca rozkaz typu skip } var currentOrder : order; getArmyResult : getArmyPair; begin new(currentOrder); if destPos = nil then currentOrder^.kind := SKIP else begin getArmyResult := getArmyByPosition(gameBoard, destPos); if (getArmyResult = nil) or (isFirstMoving and (getArmyResult^.firstArmy)) or ((not isFirstMoving) and (not getArmyResult^.firstArmy)) then begin currentOrder^.kind := MOVE; currentOrder^.destPos := gameBoard^.terrain[destPos^.x, destPos^.y]; end else begin currentOrder^.armyToAttack := getArmyResult^.arm; currentOrder^.kind := ATTACK; currentOrder^.destPos := gameBoard^.terrain[destPos^.x, destPos^.y]; end; if getArmyResult <> nil then; dispose(getArmyResult); end; getOrder := currentOrder; end; procedure wrongMove(); begin writeLn('= invalid move'); writeLn(); end; function posToString(pos: position): string; { zwraca opis pozycji wymagany przy odpowiedzi na komendę genmove } begin posToString := ''; posToString := posToString + chr(ord('a') - 1 + pos^.x); posToString := posToString + IntToStr(pos^.y); end; procedure drawGeneratedMove(generatedOrder: order); { wypisuje wygenerowany ruch } begin case generatedOrder^.kind of SKIP: writeln('= skip'); ATTACK: writeln('= ' + posToString(generatedOrder^.destPos^.pos)); end; writeln(); end; procedure sweepArmies(armies: army); { usuwa z pamięci armię, nie usuwa 'field'-ów } var armyPtr1, armyPtr2: army; begin armyPtr1 := armies; while armyPtr1 <> nil do begin armyPtr2 := armyPtr1^.nextArmy; dispose(armyPtr1); armyPtr1 := armyPtr2; end; end; procedure sweepBoard(var board: boardElements); { usuwa z pamięci planszę wraz z 'field'ami i ich 'position'ami } var i, j: Integer; begin if board <> nil then begin for i := 1 to board^.boardWidth do for j := 1 to board^.boardHeight do begin dispose(board^.terrain[i][j]^.pos); dispose(board^.terrain[i][j]); end; sweepArmies(board^.firstArmies); sweepArmies(board^.secondArmies); dispose(board); board := nil; end; end; procedure sweepCommand(command: userCommand); { usuwa polecenie wraz z 'destPos', jeśli nie jest nilem } begin if command^.destPos <> nil then dispose(command^.destPos); dispose(command); end; end.
unit caVariants; {$INCLUDE ca.inc} interface uses Windows, SysUtils, Classes; type //--------------------------------------------------------------------------- // TcaVarArray //--------------------------------------------------------------------------- TcaVarArray = class(TObject) private // Private fields FArray: Variant; FCapacity: Integer; FCount: Integer; // Private methods procedure Grow; procedure ReDim; // Property methods function GetItem(Index: Integer): Variant; procedure SetItem(Index: Integer; const Value: Variant); public constructor Create; // Public methods function Add(AItem: Variant): Integer; // Properties property Count: Integer read FCount; property Items[Index: Integer]: Variant read GetItem write SetItem; default; end; implementation //--------------------------------------------------------------------------- // TcaVarArray //--------------------------------------------------------------------------- constructor TcaVarArray.Create; begin inherited; FCapacity := 100; FArray := VarArrayCreate([0, 0], varVariant); ReDim; end; // Public methods function TcaVarArray.Add(AItem: Variant): Integer; begin Inc(FCount); if FCount = FCapacity then Grow; Result := FCount - 1; FArray[Result] := AItem; end; // Private methods procedure TcaVarArray.Grow; begin Inc(FCapacity, 100); ReDim; end; procedure TcaVarArray.ReDim; begin VarArrayRedim(FArray, FCapacity); end; // Property methods function TcaVarArray.GetItem(Index: Integer): Variant; begin Result := FArray[Index]; end; procedure TcaVarArray.SetItem(Index: Integer; const Value: Variant); begin FArray[Index] := Value; end; end.
unit unif2d; interface uses Math, Types; type bitpos = type ShortInt; PBoard = ^TBoard; TBoard = record Size: TPoint; Grid: array[0..MaxInt div 8 - 2] of UInt64; function GetAt(X, Y: integer): UInt64; inline; procedure SetAt(X, Y: integer; const NewVal: UInt64); inline; property At[X, Y: integer]: UInt64 read GetAt write SetAt; end; function AllocBoard(ASize: TPoint): PBoard; function Log2(X: UInt64): bitpos; procedure FillBoard(XX, YY: UInt64; Sb: bitpos; out Board: TBoard; out VMin, VMax: UInt64); var World: UInt64 = 0; implementation uses chacha; {$O+} function AllocBoard(ASize: TPoint): PBoard; begin Result := PBoard(AllocMem(ASize.X * ASize.Y * 8)); Result.Size := ASize; end; function TBoard.GetAt(X, Y: integer): UInt64; begin Result := Grid[Y * Size.X + X]; end; procedure TBoard.SetAt(X, Y: integer; const NewVal: UInt64); begin Grid[Y * Size.X + X] := NewVal; end; const TotalNumber = $FFFFFFFFFFFFFFFF; function Log2(X: UInt64): bitpos; begin if X = 0 then begin Result := -1; exit; end; Result := 0; if X and $FFFFFFFF00000000 <> 0 then begin X := X shr 32; Result := 32; end; if X and $FFFF0000 <> 0 then begin X := X shr 16; Inc(Result, 16); end; if X and $FF00 <> 0 then begin X := X shr 8; Inc(Result, 8); end; if X and $F0 <> 0 then begin X := X shr 4; Inc(Result, 4); end; if X and $C <> 0 then begin X := X shr 2; Inc(Result, 2); end; if X and $2 <> 0 then Inc(Result, 1); end; function Max(A, B: bitpos): bitpos; overload; begin if A > B then Result := A else Result := B; end; function Min(A, B: bitpos): bitpos; overload; begin if A < B then Result := A else Result := B; end; type TMemBlock = array[0..7] of UInt64; procedure MemBlock(X, Y: UInt64; Sb: bitpos; out MB: TMemBlock); var Key: array[0..3] of UInt64; begin Key[0] := World; Key[1] := Sb; Key[2] := 0; Key[3] := 0; ChaChaR(Key, Int64(X), Int64(Y), MB, 5); end; procedure Sort(var R1, R2: UInt64); inline; var W: UInt64; begin if R1 > R2 then begin W := R1; R1 := R2; R2 := W; end; end; procedure CorrectSum(V: UInt64; var V1, V2, V3, V4: UInt64; const R: UInt64); inline; begin V := V - V1 - V2 - V3 - V4; case R and 3 of 0: V1 := V1 + V; 1: V2 := V2 + V; 2: V3 := V3 + V; 3: V4 := V4 + V; end; end; // calculates A * B / 2^64 function M64(A, B: UInt64): UInt64; inline; type THL = packed record L, H: cardinal; end; var AA: THL absolute A; BB: THL absolute B; begin Result := UInt64(AA.H) * UInt64(BB.H) + UInt64(AA.H) * UInt64(BB.L) shr 32 + UInt64(AA.L) * UInt64(BB.H) shr 32 + ( UInt64(cardinal(AA.H * BB.L)) + UInt64(cardinal(AA.L * BB.H)) + UInt64(AA.L) * UInt64(BB.L) shr 32 + UInt64(cardinal(AA.L * BB.L)) shr 31 ) shr 32; end; // calculates A / B * 2^64 function D64(A, B: UInt64): UInt64; // inline; begin end; function Avg(const A, B: UInt64): UInt64; inline; begin Result := A shr 1 + B shr 1 + Cardinal(A) and Cardinal(B) and 1; end; function SqrtI(X: UInt64): UInt64; inline; var b: UInt64; begin Result := 0; b := UInt64(1) shl (Log2(X) and not 1); while b <> 0 do begin if (X >= Result + b) then begin X := X - Result - b; Result := (Result shr 1) + b; end else Result := Result shr 1; b := b shr 2; end; end; procedure SplitWild(V, R1, R2, R3, R4: UInt64; out V1, V2, V3, V4: UInt64); begin Sort(R1, R2); Sort(R2, R3); Sort(R1, R2); V1 := M64(V, R1); V2 := M64(V, R2 - R1); V3 := M64(V, R3 - R2); V4 := M64(V, $FFFFFFFFFFFFFFFF - R3); CorrectSum(V, V1, V2, V3, V4, R4); end; procedure SplitUnif(V: UInt64; const R: TMemBlock; out V1, V2, V3, V4: UInt64); var Q, S1, S2, S3: UInt64; i: integer; begin if V < 32 then begin V1 := 0; V2 := 0; V3 := 0; V4 := 0; for i := 0 to V - 1 do begin case R[0] shr (i*2) and 3 of 0: V1 := V1 + 1; 1: V2 := V2 + 1; 2: V3 := V3 + 1; 3: V4 := V4 + 1; end; end; end else begin S1 := V shr 2; S2 := V shr 1; S3 := S2 + S1; // now we limit delta to sqrt V. it should be a proper distribution. Q := SqrtI(V); //Q := Q shr 1 + Q shr 3 + Q shr 4; // sqrt(2) Q := Q shr 1 + Q shr 2 + Q shr 4 + Q shr 5; // 0.8 S1 := S1 + M64(Q, R[0]) - Q shr 1; S2 := S2 + M64(Q, R[1]) - Q shr 1; S3 := S3 + M64(Q, R[2]) - Q shr 1; V1 := S1; V2 := S2 - S1; V3 := S3 - S2; V4 := V - S3; CorrectSum(V, V1, V2, V3, V4, R[3]); end; end; {function F(X, Y: UInt64): double; var Xf, Yf: double; const scale = 1e7; begin // integ 1/r^3: -sqrt(x^2+y^2)/(x y) Xf := X / scale - scale/2.0; Yf := Y / scale - scale/2.0; Result := -Sqrt(Xf*Xf+Yf*Yf) / Xf / Yf; end;} function F(X, Y: UInt64): double; // inline; var F: double; XS: Int64 absolute X; YS: Int64 absolute Y; begin F := Int64(1) shl 63; F := F + XS; Result := ArcTan(F * 1e-10); F := YS; F := F + Int64(1) shl 63; Result := Result * ArcTan(F * 1e-10); end; procedure SplitR(V: UInt64; const R: TMemBlock; const Xmin, Xmax, Ymin, Ymax: UInt64; out V1, V2, V3, V4: UInt64); var Q, S1, S2, S3, S4, Xmid, Ymid: UInt64; VS, VTR, VBR, VTL, VBL, TM, LM, RM, BM, MM: double; i: integer; const MaxUInt64f = 65536.0*65536.0*65536.0*65536.0 - 1; begin if V < 32 then begin V1 := 0; V2 := 0; V3 := 0; V4 := 0; for i := 0 to V - 1 do begin case R[0] shr (i*2) and 3 of 0: V1 := V1 + 1; 1: V2 := V2 + 1; 2: V3 := V3 + 1; 3: V4 := V4 + 1; end; end; end else begin Xmid := Avg(Xmin, Xmax); Ymid := Avg(Ymin, Ymax); TM := F(Xmid, Ymin); BM := F(Xmid, Ymax); LM := F(Xmin, Ymid); RM := F(Xmax, Ymid); MM := F(Xmid, Ymid); VTR := RM + TM - F(Xmax, Ymin) - MM; VBR := F(Xmax, Ymax) - RM - BM + MM; VTL := MM - TM - LM + F(Xmin, Ymin); VBL := BM - MM - F(Xmin, Ymax) + LM; if VTR < 0 then VTR := 0; if VBR < 0 then VBR := 0; if VTL < 0 then VTL := 0; if VBL < 0 then VBL := 0; VS := VTR + VBR + VTL + VBL; // todo: rewrite to // todo: add some random if VS = 0 then begin V1 := V shr 2; V2 := V shr 2; V3 := V shr 2; V4 := V shr 2; end else begin V1 := M64(V, Trunc(VTL / VS * MaxUInt64f / 2.0) shl 1); V2 := M64(V, Trunc(VTR / VS * MaxUInt64f / 2.0) shl 1); V3 := M64(V, Trunc(VBL / VS * MaxUInt64f / 2.0) shl 1); V4 := M64(V, Trunc(VBR / VS * MaxUInt64f / 2.0) shl 1); end; CorrectSum(V, V1, V2, V3, V4, R[3]); end; end; procedure Split(const V: UInt64; const R: TMemBlock; const Xmin, Xmax, Ymin, Ymax: UInt64; out V1, V2, V3, V4: UInt64); begin // SplitWild2(V, R[0], R[1], R[2], R[3], V1, V2, V3, V4); // SplitUnif(V, R, V1, V2, V3, V4); SplitR(V, R, Xmin, Xmax, Ymin, Ymax, V1, V2, V3, V4); end; procedure FillBoard(XX, YY: UInt64; Sb: bitpos; out Board: TBoard; out VMin, VMax: UInt64); var b: bitpos; X, Y, X2, Y2, Xmin, Xmax, Ymin, Ymax, S00, S01, S10, S11: UInt64; Xd, Yd, Xo, Yo, Xn, Yn: integer; S: TMemBlock; begin Board.At[0, 0] := TotalNumber; for b := 63 downto Sb do begin Xmin := XX shr b shr 1; Xmax := (XX + UInt64(Board.Size.X-1) shl Sb) shr b shr 1; Xd := Xmax - Xmin; Ymin := YY shr b shr 1; Ymax := (YY + UInt64(Board.Size.Y-1) shl Sb) shr b shr 1; Yd := Ymax - Ymin; Vmin := UInt64(-1); Vmax := 0; for Xo := Xd downto 0 do begin for Yo := Yd downto 0 do begin X := (Xo + Xmin) shl b shl 1; Y := (Yo + Ymin) shl b shl 1; X2 := (Xo + Xmin + 1) shl b shl 1 - 1; Y2 := (Yo + Ymin + 1) shl b shl 1 - 1; MemBlock(X, Y, b, S); Split(Board.At[Xo, Yo], S, X, X2, Y, Y2, S00, S01, S10, S11); if Vmax < S00 then Vmax := S00; if Vmax < S01 then Vmax := S01; if Vmax < S10 then Vmax := S10; if Vmax < S11 then Vmax := S11; if Vmin > S00 then Vmin := S00; if Vmin > S01 then Vmin := S01; if Vmin > S10 then Vmin := S10; if Vmin > S11 then Vmin := S11; Xn := Xo shl 1 - (XX shr b and 1); Yn := Yo shl 1 - (YY shr b and 1); if (Xn >= 0) and (Yn >= 0) then Board.At[Xn, Yn] := S00; if (Xn < Board.Size.X-1) and (Yn >= 0) then Board.At[Xn+1, Yn] := S10; if (Xn >= 0) and (Yn < Board.Size.Y-1) then Board.At[Xn, Yn+1] := S01; if (Xn < Board.Size.X-1) and (Yn < Board.Size.Y-1) then Board.At[Xn+1, Yn+1] := S11; end; end; end; end; procedure BlankLog(Xmin, Xmax, Ymin, Ymax, Vmin, Vmax: UInt64); begin end; initialization chacha.Test; end.
UNIT UTILEXSD; {$N+} INTERFACE USES Types, Glblvars, SysUtils, WinTypes, WinProcs, BtrvDlg, Messages, Dialogs, Forms, wwTable, Classes, DB, DBTables, Controls,DBCtrls,StdCtrls, PASTypes, WinUtils, GlblCnst, Utilitys, wwDBLook, Graphics, RPBase, RPDefine, Prog, wwdbGrid, DataAccessUnit; Procedure GetAuditEXList(SwisSBLKey : String; TaxRollYr : String; ExemptionTable : TTable; AuditEXChangeList : TList); {Fill a TList with the exemption information for all exemptions at this time.} Procedure InsertAuditEXChanges(SwisSBLKey : String; TaxRollYr : String; AuditEXList : TList; AuditEXChangeTable : TTable; BeforeOrAfter : Char); {CHG03241998-1: Track the exemption changes as a whole picture - before and after.} Function GetExemptionAmountToDisplay(EXAppliesArray : ExemptionAppliesArrayType) : Integer; Function ValidSwisCodeForExemptionOrSpecialDistrictCode(SwisList : TStringList; SwisCode : String) : Boolean; {Based on the list of swis restrictions in SwisList, see if the SwisCode fits in. Note that each restriction can be 2 char.'s (county), 4 char.'s (city), or 6 char.'s (village).} Procedure GetHomesteadAndNonhstdExemptionAmounts( ExemptionCodes, ExemptionHomesteadCodes, {What is the homestead code for each exemption?} CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts : TStringList; var HstdEXAmounts, NonhstdEXAmounts : ExemptionTotalsArrayType); {Given the exemption amounts and the corresponding homestead codes array, divide the amounts into homestead and nonhomestead totals arrays. For parcels that are not split, all of the amounts will go into either the homestead or nonhomestead array. If this is a split parcel, the totals may be split between the two. If this is not a designated parcel, the exemptions amounts will go into the homestead exemption totals array.} Function TotalExemptionsForParcel( TaxRollYear : String; SwisSBLKey : String; ParcelExemptionTable, EXCodeTable : TTable; ParcelHomesteadCode : String; ExemptionType : Char; {(A)ll,(F)ixed,a(G)eds,(N)onresidential} ExemptionCodes, ExemptionHomesteadCodes, {What is the homestead code for each exemption?} ResidentialTypes, {What are the residential types for each exemption?} CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts : TStringList; var BasicSTARAmount, EnhancedSTARAmount : Comp) : ExemptionTotalsArrayType; {CHG12011997 - STAR support. Note that the STAR amounts are never returned in the total exemptions. They are always treated seperately.} {ExemptionType is 'A' for all, 'N' for all except nonresidential exemptions, 'F' for fixed exemption, or 'G' for all ageds. 'N' is used to calculate aged exemption, and 'F' is used to calculate percentage exemptions since the fixed exemptions are applied first.} {Go through all the exemptions and add the exemption amount. Note that we will check each exemption to see which it applies to.} {Also, we will return a string list with the exemption codes. For each entry in the ExemptionCodes list, 4 values are returned in the Amounts lists (county, town, village, school) in the corresponding positions. That is, if exemption code 41180 is in position 2 in the ExemptionCodes list, position 2 of the Amounts lists gives the corresponding amount breakdown. We will also return a list of the homestead codes for each exemption. If this is not a split parcel, the homestead codes will be that of the parcel. Otherwise, it will be the homestead code of the particular exemption.} Function PropertyIsCoopOrMobileHomePark(ParcelTable : TTable) : Boolean; Function ExemptionIsBasicVeteran(sExemptionCode : String) : Boolean; Function ExemptionIsColdWarVeteran(sExemptionCode : String) : Boolean; Function ExemptionIsAlternativeVeteran(sExemptionCode : String) : Boolean; Function ExemptionIsSTAR(EXCode : String) : Boolean; Function ExemptionIsSenior(EXCode : String) : Boolean; Function ExemptionIsLowIncomeDisabled(EXCode : String) : Boolean; Function ExemptionIsEnhancedSTAR(EXCode : String) : Boolean; Function ExemptionIsVolunteerFirefighter(EXCode : String) : Boolean; Function CalculateSTARAmount( ExemptionCodeTable, ParcelExemptionTable, ParcelTable : TTable; AssessedValue : Comp; ResidentialPercent : Real; Percent : Real; iSchoolExemptionAmount : LongInt; var FullSTARAmount : Comp) : Comp; {Given a STAR exemption code, calculate the STAR amount. Two items are returned - the full STAR amount (for exemption totals) and the actual STAR amount for this parcel. This can be different if the school taxable value before STAR is less than the full STAR amount.} {CHG12011997-2: STAR support} Procedure GetResidentialExemptionAmounts(var ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts : ExemptionTotalsArrayType; ResidentialTypes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts : TStringList); Function CalculateTaxableVal(AssessedValue, ExemptionAmount : Comp) : Comp; {FXX05261998-3: Don't let a taxable value decrease below 0.} {Return the taxable value of the property for a tax type, returning 0 if the taxable value is below 0.} Function CalculateExemptionAmount( ExemptionCodeTable, ParcelExemptionTable, {Table with the current parcel exemption} ParcelExemptionLookupTable, {Lookup table to find other exemptions.} AssessmentTable, ClassTable, SwisCodeTable, ParcelTable : TTable; TaxRollYr : String; SwisSBLKey : String; var FixedPercent : Comp; var VetMaxSet, EqualizationRateFilledIn, ExemptionRecalculated : Boolean; iLandValue : LongInt; iAssessedValue : LongInt; bUseOverrideAssessedValue : Boolean) : ExemptionTotalsArrayType; {Calculate the amount for this exemption based on the exemption calc code and the exemption code itself.} Procedure RecalculateExemptionsForParcel(ExemptionCodeTable, ParcelExemptionTable, AssessmentTable, ClassTable, SwisCodeTable, ParcelTable : TTable; TaxRollYear : String; SwisSBLKey : String; ExemptionsNotRecalculatedList : TStringList; iLandValue : LongInt; iAssessedValue : LongInt; bUseOverrideAssessedValue : Boolean); {Recalculate all the exemptions for this parcel.} Function ExApplies(ExCode : String; AppliesToVillage : Boolean) : ExemptionAppliesArrayType; {Determine if the exemption applies to county, town, village, or school. An array of Booleans is returned with 1=County, 2=Town, 3=Village, 4=School.} Function GetResidentialPercent(ParcelTable, ExemptionCodeTable : TTable; EXCode : String) : Real; Function ExemptionExistsForParcel(ExemptionCode : String; TaxRollYear : String; SwisSBLKey : String; ComparisonLength : Integer; {Number of chars to compare on} ParcelExemptionTable : TTable) : Boolean; {Go through all the exemptions and see if this exemption code exists.} Procedure GetExemptionCodesForParcel(TaxRollYr : String; SwisSBLKey : String; ExemptionTable : TTable; ExemptionList : TStringList); {Return a list of the exemption codes on a parcel.} Procedure DisplayExemptionsNotRecalculatedForm(MasterExemptionsNotRecalculatedList : TStringList); Procedure RecalculateAllExemptions( Form : TForm; ProgressDialog : TProgressDialog; ProcessingType : Integer; AssessmentYear : String; DisplayExemptionsNotRecalculated : Boolean; var Quit : Boolean); Function IsBIEExemptionCode(ExemptionCode : String) : Boolean; Function ParcelHasSTAR(ExemptionTable : TTable; SwisSBLKey : String; AssessmentYear : String) : Boolean; Procedure DetermineExemptionReadOnlyAndRequiredFields( ExemptionCodeLookupTable : TTable; ParcelTable : TTable; ExemptionCode : String; var AmountFieldRequired : Boolean; var AmountFieldReadOnly : Boolean; var PercentFieldRequired : Boolean; var PercentFieldReadOnly : Boolean; var OwnerPercentFieldRequired : Boolean; var OwnerPercentFieldReadOnly : Boolean; var TerminationDateRequired : Boolean); Procedure DetermineAssessedAndTaxableValues( AssessmentYear : String; SwisSBLKey : String; HomesteadCode : String; ExemptionTable : TTable; ExemptionCodeTable : TTable; AssessmentTable : TTable; var LandAssessedValue : LongInt; var TotalAssessedValue : LongInt; var CountyTaxableValue : LongInt; var MunicipalTaxableValue : LongInt; var SchoolTaxableValue : LongInt; var VillageTaxableValue : LongInt; var BasicSTARAmount : LongInt; var EnhancedSTARAmount : LongInt); Function ProjectExemptions(tbSourceExemptions : TTable; sTaxYear : String; sSwisSBLKey : String; iLandValue : LongInt; iAssessedValue : LongInt; iProcessingType : Integer) : ExemptionTotalsArrayType; Procedure InsertOneSDChangeTrace(SwisSBLKey : String; TaxRollYr : String; ParcelSDistTable, AuditSDChangeTable : TTable; RecordType : Char; OrigSDRec : AuditSDRecord); {CHG03161998-1: Track exemption, SD adds, av changes, parcel add/del.} Procedure InsertAuditSDChanges(SwisSBLKey : String; TaxRollYr : String; ParcelSDTable, AuditSDChangeTable : TTable; RecordType : Char); {CHG03301998-1: Trace SD, EX changes from everywhere.} {Insert an add or delete trace record for all sd's for this parcel.} Function SdExtType (ExtCode : String): Char; Function ExemptionAppliesToSpecialDistrict(DistrictType : String; ExemptionCodeRec : ExemptionCodeRecord; CMFlag : String; SDAppliesToSection490, FireDistrict, VolunteerFirefighterOrAmbulanceExemptionApplies : Boolean) : Boolean; overload; Function ExemptionAppliesToSpecialDistrict(ExemptionCodeRec : ExemptionCodeRecord; SpecialDistrictCodeRec : SpecialDistrictCodeRecord) : Boolean; overload; Function ExemptionAppliesToSpecialDistrict(SpecialDistrictCodeTable : TTable; ExemptionCodeTable : TTable; SpecialDistrictCode : String; ExemptionCode : String) : Boolean; overload; Procedure CalculateSpecialDistrictAmounts(ParcelTable, AssessmentTable, ClassTable, ParcelSDTable, SDCodeTable : TTable; ParcelExemptionList, ExemptionCodeList : TList; SDExtensionCodes, {Return lists} SDCC_OMFlags, slAssessedValues, SDValues, HomesteadCodesList : TStringList); {Based on the special district code, calculate the "values" of this special district. This can mean many different things based on the type of district it is. The values returned will always be in correspondence to the type of the district itself. That is, if this is unitary, units will be returned. If this is acreage based, acres will be returned, etc. Note that since a special district may have many extension codes, what is return is a TStringList where each entry is of type extended in string format and corresponds in order to the extension codes. That is, the first entry in the TStringList is the value of the first extension code in the SDExtensionCodes list, etc. Also, for roll totals purposes, we will return the corresponding CC_OM Flags in the list SDCC_OMFlags.} Procedure LoadExemptions(TaxRollYear : String; SwisSBLKey : String; ParcelExemptionList, ExemptionCodeList : TList; ParcelExemptionTable, ExemptionCodeTable : TTable); {CHG02221998-1 : For quicker roll total calcs, only read exemptions 1 time.} Procedure TotalSpecialDistrictsForParcel(TaxRollYr : String; SwisSBLKey : String; ParcelTable, AssessmentTable, ParcelSDTable, SDCodeTable, ParcelEXTable, EXCodeTable : TTable; SDAmounts : TList); {This is the return list of type PParcelExemptionRecord.} {This calculates all values for all special districts on one parcel. The information is returned in a TList where each element is of type PParcelSDValuesRecord.} Function SpecialDistrictIsMoveTax(SDCodeTable : TTable) : Boolean; Procedure AddOneSpecialDistrict( SpecialDistrictTable : TTable; const FieldNames : Array of const; const FieldValues : Array of const; UserName : String); Function GetExemptionTypeDescription(ExemptionCode : String) : String; Procedure DeleteAnExemption(tb_Exemptions : TTable; tb_ExemptionsLookup : TTable; tb_RemovedExemptions : TTable; tb_AuditEXChange : TTable; tb_Audit : TTable; tb_Assessment : TTable; tb_Class : TTable; tb_SwisCode : TTable; tb_Parcel : TTable; tb_ExemptionCode : TTable; AssessmentYear : String; SwisSBLKey : String; ExemptionsNotRecalculatedList : TStringList); Function ParcelHasOverrideSpecialDistricts(tbParcelSpecialDistricts : TTable; sAssessmentYear : String; sSwisSBLKey : String) : Boolean; IMPLEMENTATION uses PASUTILS, ExemptionsNotRecalculatedFormUnit; {==========================================================================} {============= EXEMPTION CALCULATION ===================================} {==========================================================================} {=============================================================} Procedure GetAuditEXList(SwisSBLKey : String; TaxRollYr : String; ExemptionTable : TTable; AuditEXChangeList : TList); {Fill a TList with the exemption information for all exemptions at this time.} var Done, Quit, FirstTimeThrough : Boolean; PAuditEXRec : PAuditEXRecord; begin Done := False; Quit := False; FirstTimeThrough := True; ExemptionTable.CancelRange; SetRangeOld(ExemptionTable, ['TaxRollYr', 'SwisSBLKey', 'ExemptionCode'], [TaxRollYr, SwisSBLKey, ' '], [TaxRollYr, SwisSBLKey, 'ZZZZZ']); ExemptionTable.First; repeat If FirstTimeThrough then FirstTimeThrough := False else try ExemptionTable.Next; except Quit := False; SystemSupport(950, ExemptionTable, 'Error getting next exemption record.', GlblUnitName, GlblErrorDlgBox); end; If ExemptionTable.EOF then Done := True; If not (Done or Quit) then begin New(PAuditEXRec); with PAuditEXRec^, ExemptionTable do begin ExemptionCode := FieldByName('ExemptionCode').Text; CountyAmount := FieldByName('CountyAmount').AsFloat; TownAmount := FieldByName('TownAmount').AsFloat; SchoolAmount := FieldByName('SchoolAmount').AsFloat; VillageAmount := FieldByName('VillageAmount').AsFloat; Percent := FieldByName('Percent').AsFloat; OwnerPercent := FieldByName('OwnerPercent').AsFloat; InitialDate := FieldByName('InitialDate').AsDateTime; TerminationDate := FieldByName('TerminationDate').AsDateTime; end; {with PAuditEXRec^, ExemptionTable do} AuditEXChangeList.Add(PAuditEXRec); end; {If not (Done or Quit)} until (Done or Quit); {FXX07172001-1: The range was not being cancelled.} ExemptionTable.CancelRange; end; {GetAuditEXList} {=============================================================} Procedure InsertAuditEXChanges(SwisSBLKey : String; TaxRollYr : String; AuditEXList : TList; AuditEXChangeTable : TTable; BeforeOrAfter : Char); {CHG03241998-1: Track the exemption changes as a whole picture - before and after.} {For each exemption, store all the information in the audit ex list to get a complete picture of all exemption before any changes and after.} var I : Integer; begin For I := 0 to (AuditEXList.Count - 1) do with PAuditEXRecord(AuditEXList[I])^, AuditEXChangeTable do begin Insert; FieldByName('SwisSBLKey').Text := SwisSBLKey; FieldByName('TaxRollYr').Text := TaxRollYr; FieldByName('ExemptionCode').Text := ExemptionCode; FieldByName('Date').AsDateTime := Date; FieldByName('Time').AsDateTime := Now; FieldByName('User').Text := GlblUserName; FieldByName('BeforeOrAfter').Text := BeforeOrAfter; FieldByName('Percent').AsFloat := Percent; FieldByName('CountyAmount').AsFloat := CountyAmount; FieldByName('TownAmount').AsFloat := TownAmount; FieldByName('SchoolAmount').AsFloat := SchoolAmount; FieldByName('VillageAmount').AsFloat := VillageAmount; FieldByName('OwnerPercent').AsFloat := OwnerPercent; FieldByName('InitialDate').AsDateTime := InitialDate; FieldByName('TerminationDate').AsDateTime := TerminationDate; try Post; except SystemSupport(951, AuditEXChangeTable, 'Error inserting exemption add\deletion trace rec.', GlblUnitName, GlblErrorDlgBox); end; end; {with PAuditEXRecord(AuditEXList[I])^, AuditEXChangeTable do} end; {InsertEXChangeTrace} {==============================================================} Function GetExemptionAmountToDisplay(EXAppliesArray : ExemptionAppliesArrayType) : Integer; {CHG10151997-3: The amount field in the grid is now a "calculated" field which is not part of the database. This is because if we show just town amount, a county only exemption will have an amount of zero.} {Show the town amount if there is one. Otherwise, county, school, or village in that order.} begin If EXAppliesArray[ExTown] then Result := EXTown else If EXAppliesArray[ExCounty] then Result := EXCounty else If EXAppliesArray[ExSchool] then Result := EXSchool else Result := EXVillage; end; {GetExemptionAmountToDisplay} {====================================================================================} Function ValidSwisCodeForExemptionOrSpecialDistrictCode(SwisList : TStringList; SwisCode : String) : Boolean; {Based on the list of swis restrictions in SwisList, see if the SwisCode fits in. Note that each restriction can be 2 char.'s (county), 4 char.'s (city), or 6 char.'s (village).} var I, SwisLength : Integer; begin If (SwisList.Count = 0) then Result := True {There are no restrictions, so any swis is valid.} else begin {Search through the list comparing the swis code to the restrictions.} Result := False; For I := 0 to (SwisList.Count - 1) do begin SwisLength := Length(Trim(SwisList[I])); If (Take(SwisLength, SwisList[I]) = Take(SwisLength, SwisCode)) then Result := True; end; {For I := 0 to (SwisList.Count - 1) do} end; {else of If (SwisList.Count = 0)} end; {ValidSwisCodeForExemptionOrSpecialDistrictCode} {===========================================================================} Procedure GetHomesteadAndNonhstdExemptionAmounts( ExemptionCodes, ExemptionHomesteadCodes, {What is the homestead code for each exemption?} CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts : TStringList; var HstdEXAmounts, NonhstdEXAmounts : ExemptionTotalsArrayType); {Given the exemption amounts and the corresponding homestead codes array, divide the amounts into homestead and nonhomestead totals arrays. For parcels that are not split, all of the amounts will go into either the homestead or nonhomestead array. If this is a split parcel, the totals may be split between the two. If this is not a designated parcel, the exemptions amounts will go into the homestead exemption totals array.} var I : Integer; begin For I := 1 to 4 do begin HstdExAmounts[I] := 0; NonhstdExAmounts[I] := 0; end; For I := 0 to (ExemptionCodes.Count - 1) do If (ExemptionHomesteadCodes[I] = 'N') then begin NonhstdExAmounts[ExCounty] := NonHstdEXAmounts[EXCounty] + StrToFloat(CountyExemptionAmounts[I]); NonhstdExAmounts[ExTown] := NonHstdEXAmounts[EXTown] + StrToFloat(TownExemptionAmounts[I]); NonhstdExAmounts[ExSchool] := NonHstdEXAmounts[EXSchool] + StrToFloat(SchoolExemptionAmounts[I]); NonhstdExAmounts[ExVillage] := NonHstdEXAmounts[EXVillage] + StrToFloat(VillageExemptionAmounts[I]); end else begin {If the homestead code is ' ' or 'H'.} HstdExAmounts[ExCounty] := HstdExAmounts[ExCounty] + StrToFloat(CountyExemptionAmounts[I]); HstdExAmounts[ExTown] := HstdExAmounts[ExTown] + StrToFloat(TownExemptionAmounts[I]); HstdExAmounts[ExSchool] := HstdExAmounts[ExSchool] + StrToFloat(SchoolExemptionAmounts[I]); HstdExAmounts[ExVillage] := HstdExAmounts[ExVillage] + StrToFloat(VillageExemptionAmounts[I]); end; {else of If (ExemptionHomesteadCodes[I] = 'N')} end; {GetHomesteadAndNonhstdExemptionAmounts} {===========================================================================} Function TotalExemptionsForParcel( TaxRollYear : String; SwisSBLKey : String; ParcelExemptionTable, EXCodeTable : TTable; ParcelHomesteadCode : String; ExemptionType : Char; {(A)ll,(F)ixed,a(G)eds,(N)onresidential} ExemptionCodes, ExemptionHomesteadCodes, {What is the homestead code for each exemption?} ResidentialTypes, {What are the residential types for each exemption?} CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts : TStringList; var BasicSTARAmount, EnhancedSTARAmount : Comp) : ExemptionTotalsArrayType; {CHG12011997 - STAR support. Note that the STAR amounts are never returned in the total exemptions. They are always treated seperately.} {ExemptionType is 'A' for all, 'N' for all except nonresidential exemptions, 'F' for fixed exemption, or 'G' for all ageds. 'N' is used to calculate aged exemption, and 'F' is used to calculate percentage exemptions since the fixed exemptions are applied first.} {Go through all the exemptions and add the exemption amount. Note that we will check each exemption to see which it applies to.} {Also, we will return a string list with the exemption codes. For each entry in the ExemptionCodes list, 4 values are returned in the Amounts lists (county, town, village, school) in the corresponding positions. That is, if exemption code 41180 is in position 2 in the ExemptionCodes list, position 2 of the Amounts lists gives the corresponding amount breakdown.} var ExemptArray : ExemptionTotalsArrayType; ApplyThisExemption, Done, Quit, FirstTimeThrough : Boolean; I, ProcessingType : Integer; OrigIndexName, TempStr : String; CalcMethod, TempHomesteadCode : String; EXCode : String; begin ExemptionCodes.Clear; ExemptionHomesteadCodes.Clear; CountyExemptionAmounts.Clear; TownExemptionAmounts.Clear; VillageExemptionAmounts.Clear; SchoolExemptionAmounts.Clear; {FXX02091998-1: Pass the residential type of each exemption.} ResidentialTypes.Clear; For I := 1 to 4 do ExemptArray[I] := 0; BasicSTARAmount := 0; EnhancedSTARAmount := 0; OrigIndexName := ParcelExemptionTable.IndexName; ParcelExemptionTable.IndexName := 'BYTAXROLLYR_SWISSBLKEY'; ParcelExemptionTable.CancelRange; LogTime('c:\trace.txt', 'Before TotalExemptionForParcel SetRange - ' + TaxRollYear + '/' + SwisSBLKey); SetRangeOld(ParcelExemptionTable, ['TaxRollYr', 'SwisSBLKey'], [TaxRollYear, SwisSBLKey], [TaxRollYear, SwisSBLKey]); LogTime('c:\trace.txt', 'After TotalExemptionForParcel SetRange'); Done := False; Quit := False; FirstTimeThrough := True; ParcelExemptionTable.First; If not (Done or Quit) then repeat If FirstTimeThrough then FirstTimeThrough := False else ParcelExemptionTable.Next; {If the SBL changes or we are at the end of the range, we are done.} TempStr := ParcelExemptionTable.FieldByName('SwisSBLKey').Text; If ParcelExemptionTable.EOF then Done := True; {We have an exemption record, so get the totals.} If not (Done or Quit) then begin ApplyThisExemption := True; FindKeyOld(EXCodeTable, ['EXCode'], [ParcelExemptionTable.FieldByName('ExemptionCode').Text]); {Now see if this exemption should be applied or not. If ExemptionType is 'N', then we do not want to apply any exemptions which are non-residential i.e. ResidentialType = 'N'. Also, if this is an aged, we don't want to apply it. If ExemptionType = 'F', then we only want to apply amount exemptions - these are exemptions with CalcMethod = F,T,I,L, or V.} If (ExemptionType in ['N', 'F']) then begin {CHG04161998-1: Add the 4193x limited income diabled exemption. It is the same as 4180x.} {CHG12291998-1: Malta has 4190x physically disabled limited income which is same as senior.} {FXX04281999-1: 41900 is calculated before 41800.} {CHG08132008-1(2.15.1.5): Add 4191x as a low income disabled exemption.} If ((ExemptionType = 'N') and ((Deblank(EXCodeTable.FieldByName('ResidentialType').Text) = 'N') or ExemptionIsLowIncomeDisabled(ParcelExemptionTable.FieldByName('ExemptionCode').AsString) or (*(Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '4190') or *) (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '4180'))) then ApplyThisExemption := False; CalcMethod := Take(1, EXCodeTable.FieldByName('CalcMethod').Text); If ((ExemptionType = 'F') and (not (CalcMethod[1] in ['F', 'T', 'I', 'L', 'V']))) then ApplyThisExemption := False; end; {If (ExemptionType in ['N', 'F'])} {Is this an aged exemption?} EXCode := ParcelExemptionTable.FieldByName('ExemptionCode').Text; If ((ExemptionType = 'G') and (Take(4, EXCode) <> '4180')) then ApplyThisExemption := False; {FXX07142010-1(2.26.1.7)[I7782]: Don't include the senior exemption even if the calc code is odd.} If (_Compare(ExemptionType, 'F', coEqual) and _Compare(EXCode, '4180', coStartsWith)) then ApplyThisExemption := False; {CHG12011997-2: STAR support.} {Do not add STAR exemptions to the overall exemption amounts - they are treated seperately.} with ParcelExemptionTable do If ((Take(4, EXCode) = '4183') or (Take(4, EXCode) = '4185')) then begin ApplyThisExemption := False; If (Take(4, EXCode) = '4183') then EnhancedSTARAmount := EnhancedSTARAmount + TCurrencyField(FieldByName('SchoolAmount')).Value; If (Take(4, EXCode) = '4185') then BasicSTARAmount := BasicSTARAmount + TCurrencyField(FieldByName('SchoolAmount')).Value; end; {If ((Take(4, EXCode) = '4183') or ...} {If we want to add this exemption to the exemption total, then do so.} If ApplyThisExemption then with ParcelExemptionTable do begin ExemptionCodes.Add(FieldByName('ExemptionCode').Text); {If this is not a split parcel, just use the homestead code of the overall parcel. Otherwise, if the homestead code is filled in for this exemption, use this homestead code.} TempHomesteadCode := Take(1, ParcelHomesteadCode); If ((ParcelHomesteadCode = 'S') and (Deblank(TempHomesteadCode) <> '')) then TempHomesteadCode := FieldByName('HomesteadCode').Text; ExemptionHomesteadCodes.Add(TempHomesteadCode); ExemptArray[EXCounty] := ExemptArray[EXCounty] + TCurrencyField(FieldByName('CountyAmount')).Value; ExemptArray[EXTown] := ExemptArray[EXTown] + TCurrencyField(FieldByName('TownAmount')).Value; ExemptArray[EXSchool] := ExemptArray[EXSchool] + TCurrencyField(FieldByName('SchoolAmount')).Value; {CHG05142002-1: Village processing} {CHG03132004-2(2.08): If this municipality does not have a village that takes a partial roll, use the town amount for the village.} {FXX02112005-1(2.8.3.7): If this is a municipality that has a village with different exemptions, only apply to the village if the apply to village flag is on.} If (VillageIsAssessingUnit(Copy(SwisSBLKey, 1, 6)) and (rtdVillageReceivingPartialRoll in GlblRollTotalsToShow)) then begin If (FieldByName('ApplyToVillage').AsBoolean or (FieldByName('ExemptionCode').Text[5] = '7')) then ExemptArray[EXVillage] := ExemptArray[EXVillage] + TCurrencyField(FieldByName('VillageAmount')).Value; end else ExemptArray[EXVillage] := ExemptArray[EXVillage] + TCurrencyField(FieldByName('TownAmount')).Value; CountyExemptionAmounts.Add(FloatToStr(TCurrencyField(FieldByName('CountyAmount')).Value)); TownExemptionAmounts.Add(FloatToStr(TCurrencyField(FieldByName('TownAmount')).Value)); SchoolExemptionAmounts.Add(FloatToStr(TCurrencyField(FieldByName('SchoolAmount')).Value)); {CHG05142002-1: Village processing} {CHG03132004-2(2.08): If this municipality does not have a village that takes a partial roll, use the town amount for the village.} {FXX02112005-1(2.8.3.7): If this is a municipality that has a village with different exemptions, only apply to the village if the apply to village flag is on.} {FXX09112008-1(2.15.1.11): Only check to see if the exemption applies to the village if this is an assessing unit. Otherwise, it always does.} If (VillageIsAssessingUnit(Copy(SwisSBLKey, 1, 6)) and (rtdVillageReceivingPartialRoll in GlblRollTotalsToShow)) then begin If (FieldByName('ApplyToVillage').AsBoolean or (FieldByName('ExemptionCode').Text[5] = '7')) then VillageExemptionAmounts.Add(FloatToStr(TCurrencyField(FieldByName('VillageAmount')).Value)) else VillageExemptionAmounts.Add('0'); end else VillageExemptionAmounts.Add(FloatToStr(TCurrencyField(FieldByName('TownAmount')).Value)); {FXX02091998-1: Pass the residential type of each exemption.} ResidentialTypes.Add(EXCodeTable.FieldByName('ResidentialType').Text); end; {with ParcelExemptionTable do} end; {If not (Done or Quit)} until (Done or Quit); LogTime('c:\trace.txt', 'After TotalExemptionForParcel loop'); If (OrigIndexName <> ParcelExemptionTable.IndexName) then ParcelExemptionTable.IndexName := OrigIndexName; LogTime('c:\trace.txt', 'After TotalExemptionForParcel loop2'); Result := ExemptArray; end; {TotalExemptionsForParcel} {==========================================================================} Function ExApplies(ExCode : String; AppliesToVillage : Boolean) : ExemptionAppliesArrayType; {Determine if the exemption applies to county, town, village, or school. An array of Booleans is returned with 1=County, 2=Town, 3=Village, 4=School. Note that the exemption applies to the village only if the village flag is on at the parcel exemption level.} var I : Integer; ExemptAppliesArray : ExemptionAppliesArrayType; begin For I := 1 to 4 do ExemptAppliesArray[I] := False; If (ExCode[5] in ['0','1','2','5']) then ExemptAppliesArray[RTCounty] := True; {FXX12161998-6: If an exemption applies in the town, it applies in the village.} {FXX02192004-1(2.07l1): An exemption code with a '7' applies to village only. Also, don't make it so that a town automatically applies to a village. Only applies if it is a '7' or AppliesToVillage is true.} If (EXCode[5] in ['0','1','3','6']) then ExemptAppliesArray[RTTown] := True; {CHG03132004-2(2.08): If this municipality does not have a village that takes a partial roll, use the town applies status for the village.} If (rtdVillageReceivingPartialRoll in GlblRollTotalsToShow) then begin If AppliesToVillage then ExemptAppliesArray[RTVillage] := True; If (ExCode[5] in ['7']) then ExemptAppliesArray[RTVillage] := True; end else ExemptAppliesArray[RTVillage] := ExemptAppliesArray[RTTown]; If (ExCode[5] in ['0','4','5','6']) then ExemptAppliesArray[RTSchool] := True; Result := ExemptAppliesArray; end; {ExApplies} {==========================================================================} Function GetResidentialPercent(ParcelTable, ExemptionCodeTable : TTable; EXCode : String) : Real; {If there is a residential percent and this is a residential or non-residential exemption, then only part of the land and total value is used for the exemption calculation. Notice that this is applied to the assessed value minus the other exemptions "above" this exemption have been applied. For example, if a property has a total value of $10,000 and an 41101 (vet elig fund) exemption for $2,000 and an aged 41800 of 50% with a residential percent of 40%, the 41800 is (10000 - 2000) * 0.5 * 0.4 = $1600.} var ResidentialPercent : Real; ResType : Char; begin Result := 1; {FXX02031998-1: Need to make sure the exemption table is pointing to the correct exemption.} FindKeyOld(ExemptionCodeTable, ['EXCode'], [EXCode]); ResidentialPercent := TFloatField(ParcelTable.FieldByName('ResidentialPercent')).Value; {This is not a classified municipality, so if this is a residential exemption, we need to multiply the assessed values by the residential percent. If this is a non-residential exemption, we need to multiply the assessed values by 100 - residential percent.} If (Roundoff(ResidentialPercent, 0) <> 0) then begin ResType := ExemptionCodeTable.FieldByName('ResidentialType').Text[1]; {FXX02021998-5: Apply residential percent correctly on a per exemption basis based on what the exemption applies to.} If (ResType = 'R') then Result := Roundoff((ResidentialPercent/100), 2); If (ResType = 'N') then Result := Roundoff(((100 - ResidentialPercent)/100), 2); {If it applies to both residential and non-residential, the percent should be 100 regardless of whether or not there is a percent.} If (ResType = 'B') then Result := 1; end {If (Roundoff(ResidentialPercent, 0) <> 0)} else Result := 1; end; {GetResidentialPercent} {==========================================================================} Function ExemptionIsSTAR(EXCode : String) : Boolean; begin Result := (Take(4, EXCode) = '4183') or (Take(4, EXCode) = '4185'); end; {ExemptionIsSTAR} {==========================================================================} Function ExemptionIsSenior(EXCode : String) : Boolean; begin Result := (Take(4, EXCode) = '4180'); end; {ExemptionIsSenior} {==========================================================================} Function ExemptionIsLowIncomeDisabled(EXCode : String) : Boolean; {CHG08132008-1(2.15.1.5): Add 4191x as a low income disabled exemption.} {FXX01102013(MDT): 4190 exemption is not income based.} begin Result := (*_Compare(EXCode, '4190', coStartsWith) or *) _Compare(EXCode, '4191', coStartsWith) or _Compare(EXCode, '4193', coStartsWith); end; {ExemptionIsLowIncomeDisabledr} {==========================================================================} Function ExemptionIsEnhancedSTAR(EXCode : String) : Boolean; begin Result := (Take(4, EXCode) = '4183'); end; {ExemptionIsEnhancedSTAR} {==========================================================================} Function ExemptionIsBasicVeteran(sExemptionCode : String) : Boolean; begin Result := (_Compare(sExemptionCode, '4100', coStartsWith) or _Compare(sExemptionCode, '4110', coStartsWith) or _Compare(sExemptionCode, '4111', coStartsWith) or _Compare(sExemptionCode, '4120', coStartsWith) or _Compare(sExemptionCode, '4130', coStartsWith)); end; {ExemptionIsBasicVeteran} {==========================================================================} Function ExemptionIsAlternativeVeteran(sExemptionCode : String) : Boolean; begin Result := (_Compare(sExemptionCode, '4112', coStartsWith) or _Compare(sExemptionCode, '4113', coStartsWith) or _Compare(sExemptionCode, '4114', coStartsWith)); end; {ExemptionIsAlternativeVeteran} {==========================================================================} Function ExemptionIsColdWarVeteran(sExemptionCode : String) : Boolean; begin Result := (_Compare(sExemptionCode, '4115', coStartsWith) or _Compare(sExemptionCode, '4116', coStartsWith) or _Compare(sExemptionCode, '4117', coStartsWith)) end; {ExemptionIsColdWarVeteran} {==========================================================================} Function ExemptionIsDisabledColdWarVeteran(sExemptionCode : String) : Boolean; begin Result := _Compare(sExemptionCode, '4117', coStartsWith); end; {ExemptionIsDisabledWarVeteran} {==========================================================================} Function ExemptionIsVolunteerFirefighter(EXCode : String) : Boolean; {CHG03242004-1(2.07l2): Firefighter exemption is 41681 not 41661 for Westchester.} {FXX06022008-1(2.13.1.6): 4164 is the start of the firefighter code in New Castle.} {FXX03092008-1(2.17.1.5): 4163x is, too.} begin Result := ((Take(4, EXCode) = '4163') or (Take(4, EXCode) = '4164') or (Take(4, EXCode) = '4166') or (Take(4, EXCode) = '4167') or (Take(4, EXCode) = '4168')); end; {ExemptionIsVolunteerFirefighter} {==========================================================================} Function PropertyIsCoopOrMobileHomePark(ParcelTable : TTable) : Boolean; {FXX12011998-18: Ownership code of C (condo) counts the same as P (co-op) for vets, senior, STARs.} {FXX01201999-1: Actually, condos are not the same as co-ops.} {CHG09152003-1: Actually extend this to any 400 property class.} {CHG10072003-1(2.07j): Actually, don't include 412 or 411C in this group.} begin with ParcelTable do begin {CHG01222006-1(2.9.5.1): Allow a municipality to treat all mixed-use parcels as residentials for exemption calculation purposes.} {CHG12122006-1(2.11.1.5): Accomodate waterfront ownership codes.} Result := (_Compare(FieldByName('OwnershipCode').AsString, ['P', 'Q'], coEqual) or {Co-op, waterfront co-op} _Compare(FieldByName('PropertyClassCode').AsString, MobileHomePropertyClass, coEqual) or ((not GlblTreatMixedUseParcelsAsResidential) and _Compare(FieldByName('PropertyClassCode').AsString, '4', coStartsWith))); {Commercial, at user discretion} {FXX07262004-2(2.07l5): Treat 483 (Converted Residence) as a regular 210.} If (Result and _Compare(FieldByName('PropertyClassCode').AsString, ['412', '483'], coEqual) or (_Compare(FieldByName('PropertyClassCode').AsString, '411', coEqual) and _Compare(FieldByName('OwnershipCode').AsString, ['C', 'D'], coEqual))) {Condo, condo waterfront} then Result := False; end; {with ParcelTable do} end; {PropertyIsCoopOrMobileHomePark} {==========================================================================} Procedure GetColdWarVetPercentandLimit( tbAssessmentYearControl : TTable; tbSwisCodes : TTable; iColdWarVeteranType : Integer; iJurisdiction : Integer; sSwisCode : String; var fPercent : Double; var iLimit : LongInt); var tbColdWarVeteranLimts : TTable; sLimitSet : String; begin iLimit := 0; fPercent := 0; tbColdWarVeteranLimts := nil; tbAssessmentYearControl.Refresh; try tbColdWarVeteranLimts := TTable.Create(nil); _OpenTable(tbColdWarVeteranLimts, 'zcoldwarvetlimits', '', 'BYVETLIMITCODE', NoProcessingType, []); case iJurisdiction of EXCounty : sLimitSet := tbAssessmentYearControl.FieldByName('ColdWarVetCntyLimitSet').AsString; EXMunicipal, EXVillage : begin _Locate(tbSwisCodes, [sSwisCode], '', []); sLimitSet := tbSwisCodes.FieldByName('ColdWarVetMunicLimitSet').AsString; end; end; {case iJurisdiction of} _Locate(tbColdWarVeteranLimts, [sLimitSet], '', []); with tbColdWarVeteranLimts do begin case iColdWarVeteranType of cwvBasic : begin fPercent := FieldByName('BasicPercent').AsFloat; iLimit := FieldByName('BasicLimit').AsInteger; end; cwvDisabled : iLimit := FieldByName('DisabledVetLimit').AsInteger; end; {case iColdWarVeteranType of} Close; end; {with tbColdWarVeteranLimts do} finally tbColdWarVeteranLimts.Free; end; end; {GetColdWarVetLimit} {==========================================================================} Function CalculateSTARAmount( ExemptionCodeTable, ParcelExemptionTable, ParcelTable : TTable; AssessedValue : Comp; ResidentialPercent : Real; Percent : Real; iSchoolExemptionAmount : LongInt; var FullSTARAmount : Comp) : Comp; {Given a STAR exemption code, calculate the STAR amount. Two items are returned - the full STAR amount (for exemption totals) and the actual STAR amount for this parcel. This can be different if the school taxable value before STAR is less than the full STAR amount.} {CHG12011997-2: STAR support} var SchoolTaxableVal : Comp; I : Integer; begin (* {Get the equalization rate for this swis.} SwisCodeTable.FindKey([TaxRollYr, SwisCode]); EqualizationRate := SwisCodeTable.FieldByName('EqualizationRate').AsFloat / 100; {FXX02051998-1: Need to figure out the processing type since this could be a STAR added to This Year or Next Year.} ProcessingType := GetProcessingTypeForTaxRollYear(TaxRollYr); {FXX02041998-1: The sales differential factor is different for basic and enhanced.} If (ProcessingType = ThisYear) then begin ResSalesPriceDifferentialFactor := GlblThisYearBasicSalesDifferential; ResSTARLimit := GlblThisYearBasicLimit; EnhSalesPriceDifferentialFactor := GlblThisYearEnhancedSalesDifferential; EnhSTARLimit := GlblThisYearEnhancedLimit; end; {If (ProcessingType = ThisYear)} If (ProcessingType = NextYear) then begin ResSalesPriceDifferentialFactor := GlblNextYearBasicSalesDifferential; ResSTARLimit := GlblNextYearBasicLimit; EnhSalesPriceDifferentialFactor := GlblNextYearEnhancedSalesDifferential; EnhSTARLimit := GlblNextYearEnhancedLimit; end; {If (ProcessingType = NextYear)} If (Take(4, EXCode) = '4183') then Result := EnhSTARLimit * EnhSalesPriceDifferentialFactor * EqualizationRate else Result := ResSTARLimit * ResSalesPriceDifferentialFactor * EqualizationRate; {Note that the STAR amount is always rounded to the nearest $10.} Result := Roundoff((Result / 10), 0) * 10; Result := Roundoff(Result, 0); *) {CHG04152007-1(2.11.1.25): The residential percent should be applied to the assessed value prior to calculating the STAR value - per Ramapo.} {FXX01272013: Residential percent does not apply to STAR.} {HXX05142013: Yes it is: Per RPTL Section 425: If the STAR exemption is to be applied to a non-residential type of parcel, a portion of which is used by the owner as a primary residence, it must be applied solely to that portion of the property used for residential purposes. Under no circumstances may the exempt value exceed the assessed value attributable to that portion. } If _Compare(ResidentialPercent, 0, coNotEqual) then AssessedValue := Trunc(AssessedValue * ResidentialPercent); Result := ExemptionCodeTable.FieldByName('FixedAmount').AsInteger; {CHG01292008(2.11.7.4): STAR can now have a percent.} If _Compare(Percent, 0, coGreaterThan) then Result := Result * (Percent / 100); Result := Roundoff(Result, 0); FullStarAmount := Result; {Now see if we need to adjust the result either because 1. This is a co-op or mobile home park 2. The STAR amount is greater than the school taxable value before STAR.} {FXX05172010-1(2.24.2.4)[I7209]: Only take residential amounts in to account for calculating STAR.} SchoolTaxableVal := AssessedValue - iSchoolExemptionAmount; (* For I := 0 to (SchoolExemptionAmounts.Count - 1) do begin try iSchoolExemptionAmount := StrToInt(SchoolExemptionAmounts[I]); except end; SchoolTaxableVal := SchoolTaxableVal - iSchoolExemptionAmount; end; {For I := 0 to (SchoolExemptionAmounts.Count - 1) do} *) If (SchoolTaxableVal < FullStarAmount) then Result := SchoolTaxableVal; {If it is a co-op or mobile home park, they must fill in the amount by hand.} {FXX08051998-1: If there is an amount already in the town or amount field, then use this amount for condos.} {CHG06062001-1: STAR can now be placed on mixed use 400 prop class.} {FXX07102001-1: If the 411 is a condo, we want to autocalc, not let them fill it in.} If (PropertyIsCoopOrMobileHomePark(ParcelTable) or ((not GlblTreatMixedUseParcelsAsResidential) and (ParcelTable.FieldByName('PropertyClassCode').Text[1] = '4') and (Trim(ParcelTable.FieldByName('OwnershipCode').Text) <> 'C'))) then with ParcelExemptionTable do If (Roundoff(FieldByName('Amount').AsFloat, 0) > 0) then Result := FieldByName('Amount').AsFloat else If (Roundoff(FieldByName('TownAmount').AsFloat, 0) > 0) then Result := FieldByName('TownAmount').AsFloat else Result := 0; end; {CalculateSTARAmount} {==========================================================================} Procedure GetResidentialExemptionAmounts(var ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts : ExemptionTotalsArrayType; ResidentialTypes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts : TStringList); {FXX02091998-1: Seperate the exemption amounts into amounts that only apply to the residential portion, non-residential portion and those that apply to the whole parcel regardless of residential percent.} var I : Integer; begin For I := 1 to 4 do begin ResidentialExemptionAmounts[I] := 0; FullParcelExemptionAmounts[I] := 0; NonResidentialExemptionAmounts[I] := 0; end; {For I := 1 to 4 do} {FXX06252001-1: If there is no ResidentialType filled in for an EX code, caused an error. Assume 'B' if not filled in.} For I := 0 to (ResidentialTypes.Count - 1) do case Take(1, ResidentialTypes[I])[1] of 'R' : begin ResidentialExemptionAmounts[EXCounty] := ResidentialExemptionAmounts[EXCounty] + StrToFloat(CountyExemptionAmounts[I]); ResidentialExemptionAmounts[EXTown] := ResidentialExemptionAmounts[EXTown] + StrToFloat(TownExemptionAmounts[I]); ResidentialExemptionAmounts[EXSchool] := ResidentialExemptionAmounts[EXSchool] + StrToFloat(SchoolExemptionAmounts[I]); ResidentialExemptionAmounts[EXVillage] := ResidentialExemptionAmounts[EXVillage] + StrToFloat(VillageExemptionAmounts[I]); end; {'R' : begin} ' ', 'B' : begin FullParcelExemptionAmounts[EXCounty] := FullParcelExemptionAmounts[EXCounty] + StrToFloat(CountyExemptionAmounts[I]); FullParcelExemptionAmounts[EXTown] := FullParcelExemptionAmounts[EXTown] + StrToFloat(TownExemptionAmounts[I]); FullParcelExemptionAmounts[EXSchool] := FullParcelExemptionAmounts[EXSchool] + StrToFloat(SchoolExemptionAmounts[I]); FullParcelExemptionAmounts[EXVillage] := FullParcelExemptionAmounts[EXVillage] + StrToFloat(VillageExemptionAmounts[I]); end; {'B' : begin} 'F' : begin NonResidentialExemptionAmounts[EXCounty] := NonResidentialExemptionAmounts[EXCounty] + StrToFloat(CountyExemptionAmounts[I]); NonResidentialExemptionAmounts[EXTown] := NonResidentialExemptionAmounts[EXTown] + StrToFloat(TownExemptionAmounts[I]); NonResidentialExemptionAmounts[EXSchool] := NonResidentialExemptionAmounts[EXSchool] + StrToFloat(SchoolExemptionAmounts[I]); NonResidentialExemptionAmounts[EXVillage] := NonResidentialExemptionAmounts[EXVillage] + StrToFloat(VillageExemptionAmounts[I]); end; {'F' : begin} end; {case ResidentialTypes[I][1] of} end; {GetResidentialExemptionAmounts} {==========================================================================} Function CalculateTaxableVal(AssessedValue, ExemptionAmount : Comp) : Comp; {FXX05261998-3: Don't let a taxable value decrease below 0.} {Return the taxable value of the property for a tax type, returning 0 if the taxable value is below 0.} begin Result := AssessedValue - ExemptionAmount; If (Result < 0) then Result := 0; end; {CalculateTaxableVal} {==========================================================================} Function CalculateExemptionWithResidentialPercent(AssessedVal : Comp; ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts : ExemptionTotalsArrayType; ResidentialPercent, CalcPercent : Real; ResidentialType : String; ExIdx : Integer) : Extended; {FXX02091998-1. For exemptions where the residential percent applies, the exemption amounts must be seperated into those that apply to the residential part, non-residential part and full parcel. The exemptions are calculated based on these amounts.} begin Result := 0; ResidentialType := Take(1, ResidentialType); {FXX02131998-1: Roundoff to 4 decimal places since percent sometimes gets divided.} case ResidentialType[1] of 'R' : Result := ((AssessedVal - FullParcelExemptionAmounts[ExIdx]) * ResidentialPercent - ResidentialExemptionAmounts[ExIdx]) * Roundoff((CalcPercent / 100), 4); {Both -> no residential percent.} ' ', 'B' : Result := (AssessedVal - (FullParcelExemptionAmounts[ExIdx] + ResidentialExemptionAmounts[ExIdx] + NonResidentialExemptionAmounts[ExIdx])) * Roundoff((CalcPercent / 100), 4); 'N' : Result := ((AssessedVal - FullParcelExemptionAmounts[ExIdx]) * ResidentialPercent - {This is already 1 - Res Percent.} NonResidentialExemptionAmounts[ExIdx]) * Roundoff((CalcPercent / 100), 4); end; {case ResidentialType of} {FXX05261998-2: If this is a negative result, return 0.} If (Roundoff(Result, 0) < 0) then Result := 0; end; {CalculateExemptionWithResidentialPercent} {==========================================================================} Function CalculateExemptionAmount( ExemptionCodeTable, ParcelExemptionTable, {Table with the current parcel exemption} ParcelExemptionLookupTable, {Lookup table to find other exemptions.} AssessmentTable, ClassTable, SwisCodeTable, ParcelTable : TTable; TaxRollYr : String; SwisSBLKey : String; var FixedPercent : Comp; var VetMaxSet, EqualizationRateFilledIn, ExemptionRecalculated : Boolean; iLandValue : LongInt; iAssessedValue : LongInt; bUseOverrideAssessedValue : Boolean): ExemptionTotalsArrayType; {Calculate the amount for this exemption based on the exemption calc code and the exemption code itself. The calculations are (by calc code): F: Fixed amount set in the exemption code table. L: Exemption is land assessed value. I: Exemption is improvement value (total assessed - land assessed). T: Exemption is total assessed value. P: Exemption is a fixed percent of the total assessed value (for now). The fixed percent is set in the exemption code table. V: Exemption is the amount which is entered in the parcel exemption record. (variable amount) blank : Variable percent (set on a per parcel basis) or Special Rule (i.e. veteran) Veteran exemptions: 4112 (War vet): Min(State Max, Vet % * Total Assessed Val) * Equalization Rate 4113 (Combat vet): Min(State Combat Max, Combat Vet % * Total Assessed Val) * Equalization Rate 4114 (Disab vet): Min(State Disab Max, User Entered % * Total Assessed Val) * Equalization Rate. Here are some of the other rules: 1. Amount based exemptions are calculated first. 2. Percentage based exemptions are calculated second (i.e. they use the taxable value after the fixed amounts are subtracted. 3. Ageds are calculated last. Only non-residential exemptions are not applied before calculating the aged amount. Note that at this point we do not prevent them from entering them in the wrong order which will cause incorrect calculations, but we will fix this.} {CHG12011997-2: STAR support.} var ClassRecordFound, Found, Quit, SpecialCase, AppliesToVillage : Boolean; Percent, OwnerPercent : Double; {FXX04292004-1(2.07l3): Change the type to Double so that exemption percents don't have to be integer.} AltVetRate, LandAssessedVal, TotalAssessedVal, VetMax, DisabledVetMax, CombatVetMax, BasicSTARAmount, EnhancedSTARAmount, STARAmount, FullSTARAmount, EqualizedMaximum : Comp; EqualizationRate : Extended; CalcCode : String; HstdEXAmounts, NonhstdEXAmounts, ExemptionTotalsArray : ExemptionTotalsArrayType; {Exemption amount totals used for calculating certain exemptions.} ThisExemptionAmountsArray : ExemptionTotalsArrayType; {The array with the exemption amounts for this exemption.} EXAppliesArray : ExemptionAppliesArrayType; {Does the exemption apply to county, town, school or village?} ResidentialPercent : Real; EXAmount : Extended; ExemptionCodes, ExemptionHomesteadCodes, ResidentialTypes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts : TStringList; I, J, EXIdx, ProcessingType : Integer; ResType : Char; EXCode : String; ResidentialType : String; ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts : ExemptionTotalsArrayType; InitialYear, InitialMonth, InitialDay, CurrentYear, CurrentMonth, CurrentDay, YearsDifference : Word; AssessmentYearControlTable : TTable; iColdWarVetLimit, iColdWarVeteranType : LongInt; begin VetMax := 0; DisabledVetMax := 0; ProcessingType := GetProcessingTypeForTaxRollYear(TaxRollYr); {CHG01282004-1(2.08): Display exemptions not recalculated. Can be nil if don't care.} ExemptionRecalculated := True; FixedPercent := 0; Quit := False; For I := 1 to 4 do ThisExemptionAmountsArray[I] := 0; {Which municipality types does this exemption apply to (county, town, school, village)?} EXAppliesArray := ExApplies(ParcelExemptionTable.FieldByName('ExemptionCode').Text, TBooleanField(ParcelExemptionTable.FieldByName('ApplyToVillage')).AsBoolean); {CHG03132004-2(2.08): If this municipality does not have a village that takes a partial roll, use the town amount for the village.} If (rtdVillageReceivingPartialRoll in GlblRollTotalsToShow) then AppliesToVillage := ParcelExemptionTable.FieldByName('ApplyToVillage').AsBoolean else AppliesToVillage := ExAppliesArray[EXTown]; ExemptionCodes := TStringList.Create; ExemptionHomesteadCodes := TStringList.Create; ResidentialTypes := TStringList.Create; CountyExemptionAmounts := TStringList.Create; TownExemptionAmounts := TStringList.Create; SchoolExemptionAmounts := TStringList.Create; VillageExemptionAmounts := TStringList.Create; {Make sure that we have the right assessment, class, exemption code, and swis code records.} Found := FindKeyOld(AssessmentTable, ['TaxRollYr', 'SwisSBLKey'], [TaxRollYr, SwisSBLKey]); If not Found then SystemSupport(955, AssessmentTable, 'Error getting assessment record.', 'PASUTILS.PAS', GlblErrorDlgBox); ClassRecordFound := FindKeyOld(ClassTable, ['TaxRollYr', 'SwisSBLKey'], [TaxRollYr, SwisSBLKey]); Found := FindKeyOld(SwisCodeTable, ['SwisCode'], [ParcelTable.FieldByName('SwisCode').Text]); If not Found then SystemSupport(958, SwisCodeTable, 'Error getting swis code record.', 'PASUTILS.PAS', GlblErrorDlgBox); Found := FindKeyOld(ExemptionCodeTable, ['EXCode'], [ParcelExemptionTable.FieldByName('ExemptionCode').Text]); If not Found then SystemSupport(960, ExemptionCodeTable, 'Error getting Exemption Code record.', 'PASUTILS.PAS', GlblErrorDlgBox); {Figure out the land and total assessed values. We will use the amounts in the assessment records unless the parcel is split, there is a class record, and they have specified a homestead code for this exemption.} If ((ParcelTable.FieldByName('HomesteadCode').Text = 'S') and ClassRecordFound and (Deblank(ParcelExemptionTable.FieldByName('HomesteadCode').Text) <> '')) then begin with ClassTable do If (ParcelExemptionTable.FieldByName('HomesteadCode').Text = 'H') then begin {Use homestead class value} LandAssessedVal := TCurrencyField(FieldByName('HstdLandVal')).Value; TotalAssessedVal := TCurrencyField(FieldByName('HstdTotalVal')).Value; end else begin {Use nonhomestead class value} LandAssessedVal := TCurrencyField(FieldByName('NonhstdLandVal')).Value; TotalAssessedVal := TCurrencyField(FieldByName('NonhstdTotalVal')).Value; end; end else begin If bUseOverrideAssessedValue then begin LandAssessedVal := iLandValue; TotalAssessedVal := iAssessedValue; end else begin LandAssessedVal := TCurrencyField(AssessmentTable.FieldByName('LandAssessedVal')).Value; TotalAssessedVal := TCurrencyField(AssessmentTable.FieldByName('TotalAssessedVal')).Value; end; end; LandAssessedVal := Roundoff(LandAssessedVal, 0); TotalAssessedVal := Roundoff(TotalAssessedVal, 0); {If this is a swis that has different vet limits for county, town\city, and school, then we must choose which maximums to use. Otherwise, we will use the county limits, even though they are all the same.} {FXX06241998-1: The veterans maximums need to be at the county and swis level.} {FXX07192006-1(2.9.7.11): If the current year county vet maximums are different then the next year ones and a person changes an exemption on a parcel with a vet, then it uses the wrong county vet maximum set for the next year.} AssessmentYearControlTable := FindTableInDataModuleForProcessingType(DataModuleAssessmentYearControlTableName, ProcessingType); If EXAppliesArray[EXCounty] then with AssessmentYearControlTable do begin VetMax := FieldByName('VeteranCntyMax').AsInteger; CombatVetMax := FieldByName('CombatVetCntyMax').AsInteger; DisabledVetMax := FieldByName('DisabledVetCntyMax').AsInteger; end; {with AssessmentYearControlTable do} If ExAppliesArray[EXTown] then begin VetMax := TCurrencyField(SwisCodeTable.FieldByName('VeteranTownMax')).Value; CombatVetMax := TCurrencyField(SwisCodeTable.FieldByName('CombatVetTownMax')).Value; DisabledVetMax := TCurrencyField(SwisCodeTable.FieldByName('DisabledVetTownMax')).Value; end; {If ExAppliesArray[EXTown]} EqualizationRateFilledIn := True; {In some cases the calc method is blank (i.e. null), so let's force it to one blank space for the case statement below.} CalcCode := ExemptionCodeTable.FieldByName('CalcMethod').Text; If (Deblank(CalcCode) = '') then CalcCode := ' '; EXCode := ParcelExemptionTable.FieldByName('ExemptionCode').Text; ResidentialType := ExemptionCodeTable.FieldByName('ResidentialType').Text; EqualizationRate := SwisCodeTable.FieldByName('EqualizationRate').AsFloat; OwnerPercent := Roundoff(ParcelExemptionTable.FieldByName('OwnerPercent').AsFloat, 2); {If the owner percent is not filled in, assume it is 100%.} If (Roundoff(OwnerPercent, 2) = 0) then OwnerPercent := 100; If (Deblank(ParcelExemptionTable.FieldByName('ExemptionCode').Text) <> '') then case CalcCode[1] of {CHG12011997-2: STAR support.} EXCMethF : If ExemptionIsSTAR(EXCode) then begin {Since the star exemption is applied last, we will get all the exemptions. Note that the STAR amount is not included in the school amount, we will get all the exemptions (which is really all except STAR).} {FXX02091998-1: Pass the residential type of each exemption.} TotalExemptionsForParcel(ParcelExemptionTable.FieldByName('TaxRollYr').Text, ParcelExemptionTable.FieldByName('SwisSBLKey').Text, ParcelExemptionLookupTable, ExemptionCodeTable, ParcelTable.FieldByName('HomesteadCode').Text, 'A', ExemptionCodes, ExemptionHomesteadCodes, ResidentialTypes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts, BasicSTARAmount, EnhancedSTARAmount); {FXX06161998-1: The above messes up the position of the ex code table, must refresh.} FindKeyOld(ExemptionCodeTable, ['EXCode'], [EXCode]); {FXX05141998-1: Instead of calculating the STAR amount each time, let's just use the fixed amount in the amount field of the exemption code.} {FXX05281998-1: Need to use the calculate STAR routine to account for parcels where full STAR would make school TV 0.} ResidentialPercent := GetResidentialPercent(ParcelTable, ExemptionCodeTable, EXCode); {FXX05172010-1(2.24.2.4)[I7209]: Only take residential amounts in to account for calculating STAR.} GetResidentialExemptionAmounts(ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts, ResidentialTypes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts); STARAmount := CalculateSTARAmount(ExemptionCodeTable, ParcelExemptionTable, ParcelTable, TotalAssessedVal, ResidentialPercent, ParcelExemptionTable.FieldByName('OwnerPercent').AsFloat, Trunc(ResidentialExemptionAmounts[EXSchool]), FullSTARAmount); {If the property is a coop or mobile home, just take the amount that they entered and never recalc.} {FXX12041997-2: Need to get the amount from the parcel ex table, not the ex code tbl.} {CHG06062001-1: STAR can now be placed on mixed use 400 prop class.} {FXX07102001-1: If the 411 is a condo, we want to autocalc, not let them fill it in.} If (PropertyIsCoopOrMobileHomePark(ParcelTable) or ((not GlblTreatMixedUseParcelsAsResidential) and (ParcelTable.FieldByName('PropertyClassCode').Text[1] = '4') and (Take(1, ParcelTable.FieldByName('OwnershipCode').Text)[1] <> 'C'))) then begin STARAmount := Roundoff(ParcelExemptionTable.FieldByName('Amount').AsFloat, 0); ExemptionRecalculated := False; end; ThisExemptionAmountsArray[EXSchool] := STARAmount; end else begin {Fixed amount} EXAmount := TCurrencyField(ExemptionCodeTable.FieldByName('FixedAmount')).Value; EXAmount := Roundoff(EXAmount, 0); {Now fill in the amounts on a per municipality type basis (county, town, school, village).} For I := 1 to 4 do If EXAppliesArray[I] then ThisExemptionAmountsArray[I] := EXAmount; end; {Fixed amount} EXCMethL : begin {Land assessed value} {They can have a percent on a land, improvement or total exemption.} Percent := ParcelExemptionTable.FieldByName('Percent').AsFloat; {If the percent is zero, then they are just adding this exemption, so we should default it to 50%. Otherwise, we will just use the percent that they already entered.} If (Roundoff(Percent, 0) = 0) then Percent := 100; {FXX02091998-4: No residential percent for land, improvement or total.} EXAmount := LandAssessedVal * (Percent / 100); EXAmount := Roundoff(EXAmount, 0); {Now fill in the amounts on a per municipality type basis (county, town, school, village).} For I := 1 to 4 do If EXAppliesArray[I] then ThisExemptionAmountsArray[I] := EXAmount; end; {Land assessed value} EXCMethI : begin {Improvement value} {They can have a percent on a land, improvement or total exemption.} Percent := ParcelExemptionTable.FieldByName('Percent').AsFloat; {If the percent is zero, then they are just adding this exemption, so we should default it to 50%. Otherwise, we will just use the percent that they already entered.} If (Roundoff(Percent, 0) = 0) then Percent := 100; {FXX02091998-4: No residential percent for land, improvement or total.} EXAmount := (TotalAssessedVal - LandAssessedVal) * (Percent / 100); EXAmount := Roundoff(EXAmount, 0); {Now fill in the amounts on a per municipality type basis (county, town, school, village).} For I := 1 to 4 do If EXAppliesArray[I] then ThisExemptionAmountsArray[I] := EXAmount; end; {Improvement value} EXCMethT : begin {Total assessed value} {They can have a percent on a land, improvement or total exemption.} Percent := ParcelExemptionTable.FieldByName('Percent').AsFloat; {FXX02091998-4: No residential percent for land, improvement or total.} {If the percent is zero, then they are just adding this exemption, so we should default it to 50%. Otherwise, we will just use the percent that they already entered.} If (Roundoff(Percent, 0) = 0) then Percent := 100; EXAmount := TotalAssessedVal * (Percent / 100); EXAmount := Roundoff(EXAmount, 0); {Now fill in the amounts on a per municipality type basis (county, town, school, village).} For I := 1 to 4 do If EXAppliesArray[I] then ThisExemptionAmountsArray[I] := EXAmount; end; {Total assessed value} EXCMethV : begin {Variable amount} {The variable amount may only be stored in the county or school field if that is all it is applied to, so we have to find it.} {FXX04161999-1: Recalc BIE amounts.} {FXX04191999-6: Only calc BIE exemption amount if this is first time entered. Otherwise, 5% per year reduction is taken in year end rollover since must be off initial amount.} If ((Take(4, EXCode) = '4760') and (ParcelExemptionTable.FieldByName('Amount').AsFloat = 0)) then begin DecodeDate(ParcelExemptionTable.FieldByName('InitialDate').AsDateTime, InitialYear, InitialMonth, InitialDay); DecodeDate(Date, CurrentYear, CurrentMonth, CurrentDay); YearsDifference := CurrentYear - InitialYear; {5% per year decreasing exemption starting at 50%.} Percent := 50 - 5 * YearsDifference; {FXX04181999-4: Make sure percent does not go below zero if exemption on too long.} If (Roundoff(Percent, 0) < 0) then EXAmount := 0 else EXAmount := (TotalAssessedVal - LandAssessedVal) * (Percent / 100); end {If (Take(4, EXCode) = '4760')} else begin {FXX03231998-2: It will always be the amount in the ex amount field unless the amount field is zero.} If (TCurrencyField(ParcelExemptionTable.FieldByName('Amount')).Value = 0) then begin EXAmount := TCurrencyField(ParcelExemptionTable.FieldByName('TownAmount')).Value; ExAmount := MaxComp(ExAmount, TCurrencyField(ParcelExemptionTable.FieldByName('CountyAmount')).Value); ExAmount := MaxComp(ExAmount, TCurrencyField(ParcelExemptionTable.FieldByName('SchoolAmount')).Value); end else ExAmount := TCurrencyField(ParcelExemptionTable.FieldByName('Amount')).Value; end; {else of If (Take(4, EXCode) = '4760')} EXAmount := Roundoff(EXAmount, 0); {Now fill in the amounts on a per municipality type basis (county, town, school, village).} For I := 1 to 4 do If EXAppliesArray[I] then ThisExemptionAmountsArray[I] := EXAmount; end; {Variable amount} EXCMethP : begin {Fixed percentage} FixedPercent := ExemptionCodeTable.FieldByName('FixedPercentage').AsFloat; {First, let's figure out the total of all amount based exemptions. This will be subtracted from the total assessed value before applying the percentage exemptions. Note that the array will be recalculated for the aged exmeptions since they come after ALL other exemptions which are not non-residential.} {FXX02091998-1: Pass the residential type of each exemption.} ExemptionTotalsArray := TotalExemptionsForParcel(ParcelExemptionTable.FieldByName('TaxRollYr').Text, ParcelExemptionTable.FieldByName('SwisSBLKey').Text, ParcelExemptionLookupTable, ExemptionCodeTable, ParcelTable.FieldByName('HomesteadCode').Text, 'F', ExemptionCodes, ExemptionHomesteadCodes, ResidentialTypes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts, BasicSTARAmount, EnhancedSTARAmount); {FXX02091998-1: Calculate the amount of the exemptions that apply to residential, nonresidential or both if there is a residential percent.} GetResidentialExemptionAmounts(ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts, ResidentialTypes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts); ResidentialPercent := GetResidentialPercent(ParcelTable, ExemptionCodeTable, EXCode); GetHomesteadAndNonhstdExemptionAmounts(ExemptionCodes, ExemptionHomesteadCodes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts, HstdEXAmounts, NonhstdEXAmounts); {If this is a split parcel, we only want to subtract homestead or non-homestead exemptions depending on what this exemption applies to.} If (ParcelTable.FieldByName('HomesteadCode').Text = SplitParcel) then If (ParcelExemptionTable.FieldByName('HomesteadCode').Text = NonhomesteadParcel) then ExemptionTotalsArray := NonhstdEXAmounts else ExemptionTotalsArray := HstdEXAmounts; {Now fill in the amounts on a per municipality type basis (county, town, school, village). Note that if the exemption applies to this municipality type, we will figure out the exemption amount for THIS municipality basis only since the totals may be different.} {CHG07262004-2(2.07l5): Allow for override on the firefighter exemptions.} If (ExemptionIsVolunteerFirefighter(EXCode) and PropertyIsCoopOrMobileHomePark(ParcelTable)) then begin ExemptionRecalculated := False; For I := 1 to 4 do If EXAppliesArray[I] then begin ExAmount := Roundoff(ParcelExemptionTable.FieldByName('Amount').AsFloat, 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end else begin For I := 1 to 4 do If EXAppliesArray[I] then begin EXAmount := CalculateExemptionWithResidentialPercent( TotalAssessedVal, ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts, ResidentialPercent, FixedPercent, ResidentialType, I); {CHG02122000-1: Add volunteer firefighter exemption.} {CHG03252005-1(2.8.3.14)[2088]: Westchester no longer has the cap.} {FXX06072009-1(2.17.1.24): The volunteer firefighter (if non-capped) is 10% off the total assessed value.} If ExemptionIsVolunteerFirefighter(EXCode) then If ((not GlblEnableExemptionCapOption) or (GlblEnableExemptionCapOption and ExemptionCodeTable.FieldByName('ApplyCap').AsBoolean)) then begin {The maximum for this exemption is 3000 equalized.} EqualizedMaximum := Roundoff((3000 * (EqualizationRate / 100)), 0); If (Roundoff(EXAmount, 0) > Roundoff(EqualizedMaximum, 0)) then EXAmount := Roundoff(EqualizedMaximum, 0); end {If ExemptionIsVolunteerFirefighter(EXCode)} else EXAmount := (TotalAssessedVal - FullParcelExemptionAmounts[I] - ResidentialExemptionAmounts[I]) * (FixedPercent / 100); EXAmount := Roundoff(EXAmount, 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end; {If (ExemptionIsVolunteerFirefighter(EXCode) and ...} end; {Fixed percentage} ' ' : begin {Exception cases - percent based for the most part.} SpecialCase := False; EqualizationRate := SwisCodeTable.FieldByName('EqualizationRate').AsFloat; {FXX10161998-1: The equalization rate filled in flag was not being set for condos.} If (Roundoff(EqualizationRate, 2) > 0) then EqualizationRateFilledIn := True; {First, let's figure out the total of all amount based exemptions. This will be subtracted from the total assessed value before applying the percentage exemptions. Note that the array will be recalculated for the aged exmeptions since they come after ALL other exemptions which are not non-residential.} {FXX02091998-1: Pass the residential type of each exemption.} {CHG04161998-1: Add the 4193x limited income diabled exemption. It is the same as 4180x.} {CHG12291998-1: Malta has 4190x physically disabled limited income which is same as senior.} {CHG08132008-1(2.15.1.5): Add 4191x as a low income disabled exemption.} If ((Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) <> '4180') and (not ExemptionIsLowIncomeDisabled(ParcelExemptionTable.FieldByName('ExemptionCode').AsString))and (* (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) <> '4193') and *) (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) <> '4190')) then begin ExemptionTotalsArray := TotalExemptionsForParcel(ParcelExemptionTable.FieldByName('TaxRollYr').Text, ParcelExemptionTable.FieldByName('SwisSBLKey').Text, ParcelExemptionLookupTable, ExemptionCodeTable, ParcelTable.FieldByName('HomesteadCode').Text, 'F', ExemptionCodes, ExemptionHomesteadCodes, ResidentialTypes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts, BasicSTARAmount, EnhancedSTARAmount); {FXX02091998-1: Calculate the amount of the exemptions that apply to residential, nonresidential or both if there is a residential percent.} GetResidentialExemptionAmounts(ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts, ResidentialTypes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts); ResidentialPercent := GetResidentialPercent(ParcelTable, ExemptionCodeTable, EXCode); GetHomesteadAndNonhstdExemptionAmounts(ExemptionCodes, ExemptionHomesteadCodes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts, HstdEXAmounts, NonhstdEXAmounts); {If this is a split parcel, we only want to subtract homestead or non-homestead exemptions depending on what this exemption applies to.} If (ParcelTable.FieldByName('HomesteadCode').Text = SplitParcel) then If (ParcelExemptionTable.FieldByName('HomesteadCode').Text = NonhomesteadParcel) then ExemptionTotalsArray := NonhstdEXAmounts else ExemptionTotalsArray := HstdEXAmounts; end; {If (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) ...} {Eligible funds. The amount is whatever they have entered. Note that there is no residential percent.} If (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '4110') then begin EXAmount := TCurrencyField(ParcelExemptionTable.FieldByName('TownAmount')).Value * (OwnerPercent / 100); EXAmount := Roundoff(EXAmount, 0); For I := 1 to 4 do If EXAppliesArray[I] then ThisExemptionAmountsArray[I] := EXAmount; end; {If (Take(4, ParcelExemptionTable. ...} {Ratio exemption.} {FXX07061999-1: Don't touch ratio vet amounts.} If (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '4111') then begin (* Percent := ParcelExemptionTable.FieldByName('Percent').AsFloat; EXAmount := TCurrencyField(ParcelExemptionTable.FieldByName('TownAmount')).Value * (Percent / 100) * (OwnerPercent / 100);*) SpecialCase := True; EXAmount := TCurrencyField(ParcelExemptionTable.FieldByName('TownAmount')).Value; {FXX08301999-1: Sometimes the amount may be in the county field if this is a county exemption.} If (Roundoff(EXAmount, 0) = 0) then EXAmount := TCurrencyField(ParcelExemptionTable.FieldByName('CountyAmount')).Value; If (Roundoff(EXAmount, 0) = 0) then EXAmount := TCurrencyField(ParcelExemptionTable.FieldByName('Amount')).Value; EXAmount := Roundoff(EXAmount, 0); For I := 1 to 4 do If EXAppliesArray[I] then ThisExemptionAmountsArray[I] := EXAmount; end; {If (Take(4, ParcelExemptionTable. ...} {Veteran exemption.} If (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '4112') then begin SpecialCase := True; {FXX09151998-1: Just use the flat amount given in the exemption record for condos.} {FXX12291998-2: LB does not use override amounts for condos and we must calc amount.} {FXX03111999-2: Remove condo exemption override and was using ParcelIsCondo routine.} If PropertyIsCoopOrMobileHomePark(ParcelTable) then begin ExemptionRecalculated := False; For I := 1 to 4 do If EXAppliesArray[I] then begin ExAmount := Roundoff(ParcelExemptionTable.FieldByName('Amount').AsFloat, 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end else begin FixedPercent := SwisCodeTable.FieldByName('VeteranCalcPercent').AsFloat; If ((Roundoff(FixedPercent, 2) > 0) and (Roundoff(EqualizationRate, 2) > 0)) then begin EqualizationRateFilledIn := True; {Set exemption amount to total asssessed * percent for each municipality type.} For I := 1 to 4 do If EXAppliesArray[I] then begin {Apply the residential percent before comparing to the max.} EXAmount := CalculateExemptionWithResidentialPercent( TotalAssessedVal, ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts, ResidentialPercent, FixedPercent, ResidentialType, I); ExAmount := Roundoff(ExAmount, 0); {FXX04081998-2: Need to apply owner percent before comparing to equalized maximum.} EXAmount := EXAmount * (OwnerPercent / 100); {If we are above the equalized max, then set it to the max.} {FXX0302011(MDT)[I8689]: The vet exemptions were not calculating correctly for different county / town vet limits.} If _Compare(I, EXCounty, coEqual) then VetMax := AssessmentYearControlTable.FieldByName('VeteranCntyMax').AsInteger else VetMax := SwisCodeTable.FieldByName('VeteranTownMax').AsInteger; If (EXAmount > (VetMax * (EqualizationRate / 100))) then begin EXAmount := VetMax * (EqualizationRate / 100); VetMaxSet := True; end; {If (EXAmount > ...} EXAmount := Roundoff(EXAmount, 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end; {If (FixedPercent > 0)} end; {else of If ParcelIsCondo(ParcelTable)} end; {If (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '4113')} {Calculate the combat veteran exemption amount and %.} If (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '4113') then begin SpecialCase := True; {FXX09151998-1: Just use the flat amount given in the exemption record for condos.} {FXX12291998-2: LB does not use override amounts for condos and we must calc amount.} {FXX03111999-2: Remove condo exemption override and was using ParcelIsCondo routine.} If PropertyIsCoopOrMobileHomePark(ParcelTable) then begin ExemptionRecalculated := False; For I := 1 to 4 do If EXAppliesArray[I] then begin ExAmount := Roundoff(ParcelExemptionTable.FieldByName('Amount').AsFloat, 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end else begin FixedPercent := SwisCodeTable.FieldByName('CombatVetCalcPercent').AsFloat; If ((Roundoff(FixedPercent, 2) > 0) and (Roundoff(EqualizationRate, 2) > 0)) then begin EqualizationRateFilledIn := True; {Set exemption amount to total asssessed * percent for each municipality type.} For I := 1 to 4 do If EXAppliesArray[I] then begin {Apply the residential percent before comparing to the max.} EXAmount := CalculateExemptionWithResidentialPercent( TotalAssessedVal, ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts, ResidentialPercent, FixedPercent, ResidentialType, I); {FXX04081998-2: Need to apply owner percent before comparing to equalized maximum.} EXAmount := EXAmount * (OwnerPercent / 100); If _Compare(I, EXCounty, coEqual) then CombatVetMax := AssessmentYearControlTable.FieldByName('CombatVetCntyMax').AsInteger else CombatVetMax := SwisCodeTable.FieldByName('CombatVetTownMax').AsInteger; {If we are above the equalized max, then set it to the max.} If (EXAmount > (CombatVetMax * (EqualizationRate / 100))) then begin EXAmount := CombatVetMax * (EqualizationRate / 100); VetMaxSet := True; end; {If (EXAmount > ...} EXAmount := Roundoff(EXAmount, 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end; {If (FixedPercent > 0)} end; {else of If ParcelIsCondo(ParcelTable)} end; {If (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '4113')} {Calculate the disabled veteran exemption amount. The percent is entered by the user.} If (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '4114') then begin SpecialCase := True; {FXX09151998-1: Just use the flat amount given in the exemption record for condos.} {FXX12291998-2: LB does not use override amounts for condos and we must calc amount.} {FXX03111999-2: Remove condo exemption override and was using ParcelIsCondo routine.} If PropertyIsCoopOrMobileHomePark(ParcelTable) then begin ExemptionRecalculated := False; For I := 1 to 4 do If EXAppliesArray[I] then begin ExAmount := Roundoff(ParcelExemptionTable.FieldByName('Amount').AsFloat, 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end else begin {For disabled veterans exemption, the percent is entered by the user.} If (Roundoff(EqualizationRate, 2) > 0) then begin EqualizationRateFilledIn := True; {Set exemption amount to percent they enter * total assessed. Note that the percent that the user enters in the parcel exemption is the full disabled percent. The actual exemption is half of that percent. We will set the exemption amount for each municipality type.} For I := 1 to 4 do If EXAppliesArray[I] then begin {Apply the residential percent before comparing to the maximum.} Percent := ParcelExemptionTable.FieldByName('Percent').AsFloat; EXAmount := CalculateExemptionWithResidentialPercent( TotalAssessedVal, ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts, ResidentialPercent, Percent * 0.5, ResidentialType, I); {If we are above the equalized max, then set it to the max.} {FXX04081998-2: Need to apply owner percent before comparing to equalized maximum.} EXAmount := EXAmount * (OwnerPercent / 100); If _Compare(I, EXCounty, coEqual) then DisabledVetMax := AssessmentYearControlTable.FieldByName('DisabledVetCntyMax').AsInteger else DisabledVetMax := SwisCodeTable.FieldByName('DisabledVetTownMax').AsInteger; If (EXAmount > (DisabledVetMax * (EqualizationRate / 100))) then begin EXAmount := DisabledVetMax * (EqualizationRate / 100); VetMaxSet := True; end; {If (EXAmount > ...} EXAmount := Roundoff(EXAmount, 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end; {If (Roundoff(AltVetRate, 2) > 0)} end; {else of If ParcelIsCondo(ParcelTable)} end; {If (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = ...)} with ParcelExemptionTable do If ExemptionIsColdWarVeteran(FieldByName('ExemptionCode').AsString) then begin SpecialCase := True; If PropertyIsCoopOrMobileHomePark(ParcelTable) then begin ExemptionRecalculated := False; For I := 1 to 4 do If EXAppliesArray[I] then begin ExAmount := Roundoff(FieldByName('Amount').AsFloat, 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end else begin {For disabled veterans exemption, the percent is entered by the user.} {Set exemption amount to percent they enter * total assessed. Note that the percent that the user enters in the parcel exemption is the full disabled percent. The actual exemption is half of that percent. We will set the exemption amount for each municipality type.} For I := 1 to 4 do If EXAppliesArray[I] then begin If ExemptionIsDisabledColdWarVeteran(FieldByName('ExemptionCode').AsString) then iColdWarVeteranType := cwvDisabled else iColdWarVeteranType := cwvBasic; GetColdWarVetPercentandLimit(AssessmentYearControlTable, SwisCodeTable, iColdWarVeteranType, I, ParcelTable.FieldByName('SwisCode').AsString, Percent, iColdWarVetLimit); FixedPercent := Percent; If ExemptionIsDisabledColdWarVeteran(FieldByName('ExemptionCode').AsString) then Percent := FieldByName('Percent').AsFloat * 0.5; {FXX01132012[PAS-125]: No exemptions should be calculated before Cold War.} For J := 1 to 4 do begin ResidentialExemptionAmounts[J] := 0; FullParcelExemptionAmounts[J] := 0; NonResidentialExemptionAmounts[J] := 0; end; {Apply the residential percent before comparing to the maximum.} EXAmount := CalculateExemptionWithResidentialPercent( TotalAssessedVal, ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts, ResidentialPercent, Percent, ResidentialType, I); {If we are above the equalized max, then set it to the max.} {FXX04081998-2: Need to apply owner percent before comparing to equalized maximum.} EXAmount := EXAmount * (OwnerPercent / 100); If (EXAmount > (iColdWarVetLimit * (EqualizationRate / 100))) then begin EXAmount := iColdWarVetLimit * (EqualizationRate / 100); VetMaxSet := True; end; {If (EXAmount > ...} EXAmount := Roundoff(EXAmount, 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end; {else of If ParcelIsCondo(ParcelTable)} end; {If ExemptionIsColdWarVeteran(FieldByName('ExemptionCode').AsString)} {For aged exemptions, the percent must be between 10% and 50% in increments of 5%. The default is 50%.} {CHG04161998-1: Add the 4193x limited income diabled exemption. It is the same as 4180x.} {CHG12291998-1: Malta has 4190x physically disabled limited income which is same as senior.} {CHG08132008-1(2.15.1.5): Add 4191x as a low income disabled exemption.} If ((Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '4180') or ExemptionIsLowIncomeDisabled(ParcelExemptionTable.FieldByName('ExemptionCode').AsString) or (* (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '4193') or *) (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '4190')) then begin SpecialCase := True; {FXX09151998-1: Just use the flat amount given in the exemption record for condos.} {FXX12291998-2: LB does not use override amounts for condos and we must calc amount.} {FXX03111999-2: Remove condo exemption override and was using ParcelIsCondo routine.} If PropertyIsCoopOrMobileHomePark(ParcelTable) then begin ExemptionRecalculated := False; For I := 1 to 4 do If EXAppliesArray[I] then begin ExAmount := Roundoff(ParcelExemptionTable.FieldByName('Amount').AsFloat, 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end else begin Percent := ParcelExemptionTable.FieldByName('Percent').AsFloat; {If the percent is zero, then they are just adding this exemption, so we should default it to 50%. Otherwise, we will just use the percent that they already entered.} If (Roundoff(Percent, 0) = 0) then FixedPercent := 50 else FixedPercent := Roundoff(Percent, 0); {To figure out the aged amount, first apply all other non aged and non non-residential only exemptions. Then subtract the amount for this municpality type.} {FXX02091998-1: Pass the residential type of each exemption.} ExemptionTotalsArray := TotalExemptionsForParcel(TaxRollYr, SwisSBLKey, ParcelExemptionLookupTable, ExemptionCodeTable, ParcelTable.FieldByName('HomesteadCode').Text, 'N', ExemptionCodes, ExemptionHomesteadCodes, ResidentialTypes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts, BasicSTARAmount, EnhancedSTARAmount); {FXX02091998-1: Calculate the amount of the exemptions that apply to residential, nonresidential or both if there is a residential percent.} GetResidentialExemptionAmounts(ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts, ResidentialTypes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts); ResidentialPercent := GetResidentialPercent(ParcelTable, ExemptionCodeTable, EXCode); GetHomesteadAndNonhstdExemptionAmounts(ExemptionCodes, ExemptionHomesteadCodes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts, HstdEXAmounts, NonhstdEXAmounts); {If this is a split parcel, we only want to subtract homestead or non-homestead exemptions depending on what this exemption applies to.} If (ParcelTable.FieldByName('HomesteadCode').Text = SplitParcel) then If (ParcelExemptionTable.FieldByName('HomesteadCode').Text = NonhomesteadParcel) then ExemptionTotalsArray := NonhstdEXAmounts else ExemptionTotalsArray := HstdEXAmounts; {Now fill in the amounts on a per municipality type basis (county, town, school, village). Note that if the exemption applies to this municipality type, we will figure out the exemption amount for THIS municipality basis only since the totals may be different.} For I := 1 to 4 do If EXAppliesArray[I] then begin {FXX10151997-3: Apply the residential percent after subtracting the exemption amount - to make MP totals balance.} (* EXAmount := (TotalAssessedVal - ExemptionTotalsArray[I]) * ResidentialPercent * Roundoff((FixedPercent/100), 2); {MP} EXAmount := ((TotalAssessedVal * ResidentialPercent) - ExemptionTotalsArray[I]) * Roundoff((FixedPercent/100), 2); {Ramapo & LB} *) EXAmount := CalculateExemptionWithResidentialPercent( TotalAssessedVal, ResidentialExemptionAmounts, FullParcelExemptionAmounts, NonResidentialExemptionAmounts, ResidentialPercent, FixedPercent, ResidentialType, I); EXAmount := Roundoff((EXAmount * (OwnerPercent / 100)), 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end; {else of If ParcelIsCondo(ParcelTable)} end; {If (Take(4, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '4180')} {System exemptions. The amount is the difference between the total assessed value and any exemptions so far.} If (Take(1, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '5') then begin SpecialCase := True; For I := 1 to 4 do If EXAppliesArray[I] then begin EXAmount := TotalAssessedVal - ExemptionTotalsArray[I]; EXAmount := Roundoff(EXAmount, 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end; {If (Take(1, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = '5')} {If this is not a special case, calculate as a percent of the total value.} If not SpecialCase then begin {If the percent is zero, then they are just adding this exemption, so we should default it to 100%. Otherwise, we will just use the percent that they already entered.} Percent := ParcelExemptionTable.FieldByName('Percent').AsFloat; If (Roundoff(Percent, 0) = 0) then FixedPercent := 100 else FixedPercent := Roundoff(Percent, 0); For I := 1 to 4 do If EXAppliesArray[I] then begin EXAmount := (TotalAssessedVal - ExemptionTotalsArray[I]) * Roundoff((Percent / 100), 2); EXAmount := Roundoff(EXAmount, 0); ThisExemptionAmountsArray[I] := EXAmount; end; {If EXAppliesArray[I]} end; {If not SpecialCase} end; {blank} end; {case CalcCode[1] of} For I := 1 to 4 do Result[I] := Roundoff(ThisExemptionAmountsArray[I], 0); {Whole dollars only.} ExemptionCodes.Free; ExemptionHomesteadCodes.Free; ResidentialTypes.Free; CountyExemptionAmounts.Free; TownExemptionAmounts.Free; SchoolExemptionAmounts.Free; VillageExemptionAmounts.Free; end; {CalculateExemptionAmount} {===========================================================================} Procedure RecalculateExemptionsForParcel(ExemptionCodeTable, ParcelExemptionTable, AssessmentTable, ClassTable, SwisCodeTable, ParcelTable : TTable; TaxRollYear : String; SwisSBLKey : String; ExemptionsNotRecalculatedList : TStringList; iLandValue : LongInt; iAssessedValue : LongInt; bUseOverrideAssessedValue : Boolean); {Recalculate all the exemptions for this parcel.} type ExemptionSortRecord = record ExemptionCode : String; ExemptionType : Char; {(F)ixed, (P)ercentage, (X) = Aged and limited income disabled, (Z)=STAR} end; PExemptionSortRecord = ^ExemptionSortRecord; var EXAmountsArray, TotalEXAmountsArray : ExemptionTotalsArrayType; Found, SpecialCase, Done, Quit, FirstTimeThrough, VetMaxSet, EqualizationRateFilledIn : Boolean; FixedPercent : Comp; I, J, ExIdx : Integer; TempStr : String; ExemptionList, BookmarkList : TList; PExemptionSortRec : PExemptionSortRecord; TempBookmark : TBookmark; CalcCode : String; ParcelExemptionLookupTable : TTable; ExAppliesArray : ExemptionAppliesArrayType; ExemptionRecalculated : Boolean; begin {CHG01282004-1(2.08): Display exemptions not recalculated. Can be nil if don't care.} If (ExemptionsNotRecalculatedList <> nil) then ExemptionsNotRecalculatedList.Clear; ExemptionList := TList.Create; BookmarkList := TList.Create; For I := 1 to 4 do begin EXAmountsArray[I] := 0; TotalEXAmountsArray[I] := 0; end; ParcelExemptionTable.CancelRange; SetRangeOld(ParcelExemptionTable, ['TaxRollYr', 'SwisSBLKey', 'ExemptionCode'], [TaxRollYear, SwisSBLKey, ' '], [TaxRollYear, SwisSBLKey, 'ZZZZZ']); Done := False; Quit := False; FirstTimeThrough := True; ParcelExemptionTable.First; If not (Done or Quit) then repeat If FirstTimeThrough then FirstTimeThrough := False else ParcelExemptionTable.Next; {If the SBL changes or we are at the end of the range, we are done.} TempStr := ParcelExemptionTable.FieldByName('SwisSBLKey').Text; If ParcelExemptionTable.EOF then Done := True; {We have an exemption record, so get the totals.} {FXX04181999-1: Some exemptions got out with a blank code.} If ((not (Done or Quit)) and (Deblank(ParcelExemptionTable.FieldByName('ExemptionCode').Text) <> '')) then begin New(PExemptionSortRec); PExemptionSortRec^.ExemptionCode := ParcelExemptionTable.FieldByName('ExemptionCode').Text; {Look up the exemption code in the exemption code table so that we can figure out what kind it is.} Found := FindKeyOld(ExemptionCodeTable, ['EXCode'], [PExemptionSortRec^.ExemptionCode]); If not Found then begin Quit := True; SystemSupport(964, ExemptionCodeTable, 'Error getting exemption code record. ' + PExemptionSortRec^.ExemptionCode +' - ' + Swissblkey, 'PASUTILS.PAS', GlblErrorDlgBox); end; CalcCode := ExemptionCodeTable.FieldByName('CalcMethod').Text; If (Deblank(CalcCode) = '') then CalcCode := ' '; {CHG12011997-2: STAR support} case CalcCode[1] of EXCMethF : If ExemptionIsSTAR(PExemptionSortRec^.ExemptionCode) then PExemptionSortRec^.ExemptionType := 'Z' {Always last} else PExemptionSortRec^.ExemptionType := 'F'; {Fixed} EXCMethI, {Improve val} EXCMethL, {land val} EXCMethT, {total val} EXCMethV : {variable amount} PExemptionSortRec^.ExemptionType := 'F'; EXCMethP : {Fixed %} PExemptionSortRec^.ExemptionType := 'P'; ' ' : begin {Special case} SpecialCase := False; {Ratio vet is fixed.} If (Take(4, PExemptionSortRec^.ExemptionCode) = '4110') then begin PExemptionSortRec^.ExemptionType := 'F'; SpecialCase := True; end; {Vet, combat vet, and disabled vet are percentage.} If ((Take(4, PExemptionSortRec^.ExemptionCode) = '4112') or (Take(4, PExemptionSortRec^.ExemptionCode) = '4113') or (Take(4, PExemptionSortRec^.ExemptionCode) = '4114')) then begin PExemptionSortRec^.ExemptionType := 'P'; SpecialCase := True; end; {Aged and limited income disabled.} {CHG04161998-1: Add the 4193x limited income diabled exemption. It is the same as 4180x.} {CHG12291998-1: Malta has 4190x physically disabled limited income which is same as senior.} {CHG08132008-1(2.15.1.5): Add 4191x as a low income disabled exemption.} If ((Take(4, PExemptionSortRec^.ExemptionCode) = '4180') or ExemptionIsLowIncomeDisabled(PExemptionSortRec^.ExemptionCode) or (* (Take(4, PExemptionSortRec^.ExemptionCode) = '4193') or *) (Take(4, PExemptionSortRec^.ExemptionCode) = '4190')) then begin PExemptionSortRec^.ExemptionType := 'X'; SpecialCase := True; end; {Anything else is percentage.} If not SpecialCase then PExemptionSortRec^.ExemptionType := 'P'; end; {' ' : begin (Special case)} end; {case CalcCode of} {Add a bookmark on the list for this exemption code record. This is in case there are 2 exemptions of the same code. If we did a find key, we would always get the 1st one twice. Instead, we will look up the exemptions by bookmark whend we recalculate.} BookmarkList.Add(ParcelExemptionTable.GetBookmark); ExemptionList.Add(PExemptionSortRec); end; {If not (Done or Quit)} until (Done or Quit); {Now sort the exemption list.} For I := 0 to (ExemptionList.Count - 1) do For J := (I + 1) to (ExemptionList.Count - 1) do If (PExemptionSortRecord(ExemptionList[J])^.ExemptionType < PExemptionSortRecord(ExemptionList[I])^.ExemptionType) then begin {The Jth exemption should be calculated before the Ith exemption So, we will swap the exemptions and the bookmarks that point to the exemption records.} PExemptionSortRec := ExemptionList[I]; ExemptionList[I] := ExemptionList[J]; ExemptionList[J] := PExemptionSortRec; TempBookmark := BookmarkList[I]; BookmarkList[I] := BookmarkList[J]; BookmarkList[J] := TempBookmark; end; {If (PExemptionSortRec(ExemptionList[J])^.ExemptionType ...} {Now go through the exemptions and recalculate each one.} I := 0; ParcelExemptionLookupTable := nil; If (ExemptionList.Count > 0) then begin ParcelExemptionLookupTable := TTable.Create(nil); OpenTableForProcessingType(ParcelExemptionLookupTable, ExemptionsTableName, GetProcessingTypeForTaxRollYear(TaxRollYear), Quit); end; {If (ExemptionList.Count > 0)} while ((I <= (ExemptionList.Count - 1)) and (not Quit)) do begin ParcelExemptionTable.GotoBookmark(BookmarkList[I]); {Recalculate the exemption amounts and store them.} EXAmountsArray := CalculateExemptionAmount(ExemptionCodeTable, ParcelExemptionTable, ParcelExemptionLookupTable, AssessmentTable, ClassTable, SwisCodeTable, ParcelTable, TaxRollYear, SwisSBLKey, FixedPercent, VetMaxSet, EqualizationRateFilledIn, ExemptionRecalculated, iLandValue, iAssessedValue, bUseOverrideAssessedValue); {CHG01282004-1(2.08): Display exemptions not recalculated. Can be nil if don't care.} If ((not ExemptionRecalculated) and (ExemptionsNotRecalculatedList <> nil)) then ExemptionsNotRecalculatedList.Add(ParcelExemptionTable.FieldByName('ExemptionCode').Text); with ParcelExemptionTable do try Edit; {Let's make sure that the town amount field has not been set to read only.} FieldByName('TownAmount').ReadOnly := False; {CHG10161997-1: Fill in the amount field with an exemption amount. This is what will display on screen.} ExAppliesArray := ExApplies(FieldByName('ExemptionCode').Text, FieldByName('ApplyToVillage').AsBoolean); ExIdx := GetExemptionAmountToDisplay(EXAppliesArray); TCurrencyField(FieldByName('Amount')).Value := EXAmountsArray[ExIdx]; TCurrencyField(FieldByName('CountyAmount')).Value := EXAmountsArray[EXCounty]; TCurrencyField(FieldByName('TownAmount')).Value := EXAmountsArray[EXTown]; TCurrencyField(FieldByName('SchoolAmount')).Value := EXAmountsArray[EXSchool]; TCurrencyField(FieldByName('VillageAmount')).Value := EXAmountsArray[EXVillage]; TotalEXAmountsArray[EXCounty] := TotalEXAmountsArray[EXCounty] + EXAmountsArray[EXCounty]; TotalEXAmountsArray[EXTown] := TotalEXAmountsArray[EXTown] + EXAmountsArray[EXTown]; TotalEXAmountsArray[EXSchool] := TotalEXAmountsArray[EXSchool] + EXAmountsArray[EXSchool]; TotalEXAmountsArray[EXVillage] := TotalEXAmountsArray[EXVillage] + EXAmountsArray[EXVillage]; Post; except Quit := True; SystemSupport(965, ParcelExemptionTable, 'Error updating parcel exemption record.', 'PASUTILS.PAS', GlblErrorDlgBox); end; I := I + 1; end; {For I := 0 to (ExemptionList.Count - 1) do} If (ExemptionList.Count > 0) then begin ParcelExemptionLookupTable.Close; ParcelExemptionLookupTable.Free; end; FreeTList(ExemptionList, SizeOf(ExemptionSortRecord)); For I := BookMarkList.Count-1 downto 0 do ParcelExemptionTable.FreeBookMark(BookmarkList[I]); BookmarkList.Free; end; {RecalculateExemptionsForParcel} {===========================================================================} Function ExemptionExistsForParcel(ExemptionCode : String; TaxRollYear : String; SwisSBLKey : String; ComparisonLength : Integer; {Number of chars to compare on} ParcelExemptionTable : TTable) : Boolean; {Go through all the exemptions and see if this exemption code exists.} var Done, Quit, FirstTimeThrough : Boolean; TempStr : String; begin Result := False; ParcelExemptionTable.CancelRange; SetRangeOld(ParcelExemptionTable, ['TaxRollYr', 'SwisSBLKey', 'ExemptionCode'], [TaxRollYear, SwisSBLKey, ' '], [TaxRollYear, SwisSBLKey, 'ZZZZZ']); Done := False; Quit := False; FirstTimeThrough := True; ParcelExemptionTable.First; If not (Done or Quit) then repeat If FirstTimeThrough then FirstTimeThrough := False else ParcelExemptionTable.Next; {If the SBL changes or we are at the end of the range, we are done.} TempStr := ParcelExemptionTable.FieldByName('SwisSBLKey').Text; If ParcelExemptionTable.EOF then Done := True; {We have an exemption record, so get the totals.} If not (Done or Quit) then begin If (Take(ComparisonLength, ParcelExemptionTable.FieldByName('ExemptionCode').Text) = Take(ComparisonLength, ExemptionCode)) then Result := True; end; {If not (Done or Quit)} until (Done or Quit); end; {ExemptionExistsForParcel} {=================================================================================} Procedure GetExemptionCodesForParcel(TaxRollYr : String; SwisSBLKey : String; ExemptionTable : TTable; ExemptionList : TStringList); {Return a list of the exemption codes on a parcel.} var Done, FirstTimeThrough : Boolean; begin Done := False; FirstTimeThrough := True; SetRangeOld(ExemptionTable, ['TaxRollYr', 'SwisSBLKey', 'ExemptionCode'], [TaxRollYr, SwisSBLKey, ' '], [TaxRollYr, SwisSBLKey, 'ZZZZZ']); ExemptionTable.First; repeat If FirstTimeThrough then FirstTimeThrough := False else ExemptionTable.Next; If ExemptionTable.EOF then Done := True; If not Done then ExemptionList.Add(Take(5, ExemptionTable.FieldByName('ExemptionCode').Text)); until Done; end; {GetExemptionCodesForParcel} {=================================================================================================} Procedure DisplayExemptionsNotRecalculatedForm(MasterExemptionsNotRecalculatedList : TStringList); {CHG01282004-1(2.08): Display exemptions not recalculated. Can be nil if don't care.} begin If _Compare(MasterExemptionsNotRecalculatedList.Count, 0, coGreaterThan) then try ExemptionsNotRecalculatedForm := TExemptionsNotRecalculatedForm.Create(nil); ExemptionsNotRecalculatedForm.ExemptionsNotRecalculatedList := MasterExemptionsNotRecalculatedList; ExemptionsNotRecalculatedForm.InitializeForm; ExemptionsNotRecalculatedForm.ShowModal; finally ExemptionsNotRecalculatedForm.Free; end; end; {DisplayExemptionsNotRecalculatedForm} {=================================================================================================} Procedure RecalculateAllExemptions( Form : TForm; ProgressDialog : TProgressDialog; ProcessingType : Integer; AssessmentYear : String; DisplayExemptionsNotRecalculated : Boolean; var Quit : Boolean); var Done, FirstTimeThrough, ExemptionAmountsChanged : Boolean; I, RecCount : LongInt; SwisSBLKey : String; ParcelTable, ExemptionCodeTable, ParcelExemptionTable, AssessmentTable, ClassTable, SwisCodeTable, AuditEXChangeTable : TTable; AuditEXChangeList, NewAuditEXChangeList : TList; OrigExemptionCodes, OrigExemptionHomesteadCodes, OrigResidentialTypes, OrigCountyExemptionAmounts, OrigTownExemptionAmounts, OrigSchoolExemptionAmounts, OrigVillageExemptionAmounts, NewExemptionCodes, NewExemptionHomesteadCodes, NewResidentialTypes, NewCountyExemptionAmounts, NewTownExemptionAmounts, NewSchoolExemptionAmounts, NewVillageExemptionAmounts : TStringList; TotalOrigExemptionAmount, TotalNewExemptionAmount, TotalOrigCountyExemptionAmount, TotalOrigTownExemptionAmount, TotalOrigSchoolExemptionAmount, TotalOrigVillageExemptionAmount, TotalOrigBasicSTARAmount, TotalOrigEnhancedSTARAmount, TotalNewCountyExemptionAmount, TotalNewTownExemptionAmount, TotalNewSchoolExemptionAmount, TotalNewVillageExemptionAmount, TotalNewBasicSTARAmount, TotalNewEnhancedSTARAmount : Comp; OrigBasicSTARAmount, OrigEnhancedSTARAmount, NewBasicSTARAmount, NewEnhancedSTARAmount : Comp; ExemptionsNotRecalculatedList, MasterExemptionsNotRecalculatedList : TStringList; begin AuditEXChangeList := TList.Create; NewAuditEXChangeList := TList.Create; ExemptionsNotRecalculatedList := TStringList.Create; MasterExemptionsNotRecalculatedList := TStringList.Create; FirstTimeThrough := True; Done := False; OrigExemptionCodes := TStringList.Create; OrigExemptionHomesteadCodes := TStringList.Create; OrigResidentialTypes := TStringList.Create; OrigCountyExemptionAmounts := TStringList.Create; OrigTownExemptionAmounts := TStringList.Create; OrigSchoolExemptionAmounts := TStringList.Create; OrigVillageExemptionAmounts := TStringList.Create; NewExemptionCodes := TStringList.Create; NewExemptionHomesteadCodes := TStringList.Create; NewResidentialTypes := TStringList.Create; NewCountyExemptionAmounts := TStringList.Create; NewTownExemptionAmounts := TStringList.Create; NewSchoolExemptionAmounts := TStringList.Create; NewVillageExemptionAmounts := TStringList.Create; TotalOrigCountyExemptionAmount := 0; TotalOrigTownExemptionAmount := 0; TotalOrigSchoolExemptionAmount := 0; TotalOrigVillageExemptionAmount := 0; TotalNewCountyExemptionAmount := 0; TotalNewTownExemptionAmount := 0; TotalNewSchoolExemptionAmount := 0; TotalNewVillageExemptionAmount := 0; TotalOrigBasicSTARAmount := 0; TotalOrigEnhancedSTARAmount := 0; TotalNewBasicSTARAmount := 0; TotalNewEnhancedSTARAmount := 0; ExemptionCodeTable := TTable.Create(nil); ParcelExemptionTable := TTable.Create(nil); AssessmentTable := TTable.Create(nil); ClassTable := TTable.Create(nil); SwisCodeTable := TTable.Create(nil); ParcelTable := TTable.Create(nil); AuditEXChangeTable := TTable.Create(nil); OpenTableForProcessingType(ExemptionCodeTable, ExemptionCodesTableName, ProcessingType, Quit); OpenTableForProcessingType(ParcelExemptionTable, ExemptionsTableName, ProcessingType, Quit); OpenTableForProcessingType(AssessmentTable, AssessmentTableName, ProcessingType, Quit); OpenTableForProcessingType(ClassTable, ClassTableName, ProcessingType, Quit); OpenTableForProcessingType(SwisCodeTable, SwisCodeTableName, ProcessingType, Quit); OpenTableForProcessingType(ParcelTable, ParcelTableName, ProcessingType, Quit); OpenTableForProcessingType(AuditEXChangeTable, 'AuditEXChangeTbl', ProcessingType, Quit); ExemptionCodeTable.IndexName := 'BYEXCode'; ParcelExemptionTable.IndexName := 'BYYEAR_SWISSBLKEY_EXCODE'; AssessmentTable.IndexName := 'BYTAXROLLYR_SWISSBLKEY'; ClassTable.IndexName := 'BYTAXROLLYR_SWISSBLKEY'; SwisCodeTable.IndexName := 'BYSWISCODE'; ParcelTable.IndexName := 'BYTAXROLLYR_SWISSBLKEY'; {FXX03152004-1(2.08): Make sure to limit the swis code records for history exemption recalc.} If (ProcessingType = History) then begin SwisCodeTable.Filter := 'TaxRollYr = ' + GlblHistYear; SwisCodeTable.Filtered := True; end; ParcelTable.First; ProgressDialog.Reset; ProgressDialog.TotalNumRecords := GetRecordCount(ParcelTable); ProgressDialog.UserLabelCaption := 'Recalculating Exemptions.'; repeat If FirstTimeThrough then FirstTimeThrough := False else ParcelTable.Next; If ParcelTable.EOF then Done := True; Application.ProcessMessages; If not Done then begin SwisSBLKey := ExtractSSKey(ParcelTable); If (ProgressDialog <> nil) then ProgressDialog.Update(Form, ConvertSwisSBLToDashDot(SwisSBLKey)); TotalExemptionsForParcel(AssessmentYear, SwisSBLKey, ParcelExemptionTable, ExemptionCodeTable, ParcelTable.FieldByName('HomesteadCode').Text, 'A', OrigExemptionCodes, OrigExemptionHomesteadCodes, OrigResidentialTypes, OrigCountyExemptionAmounts, OrigTownExemptionAmounts, OrigSchoolExemptionAmounts, OrigVillageExemptionAmounts, OrigBasicSTARAmount, OrigEnhancedSTARAmount); {CHG06222003-2(2.07e): Audit exemptions that are recalculated.} ClearTList(AuditEXChangeList, SizeOf(AuditEXRecord)); GetAuditEXList(SwisSBLKey, AssessmentYear, ParcelExemptionTable, AuditEXChangeList); RecalculateExemptionsForParcel(ExemptionCodeTable, ParcelExemptionTable, AssessmentTable, ClassTable, SwisCodeTable, ParcelTable, AssessmentYear, SwisSBLKey, ExemptionsNotRecalculatedList, 0, 0, False); If (ExemptionsNotRecalculatedList.Count > 0) then For I := 0 to (ExemptionsNotRecalculatedList.Count - 1) do begin MasterExemptionsNotRecalculatedList.Add(SwisSBLKey); MasterExemptionsNotRecalculatedList.Add(ExemptionsNotRecalculatedList[I]); end; TotalExemptionsForParcel(AssessmentYear, SwisSBLKey, ParcelExemptionTable, ExemptionCodeTable, ParcelTable.FieldByName('HomesteadCode').Text, 'A', NewExemptionCodes, NewExemptionHomesteadCodes, NewResidentialTypes, NewCountyExemptionAmounts, NewTownExemptionAmounts, NewSchoolExemptionAmounts, NewVillageExemptionAmounts, NewBasicSTARAmount, NewEnhancedSTARAmount); {Now see if anything changed. Note that the # of exemptions and their positions in the list will be the same.} ExemptionAmountsChanged := False; For I := 0 to (OrigExemptionCodes.Count - 1) do If ((OrigCountyExemptionAmounts[I] <> NewCountyExemptionAmounts[I]) or (OrigTownExemptionAmounts[I] <> NewTownExemptionAmounts[I]) or (OrigSchoolExemptionAmounts[I] <> NewSchoolExemptionAmounts[I]) or (OrigVillageExemptionAmounts[I] <> NewVillageExemptionAmounts[I])) then ExemptionAmountsChanged := True; If ((OrigBasicSTARAmount <> NewBasicSTARAmount) or (OrigEnhancedSTARAmount <> NewEnhancedSTARAmount)) then ExemptionAmountsChanged := True; If ExemptionAmountsChanged then begin InsertAuditEXChanges(SwisSBLKey, AssessmentYear, AuditEXChangeList, AuditEXChangeTable, 'B'); ClearTList(NewAuditEXChangeList, SizeOf(AuditEXRecord)); GetAuditEXList(SwisSBLKey, AssessmentYear, ParcelExemptionTable, NewAuditEXChangeList); InsertAuditEXChanges(SwisSBLKey, AssessmentYear, NewAuditEXChangeList, AuditEXChangeTable, 'A'); end; {If ExemptionAmountsChanged} end; {If not Done} until Done; ExemptionCodeTable.Close; ParcelExemptionTable.Close; AssessmentTable.Close; ClassTable.Close; SwisCodeTable.Close; ParcelTable.Close; AuditEXChangeTable.Close; ExemptionCodeTable.Free; ParcelExemptionTable.Free; AssessmentTable.Free; ClassTable.Free; SwisCodeTable.Free; ParcelTable.Free; AuditEXChangeTable.Free; FreeTList(AuditEXChangeList, SizeOf(AuditEXRecord)); FreeTList(NewAuditEXChangeList, SizeOf(AuditEXRecord)); {CHG01282004-1(2.08): Display exemptions not recalculated. Can be nil if don't care.} If DisplayExemptionsNotRecalculated then DisplayExemptionsNotRecalculatedForm(MasterExemptionsNotRecalculatedList); ExemptionsNotRecalculatedList.Free; MasterExemptionsNotRecalculatedList.Free; end; {RecalculateAllExemptions} {==========================================================================} Function IsBIEExemptionCode(ExemptionCode : String) : Boolean; {FXX12081999-4: Need function to test for BIE in case not 47600.} {CHG07172004-2(2.08): Exemptions starting with 4761 are BIE, also.} begin Result := ((Take(4, ExemptionCode) = '4760') or (Take(4, ExemptionCode) = '4761')); end; {==========================================================================} Function ParcelHasSTAR(ExemptionTable : TTable; SwisSBLKey : String; AssessmentYear : String) : Boolean; begin Result := FindKeyOld(ExemptionTable, ['TaxRollYr', 'SwisSBLKey', 'ExemptionCode'], [AssessmentYear, SwisSBLKey, BasicSTARExemptionCode]); Result := Result or FindKeyOld(ExemptionTable, ['TaxRollYr', 'SwisSBLKey', 'ExemptionCode'], [AssessmentYear, SwisSBLKey, EnhancedSTARExemptionCode]); end; {ParcelHasSTAR} {==========================================================================} Procedure DetermineExemptionReadOnlyAndRequiredFields( ExemptionCodeLookupTable : TTable; ParcelTable : TTable; ExemptionCode : String; var AmountFieldRequired : Boolean; var AmountFieldReadOnly : Boolean; var PercentFieldRequired : Boolean; var PercentFieldReadOnly : Boolean; var OwnerPercentFieldRequired : Boolean; var OwnerPercentFieldReadOnly : Boolean; var TerminationDateRequired : Boolean); {FXX09292003-1(2.07j): Move this to a common procedure so that grievance entry can follow the same rules for exemption entry.} var ReadOnlyFieldsSet : Boolean; CalcCode : String; begin AmountFieldRequired := False; AmountFieldReadOnly := False; PercentFieldRequired := False; PercentFieldReadOnly := False; OwnerPercentFieldRequired := False; OwnerPercentFieldReadOnly := False; TerminationDateRequired := False; {In some cases the calc method is blank (i.e. null), so let's force it to one blank space for the case statement below.} FindKeyOld(ExemptionCodeLookupTable, ['EXCode'], [ExemptionCode]); CalcCode := ExemptionCodeLookupTable.FieldByName('CalcMethod').Text; If (Deblank(CalcCode) = '') then CalcCode := ' '; case CalcCode[1] of ExCMethF : begin {CHG12011997-2: STAR support. If this property is a co-op or mobile home park, allow them to edit the amount, since this is calculated by hand.} {CHG06062001-1: STAR can now be placed on mixed use 400 prop class.} If not ExemptionIsSTAR(ExemptionCode) then AmountFieldReadOnly := True; If (ExemptionIsSTAR(ExemptionCode) and (not PropertyIsCoopOrMobileHomePark(ParcelTable)) and (ParcelTable.FieldByName('PropertyClassCode').Text[1] <> '4')) then AmountFieldReadOnly := True; OwnerPercentFieldReadOnly := False; end; {ExCMethF} ExCMethP, ExCMethL, ExCMethI, ExCMethT : begin {Ramapo has some total exemptions (type T) where they put a percent on the exemption rather than in the res. percent, so we will leave percent as changable.} AmountFieldReadOnly := True; OwnerPercentFieldReadOnly := True; end; {ExCMethF, ...} ExCMethV : {Variable amount} begin AmountFieldRequired := True; PercentFieldReadOnly := True; {If this is a veteran, they can enter the owner percent. Otherwise, they can not.} If (Take(4, ExemptionCode) <> '4110') then OwnerPercentFieldReadOnly := True; {11012013: Allow percent entry for seniors that are being entered as variable flat amounts.} If _Compare(ExemptionCode, '4180', coStartsWith) then PercentFieldReadOnly := False; end; {ExCMethV} ' ': {Exception cases} begin {Exception cases such as business improvement, alt veteran, and aged are percent based.} ReadOnlyFieldsSet := False; {For ratio vets., they should enter % and the fixed amount. Note that the percent may not match the amount. That is, they may enter 10% for a parcel with AV 30,000 but only have an amount of $2,500 since the exemption amount can never exceed the original, but they want to bring that ratio percent with them in case they move again to a parcel with AV under $25,000.} If (Take(4, ExemptionCode) = '4111') then begin ReadOnlyFieldsSet := True; AmountFieldRequired := True; end; {If (Take(4, ExemptionCode) ...} {For war and combat veterans exemptions, the amount and % is read only.} {FXX10161998-2: Can have flat amount for co-op or mobile home.} If (((Take(4, ExemptionCode) = '4112') or (Take(4, ExemptionCode) = '4113')) and (not PropertyIsCoopOrMobileHomePark(ParcelTable))) then begin ReadOnlyFieldsSet := True; AmountFieldReadOnly := True; PercentFieldReadOnly := True; end; {If (Take(4, ExemptionCode) ...} {For disabled vets., they enter a % and the fixed amount is calculated.} If ((Take(4, ExemptionCode) = '4114') and (not PropertyIsCoopOrMobileHomePark(ParcelTable))) then begin ReadOnlyFieldsSet := True; AmountFieldReadOnly := True; PercentFieldRequired := True; end; {If (Take(4, ExemptionCode) ...} {For a exception exemption, make the owner percent and amount read only and make the percent required.} If ((not ReadOnlyFieldsSet) and (not PropertyIsCoopOrMobileHomePark(ParcelTable))) then begin AmountFieldReadOnly := True; PercentFieldRequired := True; {FXX04102012-1(MDT)[PAS-260]: Users should be able to enter an owner percent for special case exemptions.} (*OwnerPercentFieldReadOnly := True; *) end; {If not ReadOnlyFieldsSet} end; {Exception cases} end; {case CalcCode[1] of} {CHG07262004-2(2.07l5): Allow for override on the firefighter exemptions.} If (ExemptionIsVolunteerFirefighter(ExemptionCode) and PropertyIsCoopOrMobileHomePark(ParcelTable)) then AmountFieldReadOnly := False; {If this exemption requires an expiration date, then make sure they enter it.} If ExemptionCodeLookupTable.FieldByName('ExpirationDateReqd').AsBoolean then TerminationDateRequired := True; end; {DetermineExemptionReadOnlyAndRequiredFields} {==========================================================================} Procedure DetermineAssessedAndTaxableValues( AssessmentYear : String; SwisSBLKey : String; HomesteadCode : String; ExemptionTable : TTable; ExemptionCodeTable : TTable; AssessmentTable : TTable; var LandAssessedValue : LongInt; var TotalAssessedValue : LongInt; var CountyTaxableValue : LongInt; var MunicipalTaxableValue : LongInt; var SchoolTaxableValue : LongInt; var VillageTaxableValue : LongInt; var BasicSTARAmount : LongInt; var EnhancedSTARAmount : LongInt); var ExemptArray : ExemptionTotalsArrayType; ExemptionCodes, ExemptionHomesteadCodes, ResidentialTypes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts : TStringList; _BasicSTARAmount, _EnhancedSTARAmount : Comp; begin ExemptionCodes := TStringList.Create; ExemptionHomesteadCodes := TStringList.Create; ResidentialTypes := TStringList.Create; CountyExemptionAmounts := TStringList.Create; TownExemptionAmounts := TStringList.Create; SchoolExemptionAmounts := TStringList.Create; VillageExemptionAmounts := TStringList.Create; LandAssessedValue := 0; TotalAssessedValue := 0; CountyTaxableValue := 0; MunicipalTaxableValue := 0; SchoolTaxableValue := 0; VillageTaxableValue := 0; BasicSTARAmount := 0; EnhancedSTARAmount := 0; If FindKeyOld(AssessmentTable, ['TaxRollYr', 'SwisSBLKey'], [AssessmentYear, SwisSBLKey]) then begin with AssessmentTable do begin LandAssessedValue := FieldByName('LandAssessedVal').AsInteger; TotalAssessedValue := FieldByName('TotalAssessedVal').AsInteger; end; ExemptArray := TotalExemptionsForParcel(AssessmentYear, SwisSBLKey, ExemptionTable, ExemptionCodeTable, HomesteadCode, 'A', ExemptionCodes, ExemptionHomesteadCodes, ResidentialTypes, CountyExemptionAmounts, TownExemptionAmounts, SchoolExemptionAmounts, VillageExemptionAmounts, _BasicSTARAmount, _EnhancedSTARAmount); BasicSTARAmount := Trunc(_BasicSTARAmount); EnhancedSTARAmount := Trunc(_EnhancedSTARAmount); CountyTaxableValue := Trunc(CalculateTaxableVal(TotalAssessedValue, ExemptArray[EXCounty])); MunicipalTaxableValue := Trunc(CalculateTaxableVal(TotalAssessedValue, ExemptArray[EXTown])); SchoolTaxableValue := Trunc(CalculateTaxableVal(TotalAssessedValue, ExemptArray[EXSchool])); VillageTaxableValue := Trunc(CalculateTaxableVal(TotalAssessedValue, ExemptArray[EXVillage])); end; {If FindKeyOld(AssessmentTable ...} ExemptionCodes.Free; ExemptionHomesteadCodes.Free; ResidentialTypes.Free; CountyExemptionAmounts.Free; TownExemptionAmounts.Free; SchoolExemptionAmounts.Free; VillageExemptionAmounts.Free; end; {DetermineTaxableValues} {==========================================================================} Function ProjectExemptions(tbSourceExemptions : TTable; sTaxYear : String; sSwisSBLKey : String; iLandValue : LongInt; iAssessedValue : LongInt; iProcessingType : Integer) : ExemptionTotalsArrayType; var tbTempExemptions, tbExemptionCodes, tbAssessments, tbClass, tbSwisCodes, tbParcels : TTable; slExemptionsNotRecalculated, slOrigExemptionCodes, slOrigExemptionHomesteadCodes, slOrigResidentialTypes, slOrigCountyExemptionAmounts, slOrigTownExemptionAmounts, slOrigSchoolExemptionAmounts, slOrigVillageExemptionAmounts : TStringList; I : Integer; OrigBasicSTARAmount, OrigEnhancedSTARAmount : Comp; begin For I := 1 to 4 do Result[I] := 0; slOrigExemptionCodes := TStringList.Create; slOrigExemptionHomesteadCodes := TStringList.Create; slOrigResidentialTypes := TStringList.Create; slOrigCountyExemptionAmounts := TStringList.Create; slOrigTownExemptionAmounts := TStringList.Create; slOrigSchoolExemptionAmounts := TStringList.Create; slOrigVillageExemptionAmounts := TStringList.Create; slExemptionsNotRecalculated := TStringList.Create; tbTempExemptions := TTable.Create(nil); tbExemptionCodes := TTable.Create(nil); tbAssessments := TTable.Create(nil); tbClass := TTable.Create(nil); tbSwisCodes := TTable.Create(nil); tbParcels := TTable.Create(nil); _OpenTable(tbTempExemptions, 'SortTempExemptions', '', 'BYYEAR_SWISSBLKEY_EXCODE', NoProcessingType, []); _SetRange(tbTempExemptions, [sTaxYear, sSwisSBLKey, ''], [sTaxYear, sSwisSBlKey, '99999'], '', []); DeleteTableRange(tbTempExemptions); CopyTableRange(tbSourceExemptions, tbTempExemptions, 'SwisSBLKey', [], []); If _Compare(iProcessingType, NoProcessingType, coEqual) then iProcessingType := GetProcessingTypeForTaxRollYear(sTaxYear); _OpenTable(tbExemptionCodes, ExemptionCodesTableName, '', 'BYEXCODE', iProcessingType, []); _OpenTable(tbAssessments, AssessmentTableName, '', 'BYTAXROLLYR_SWISSBLKEY', iProcessingType, []); _OpenTable(tbClass, ClassTableName, '', 'BYTAXROLLYR_SWISSBLKEY', iProcessingType, []); _OpenTable(tbSwisCodes, SwisCodeTableName, '', 'BYSWISCODE', iProcessingType, []); _OpenTable(tbParcels, ParcelTableName, '', 'BYTAXROLLYR_SWISSBLKEY', iProcessingType, []); If _Locate(tbParcels, [sTaxYear, sSwisSBLKey], '', [loParseSwisSBLKey]) then begin RecalculateExemptionsForParcel(tbExemptionCodes, tbTempExemptions, tbAssessments, tbClass, tbSwisCodes, tbParcels, sTaxYear, sSwisSBLKey, slExemptionsNotRecalculated, iLandValue, iAssessedValue, True); Result := TotalExemptionsForParcel(sTaxYear, sSwisSBLKey, tbTempExemptions, tbExemptionCodes, tbParcels.FieldByName('HomesteadCode').Text, 'A', slOrigExemptionCodes, slOrigExemptionHomesteadCodes, slOrigResidentialTypes, slOrigCountyExemptionAmounts, slOrigTownExemptionAmounts, slOrigSchoolExemptionAmounts, slOrigVillageExemptionAmounts, OrigBasicSTARAmount, OrigEnhancedSTARAmount); end; {If _Locate(tbParcels ...} tbTempExemptions.Close; tbExemptionCodes.Close; tbAssessments.Close; tbClass.Close; tbSwisCodes.Close; tbParcels.Close; tbTempExemptions.Free; tbExemptionCodes.Free; tbAssessments.Free; tbClass.Free; tbSwisCodes.Free; tbParcels.Free; slExemptionsNotRecalculated.Free; slOrigExemptionCodes.Free; slOrigExemptionHomesteadCodes.Free; slOrigResidentialTypes.Free; slOrigCountyExemptionAmounts.Free; slOrigTownExemptionAmounts.Free; slOrigSchoolExemptionAmounts.Free; slOrigVillageExemptionAmounts.Free; end; {ProjectExemptions} {==========================================================================} {============= SPECIAL DISTRICT CALCULATION ==========================} {==========================================================================} Procedure InsertOneSDChangeTrace(SwisSBLKey : String; TaxRollYr : String; ParcelSDistTable, AuditSDChangeTable : TTable; RecordType : Char; OrigSDRec : AuditSDRecord); {CHG03161998-1: Track exemption, SD adds, av changes, parcel add/del.} begin with AuditSDChangeTable do begin Insert; FieldByName('SwisSBLKey').Text := SwisSBLKey; FieldByName('TaxRollYr').Text := TaxRollYr; FieldByName('SDistCode').Text := ParcelSDistTable.FieldByName('SDistCode').Text; FieldByName('Date').AsDateTime := Date; FieldByName('Time').AsDateTime := Now; FieldByName('User').Text := GlblUserName; FieldByName('RecordType').Text := RecordType; If (RecordType in ['A', 'C']) then begin FieldByName('NewPrimaryUnits').AsFloat := ParcelSDistTable.FieldByName('PrimaryUnits').AsFloat; FieldByName('NewSecondaryUnits').AsFloat := ParcelSDistTable.FieldByName('SecondaryUnits').AsFloat; FieldByName('NewCalcAmount').AsFloat := ParcelSDistTable.FieldByName('CalcAmount').AsFloat; FieldByName('NewSDPercentage').AsFloat := ParcelSDistTable.FieldByName('SDPercentage').AsFloat; FieldByName('NewCalcCode').Text := ParcelSDistTable.FieldByName('CalcCode').Text; end else begin FieldByName('OldPrimaryUnits').AsFloat := ParcelSDistTable.FieldByName('PrimaryUnits').AsFloat; FieldByName('OldSecondaryUnits').AsFloat := ParcelSDistTable.FieldByName('SecondaryUnits').AsFloat; FieldByName('OldCalcAmount').AsFloat := ParcelSDistTable.FieldByName('CalcAmount').AsFloat; FieldByName('OldSDPercentage').AsFloat := ParcelSDistTable.FieldByName('SDPercentage').AsFloat; FieldByName('OldCalcCode').Text := ParcelSDistTable.FieldByName('CalcCode').Text; end; {else of If ((RecordType in ['A', 'C'])} {In order to figure out what changed in the SD, we will look in the OrigSDAmounts list for this special district and then record those amounts.} If (RecordType = 'C') then with OrigSDRec do begin FieldByName('OldPrimaryUnits').AsFloat := PrimaryUnits; FieldByName('OldSecondaryUnits').AsFloat := SecondaryUnits; FieldByName('OldCalcAmount').AsFloat := CalcAmount; FieldByName('OldSDPercentage').AsFloat := SDPercentage; FieldByName('OldCalcCode').Text := CalcCode; end; {with OrigSDRec do} try Post; except SystemSupport(969, AuditSDChangeTable, 'Error adding SD deletion trace rec.', GlblUnitName, GlblErrorDlgBox); end; end; {with AuditSDChangeTable do} end; {InsertOneSDChangeTrace} {==========================================================================} Procedure InsertAuditSDChanges(SwisSBLKey : String; TaxRollYr : String; ParcelSDTable, AuditSDChangeTable : TTable; RecordType : Char); {CHG03301998-1: Trace SD, EX changes from everywhere.} {Insert an add or delete trace record for all sd's for this parcel.} var FirstTimeThrough, Done, Quit : Boolean; OrigSDRec : AuditSDRecord; begin FirstTimeThrough := True; Done := False; Quit := False; SetRangeOld(ParcelSDTable, ['TaxRollYr', 'SwisSBLKey', 'SDistCode'], [TaxRollYr, SwisSBLKey, ' '], [TaxRollYr, SwisSBLKey, 'ZZZZZ']); ParcelSDTable.First; repeat If FirstTimeThrough then FirstTimeThrough := False else try ParcelSDTable.Next; except Quit := True; SystemSupport(970, ParcelSDTable, 'Error getting parcel SD rec.', GlblUnitName, GlblErrorDlgBox); end; If ParcelSDTable.EOF then Done := True; If not (Done or Quit) then begin with OrigSDRec do begin PrimaryUnits := ParcelSDTable.FieldByName('PrimaryUnits').AsFloat; SecondaryUnits := ParcelSDTable.FieldByName('SecondaryUnits').AsFloat; CalcAmount := ParcelSDTable.FieldByName('CalcAmount').AsFloat; SDPercentage := ParcelSDTable.FieldByName('SDPercentage').AsFloat; CalcCode := Take(1, ParcelSDTable.FieldByName('CalcCode').Text)[1]; end; {with OrigSDRecord do} InsertOneSDChangeTrace(SwisSBLKey, TaxRollYr, ParcelSDTable, AuditSDChangeTable, RecordType, OrigSDRec); end; {If not (Done or Quit)} until (Done or Quit); end; {InsertAuditSDChanges} {==========================================================================} Function SdExtType(ExtCode : String) : Char; {input is ext code for spcl dist, output is ordinal constant as follows: 'A' = Advalorum, 'U' = Unitary, 'D' = dimension, 'S' = stepped unitary, 'F' = Fixed } Begin If (ExtCode = SDistEcIM) OR (ExtCode = SDistEcLD) OR (ExtCode = SDistEcTO) then SdExtType := SDExtCatA {Ad Valorum} else If (ExtCode = SDistEcUN) OR (ExtCode = SDistEcSU) then SdExtType := SDExtCatU {Unitary} else If (ExtCode = SDistEcAC) OR (ExtCode = SDistEcFR) OR (ExtCode = SDistEcSQ) then SdExtType := SDExtCatD {Dimension} else If (ExtCode = SDistEcMT) OR (ExtCode = SDistEcFE) then SdExtType := SDExtCatF {Fixed} Else If (ExtCode = SDistEcF1) OR (ExtCode = SDistEcF2) OR (ExtCode = SDistEcF3) OR (ExtCode = SDistEcF4) OR (ExtCode = SDistEcU1) OR (ExtCode = SDistEcU2) OR (ExtCode = SDistEcU3) OR (ExtCode = SDistEcU4) OR (ExtCode = SDistEcS1) OR (ExtCode = SDistEcS2) OR (ExtCode = SDistEcS3) OR (ExtCode = SDistEcS4) then SdExtType := SdExtCatS {Stepped Unitary} Else SDExtType := ' '; end; {SdExtType} {===========================================================================} Function ExemptionAppliesToSpecialDistrict(DistrictType : String; ExemptionCodeRec : ExemptionCodeRecord; CMFlag : String; SDAppliesToSection490, FireDistrict, VolunteerFirefighterOrAmbulanceExemptionApplies : Boolean) : Boolean; overload; {Apply rules for what exemptions apply to what spcl districts and return results as a boolean 2/12/97 version.} {CHG02221998-1 : For quicker roll total calcs, only read exemptions 1 time.} Var Applies : Boolean; Begin {FXX12101998-5: Need to default applies to false. In some cases, it was not getting set.} Applies := False; {Case 1} If ExemptionCodeRec.AppliesToSection490 then begin If ((DistrictType = SDAdValorumType) {'A'} OR (DistrictType = SDSpclAssessmentType) {'S'} ) then If SDAppliesToSection490 then begin If CMFlag = SDMaintenanceCostType then Applies := True; {Ex=490, SD = A/S, and (SD = 490 and Maint)} end else Applies := True; {Ex=490, SD = A/S, and NOT 490} end {Case 2: Ex applies to Advalorum} else If ExemptionCodeRec.AppliesToAdValorumDistrict then begin {Case 2a: Ex applies to ADvalorum, but not Spcl Assessment distr.} If (NOT ExemptionCodeRec.AppliesToSpecialAssessmentDistrict) then If (DistrictType = SDAdValorumType) {'A'} then Applies := True {ex = AD but not spcl ass dist, and SD is advalorum} else Applies := False {Case 2b: Ex Ex applies to ADvalorum, AND Spcl Assessment distr.} else Applies := True; {EX = Adv and SpclAs so always applies} end {case 3} {EX Does NOT apply to Advalorum districts} {but if it DOES apply to spcl ass dist, apply it: Case 3} else If ExemptionCodeRec.AppliesToSpecialAssessmentDistrict then begin IF ((DistrictType = SDSpclAssessmentType) {'S'} OR (DistrictType = SDVillageSpclAssessmentType) {'V'} ) then Applies := True; {EX NOT 490 or Adv, but IS spclAss, and SD is spcl Assessment ,(C3)} end {Case 4: ex is NOT 490, NOT AD, & NOT Spcl Ass dist} else Applies := False; {CHG04161998-3: Add FireDistrict and AppliesToSchool flag.} {Business incentive exemptions (4761x) never apply to fire districts as per RPS memo.} If ((Take(4, ExemptionCodeRec.ExemptionCode) = '4761') and FireDistrict) then Applies := False; {CHG10252004-1(2.8.0.15): Allow for application of 4168x to selected SDs.} If (ExemptionCodeRec.IsVolunteerFirefighterOrAmbulanceExemption and VolunteerFirefighterOrAmbulanceExemptionApplies) then Applies := True; ExemptionAppliesToSpecialDistrict := Applies; end; {ExAppliesToSpecialDistrict} {===========================================================================} Function GetExemptionType(ExemptionCode : String) : TExemptionTypes; begin Result := extOther; If ExemptionIsSTAR(ExemptionCode) then Result := extBasicSTAR; If ExemptionIsEnhancedSTAR(ExemptionCode) then Result := extEnhancedSTAR; If ExemptionIsSenior(ExemptionCode) then Result := extSenior; If IsBIEExemptionCode(ExemptionCode) then Result := extBIE; If ExemptionIsVolunteerFirefighter(ExemptionCode) then Result := extVolunteerFirefighterOrAmbulance; end; {GetExemptionType} {===========================================================================} Procedure FillInExemptionCodeRec( ExemptionCodeTable : TTable; var ExemptionCodeRec : ExemptionCodeRecord); begin with ExemptionCodeRec, ExemptionCodeTable do begin ExemptionCode := FieldByName('EXCode').Text; ExemptionType := GetExemptionType(ExemptionCode); CalculationMethod := FieldByName('CalcMethod').Text; ResidentialType := FieldByName('ResidentialType').Text; AppliesToSection490 := FieldByName('Section490').AsBoolean; AppliesToAdValorumDistrict := FieldByName('AdValorum').AsBoolean; AppliesToSpecialAssessmentDistrict := FieldByName('ApplySpclAssessmentD').AsBoolean; IsVolunteerFirefighterOrAmbulanceExemption := FieldByName('VolFireAmbExemption').AsBoolean; end; {with ExemptionCodeRec, ExemptionCodeTable do} end; {FillInExemptionCodeRec} {===========================================================================} Procedure FillInSpecialDistrictCodeRec( SpecialDistrictCodeTable : TTable; var SpecialDistrictCodeRec : SpecialDistrictCodeRecord); var I : Integer; TempFieldName : String; begin with SpecialDistrictCodeRec, SpecialDistrictCodeTable do begin SpecialDistrictCode := FieldByName('SDistCode').Text; Description := FieldByName('Description').Text; HomesteadCode := FieldByName('SDHomestead').Text; DistrictType := FieldByName('DistrictType').Text; Section490 := FieldByName('Section490').AsBoolean; Chapter562 := FieldByName('Chapter562').AsBoolean; RollSection9 := FieldByName('SDRS9').AsBoolean; FireDistrict := FieldByName('FireDistrict').AsBoolean; Prorata_Omitted_District := FieldByName('ProrataOmit').AsBoolean; try DefaultUnits := FieldByName('DefaultUnits').AsFloat; except DefaultUnits := 0; end; try DefaultSecondaryUnits := FieldByName('Default2ndUnits').AsFloat; except DefaultSecondaryUnits := 0; end; VolunteerFirefighterOrAmbulanceExemptionApplies := FieldByName('VolFireAmbApplies').AsBoolean; LateralDistrict := FieldByName('LateralDistrict').AsBoolean; OperatingDistrict := FieldByName('OperatingDistrict').AsBoolean; TreatmentDistrict := FieldByName('TreatmentDistrict').AsBoolean; try Step1 := FieldByName('Step1').AsFloat; except Step1 := 0; end; try Step2 := FieldByName('Step2').AsFloat; except Step2 := 0; end; try Step3 := FieldByName('Step3').AsFloat; except end; For I := 1 to MaximumSpecialDistrictExtensions do begin TempFieldName := 'ECd' + IntToStr(I); ExtensionCodes[I] := FieldByName(TempFieldName).Text; TempFieldName := 'ECFlg' + IntToStr(I); CapitalCostOrMaintenanceCodes[I] := FieldByName(TempFieldName).Text; end; {For I := 1 to MaximumSpecialDistrictExtensions do} end; {with SpecialDistrictCodeRec, SpecialDistrictCodeTable do} end; {FillInSpecialDistrictCodeRec} {===========================================================================} Function ExemptionAppliesToSpecialDistrict(ExemptionCodeRec : ExemptionCodeRecord; SpecialDistrictCodeRec : SpecialDistrictCodeRecord) : Boolean; overload; begin Result := False; If (ExemptionCodeRec.AppliesToSection490 and _Compare(SpecialDistrictCodeRec.DistrictType, [SDAdValorumType, SDSpclAssessmentType], coEqual) and SpecialDistrictCodeRec.Section490 and _Compare(SpecialDistrictCodeRec.CapitalCostOrMaintenanceCodes[1], SDMaintenanceCostType, coEqual)) then Result := True; If (ExemptionCodeRec.AppliesToSection490 and _Compare(SpecialDistrictCodeRec.DistrictType, [SDAdValorumType, SDSpclAssessmentType], coEqual) and (not SpecialDistrictCodeRec.Section490)) then Result := True; If ((not ExemptionCodeRec.AppliesToSection490) and ExemptionCodeRec.AppliesToAdValorumDistrict and (not ExemptionCodeRec.AppliesToSpecialAssessmentDistrict) and _Compare(SpecialDistrictCodeRec.DistrictType, SDAdValorumType, coEqual)) then Result := True; If ((not ExemptionCodeRec.AppliesToSection490) and ExemptionCodeRec.AppliesToAdValorumDistrict and ExemptionCodeRec.AppliesToSpecialAssessmentDistrict) then Result := True; If ((not ExemptionCodeRec.AppliesToSection490) and (not ExemptionCodeRec.AppliesToAdValorumDistrict) and ExemptionCodeRec.AppliesToSpecialAssessmentDistrict and _Compare(SpecialDistrictCodeRec.DistrictType, SDSpclAssessmentType, coEqual)) then Result := True; {Business incentive exemptions (4761x) never apply to fire districts as per RPS memo.} If (IsBIEExemptionCode(ExemptionCodeRec.ExemptionCode) and SpecialDistrictCodeRec.FireDistrict) then Result := False; {CHG10252004-1(2.8.0.15): Allow for application of 4168x to selected SDs.} If (ExemptionCodeRec.IsVolunteerFirefighterOrAmbulanceExemption and SpecialDistrictCodeRec.VolunteerFirefighterOrAmbulanceExemptionApplies) then Result := True; end; {ExemptionAppliesToSpecialDistrict} {===========================================================================} Function ExemptionAppliesToSpecialDistrict(SpecialDistrictCodeTable : TTable; ExemptionCodeTable : TTable; SpecialDistrictCode : String; ExemptionCode : String) : Boolean; overload; var ExemptionCodeRec : ExemptionCodeRecord; SpecialDistrictCodeRec : SpecialDistrictCodeRecord; begin _Locate(SpecialDistrictCodeTable, [SpecialDistrictCode], '', []); _Locate(ExemptionCodeTable, [ExemptionCode], '', []); FillInExemptionCodeRec(ExemptionCodeTable, ExemptionCodeRec); FillInSpecialDistrictCodeRec(SpecialDistrictCodeTable, SpecialDistrictCodeRec); Result := ExemptionAppliesToSpecialDistrict(ExemptionCodeRec, SpecialDistrictCodeRec); end; {ExemptionAppliesToSpecialDistrict} {===========================================================================} Function RTTotalSDApplicableExemptionsForParcel(ParcelExemptionList, ExemptionCodeList : TList; DistrictType : String; SDAppliesToSection490, FireDistrict, VolunteerFirefighterOrAmbulanceExemptionApplies : Boolean; CMFlag : String; _HomesteadCode : String; SplitDistrict, ParcelIsSplit : Boolean) : ExemptionTotalsArrayType; {Go through all the exemptions and add the exemption amount. Note that we will check each exemption to see which munic. type it applies to and also be sure it applies to the sd type passed in} {CHG02221998-1 : For quicker roll total calcs, only read exemptions 1 time.} var ExemptArray : ExemptionTotalsArrayType; I, J : Integer; Applies : Boolean; begin For I := 1 to 4 do ExemptArray[I] := 0; {CHG04161998-3: Add FireDistrict and AppliesToSchool flag.} {CHG09122004-1(2.8.0.11): Add homestead split to SD Calcs} For J := 0 to (ParcelExemptionList.Count - 1) do If ExemptionAppliesToSpecialDistrict(DistrictType, PExemptionCodeRecord(ExemptionCodeList[J])^, CMFlag, SDAppliesToSection490, FireDistrict, VolunteerFirefighterOrAmbulanceExemptionApplies) then begin {ExemptAppliesArray index indicates munic type, which then} {governs exemption amount field to be referenced; } {1 = County, 2 = Town, 3 = Village, 4 = School, see also } {ExemptionAppliesArrayType in Pastypes} For I := 1 to 4 do with PParcelExemptionRecord(ParcelExemptionList[J])^ do begin Applies := True; If (SplitDistrict and ParcelIsSplit and (HomesteadCode <> _HomesteadCode)) then Applies := False; If Applies then case I of RTCounty: ExemptArray[I] := ExemptArray[I] + CountyAmount; RTTown: ExemptArray[I] := ExemptArray[I] + TownAmount; RTSchool: ExemptArray[I] := ExemptArray[I] + SchoolAmount; RTVillage: ExemptArray[I] := ExemptArray[I] + VillageAmount; end; {case I of} end; {with PParcelExemptionRecord(ParcelExemptionList[J])^ do} end; {If ExAppliesToSpecialDistrict ...} Result := ExemptArray; end; {RTTotalSDApplicableExemptionsForParcel} {=========================================================================} Procedure CalculateSpecialDistrictAmounts(ParcelTable, AssessmentTable, ClassTable, ParcelSDTable, SDCodeTable : TTable; ParcelExemptionList, ExemptionCodeList : TList; SDExtensionCodes, {Return lists} SDCC_OMFlags, slAssessedValues, SDValues, HomesteadCodesList : TStringList); {Based on the special district code, calculate the "values" of this special district. This can mean many different things based on the type of district it is. The values returned will always be in correspondence to the type of the district itself. That is, if this is unitary, units will be returned. If this is acreage based, acres will be returned, etc. Note that since a special district may have many extension codes, what is return is a TStringList where each entry is of type extended in string format and corresponds in order to the extension codes. That is, the first entry in the TStringList is the value of the first extension code in the SDExtensionCodes list, etc. Also, for roll totals purposes, we will return the corresponding CC_OM Flags in the list SDCC_OMFlags.} var SDExtensionType : Char; ExtensionIndex : Integer; OrigIndex, CC_OMFlag, TempFieldName : String; SDExtension : String; CalcAmount, Value : Extended; ExemptionTotArray : ExemptionTotalsArrayType; TempSDCd : String; TempPct : Double; DistrictType : String; SDAppliesToSection490, FireDistrict, SplitDistrict, ParcelIsSplit, VolunteerFirefighterOrAmbulanceExemptionApplies : Boolean; HomesteadCode : String; AssessedValue : Extended; HstdLandVal, NonhstdLandVal, HstdAssessedVal, NonhstdAssessedVal : Comp; BaseValue : Double; HstdAcres, NonhstdAcres : Real; AssessmentRecordFound, ClassRecordFound, SDFormated : Boolean; begin SDExtensionType := ' '; Value := 0; {CHG09122004-1(2.8.0.11): Add homestead split to SD Calcs} {First look up this special district code in the code table in order to look at its extensions.} OrigIndex := SDCodeTable.IndexName; If (SDCodeTable.IndexName <> 'BYSDISTCODE') then SDCodeTable.IndexName := 'BYSDISTCODE'; FindKeyOld(SDCodeTable, ['SDistCode'], [ParcelSDTable.FieldByName('SDistCode').Text]); {Clear the return lists so that there are no previous results left over.} SDValues.Clear; SDExtensionCodes.Clear; SDCC_OMFlags.Clear; HomesteadCodesList.Clear; {FXX02221998-2: Only get the district type 1 time for this SD code.} DistrictType := SDCodeTable.FieldByName('DistrictType').Text; SDAppliesToSection490 := SDCodeTable.FieldByName('Section490').AsBoolean; {CHG04161998-3: Add FireDistrict and AppliesToSchool flag.} FireDistrict := SDCodeTable.FieldByName('FireDistrict').AsBoolean; SplitDistrict := SDCodeTable.FieldByName('SDHomestead').AsBoolean; {CHG10252004-1(2.8.0.15): Allow for application of 4168x to selected SDs.} VolunteerFirefighterOrAmbulanceExemptionApplies := SDCodeTable.FieldByName('VolFireAmbApplies').AsBoolean; ParcelIsSplit := False; CalculateHstdAndNonhstdAmounts(ParcelTable.FieldByName('TaxRollYr').Text, ExtractSSKey(ParcelTable), AssessmentTable, ClassTable, ParcelTable, HstdAssessedVal, NonhstdAssessedVal, HstdLandVal, NonhstdLandVal, HstdAcres, NonhstdAcres, AssessmentRecordFound, ClassRecordFound); AssessedValue := HstdAssessedVal + NonhstdAssessedVal; If SplitDistrict then begin HomesteadCode := ParcelTable.FieldByName('HomesteadCode').Text; If (HomesteadCode = SplitParcel) then begin HomesteadCode := 'H'; AssessedValue := HstdAssessedVal; ParcelIsSplit := True; end; end else HomesteadCode := ''; ExtensionIndex := 1; while (ExtensionIndex <= 10) do begin TempFieldName := 'ECd' + IntToStr(ExtensionIndex); SDExtension := Take(2, SDCodeTable.FieldByName(TempFieldName).Text); TempFieldName := 'ECFlg' + IntToStr(ExtensionIndex); CC_OMFlag := SDCodeTable.FieldByName(TempFieldName).Text; If (Deblank(SDExtension) <> '') then begin {determine Sd extension type that will govern processing} SDExtensionType := SDExtType(SDExtension); case SDExtensionType of {AdValorum} SDExtCatA : begin ExemptionTotArray := RTTotalSDApplicableExemptionsForParcel(ParcelExemptionList, ExemptionCodeList, DistrictType, SDAppliesToSection490, FireDistrict, VolunteerFirefighterOrAmbulanceExemptionApplies, CC_OMFlag, HomesteadCode, SplitDistrict, ParcelIsSplit); {If the special district record has a value amount, it overrides the assessed value of the parcel.} {FXX07251997-1, if parcel sd calc code = 'E', it overrides} {base valuation of parcel} {S = assessed val override, E = taxable val override} CalcAmount := 0; If ((ParcelSDTable.FieldByName('CalcCode').Text = PrclSDCcE) or {'E'} (ParcelSDTable.FieldByName('CalcCode').Text = PrclSDCcS)) {'S'} then CalcAmount := TCurrencyField(ParcelSDTable.FieldByName('CalcAmount')).Value; {If they specify an overriding ad valorum amount, BUT ONLY IF they put in a calc. code of 'S', then we need to subtract any applicable exemptions from the amount that they have entered. Otherwise, we just take the amount that they have entered.} {process advalorum overried} If (ParcelSDTable.FieldByName('CalcCode').Text = 'S') then begin Value := CalcAmount - ExemptionTotArray[GetMunicipalityType(GlblMunicipalityType)]; {FXX07142004-1(2.08): Make sure the value does not go below 0.} If (Value < 0) then Value := 0; end else begin {if no percentage specified for Adval. SD then calc val} If (RoundOff(ParcelSDTable.FieldByName('SDPercentage').AsFloat,2) <= 0) then begin {FXX07251997-1, if parcel sd calc code = 'E', it overrides} {base valuation of parcel. process taxable val override} {FXX01282002-1: Need to add the calculation for a land based ad valorum.} If (ParcelSDTable.FieldByName('CalcCode').Text = PrclSDCcE) {'E'} then Value := CalcAmount else If (SDExtension = SDistEcLD) then begin Value := AssessmentTable.FieldByName('LandAssessedVal').AsFloat - ExemptionTotArray[GetMunicipalityType(GlblMunicipalityType)]; If (Roundoff(Value, 0) < 0) then Value := 0; end else Value := AssessedValue - ExemptionTotArray[GetMunicipalityType(GlblMunicipalityType)]; end else begin {percentage is applied to both Assesed val and exempt amts} {for parcels where percentage is applied RPS pg 3.2A-31} TempPct := (RoundOff(ParcelSDTable.FieldByName('SDPercentage').AsFloat,2)/100); {round off to 4 places for this percentage} TempPct := RoundOff(TempPct,4); {FXX10112012(MDT): The percentage calculation always used the total AV, even if this was a land AV dist.} If (SDExtension = SDistEcLD) then BaseValue := AssessmentTable.FieldByName('LandAssessedVal').AsFloat else BaseValue := AssessmentTable.FieldByName('TotalAssessedVal').AsFloat; Value := RoundOff((BaseValue*TempPct), 0) - RoundOff((ExemptionTotArray[GetMunicipalityType(GlblMunicipalityType)]*TempPct), 0); end; {else of If (RoundOff(ParcelSDTable.FieldByName('SDPercentage').AsFloat,2) <= 0)} end; {else of If (ParcelSDTable.FieldByName('CalcCode').Text = 'S')} end; {SDExtCatA} {Unitary category} SDExtCatU : If SDExtension = SDistECUn {primary units} then Value := TCurrencyField(ParcelSDTable.FieldByName('PrimaryUnits')).Value else If SDExtension = SDistECSU {secondary units} then begin {debug} TempSDCd := ParcelSDTable.FieldByName('SDistCode').Text; Value := TCurrencyField(ParcelSDTable.FieldByName('SecondaryUnits')).Value; end; {Fixed} SDExtCatF : Value := TCurrencyField(ParcelSDTable.FieldByName('CalcAmount')).Value; {Dimension} SDExtCatD : begin If (SDExtension = SDistECAC) then Value := TFloatField(ParcelTable.FieldByName('Acreage')).Value; If (SDExtension = SDistECFR) then Value := TFloatField(ParcelTable.FieldByName('Frontage')).Value; If (SDExtension = SDistECSQ) then Value := TFloatField(ParcelTable.FieldByName('Frontage')).Value * TFloatField(ParcelTable.FieldByName('Depth')).Value; end; {Dimension} end; {case SDExtensionType of} {Now add this value to the list.} {FXX11172004-1(2.8.0.21): Format the SD value when it is put in the SD list.} {FXX12202004-1(2.8.1.5): Make sure that move taxes do not get rounded.} SDFormated := False; If ((SDExtension = SDistECAC) or (SDExtension = SDistECFR) or (SDExtension = SDistECSQ) or (SDExtension = SDistECUN) or (SDExtension = SDistECSU)) then begin SDValues.Add(FormatFloat(_3DecimalEditDisplay, Value)); slAssessedValues.Add('0'); SDFormated := True; end; If ((SDExtension = SDistEcIM) or (SDExtension = SDistEcLD) or (SDExtension = SDistEcTO)) then begin SDValues.Add(FormatFloat(NoDecimalDisplay, Value)); {FXX03082010-1(2.22.2.3)[]: The assessed value for a type 'S' override should be the override amount.} If _Compare(ParcelSDTable.FieldByName('CalcCode').AsString, PrclSDCcS, coEqual) then slAssessedValues.Add(FormatFloat(NoDecimalDisplay, ParcelSDTable.FieldByName('CalcAmount').AsInteger)) else slAssessedValues.Add(FormatFloat(NoDecimalDisplay, AssessedValue)); SDFormated := True; end; If not SDFormated then begin SDValues.Add(FormatFloat(DecimalEditDisplay, Value)); slAssessedValues.Add(FormatFloat(DecimalEditDisplay, Value)); end; SDExtensionCodes.Add(SDExtension); SDCC_OMFlags.Add(CC_OMFlag); HomesteadCodesList.Add(HomesteadCode); end; {If (Deblank(SDCodeTable) <> '')} {If the parcel is split and this is an AdValorum district, go back through this extension and compute the non-homestead value.} If ((SDExtensionType = SDExtCatA) and ParcelIsSplit and (HomesteadCode <> 'N')) then begin HomesteadCode := 'N'; AssessedValue := NonhstdAssessedVal; end else ExtensionIndex := ExtensionIndex + 1; end; {while (ExtensionIndex <= 10) do} If (OrigIndex <> 'BYSDISTCODE') then SDCodeTable.IndexName := OrigIndex; end; {CalculateSpecialDistrictAmount} {================================================================} Procedure FillInParcelSDValuesRecord(ParcelTable, AssessmentTable, ClassTable, ParcelSDTable, SDCodeTable : TTable; ParcelExemptionList, ExemptionCodeList : TList; PParcelSDValuesRec : PParcelSDValuesRecord); {Calculate the SD values for this sd code and fill in a parcel SD values record.} var slAssessedValues, SDValuesList, SDExtensionCodesList, SDCC_OMFlagsList, HomesteadCodesList : TStringList; I : Integer; begin {CHG09122004-1(2.8.0.11): Add homestead split to SD Calcs} SDValuesList := TStringList.Create; SDExtensionCodesList := TStringList.Create; SDCC_OMFlagsList := TStringList.Create; HomesteadCodesList := TStringList.Create; slAssessedValues := TStringList.Create; CalculateSpecialDistrictAmounts(ParcelTable, AssessmentTable, ClassTable, ParcelSDTable, SDCodeTable, ParcelExemptionList, ExemptionCodeList, SDExtensionCodesList, SDCC_OMFlagsList, slAssessedValues, SDValuesList, HomesteadCodesList); with PParcelSDValuesRec^ do begin {Initialize the values.} For I := 1 to 10 do begin SDExtensionCodes[I] := Take(2, ''); SDCC_OMFlags[I] := Take(1, ''); SDValues[I] := Take(15, ''); AssessedValues[I] := Take(15, ''); HomesteadCodes[I] := ''; end; SDCode := ParcelSDTable.FieldByName('SDistCode').Text; {Now fill in the lists.} For I := 0 to (SDExtensionCodesList.Count - 1) do SDExtensionCodes[I + 1] := Take(2, SDExtensionCodesList[I]); {FXX12221997-1: We were setting SDCC_OMFlags to itself rather than from the list.} For I := 0 to (SDCC_OMFlagsList.Count - 1) do SDCC_OMFlags[I + 1] := Take(1, SDCC_OMFlagsList[I]); For I := 0 to (SDValuesList.Count - 1) do SDValues[I + 1] := SDValuesList[I]; For I := 0 to (SDValuesList.Count - 1) do AssessedValues[I + 1] := slAssessedValues[I]; For I := 0 to (HomesteadCodesList.Count - 1) do HomesteadCodes[I + 1] := HomesteadCodesList[I]; SplitDistrict := SDCodeTable.FieldByName('SDHomestead').AsBoolean; end; {with PParcelSDValuesRec^ do} SDValuesList.Free; SDExtensionCodesList.Free; SDCC_OMFlagsList.Free; HomesteadCodesList.Free; slAssessedValues.Free; end; {FillInParcelSDValueRecord} {=======================================================} Procedure LoadExemptions(TaxRollYear : String; SwisSBLKey : String; ParcelExemptionList, ExemptionCodeList : TList; ParcelExemptionTable, ExemptionCodeTable : TTable); {CHG02221998-1 : For quicker roll total calcs, only read exemptions 1 time.} var Done, Quit, FirstTimeThrough : Boolean; ExemptionCodeRec : PExemptionCodeRecord; ParcelExemptionRec : PParcelExemptionRecord; begin If (ExemptionCodeTable.IndexName <> 'BYEXCODE') then ExemptionCodeTable.IndexName := 'BYEXCODE'; ParcelExemptionTable.IndexName := 'BYTAXROLLYR_SWISSBLKEY'; ParcelExemptionTable.CancelRange; SetRangeOld(ParcelExemptionTable, ['TaxRollYr', 'SwisSBLKey'], [TaxRollYear, SwisSBLKey], [TaxRollYear, SwisSBLKey]); Done := False; Quit := False; FirstTimeThrough := True; ParcelExemptionTable.First; If not (Done or Quit) then repeat If FirstTimeThrough then FirstTimeThrough := False else ParcelExemptionTable.Next; If ParcelExemptionTable.EOF then Done := True; {We have an exemption record, so put it in the list.} If not (Done or Quit) then begin New(ParcelExemptionRec); {CHG09122004-1(2.8.0.11): Add homestead split to SD Calcs} with ParcelExemptionTable, ParcelExemptionRec^ do begin EXCode := FieldByName('ExemptionCode').Text; CountyAmount := FieldByName('CountyAmount').AsFloat; TownAmount := FieldByName('TownAmount').AsFloat; SchoolAmount := FieldByName('SchoolAmount').AsFloat; VillageAmount := FieldByName('VillageAmount').AsFloat; HomesteadCode := FieldByName('HomesteadCode').Text; end; {with ParcelExemptionTable, ParcelExemptionRec^ do} ParcelExemptionList.Add(ParcelExemptionRec); {Now add the corresponding exemption code record.} FindKeyOld(ExemptionCodeTable, ['EXCode'], [ParcelExemptionRec^.EXCode]); New(ExemptionCodeRec); with ExemptionCodeTable, ExemptionCodeRec^ do begin ExemptionCode := ParcelExemptionRec^.EXCode; AppliesToSection490 := FieldByName('Section490').AsBoolean; AppliesToAdValorumDistrict := FieldByName('AdValorum').AsBoolean; AppliesToSpecialAssessmentDistrict := FieldByName('ApplySpclAssessmentD').AsBoolean; {CHG10252004-1(2.8.0.15): Allow for application of 4168x to selected SDs.} IsVolunteerFirefighterOrAmbulanceExemption := ExemptionIsVolunteerFirefighter(ExemptionCode); end; {with ParcelExemptionTable, PExemptionCodeRec^ do} ExemptionCodeList.Add(ExemptionCodeRec); end; {If not (Done or Quit)} until (Done or Quit); end; {LoadExemptions} {=======================================================} Procedure TotalSpecialDistrictsForParcel(TaxRollYr : String; SwisSBLKey : String; ParcelTable, AssessmentTable, ParcelSDTable, SDCodeTable, ParcelEXTable, EXCodeTable : TTable; SDAmounts : TList); {This is the return list of type PParcelExemptionRecord.} {This calculates all values for all special districts on one parcel. The information is returned in a TList where each element is of type PParcelSDValuesRecord.} var ParcelExemptionList, ExemptionCodeList : TList; FirstTimeThrough, Done, Quit, ExemptionListsCreated : Boolean; PParcelSDValuesRec : PParcelSDValuesRecord; ClassTable : TTable; I : Integer; begin ParcelExemptionList := nil; ExemptionCodeList := nil; ClearTList(SDAmounts, SizeOf(PParcelSDValuesRecord)); ClassTable := TTable.Create(nil); with ClassTable do begin TableType := ttDBase; DatabaseName := 'PASSystem'; IndexName := 'BYTAXROLLYR_SWISSBLKEY'; end; {with ClassTable do} OpenTableForProcessingType(ClassTable, ClassTableName, GetProcessingTypeForTaxRollYear(TaxRollYr), Quit); ParcelSDTable.CancelRange; SetRangeOld(ParcelSDTable, ['TaxRollYr', 'SwisSBLKey', 'SDistCode'], [TaxRollYr, SwisSBLKey, ' '], [TaxRollYr, SwisSBLKey, 'ZZZZZ']); Done := False; Quit := False; FirstTimeThrough := True; ExemptionListsCreated := False; ParcelSDTable.First; repeat If FirstTimeThrough then begin FirstTimeThrough := False; {CHG02221998-1 : For quicker roll total calcs, only read exemptions 1 time.} ParcelExemptionList := TList.Create; ExemptionCodeList := TList.Create; LoadExemptions(TaxRollYr, SwisSBLKey, ParcelExemptionList, ExemptionCodeList, ParcelEXTable, EXCodeTable); ExemptionListsCreated := True; end else ParcelSDTable.Next; If ParcelSDTable.EOF then Done := True; {We have an exemption record, so adjust the exemption roll totals.} If not (Done or Quit) then begin New(PParcelSDValuesRec); FillInParcelSDValuesRecord(ParcelTable, AssessmentTable, ClassTable, ParcelSDTable, SDCodeTable, ParcelExemptionList, ExemptionCodeList, PParcelSDValuesRec); For I := 1 to 10 do If _Compare(PParcelSDValuesRec.SDValues[I], coBlank) then PParcelSDValuesRec.SDValues[I] := '0'; SDAmounts.Add(PParcelSDValuesRec); end; {If not (Done or Quit)} until (Done or Quit); If ExemptionListsCreated then begin FreeTList(ParcelExemptionList, SizeOf(ParcelExemptionRecord)); FreeTList(ExemptionCodeList, SizeOf(ExemptionCodeRecord)); end; ClassTable.Close; ClassTable.Free; end; {TotalSpecialDistrictsForParcel} {===========================================================================} Function SpecialDistrictIsMoveTax(SDCodeTable : TTable) : Boolean; var FieldName : String; I : Integer; begin Result := False; with SDCodeTable do For I := 1 to 10 do begin FieldName := 'Ecd' + IntToStr(I); If (FieldByName(FieldName).Text = SdistEcMT) then Result := True; end; {For I := 1 to 10 do} end; {SpecialDistrictIsMoveTax} {====================================================================} Procedure AddOneSpecialDistrict( SpecialDistrictTable : TTable; const FieldNames : Array of const; const FieldValues : Array of const; UserName : String); begin _InsertRecord(SpecialDistrictTable, FieldNames, FieldValues, []); {Now add the audit information and update the roll totals.} end; {AddOneSpecialDistrict} {================================================================} Function GetExemptionTypeDescription(ExemptionCode : String) : String; begin Result := ''; If _Compare(ExemptionCode[5], ['0','1','2','5'], coEqual) then Result := 'County'; If _Compare(ExemptionCode[5], ['0','1','3','6'], coEqual) then begin If _Compare(Result, coNotBlank) then Result := Result + ','; Result := Result + GetMunicipalityTypeName(GlblMunicipalityType); end; {If _Compare(ExemptionCode[5] ...} If _Compare(ExemptionCode[5], ['0','4','5','6'], coEqual) then begin If _Compare(Result, coNotBlank) then Result := Result + ','; Result := Result + 'School'; end; {If _Compare(ExemptionCode[5] ...} If _Compare(ExemptionCode[5], '0', coEqual) then Result := 'Cty\' + GetMunicipalityTypeName(GlblMunicipalityType) + '\Schl'; If _Compare(ExemptionCode[5], '7', coEqual) then begin If _Compare(Result, coNotBlank) then Result := Result + ','; Result := Result + 'Village'; end; {If _Compare(ExemptionCode[5] ...} end; {GetExemptionTypeDescription} {===========================================================================} Procedure DeleteAnExemption(tb_Exemptions : TTable; tb_ExemptionsLookup : TTable; tb_RemovedExemptions : TTable; tb_AuditEXChange : TTable; tb_Audit : TTable; tb_Assessment : TTable; tb_Class : TTable; tb_SwisCode : TTable; tb_Parcel : TTable; tb_ExemptionCode : TTable; AssessmentYear : String; SwisSBLKey : String; ExemptionsNotRecalculatedList : TStringList); {The steps to delete an exemption are: 1. Record all the current exemption values in the AuditEXChange table. 2. Place the exemption in the RemovedExemptions table. 3. Add deleted exemption records to the Audit table. 4. Delete the exemption. 5. Recalculate exemptions for the parcel. 6. Record the new exemption values in the AuditEXChange table.} var AuditEXChangeList, AuditList : TList; begin {Step 1.} AuditEXChangeList := TList.Create; GetAuditEXList(SwisSBLKey, AssessmentYear, tb_ExemptionsLookup, AuditEXChangeList); InsertAuditEXChanges(SwisSBLKey, AssessmentYear, AuditEXChangeList, tb_AuditEXChange, 'B'); {Step 2.} with tb_RemovedExemptions do try Insert; FieldByName('SwisSBLKey').AsString := SwisSBLKey; FieldByName('ActualDateRemoved').AsDateTime := Date; FieldByName('RemovedBy').AsString := GlblUserName; FieldByName('ExemptionCode').AsString := tb_Exemptions.FieldByName('ExemptionCode').AsString; FieldByName('CountyAmount').AsInteger := tb_Exemptions.FieldByName('CountyAmount').AsInteger; FieldByName('TownAmount').AsInteger := tb_Exemptions.FieldByName('TownAmount').AsInteger; FieldByName('SchoolAmount').AsInteger := tb_Exemptions.FieldByName('SchoolAmount').AsInteger; FieldByName('YearRemovedFrom').AsString := AssessmentYear; FieldByName('EffectiveDateRemoved').AsDateTime := Date; try FieldByName('InitialDate').AsDateTime := tb_Exemptions.FieldByName('InitialDate').AsDateTime; except end; try FieldByName('Percent').AsFloat := tb_Exemptions.FieldByName('Percent').AsFloat; except end; Post; except SystemSupport(010, tb_RemovedExemptions, 'Error inserting an exemption removal record.', 'UTILEXSD', GlblErrorDlgBox); end; {Step 3.} (* AuditList := TList.Create; GetAuditInformation(tb_Exemptions, AuditList); StoreAuditInformation(AuditList, nil, GlblUserName, emDelete, kfSwisSBLKey); FreeTList(AuditList, SizeOf(AuditRecord)); *) {Step 4.} try tb_Exemptions.Delete; except SystemSupport(010, tb_Exemptions, 'Error deleting exemption ' + SwisSBLKey + '\' + tb_Exemptions.FieldByName('ExemptionCode').AsString, 'UTILEXSD', GlblErrorDlgBox); end; {Step 5.} RecalculateExemptionsForParcel(tb_ExemptionCode, tb_ExemptionsLookup, tb_Assessment, tb_Class, tb_SwisCode, tb_Parcel, AssessmentYear, SwisSBLKey, nil, 0, 0, False); {Step 6.} ClearTList(AuditEXChangeList, SizeOf(AuditEXRecord)); GetAuditEXList(SwisSBLKey, AssessmentYear, tb_ExemptionsLookup, AuditEXChangeList); InsertAuditEXChanges(SwisSBLKey, AssessmentYear, AuditEXChangeList, tb_AuditEXChange, 'A'); FreeTList(AuditEXChangeList, SizeOf(AuditEXRecord)); end; {DeleteAnExemption} {==================================================================================} Function ParcelHasOverrideSpecialDistricts(tbParcelSpecialDistricts : TTable; sAssessmentYear : String; sSwisSBLKey : String) : Boolean; begin Result := False; _SetRange(tbParcelSpecialDistricts, [sAssessmentYear, sSwisSBLKey], [], '', [loSameEndingRange]); with tbParcelSpecialDistricts do begin First; while not EOF do begin If _Compare(FieldByName('CalcCode').AsString, ['E', 'S'], coEqual) then Result := True; Next; end; {while not EOF do} end; {with tbParcelSpecialDistricts do} end; {ParcelHasOverrideSpecialDistricts} {INITIALIZATION CODE IS VACUOUS } BEGIN END.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFileX<p> Simple X format support for Delphi (Microsoft's favorite format)<p> <b>History : </b><font size=-1><ul> <li>07/11/09 - DaStr - Initial version (Added from the GLScene-Lazarus SVN) </ul></font> <b>Previous version history : </b><font size=-1><ul> $Log$ Revision 1.1 2009/11/07 22:12:25 da_stranger Initial version (Added from the GLScene-Lazarus SVN) Revision 1.1 2006/01/10 20:50:44 z0m3ie recheckin to make shure that all is lowercase Revision 1.1 2006/01/09 21:02:31 z0m3ie *** empty log message *** Revision 1.3 2005/12/04 16:53:04 z0m3ie renamed everything to lowercase to get better codetools support and avoid unit finding bugs Revision 1.2 2005/08/03 00:41:38 z0m3ie - added automatical generated History from CVS </ul></font> } unit GLFileX; interface {$i GLScene.inc} uses System.Classes, System.SysUtils, // GLS GLVectorFileObjects, GLApplicationFileIO, GLVectorGeometry, GLTexture, GLVectorLists, GLMaterial, // Misc FileX; type TGLXVectorFile = class (TVectorFile) public { Public Declarations } class function Capabilities: TDataFileCapabilities; override; procedure LoadFromStream(aStream : TStream); override; end; //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- implementation //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- class function TGLXVectorFile.Capabilities : TDataFileCapabilities; begin Result := [dfcRead]; end; procedure TGLXVectorFile.LoadFromStream(aStream: TStream); var DXFile : TDXFile; procedure RecursDXFile(DXNode : TDXNode); var i,j,k,l,vertcount : integer; mo : TMeshObject; mat : TMatrix; libmat : TGLLibMaterial; fg : TFGVertexNormalTexIndexList; str : String; begin mat:=IdentityHMGMatrix; if Assigned(DXNode.Owner) then if DXNode.Owner is TDXFrame then begin mat:=TDXFrame(DXNode.Owner).GlobalMatrix; TransposeMatrix(mat); end; if DXNode is TDXMesh then begin mo:=TMeshObject.CreateOwned(Owner.MeshObjects); mo.Mode:=momFaceGroups; mo.Vertices.Assign(TDXMesh(DXNode).Vertices); mo.Vertices.TransformAsPoints(mat); mo.Normals.Assign(TDXMesh(DXNode).Normals); mo.Normals.TransformAsVectors(mat); mo.TexCoords.Assign(TDXMesh(DXNode).TexCoords); if TDXMesh(DXNode).MaterialList.Count>0 then begin // Add the materials if (Owner.UseMeshMaterials) and Assigned(Owner.MaterialLibrary) then begin for i:=0 to TDXMesh(DXNode).MaterialList.Count-1 do begin Str:=TDXMesh(DXNode).MaterialList.Items[i].Texture; if FileExists(Str) then libmat:=Owner.MaterialLibrary.AddTextureMaterial('', Str) else libmat:=Owner.MaterialLibrary.Materials.Add; libmat.Name:=Format('%s_%d',[DXNode.Name,i]); with libmat.Material.FrontProperties do begin Diffuse.Color:=TDXMesh(DXNode).MaterialList.Items[i].Diffuse; Shininess:=Round(TDXMesh(DXNode).MaterialList.Items[i].SpecPower/2); Specular.Color:=VectorMake(TDXMesh(DXNode).MaterialList.Items[i].Specular); Emission.Color:=VectorMake(TDXMesh(DXNode).MaterialList.Items[i].Emissive); end; end; end; // Add the facegroups (separate since material library // can be unassigned) for i:=0 to TDXMesh(DXNode).MaterialList.Count-1 do begin fg:=TFGVertexNormalTexIndexList.CreateOwned(mo.FaceGroups); fg.MaterialName:=Format('%s_%d',[DXNode.Name,i]); end; // Now add the indices per material vertcount:=0; for i:=0 to TDXMesh(DXNode).VertCountIndices.Count-1 do begin if (i<TDXMesh(DXNode).MaterialIndices.Count) then begin j:=TDXMesh(DXNode).MaterialIndices[i]; k:=TDXMesh(DXNode).VertCountIndices[i]; for l:=vertcount to vertcount+k-1 do begin TFGVertexNormalTexIndexList(mo.FaceGroups[j]).VertexIndices.Add(TDXMesh(DXNode).VertexIndices[l]); if mo.TexCoords.Count>0 then TFGVertexNormalTexIndexList(mo.FaceGroups[j]).TexCoordIndices.Add(TDXMesh(DXNode).VertexIndices[l]); if TDXMesh(DXNode).NormalIndices.Count>0 then TFGVertexNormalTexIndexList(mo.FaceGroups[j]).NormalIndices.Add(TDXMesh(DXNode).NormalIndices[l]) end; vertcount:=vertcount+k; end; end; end else begin fg:=TFGVertexNormalTexIndexList.CreateOwned(mo.FaceGroups); fg.NormalIndices.Assign(TDXMesh(DXNode).NormalIndices); fg.VertexIndices.Assign(TDXMesh(DXNode).VertexIndices); end; end; for i:=0 to DXNode.Count-1 do RecursDXFile(TDXNode(DXNode[i])); end; begin DXFile:=TDXFile.Create; try DXFile.LoadFromStream(aStream); RecursDXFile(DXFile.RootNode); finally DXFile.Free; end; end; initialization RegisterVectorFileFormat('x', 'DirectX Model files', TGLXVectorFile); end.
unit ansi_to_unicode_1; interface implementation var SA: AnsiString; SU: String; procedure Test; begin SA := 'ansi'; SU := SA; end; initialization Test(); finalization Assert(SU = 'ansi'); end.
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium E-Mail: mshkolnik@scalabium.com mshkolnik@yahoo.com WEB: http://www.scalabium.com } unit CharMap; interface {$I SMVersion.inc} uses Windows, Classes, Messages, StdCtrls, Graphics, Buttons, Controls; type TSMPopupListbox = class(TWinControl) private FCharacter: Char; procedure BtnClick(Sender: TObject); procedure WMMouseActivate(var Message: TMessage); message WM_MOUSEACTIVATE; protected procedure CreateParams(var Params: TCreateParams); override; public constructor Create(AOwner: TComponent); override; end; {$IFDEF SM_ADD_ComponentPlatformsAttribute} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TCharMapCombo = class(TCustomEdit) private { Private declarations } FButton: TSpeedButton; FBtnControl: TWinControl; FOnButtonClick: TNotifyEvent; FPickList: TSMPopupListbox; FAlignment: TAlignment; procedure SetAlignment(Value: TAlignment); function GetCharacter: Char; procedure SetCharacter(Value: Char); procedure CMCancelMode(var Message: TCMCancelMode); message CM_CancelMode; procedure WMKillFocus(var Message: TMessage); message WM_KillFocus; procedure EditButtonClick(Sender: TObject); procedure SetEditRect; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; procedure WMSize(var Message: TWMSize); message WM_SIZE; protected { Protected declarations } procedure ButtonClick; dynamic; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure CloseUp(Accept: Boolean); procedure DropDown; procedure WndProc(var Message: TMessage); override; procedure CreateWnd; override; procedure CreateParams(var Params: TCreateParams); override; procedure Change; override; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Button: TSpeedButton read FButton; published { Published declarations } property Alignment: TAlignment read FAlignment write SetAlignment; property Character: Char read GetCharacter write SetCharacter; property OnButtonClick: TNotifyEvent read FOnButtonClick write FOnButtonClick; property AutoSize; property BorderStyle; property CharCase; property Color; property Ctl3D; property DragCursor; property DragMode; property Enabled; property Font; property ImeMode; property ImeName; property OEMConvert; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PasswordChar; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Visible; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; procedure Register; implementation uses SysUtils, menus, forms, extctrls; procedure Register; begin RegisterComponents('SMComponents', [TCharMapCombo]); end; { TSMPopupListBox } constructor TSMPopupListBox.Create(AOwner: TComponent); var i, j: Integer; BackPanel: TPanel; begin inherited Create(AOwner); ControlStyle := ControlStyle + [csNoDesignVisible, csReplicatable]; Color := clBtnFace; Parent := TWinControl(AOWner); BackPanel := TPanel.Create(Self); with BackPanel do begin Parent := Self; Align := alClient; ParentColor := True; end; for i := 1 to 14 do for j := 1 to 16 do with TSpeedButton.Create(Self) do try Caption := Chr(i*16+j+15); if Caption = '&' then Caption := Caption + '&'; Hint := Format('ASCII dec value: %d'#13#10'ASCII hex value: $%x'#13#10'Symbol: %s', [i*16+j+15, i*16+j+15, Chr(i*16+j+15)]); Tag := i*16+j+15; Flat := True; GroupIndex := 1; Height := 18; Width := 18; Left := j*20 - 15; Top := i*20 - 15; Parent := BackPanel; //Self; OnClick := BtnClick finally end; end; procedure TSMPopupListBox.CreateParams(var Params: TCreateParams); begin inherited; with Params do begin Style := Style or WS_POPUP or WS_BORDER; ExStyle := WS_EX_TOOLWINDOW {or WS_EX_TOPMOST}; WindowClass.Style := WindowClass.Style or CS_SAVEBITS; end; end; procedure TSMPopupListbox.BtnClick(Sender: TObject); begin with TCharMapCombo(Owner) do begin if not ReadOnly then Character := Chr(TSpeedButton(Sender).Tag); CloseUp(True); end; end; procedure TSMPopupListbox.WMMouseActivate(var Message: TMessage); begin Message.Result := MA_NOACTIVATE; end; { TCharMapCombo } constructor TCharMapCombo.Create(AOwner: TComponent); begin inherited Create(AOwner); FAlignment := taLeftJustify; FBtnControl := TWinControl.Create(Self); with FBtnControl do ControlStyle := ControlStyle + [csReplicatable]; FBtnControl.Width := GetSystemMetrics(SM_CXVSCROLL); FBtnControl.Height := 17; FBtnControl.Visible := True; FBtnControl.Parent := Self; FButton := TSpeedButton.Create(Self); FButton.SetBounds(0, 0, FBtnControl.Width, FBtnControl.Height); FButton.Visible := True; FButton.Parent := FBtnControl; FButton.Glyph.Handle := LoadBitmap(0, PChar(32738)); FButton.OnClick := EditButtonClick; Height := 21; FPickList := TSMPopupListbox.Create(Self); FPickList.Visible := False; FPickList.Width := 330; FPickList.Height := 290; FPickList.Parent := Self; MaxLength := 1; end; destructor TCharMapCombo.Destroy; begin FButton.OnClick := nil; FPickList.Free; inherited Destroy; end; procedure TCharMapCombo.CreateParams(var Params: TCreateParams); const Alignments: array[TAlignment] of dWord = (ES_LEFT, ES_RIGHT, ES_CENTER); Multilines: array[Boolean] of dWord = (0, ES_MULTILINE); begin inherited CreateParams(Params); Params.Style := Params.Style or Multilines[PasswordChar = #0] or Alignments[FAlignment]; end; procedure TCharMapCombo.CreateWnd; begin inherited CreateWnd; SetEditRect; end; procedure TCharMapCombo.SetAlignment(Value: TAlignment); begin if FAlignment <> Value then begin FAlignment := Value; RecreateWnd; end; end; procedure TCharMapCombo.Change; begin inherited Change; if Length(Text) > 0 then Character := Text[1] end; procedure TCharMapCombo.SetEditRect; var Loc: TRect; begin if NewStyleControls then begin if Ctl3D then FBtnControl.SetBounds(Width - FButton.Width - 4, 0, FButton.Width, Height - 4) else FBtnControl.SetBounds(Width - FButton.Width - 2, 2, FButton.Width, Height - 4); end else FBtnControl.SetBounds(Width - FButton.Width - 2, 1, FButton.Width, ClientHeight - 2); FButton.Height := FBtnControl.Height; SetRect(Loc, 0, 0, ClientWidth - FBtnControl.Width - 2, ClientHeight + 1); SendMessage(Handle, EM_SETRECTNP, 0, LongInt(@Loc)); end; procedure TCharMapCombo.CMCtl3DChanged(var Message: TMessage); begin inherited; SetEditRect; end; procedure TCharMapCombo.WMSize(var Message: TWMSize); begin inherited; SetEditRect; end; function TCharMapCombo.GetCharacter: Char; begin Result := FPickList.FCharacter; end; procedure TCharMapCombo.SetCharacter(Value: Char); var i: Integer; begin if FPickList.FCharacter <> Value then begin FPickList.FCharacter := Value; Text := Value; for i := 0 to FPickList.ComponentCount-1 do if FPickList.Components[i] is TSpeedButton then with TSpeedButton(FPickList.Components[i]) do if Chr(Tag) = Character then Down := True; end; end; procedure TCharMapCombo.EditButtonClick(Sender: TObject); begin if Enabled then ButtonClick; end; procedure TCharMapCombo.ButtonClick; begin DropDown; if Assigned(FOnButtonClick) then FOnButtonClick(Self); end; procedure TCharMapCombo.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); if (scAlt + vk_Down = ShortCut(Key, Shift)) then begin EditButtonClick(Self); Key := 0; end; end; procedure TCharMapCombo.CloseUp(Accept: Boolean); begin if Assigned(FPickList) and FPickList.Visible then begin if GetCapture <> 0 then SendMessage(GetCapture, WM_CANCELMODE, 0, 0); SetWindowPos(FPickList.Handle, 0, 0, 0, 0, 0, SWP_NOZORDER or SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE or SWP_HIDEWINDOW); FPickList.Visible := False; Invalidate; SetFocus; end; end; procedure TCharMapCombo.DropDown; var P: TPoint; i: Integer; begin if Assigned(FPickList) and (not FPickList.Visible) then begin FPickList.ShowHint := ShowHint; // FPickList.Width := Width; // FPickList.Color := Color; FPickList.Font := Font; P := Parent.ClientToScreen(Point(Left, Top)); i := P.Y + Height; if i + FPickList.Height > Screen.Height then i := P.Y - FPickList.Height; SetWindowPos(FPickList.Handle, HWND_TOP, P.X, i, 0, 0, SWP_NOSIZE or SWP_NOACTIVATE or SWP_SHOWWINDOW); FPickList.Visible := True; Invalidate; SetFocus; end; end; procedure TCharMapCombo.CMCancelMode(var Message: TCMCancelMode); begin if (Message.Sender <> Self) and (Message.Sender <> FPickList) then CloseUp(False); end; procedure TCharMapCombo.WMKillFocus(var Message: TMessage); begin inherited; CloseUp(False); end; procedure TCharMapCombo.WndProc(var Message: TMessage); procedure DoDropDownKeys(var Key: Word; Shift: TShiftState); begin case Key of VK_UP, VK_DOWN: if ssAlt in Shift then begin if FPickList.Visible then CloseUp(True) else DropDown; Key := 0; end; VK_RETURN, VK_ESCAPE: if FPickList.Visible and not (ssAlt in Shift) then begin CloseUp(Key = VK_RETURN); Key := 0; end; end; end; begin case Message.Msg of WM_KeyDown, WM_SysKeyDown, WM_Char: with TWMKey(Message) do begin DoDropDownKeys(CharCode, KeyDataToShiftState(KeyData)); if (CharCode <> 0) and FPickList.Visible then begin with TMessage(Message) do SendMessage(FPickList.Handle, Msg, WParam, LParam); Exit; end; end end; inherited; end; end.
{*******************************************************} { } { Delphi Runtime Library } { SOAP Support } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Soap.SOAPMidas; interface uses Datasnap.Midas, Soap.InvokeRegistry, System.Types; type { IAppServerSOAP: IAppServer for SOAP IAppServerSOAP is essentially IAppServer with __stdcall instead of __safecall. This allows environment that don't support safecall to receive packets analogous to IAppServer. } IAppServerSOAP = interface(IInvokable) ['{C99F4735-D6D2-495C-8CA2-E53E5A439E61}'] function SAS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer; var OwnerData: OleVariant): OleVariant; stdcall; function SAS_GetRecords(const ProviderName: WideString; Count: Integer; out RecsOut: Integer; Options: Integer; const CommandText: WideString; var Params: OleVariant; var OwnerData: OleVariant): OleVariant; stdcall; function SAS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; stdcall; function SAS_GetProviderNames: TWideStringDynArray; stdcall; function SAS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; stdcall; function SAS_RowRequest(const ProviderName: WideString; Row: OleVariant; RequestType: Integer; var OwnerData: OleVariant): OleVariant; stdcall; procedure SAS_Execute(const ProviderName: WideString; const CommandText: WideString; var Params: OleVariant; var OwnerData: OleVariant); stdcall; end; procedure RegDefIAppServerInvClass; implementation uses Soap.SOAPConst, Soap.SOAPDm; procedure RegDefIAppServerInvClass; begin InvRegistry.RegisterInvokableClass(TSoapDataModule); end; initialization { For backwards compatibility, we'll set the namespace of IAppServer explicitly - therefore allowing this code to move to a different module; and also handling the case where the AppNameSpacePrefix is defined } InvRegistry.RegisterInterface(TypeInfo(IAppServer), 'urn:Midas-IAppServer'); { Do not localize } InvRegistry.RegisterInterface(TypeInfo(IAppServerSOAP), SBorlandTypeNamespace); { Do not localize } InvRegistry.RegisterDefaultSOAPAction(TypeInfo(IAppServerSOAP), SBorlandTypeNamespace + '-IAppServerSOAP'); { Do not localize } end.
unit BrickCamp.TDB; interface uses Spring.Persistence.Adapters.FireDac, Spring.Container.Common, Spring.Persistence.Core.Session, BrickCamp.IDB, BrickCamp.ISettings; type TCbdDB = class(TInterfacedObject, IBrickCampDb) protected var [Inject] FSettings: IBrickCampSettings; FCon: TFireDACConnectionAdapter; FSession: TSession; public destructor Destroy; override; procedure InitializeDbConnection; function GetSession: TSession; end; implementation uses Spring.Container, Spring.Persistence.Core.ListSession, Spring.Collections, FireDAC.Comp.Client, FireDAC.Phys.IBDef, FireDAC.Phys.IBWrapper, FireDAC.Phys.IBBase, FireDAC.Phys.IB, FireDAC.Phys.FB; { TCbdDB } procedure TCbdDB.InitializeDbConnection; begin if FCon <> nil then Exit; FCon := TFireDACConnectionAdapter.Create(TFDConnection.Create(nil)); FCon.Connection.ConnectionString := FSettings.GetDBStringConnection; FCon.Connection.LoginPrompt := false; FCon.Connect; FSession := TSession.Create(FCon); end; destructor TCbdDB.Destroy; begin inherited; end; function TCbdDB.GetSession: TSession; begin InitializeDbConnection; Result := FSession; end; end.
unit MgPrimitives; interface uses Classes; type TMgCustomPrimitive = class(TPersistent) private FOnChange : TNotifyEvent; protected procedure AssignTo(Dest: TPersistent); override; procedure Changed; virtual; public property OnChange: TNotifyEvent read FOnChange write FOnChange; end; TMgPrimitiveVerticalLine = class(TMgCustomPrimitive) private FY1: Integer; FY2: Integer; FX: Integer; procedure SetY1(const Value: Integer); procedure SetY2(const Value: Integer); procedure SetX(const Value: Integer); protected procedure AssignTo(Dest: TPersistent); override; procedure Y1Changed; procedure Y2Changed; procedure XChanged; public constructor Create(X, Y1, Y2: Integer); virtual; property X: Integer read FX write SetX; property Y1: Integer read FY1 write SetY1; property Y2: Integer read FY2 write SetY2; end; TMgPrimitiveHorizontalLine = class(TMgCustomPrimitive) private FX1: Integer; FX2: Integer; FY: Integer; procedure SetX1(const Value: Integer); procedure SetX2(const Value: Integer); procedure SetY(const Value: Integer); protected procedure AssignTo(Dest: TPersistent); override; procedure X1Changed; procedure X2Changed; procedure YChanged; public constructor Create(X1, X2, Y: Integer); virtual; property Y: Integer read FY write SetY; property X1: Integer read FX1 write SetX1; property X2: Integer read FX2 write SetX2; end; TMgPrimitiveLine = class(TMgCustomPrimitive) private FX2: Integer; FY2: Integer; FX1: Integer; FY1: Integer; procedure SetX1(const Value: Integer); procedure SetX2(const Value: Integer); procedure SetY1(const Value: Integer); procedure SetY2(const Value: Integer); protected procedure AssignTo(Dest: TPersistent); override; procedure X1Changed; procedure X2Changed; procedure Y1Changed; procedure Y2Changed; public constructor Create(X1, Y1, X2, Y2: Integer); virtual; property Y1: Integer read FY1 write SetY1; property Y2: Integer read FY2 write SetY2; property X1: Integer read FX1 write SetX1; property X2: Integer read FX2 write SetX2; end; TMgPrimitiveRect = class(TMgCustomPrimitive) private FLeft: Integer; FTop: Integer; FRight: Integer; FBottom: Integer; procedure SetLeft(const Value: Integer); procedure SetRight(const Value: Integer); procedure SetTop(const Value: Integer); procedure SetBottom(const Value: Integer); protected procedure AssignTo(Dest: TPersistent); override; procedure LeftChanged; procedure RightChanged; procedure TopChanged; procedure BottomChanged; public constructor Create(Left, Right, Top, Bottom: Integer); virtual; property Top: Integer read FTop write SetTop; property Bottom: Integer read FBottom write SetBottom; property Left: Integer read FLeft write SetLeft; property Right: Integer read FRight write SetRight; end; TMgPrimitiveCircle = class(TMgCustomPrimitive) end; TMgPrimitivePolygon = class(TMgCustomPrimitive) end; implementation { TMgCustomPrimitive } procedure TMgCustomPrimitive.AssignTo(Dest: TPersistent); begin if Dest is TMgCustomPrimitive then with TMgCustomPrimitive(Dest) do begin FOnChange := Self.FOnChange; end else inherited; end; procedure TMgCustomPrimitive.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; { TMgPrimitiveVerticalLine } constructor TMgPrimitiveVerticalLine.Create(X, Y1, Y2: Integer); begin FX := X; FY1 := Y1; FY2 := Y2; end; procedure TMgPrimitiveVerticalLine.AssignTo(Dest: TPersistent); begin inherited; if Dest is TMgPrimitiveVerticalLine then with TMgPrimitiveVerticalLine(Dest) do begin FX := Self.X; FY1 := Self.Y1; FY2 := Self.Y2; end else if Dest is TMgPrimitiveLine then with TMgPrimitiveLine(Dest) do begin FX1 := Self.X; FX2 := Self.X; FY1 := Self.Y1; FY2 := Self.Y2; end; end; procedure TMgPrimitiveVerticalLine.SetY1(const Value: Integer); begin if FY1 <> Value then begin FY1 := Value; Y1Changed; end; end; procedure TMgPrimitiveVerticalLine.SetY2(const Value: Integer); begin if FY2 <> Value then begin FY2 := Value; Y2Changed; end; end; procedure TMgPrimitiveVerticalLine.SetX(const Value: Integer); begin if FX <> Value then begin FX := Value; XChanged; end; end; procedure TMgPrimitiveVerticalLine.Y1Changed; begin Changed; end; procedure TMgPrimitiveVerticalLine.Y2Changed; begin Changed; end; procedure TMgPrimitiveVerticalLine.XChanged; begin Changed; end; { TMgPrimitiveHorizontalLine } constructor TMgPrimitiveHorizontalLine.Create(X1, X2, Y: Integer); begin FX1 := X1; FX2 := X2; FY := Y; end; procedure TMgPrimitiveHorizontalLine.AssignTo(Dest: TPersistent); begin inherited; if Dest is TMgPrimitiveHorizontalLine then with TMgPrimitiveHorizontalLine(Dest) do begin FX1 := Self.X1; FX2 := Self.X2; FY := Self.Y; end else if Dest is TMgPrimitiveLine then with TMgPrimitiveLine(Dest) do begin FX1 := Self.X1; FX2 := Self.X2; FY1 := Self.Y; FY2 := Self.Y; end; end; procedure TMgPrimitiveHorizontalLine.SetX1(const Value: Integer); begin if FX1 <> Value then begin FX1 := Value; X1Changed; end; end; procedure TMgPrimitiveHorizontalLine.SetX2(const Value: Integer); begin if FX2 <> Value then begin FX2 := Value; X2Changed; end; end; procedure TMgPrimitiveHorizontalLine.SetY(const Value: Integer); begin if FY <> Value then begin FY := Value; YChanged; end; end; procedure TMgPrimitiveHorizontalLine.YChanged; begin Changed; end; procedure TMgPrimitiveHorizontalLine.X1Changed; begin Changed; end; procedure TMgPrimitiveHorizontalLine.X2Changed; begin Changed; end; { TMgPrimitiveLine } constructor TMgPrimitiveLine.Create(X1, Y1, X2, Y2: Integer); begin FX1 := X1; FX2 := X2; FY1 := Y1; FY2 := Y2; end; procedure TMgPrimitiveLine.AssignTo(Dest: TPersistent); begin inherited; if Dest is TMgPrimitiveLine then with TMgPrimitiveLine(Dest) do begin FX1 := Self.X1; FX2 := Self.X2; FY1 := Self.Y1; FY2 := Self.Y2; end; end; procedure TMgPrimitiveLine.SetX1(const Value: Integer); begin if FX1 <> Value then begin FX1 := Value; X1Changed; end; end; procedure TMgPrimitiveLine.SetX2(const Value: Integer); begin if FX2 <> Value then begin FX2 := Value; X2Changed; end; end; procedure TMgPrimitiveLine.SetY1(const Value: Integer); begin if FY1 <> Value then begin FY1 := Value; Y1Changed; end; end; procedure TMgPrimitiveLine.SetY2(const Value: Integer); begin if FY2 <> Value then begin FY2 := Value; Y2Changed; end; end; procedure TMgPrimitiveLine.X1Changed; begin Changed; end; procedure TMgPrimitiveLine.X2Changed; begin Changed; end; procedure TMgPrimitiveLine.Y1Changed; begin Changed; end; procedure TMgPrimitiveLine.Y2Changed; begin Changed; end; { TMgPrimitiveRect } constructor TMgPrimitiveRect.Create(Left, Right, Top, Bottom: Integer); begin FLeft := Left; FTop := Top; FRight := Right; FBottom := Bottom; end; procedure TMgPrimitiveRect.AssignTo(Dest: TPersistent); begin inherited; if Dest is TMgPrimitiveRect then with TMgPrimitiveRect(Dest) do begin FLeft := Self.Left; FTop := Self.Top; FRight := Self.Right; FBottom := Self.Bottom; end; end; procedure TMgPrimitiveRect.SetLeft(const Value: Integer); begin FLeft := Value; end; procedure TMgPrimitiveRect.SetTop(const Value: Integer); begin FTop := Value; end; procedure TMgPrimitiveRect.SetRight(const Value: Integer); begin FRight := Value; end; procedure TMgPrimitiveRect.SetBottom(const Value: Integer); begin FBottom := Value; end; procedure TMgPrimitiveRect.LeftChanged; begin Changed; end; procedure TMgPrimitiveRect.TopChanged; begin Changed; end; procedure TMgPrimitiveRect.RightChanged; begin Changed; end; procedure TMgPrimitiveRect.BottomChanged; begin Changed; end; end.
unit MIRTErrorLogFrm; ////////////////////////////////////// // // // Description: MIRT Error Log form // // // ////////////////////////////////////// interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ActnList, StdCtrls, Menus; type TfrmErrorLog = class(TForm) lbErrors: TListBox; btnClose: TButton; lblDescription: TLabel; alActions: TActionList; actClose: TAction; pmMenu: TPopupMenu; miSaveToFile: TMenuItem; actSaveToFile: TAction; dlgSave: TSaveDialog; procedure actCloseExecute(Sender: TObject); procedure actSaveToFileExecute(Sender: TObject); private { Private declarations } public { Public declarations } procedure SetErrorLogList(slLog: TStringList); end; implementation {$R *.DFM} procedure TfrmErrorLog.actCloseExecute(Sender: TObject); begin ModalResult := mrOK; end; procedure TfrmErrorLog.SetErrorLogList(slLog: TStringList); var i: integer; begin lbErrors.Clear; if slLog.Count > 0 then for i := 0 to slLog.Count - 1 do lbErrors.Items.Add(slLog.Strings[i]); end; procedure TfrmErrorLog.actSaveToFileExecute(Sender: TObject); var i: integer; slLog: TStringList; begin slLog := TStringList.Create; try if dlgSave.Execute then begin slLog.Add('MIRT ERROR LOG, PROCESSED ON ' + DateTimeToStr(Now)); slLog.Add('Skipped ' + IntToStr(lbErrors.Items.Count) + ' files :'); slLog.Add(''); if lbErrors.Items.Count > 0 then for i := 0 to lbErrors.Items.Count - 1 do slLog.Add(lbErrors.Items[i]); slLog.SaveToFile(dlgSave.FileName); end; // if dlgSave.Execute finally slLog.Free; end; // try..finally end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit System.Generics.Defaults; {$R-,T-,X+,H+,B-} (*$HPPEMIT '#pragma option -w-8022'*) interface uses System.SysUtils, System.TypInfo; type IComparer<T> = interface function Compare(const Left, Right: T): Integer; end; IEqualityComparer<T> = interface function Equals(const Left, Right: T): Boolean; function GetHashCode(const Value: T): Integer; end; TComparison<T> = reference to function(const Left, Right: T): Integer; // Abstract base class for IComparer<T> implementations, and a provider // of default IComparer<T> implementations. TComparer<T> = class(TInterfacedObject, IComparer<T>) public class function Default: IComparer<T>; class function Construct(const Comparison: TComparison<T>): IComparer<T>; function Compare(const Left, Right: T): Integer; virtual; abstract; end; TEqualityComparison<T> = reference to function(const Left, Right: T): Boolean; THasher<T> = reference to function(const Value: T): Integer; // Abstract base class for IEqualityComparer<T> implementations, and a provider // of default IEqualityComparer<T> implementations. TEqualityComparer<T> = class(TInterfacedObject, IEqualityComparer<T>) public class function Default: IEqualityComparer<T>; static; class function Construct(const EqualityComparison: TEqualityComparison<T>; const Hasher: THasher<T>): IEqualityComparer<T>; function Equals(const Left, Right: T): Boolean; reintroduce; overload; virtual; abstract; function GetHashCode(const Value: T): Integer; reintroduce; overload; virtual; abstract; end; // A non-reference-counted IInterface implementation. TSingletonImplementation = class(TObject, IInterface) protected function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; end; TDelegatedEqualityComparer<T> = class(TEqualityComparer<T>) private FEquals: TEqualityComparison<T>; FGetHashCode: THasher<T>; public constructor Create(const AEquals: TEqualityComparison<T>; const AGetHashCode: THasher<T>); function Equals(const Left, Right: T): Boolean; overload; override; function GetHashCode(const Value: T): Integer; overload; override; end; TDelegatedComparer<T> = class(TComparer<T>) private FCompare: TComparison<T>; public constructor Create(const ACompare: TComparison<T>); function Compare(const Left, Right: T): Integer; override; end; TCustomComparer<T> = class(TSingletonImplementation, IComparer<T>, IEqualityComparer<T>) protected function Compare(const Left, Right: T): Integer; virtual; abstract; function Equals(const Left, Right: T): Boolean; reintroduce; overload; virtual; abstract; function GetHashCode(const Value: T): Integer; reintroduce; overload; virtual; abstract; end; TStringComparer = class(TCustomComparer<string>) private class var FOrdinal: TCustomComparer<string>; public class function Ordinal: TStringComparer; end; TIStringComparer = class(TCustomComparer<string>) private class var FOrdinal: TCustomComparer<string>; public class function Ordinal: TStringComparer; end; function BobJenkinsHash(const Data; Len, InitData: Integer): Integer; function BinaryCompare(const Left, Right: Pointer; Size: Integer): Integer; // Must be in interface section to be used by generic method. For internal use only. type TDefaultGenericInterface = (giComparer, giEqualityComparer); function _LookupVtableInfo(intf: TDefaultGenericInterface; info: PTypeInfo; size: Integer): Pointer; implementation uses System.SyncObjs, System.Math, System.AnsiStrings, System.Generics.Collections, System.Variants; type PSimpleInstance = ^TSimpleInstance; TSimpleInstance = record Vtable: Pointer; RefCount: Integer; Size: Integer; end; TInfoFlags = set of (ifVariableSize, ifSelector); PVtableInfo = ^TVtableInfo; TVtableInfo = record Flags: TInfoFlags; Data: Pointer; end; TTypeInfoSelector = function(info: PTypeInfo; size: Integer): Pointer; function MakeInstance(vtable: Pointer; sizeField: Integer): Pointer; var inst: PSimpleInstance; begin GetMem(inst, SizeOf(inst^)); inst^.Vtable := vtable; inst^.RefCount := 0; inst^.Size := sizeField; Result := inst; end; function NopAddref(inst: Pointer): Integer; stdcall; begin Result := -1; end; function NopRelease(inst: Pointer): Integer; stdcall; begin Result := -1; end; function NopQueryInterface(inst: Pointer; const IID: TGUID; out Obj): HResult; stdcall; begin Result := E_NOINTERFACE; end; function MemAddref(inst: PSimpleInstance): Integer; stdcall; begin Result := TInterlocked.Increment(inst^.RefCount); end; function MemRelease(inst: PSimpleInstance): Integer; stdcall; begin Result := TInterlocked.Decrement(inst^.RefCount); if Result = 0 then FreeMem(inst); end; // I/U 1-4 function Compare_I1(Inst: Pointer; const Left, Right: Shortint): Integer; begin { Use subtraction } Result := Left - Right; end; function Equals_I1(Inst: Pointer; const Left, Right: Shortint): Boolean; begin Result := Left = Right; end; function GetHashCode_I1(Inst: Pointer; const Value: Shortint): Integer; begin Result := BobJenkinsHash(Value, SizeOf(Value), 0); end; function Compare_I2(Inst: Pointer; const Left, Right: Smallint): Integer; begin { Use subtraction } Result := Left - Right; end; function Equals_I2(Inst: Pointer; const Left, Right: Smallint): Boolean; begin Result := Left = Right; end; function GetHashCode_I2(Inst: Pointer; const Value: Smallint): Integer; begin Result := BobJenkinsHash(Value, SizeOf(Value), 0); end; function Compare_I4(Inst: Pointer; const Left, Right: Integer): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; function Equals_I4(Inst: Pointer; const Left, Right: Integer): Boolean; begin Result := Left = Right; end; function GetHashCode_I4(Inst: Pointer; const Value: Integer): Integer; begin Result := BobJenkinsHash(Value, SizeOf(Value), 0); end; function Compare_U1(Inst: Pointer; const Left, Right: Byte): Integer; begin { Use subtraction } Result := Integer(Left) - Integer(Right); end; function Compare_U2(Inst: Pointer; const Left, Right: Word): Integer; begin { Use subtraction } Result := Integer(Left) - Integer(Right); end; function Compare_U4(Inst: Pointer; const Left, Right: LongWord): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; const Comparer_Vtable_I1: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_I1 ); Comparer_Vtable_U1: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_U1 ); Comparer_Vtable_I2: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_I2 ); Comparer_Vtable_U2: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_U2 ); Comparer_Vtable_I4: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_I4 ); Comparer_Vtable_U4: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_U4 ); Comparer_Instance_I1: Pointer = @Comparer_Vtable_I1; Comparer_Instance_U1: Pointer = @Comparer_Vtable_U1; Comparer_Instance_I2: Pointer = @Comparer_Vtable_I2; Comparer_Instance_U2: Pointer = @Comparer_Vtable_U2; Comparer_Instance_I4: Pointer = @Comparer_Vtable_I4; Comparer_Instance_U4: Pointer = @Comparer_Vtable_U4; EqualityComparer_Vtable_I1: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_I1, @GetHashCode_I1 ); EqualityComparer_Vtable_I2: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_I2, @GetHashCode_I2 ); EqualityComparer_Vtable_I4: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_I4, @GetHashCode_I4 ); EqualityComparer_Instance_I1: Pointer = @EqualityComparer_VTable_I1; EqualityComparer_Instance_I2: Pointer = @EqualityComparer_VTable_I2; EqualityComparer_Instance_I4: Pointer = @EqualityComparer_VTable_I4; function Comparer_Selector_Integer(info: PTypeInfo; size: Integer): Pointer; begin case GetTypeData(info)^.OrdType of otSByte: Result := @Comparer_Instance_I1; otUByte: Result := @Comparer_Instance_U1; otSWord: Result := @Comparer_Instance_I2; otUWord: Result := @Comparer_Instance_U2; otSLong: Result := @Comparer_Instance_I4; otULong: Result := @Comparer_Instance_U4; else System.Error(reRangeError); Exit(nil); end; end; function EqualityComparer_Selector_Integer(info: PTypeInfo; size: Integer): Pointer; begin case GetTypeData(info)^.OrdType of otSByte, otUByte: Result := @EqualityComparer_Instance_I1; otSWord, otUWord: Result := @EqualityComparer_Instance_I2; otSLong, otULong: Result := @EqualityComparer_Instance_I4; else System.Error(reRangeError); Exit(nil); end; end; // I8 & U8 function Equals_I8(Inst: Pointer; const Left, Right: Int64): Boolean; begin Result := Left = Right; end; function GetHashCode_I8(Inst: Pointer; const Value: Int64): Integer; begin Result := BobJenkinsHash(Value, SizeOf(Value), 0); end; function Compare_I8(Inst: Pointer; const Left, Right: Int64): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; function Compare_U8(Inst: Pointer; const Left, Right: UInt64): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; const Comparer_Vtable_I8: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_I8 ); Comparer_Instance_I8: Pointer = @Comparer_Vtable_I8; Comparer_Vtable_U8: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_U8 ); Comparer_Instance_U8: Pointer = @Comparer_Vtable_U8; EqualityComparer_Vtable_I8: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_I8, @GetHashCode_I8 ); EqualityComparer_Instance_I8: Pointer = @EqualityComparer_Vtable_I8; function Comparer_Selector_Int64(info: PTypeInfo; size: Integer): Pointer; begin if GetTypeData(info)^.MaxInt64Value > GetTypeData(info)^.MinInt64Value then Result := @Comparer_Instance_I8 else Result := @Comparer_Instance_U8; end; // Float function Compare_R4(Inst: Pointer; const Left, Right: Single): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; function Equals_R4(Inst: Pointer; const Left, Right: Single): Boolean; begin Result := Left = Right; end; function GetHashCode_R4(Inst: Pointer; const Value: Single): Integer; var m: Extended; e: Integer; begin // Denormalized floats and positive/negative 0.0 complicate things. Frexp(Value, m, e); if m = 0 then m := Abs(m); Result := BobJenkinsHash(m, SizeOf(m), 0); Result := BobJenkinsHash(e, SizeOf(e), Result); end; const Comparer_Vtable_R4: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_R4 ); Comparer_Instance_R4: Pointer = @Comparer_Vtable_R4; EqualityComparer_Vtable_R4: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_R4, @GetHashCode_R4 ); EqualityComparer_Instance_R4: Pointer = @EqualityComparer_Vtable_R4; function Compare_R8(Inst: Pointer; const Left, Right: Double): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; function Equals_R8(Inst: Pointer; const Left, Right: Double): Boolean; begin Result := Left = Right; end; function GetHashCode_R8(Inst: Pointer; const Value: Double): Integer; var m: Extended; e: Integer; begin // Denormalized floats and positive/negative 0.0 complicate things. Frexp(Value, m, e); if m = 0 then m := Abs(m); Result := BobJenkinsHash(m, SizeOf(m), 0); Result := BobJenkinsHash(e, SizeOf(e), Result); end; const Comparer_Vtable_R8: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_R8 ); Comparer_Instance_R8: Pointer = @Comparer_Vtable_R8; EqualityComparer_Vtable_R8: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_R8, @GetHashCode_R8 ); EqualityComparer_Instance_R8: Pointer = @EqualityComparer_Vtable_R8; function Compare_R10(Inst: Pointer; const Left, Right: Extended): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; function Equals_R10(Inst: Pointer; const Left, Right: Extended): Boolean; begin Result := Left = Right; end; function GetHashCode_R10(Inst: Pointer; const Value: Extended): Integer; var m: Extended; e: Integer; begin // Denormalized floats and positive/negative 0.0 complicate things. Frexp(Value, m, e); if m = 0 then m := Abs(m); Result := BobJenkinsHash(m, SizeOf(m), 0); Result := BobJenkinsHash(e, SizeOf(e), Result); end; const Comparer_Vtable_R10: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_R10 ); Comparer_Instance_R10: Pointer = @Comparer_Vtable_R10; EqualityComparer_Vtable_R10: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_R10, @GetHashCode_R10 ); EqualityComparer_Instance_R10: Pointer = @EqualityComparer_Vtable_R10; function Compare_RI8(Inst: Pointer; const Left, Right: Comp): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; function Equals_RI8(Inst: Pointer; const Left, Right: Comp): Boolean; begin Result := Left = Right; end; function GetHashCode_RI8(Inst: Pointer; const Value: Comp): Integer; begin Result := BobJenkinsHash(Value, SizeOf(Value), 0); end; const Comparer_Vtable_RI8: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_RI8 ); Comparer_Instance_RI8: Pointer = @Comparer_Vtable_RI8; EqualityComparer_Vtable_RI8: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_RI8, @GetHashCode_RI8 ); EqualityComparer_Instance_RI8: Pointer = @EqualityComparer_Vtable_RI8; function Compare_RC8(Inst: Pointer; const Left, Right: Currency): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; function Equals_RC8(Inst: Pointer; const Left, Right: Currency): Boolean; begin Result := Left = Right; end; function GetHashCode_RC8(Inst: Pointer; const Value: Currency): Integer; begin Result := BobJenkinsHash(Value, SizeOf(Value), 0); end; const Comparer_Vtable_RC8: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_RC8 ); Comparer_Instance_RC8: Pointer = @Comparer_Vtable_RC8; EqualityComparer_Vtable_RC8: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_RC8, @GetHashCode_RC8 ); EqualityComparer_Instance_RC8: Pointer = @EqualityComparer_Vtable_RC8; function Comparer_Selector_Float(info: PTypeInfo; size: Integer): Pointer; begin case GetTypeData(info)^.FloatType of ftSingle: Result := @Comparer_Instance_R4; ftDouble: Result := @Comparer_Instance_R8; ftExtended: Result := @Comparer_Instance_R10; ftComp: Result := @Comparer_Instance_RI8; ftCurr: Result := @Comparer_Instance_RC8; else System.Error(reRangeError); Exit(nil); end; end; function EqualityComparer_Selector_Float(info: PTypeInfo; size: Integer): Pointer; begin case GetTypeData(info)^.FloatType of ftSingle: Result := @EqualityComparer_Instance_R4; ftDouble: Result := @EqualityComparer_Instance_R8; ftExtended: Result := @EqualityComparer_Instance_R10; ftComp: Result := @EqualityComparer_Instance_RI8; ftCurr: Result := @EqualityComparer_Instance_RC8; else System.Error(reRangeError); Exit(nil); end; end; // Binary function BinaryCompare(const Left, Right: Pointer; Size: Integer): Integer; var pl, pr: PByte; len: Integer; begin pl := Left; pr := Right; len := Size; while len > 0 do begin Result := pl^ - pr^; if Result <> 0 then Exit; Dec(len); Inc(pl); Inc(pr); end; Result := 0; end; function Compare_Binary(Inst: PSimpleInstance; const Left, Right): Integer; begin Result := BinaryCompare(@Left, @Right, Inst^.Size); end; function Equals_Binary(Inst: PSimpleInstance; const Left, Right): Boolean; begin Result := CompareMem(@Left, @Right, Inst^.Size); end; function GetHashCode_Binary(Inst: PSimpleInstance; const Value): Integer; begin Result := BobJenkinsHash(Value, Inst^.Size, 0); end; const Comparer_Vtable_Binary: array[0..3] of Pointer = ( @NopQueryInterface, @MemAddref, @MemRelease, @Compare_Binary ); EqualityComparer_Vtable_Binary: array[0..4] of Pointer = ( @NopQueryInterface, @MemAddref, @MemRelease, @Equals_Binary, @GetHashCode_Binary ); function Comparer_Selector_Binary(info: PTypeInfo; size: Integer): Pointer; begin case size of // NOTE: Little-endianness may cause counterintuitive results, // but the results will at least be consistent. 1: Result := @Comparer_Instance_U1; 2: Result := @Comparer_Instance_U2; 4: Result := @Comparer_Instance_U4; {$IFDEF CPUX64} // 64-bit will pass const args in registers 8: Result := @Comparer_Instance_U8; {$ENDIF} else Result := MakeInstance(@Comparer_Vtable_Binary, size); end; end; function EqualityComparer_Selector_Binary(info: PTypeInfo; size: Integer): Pointer; begin case size of 1: Result := @EqualityComparer_Instance_I1; 2: Result := @EqualityComparer_Instance_I2; 4: Result := @EqualityComparer_Instance_I4; {$IFDEF CPUX64} // 64-bit will pass const args in registers 8: Result := @EqualityComparer_Instance_I8; {$ENDIF} else Result := MakeInstance(@EqualityComparer_Vtable_Binary, size); end; end; // Class (i.e. instances) function Equals_Class(Inst: PSimpleInstance; Left, Right: TObject): Boolean; begin if Left = nil then Result := Right = nil else Result := Left.Equals(Right); end; function GetHashCode_Class(Inst: PSimpleInstance; Value: TObject): Integer; begin if Value = nil then Result := 42 else Result := Value.GetHashCode; end; // DynArray function DynLen(Arr: Pointer): Longint; inline; begin if Arr = nil then Exit(0); Result := PLongint(PByte(Arr) - SizeOf(Longint))^; end; function Compare_DynArray(Inst: PSimpleInstance; Left, Right: Pointer): Integer; var len, lenDiff: Integer; begin len := DynLen(Left); lenDiff := len - DynLen(Right); if lenDiff < 0 then Inc(len, lenDiff); Result := BinaryCompare(Left, Right, Inst^.Size * len); if Result = 0 then Result := lenDiff; end; function Equals_DynArray(Inst: PSimpleInstance; Left, Right: Pointer): Boolean; var lenL, lenR: Longint; begin lenL := DynLen(Left); lenR := DynLen(Right); if lenL <> lenR then Exit(False); Result := CompareMem(Left, Right, Inst^.Size * lenL); end; function GetHashCode_DynArray(Inst: PSimpleInstance; Value: Pointer): Integer; begin Result := BobJenkinsHash(Value^, Inst^.Size * DynLen(Value), 0); end; const Comparer_Vtable_DynArray: array[0..3] of Pointer = ( @NopQueryInterface, @MemAddref, @MemRelease, @Compare_DynArray ); EqualityComparer_Vtable_DynArray: array[0..4] of Pointer = ( @NopQueryInterface, @MemAddref, @MemRelease, @Equals_DynArray, @GetHashCode_DynArray ); function Comparer_Selector_DynArray(info: PTypeInfo; size: Integer): Pointer; begin Result := MakeInstance(@Comparer_Vtable_DynArray, GetTypeData(info)^.elSize); end; function EqualityComparer_Selector_DynArray(info: PTypeInfo; size: Integer): Pointer; begin Result := MakeInstance(@EqualityComparer_Vtable_DynArray, GetTypeData(info)^.elSize); end; // PStrings type TPS1 = string[1]; TPS2 = string[2]; TPS3 = string[3]; function Compare_PS1(Inst: PSimpleInstance; const Left, Right: TPS1): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; function Compare_PS2(Inst: PSimpleInstance; const Left, Right: TPS2): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; function Compare_PS3(Inst: PSimpleInstance; const Left, Right: TPS3): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; function Compare_PSn(Inst: PSimpleInstance; const Left, Right: OpenString): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; function Equals_PS1(Inst: PSimpleInstance; const Left, Right: TPS1): Boolean; begin Result := Left = Right; end; function Equals_PS2(Inst: PSimpleInstance; const Left, Right: TPS2): Boolean; begin Result := Left = Right; end; function Equals_PS3(Inst: PSimpleInstance; const Left, Right: TPS3): Boolean; begin Result := Left = Right; end; function Equals_PSn(Inst: PSimpleInstance; const Left, Right: OpenString): Boolean; begin Result := Left = Right; end; function GetHashCode_PS1(Inst: PSimpleInstance; const Value: TPS1): Integer; begin Result := BobJenkinsHash(Value[1], Length(Value), 0); end; function GetHashCode_PS2(Inst: PSimpleInstance; const Value: TPS2): Integer; begin Result := BobJenkinsHash(Value[1], Length(Value), 0); end; function GetHashCode_PS3(Inst: PSimpleInstance; const Value: TPS3): Integer; begin Result := BobJenkinsHash(Value[1], Length(Value), 0); end; function GetHashCode_PSn(Inst: PSimpleInstance; const Value: OpenString): Integer; begin Result := BobJenkinsHash(Value[1], Length(Value), 0); end; const Comparer_Vtable_PS1: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_PS1 ); Comparer_Instance_PS1: Pointer = @Comparer_Vtable_PS1; Comparer_Vtable_PS2: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_PS2 ); Comparer_Instance_PS2: Pointer = @Comparer_Vtable_PS2; Comparer_Vtable_PS3: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_PS3 ); Comparer_Instance_PS3: Pointer = @Comparer_Vtable_PS3; Comparer_Vtable_PSn: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_PSn ); Comparer_Instance_PSn: Pointer = @Comparer_Vtable_PSn; EqualityComparer_Vtable_PS1: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_PS1, @GetHashCode_PS1 ); EqualityComparer_Instance_PS1: Pointer = @EqualityComparer_Vtable_PS1; EqualityComparer_Vtable_PS2: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_PS2, @GetHashCode_PS2 ); EqualityComparer_Instance_PS2: Pointer = @EqualityComparer_Vtable_PS2; EqualityComparer_Vtable_PS3: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_PS3, @GetHashCode_PS3 ); EqualityComparer_Instance_PS3: Pointer = @EqualityComparer_Vtable_PS3; EqualityComparer_Vtable_PSn: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_PSn, @GetHashCode_PSn ); EqualityComparer_Instance_PSn: Pointer = @EqualityComparer_Vtable_PSn; function Comparer_Selector_String(info: PTypeInfo; size: Integer): Pointer; begin case size of 2: Result := @Comparer_Instance_PS1; 3: Result := @Comparer_Instance_PS2; 4: Result := @Comparer_Instance_PS3; else Result := @Comparer_Instance_PSn; end; end; function EqualityComparer_Selector_String(info: PTypeInfo; size: Integer): Pointer; begin case size of 2: Result := @EqualityComparer_Instance_PS1; 3: Result := @EqualityComparer_Instance_PS2; 4: Result := @EqualityComparer_Instance_PS3; else Result := @EqualityComparer_Instance_PSn; end; end; // LStrings function Compare_LString(Inst: PSimpleInstance; const Left, Right: AnsiString): Integer; begin Result := CompareStr(Left, Right); end; function Equals_LString(Inst: PSimpleInstance; const Left, Right: AnsiString): Boolean; begin Result := Left = Right; end; function GetHashCode_LString(Inst: PSimpleInstance; const Value: AnsiString): Integer; begin Result := BobJenkinsHash(Value[1], Length(Value) * SizeOf(Value[1]), 0); end; // UStrings function Compare_UString(Inst: PSimpleInstance; const Left, Right: UnicodeString): Integer; begin Result := CompareStr(Left, Right); end; function Equals_UString(Inst: PSimpleInstance; const Left, Right: UnicodeString): Boolean; begin Result := Left = Right; end; function GetHashCode_UString(Inst: PSimpleInstance; const Value: UnicodeString): Integer; begin Result := BobJenkinsHash(Value[1], Length(Value) * SizeOf(Value[1]), 0); end; // Methods type TMethodPointer = procedure of object; function Compare_Method(Inst: PSimpleInstance; const Left, Right: TMethodPointer): Integer; begin if PInt64(@Left)^ < PInt64(@Right)^ then Result := -1 else if PInt64(@Left)^ > PInt64(@Right)^ then Result := 1 else Result := 0; end; function Equals_Method(Inst: PSimpleInstance; const Left, Right: TMethodPointer): Boolean; begin Result := (TMethod(Left).Code = TMethod(Right).Code) and (TMethod(Left).Data = TMethod(Right).Data); end; function GetHashCode_Method(Inst: PSimpleInstance; const Value: TMethodPointer): Integer; begin Result := BobJenkinsHash(Value, SizeOf(Value), 0); end; // WStrings function Compare_WString(Inst: PSimpleInstance; const Left, Right: WideString): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; function Equals_WString(Inst: PSimpleInstance; const Left, Right: WideString): Boolean; begin Result := Left = Right; end; function GetHashCode_WString(Inst: PSimpleInstance; const Value: WideString): Integer; begin Result := BobJenkinsHash(Value[1], Length(Value) * SizeOf(Value[1]), 0); end; // Variants function Compare_Variant(Inst: PSimpleInstance; Left, Right: Pointer): Integer; var l, r: Variant; lAsString, rAsString: string; begin Result := 0; // Avoid warning. l := PVariant(Left)^; r := PVariant(Right)^; try case VarCompareValue(l, r) of vrEqual: Exit(0); vrLessThan: Exit(-1); vrGreaterThan: Exit(1); vrNotEqual: begin if VarIsEmpty(L) or VarIsNull(L) then Exit(1) else Exit(-1); end; end; except // if comparison failed with exception, compare as string. try lAsString := PVariant(Left)^; rAsString := PVariant(Right)^; Result := Compare_UString(nil, lAsString, rAsString); except // if comparison fails again, compare bytes. Result := BinaryCompare(Left, Right, SizeOf(Variant)); end; end; end; function Equals_Variant(Inst: PSimpleInstance; Left, Right: Pointer): Boolean; var l, r: Variant; begin l := PVariant(Left)^; r := PVariant(Right)^; Result := VarCompareValue(l, r) = vrEqual; end; function GetHashCode_Variant(Inst: PSimpleInstance; Value: Pointer): Integer; var v: string; begin try v := PVariant(Value)^; Result := GetHashCode_UString(nil, v); except Result := BobJenkinsHash(Value^, SizeOf(Variant), 0); end; end; // Pointers function Compare_Pointer(Inst: PSimpleInstance; Left, Right: NativeUInt): Integer; begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end; function Equals_Pointer(Inst: Pointer; const Left, Right: NativeUInt): Boolean; begin Result := Left = Right; end; function GetHashCode_Pointer(Inst: Pointer; const Value: NativeUInt): Integer; begin Result := BobJenkinsHash(Value, SizeOf(Value), 0); end; const Comparer_Vtable_Pointer: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_Pointer ); Comparer_Vtable_LString: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_LString ); Comparer_Vtable_WString: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_WString ); Comparer_Vtable_Variant: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_Variant ); Comparer_Vtable_UString: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_UString ); Comparer_Vtable_Method: array[0..3] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Compare_Method ); Comparer_Instance_Pointer: Pointer = @Comparer_Vtable_Pointer; Comparer_Instance_LString: Pointer = @Comparer_Vtable_LString; Comparer_Instance_WString: Pointer = @Comparer_Vtable_WString; Comparer_Instance_Variant: Pointer = @Comparer_Vtable_Variant; Comparer_Instance_UString: Pointer = @Comparer_Vtable_UString; Comparer_Instance_Method: Pointer = @Comparer_Vtable_Method; EqualityComparer_Vtable_Pointer: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_Pointer, @GetHashCode_Pointer ); EqualityComparer_Vtable_Class: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_Class, @GetHashCode_Class ); EqualityComparer_Vtable_LString: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_LString, @GetHashCode_LString ); EqualityComparer_Vtable_WString: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_WString, @GetHashCode_WString ); EqualityComparer_Vtable_Variant: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_Variant, @GetHashCode_Variant ); EqualityComparer_Vtable_UString: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_UString, @GetHashCode_UString ); EqualityComparer_Vtable_Method: array[0..4] of Pointer = ( @NopQueryInterface, @NopAddref, @NopRelease, @Equals_Method, @GetHashCode_Method ); EqualityComparer_Instance_Pointer: Pointer = @EqualityComparer_Vtable_Pointer; EqualityComparer_Instance_Class: Pointer = @EqualityComparer_Vtable_Class; EqualityComparer_Instance_LString: Pointer = @EqualityComparer_Vtable_LString; EqualityComparer_Instance_WString: Pointer = @EqualityComparer_Vtable_WString; EqualityComparer_Instance_Variant: Pointer = @EqualityComparer_Vtable_Variant; EqualityComparer_Instance_UString: Pointer = @EqualityComparer_Vtable_UString; EqualityComparer_Instance_Method: Pointer = @EqualityComparer_Vtable_Method; VtableInfo: array[TDefaultGenericInterface, TTypeKind] of TVtableInfo = ( // IComparer ( // tkUnknown (Flags: [ifSelector]; Data: @Comparer_Selector_Binary), // tkInteger (Flags: [ifSelector]; Data: @Comparer_Selector_Integer), // tkChar (Flags: [ifSelector]; Data: @Comparer_Selector_Binary), // tkEnumeration (Flags: [ifSelector]; Data: @Comparer_Selector_Integer), // tkFloat (Flags: [ifSelector]; Data: @Comparer_Selector_Float), // tkString (Flags: [ifSelector]; Data: @Comparer_Selector_String), // tkSet (Flags: [ifSelector]; Data: @Comparer_Selector_Binary), // tkClass (Flags: []; Data: @Comparer_Instance_Pointer), // tkMethod (Flags: []; Data: @Comparer_Instance_Method), // tkWChar (Flags: [ifSelector]; Data: @Comparer_Selector_Binary), // tkLString (Flags: []; Data: @Comparer_Instance_LString), // tkWString (Flags: []; Data: @Comparer_Instance_WString), // tkVariant (Flags: []; Data: @Comparer_Instance_Variant), // tkArray (Flags: [ifSelector]; Data: @Comparer_Selector_Binary), // tkRecord (Flags: [ifSelector]; Data: @Comparer_Selector_Binary), // tkInterface (Flags: []; Data: @Comparer_Instance_Pointer), // tkInt64 (Flags: [ifSelector]; Data: @Comparer_Selector_Int64), // tkDynArray (Flags: [ifSelector]; Data: @Comparer_Selector_DynArray), // tkUString (Flags: []; Data: @Comparer_Instance_UString), // tkClassRef (Flags: []; Data: @Comparer_Instance_Pointer), // tkPointer (Flags: []; Data: @Comparer_Instance_Pointer), // tkProcedure (Flags: []; Data: @Comparer_Instance_Pointer) ), // IEqualityComparer ( // tkUnknown (Flags: [ifSelector]; Data: @EqualityComparer_Selector_Binary), // tkInteger (Flags: [ifSelector]; Data: @EqualityComparer_Selector_Integer), // tkChar (Flags: [ifSelector]; Data: @EqualityComparer_Selector_Binary), // tkEnumeration (Flags: [ifSelector]; Data: @EqualityComparer_Selector_Integer), // tkFloat (Flags: [ifSelector]; Data: @EqualityComparer_Selector_Float), // tkString (Flags: [ifSelector]; Data: @EqualityComparer_Selector_String), // tkSet (Flags: [ifSelector]; Data: @EqualityComparer_Selector_Binary), // tkClass (Flags: []; Data: @EqualityComparer_Instance_Class), // tkMethod (Flags: []; Data: @EqualityComparer_Instance_Method), // tkWChar (Flags: [ifSelector]; Data: @EqualityComparer_Selector_Binary), // tkLString (Flags: []; Data: @EqualityComparer_Instance_LString), // tkWString (Flags: []; Data: @EqualityComparer_Instance_WString), // tkVariant (Flags: []; Data: @EqualityComparer_Instance_Variant), // tkArray (Flags: [ifSelector]; Data: @EqualityComparer_Selector_Binary), // tkRecord (Flags: [ifSelector]; Data: @EqualityComparer_Selector_Binary), // tkInterface (Flags: []; Data: @EqualityComparer_Instance_Pointer), // tkInt64 (Flags: []; Data: @EqualityComparer_Instance_I8), // tkDynArray (Flags: [ifSelector]; Data: @EqualityComparer_Selector_DynArray), // tkUString (Flags: []; Data: @EqualityComparer_Instance_UString), // tkClassRef (Flags: []; Data: @EqualityComparer_Instance_Pointer), // tkPointer (Flags: []; Data: @EqualityComparer_Instance_Pointer), // tkProcedure (Flags: []; Data: @EqualityComparer_Instance_Pointer) ) ); function _LookupVtableInfo(intf: TDefaultGenericInterface; info: PTypeInfo; size: Integer): Pointer; var pinfo: PVtableInfo; begin if info <> nil then begin pinfo := @VtableInfo[intf, info^.Kind]; Result := pinfo^.Data; if ifSelector in pinfo^.Flags then Result := TTypeInfoSelector(Result)(info, size); if ifVariableSize in pinfo^.Flags then Result := MakeInstance(Result, size); end else begin case intf of giComparer: Result := Comparer_Selector_Binary(info, size); giEqualityComparer: Result := EqualityComparer_Selector_Binary(info, size); else System.Error(reRangeError); Result := nil; end; end; end; { TSingletonImplementation } function TSingletonImplementation.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TSingletonImplementation._AddRef: Integer; begin Result := -1; end; function TSingletonImplementation._Release: Integer; begin Result := -1; end; { Delegated Comparers } constructor TDelegatedEqualityComparer<T>.Create(const AEquals: TEqualityComparison<T>; const AGetHashCode: THasher<T>); begin FEquals := AEquals; FGetHashCode := AGetHashCode; end; function TDelegatedEqualityComparer<T>.Equals(const Left, Right: T): Boolean; begin Result := FEquals(Left, Right); end; function TDelegatedEqualityComparer<T>.GetHashCode(const Value: T): Integer; begin Result := FGetHashCode(Value); end; constructor TDelegatedComparer<T>.Create(const ACompare: TComparison<T>); begin FCompare := ACompare; end; function TDelegatedComparer<T>.Compare(const Left, Right: T): Integer; begin Result := FCompare(Left, Right); end; { TOrdinalStringComparer } type TOrdinalStringComparer = class(TStringComparer) public function Compare(const Left, Right: string): Integer; override; function Equals(const Left, Right: string): Boolean; reintroduce; overload; override; function GetHashCode(const Value: string): Integer; reintroduce; overload; override; end; function TOrdinalStringComparer.Compare(const Left, Right: string): Integer; var len, lenDiff: Integer; begin len := Length(Left); lenDiff := len - Length(Right); if lenDiff < 0 then Inc(len, lenDiff); Result := BinaryCompare(PChar(Left), PChar(Right), len * SizeOf(Char)); if Result = 0 then Exit(lenDiff); end; function TOrdinalStringComparer.Equals(const Left, Right: string): Boolean; var len: Integer; begin len := Length(Left); Result := (len - Length(Right) = 0) and CompareMem(PChar(Left), PChar(Right), len * SizeOf(Char)); end; function TOrdinalStringComparer.GetHashCode(const Value: string): Integer; begin Result := BobJenkinsHash(PChar(Value)^, SizeOf(Char) * Length(Value), 0); end; { TStringComparer } class function TStringComparer.Ordinal: TStringComparer; begin if FOrdinal = nil then FOrdinal := TOrdinalStringComparer.Create; Result := TStringComparer(FOrdinal); end; { TOrdinalIStringComparer } type TOrdinalIStringComparer = class(TStringComparer) public function Compare(const Left, Right: string): Integer; override; function Equals(const Left, Right: string): Boolean; reintroduce; overload; override; function GetHashCode(const Value: string): Integer; reintroduce; overload; override; end; function TOrdinalIStringComparer.Compare(const Left, Right: string): Integer; var L, R: string; len, lenDiff: Integer; begin L := AnsiLowerCase(Left); R := AnsiLowerCase(Right); len := Length(L); lenDiff := len - Length(R); if lenDiff < 0 then Inc(len, lenDiff); Result := BinaryCompare(PChar(L), PChar(R), len * SizeOf(Char)); if Result = 0 then Exit(lenDiff); end; function TOrdinalIStringComparer.Equals(const Left, Right: string): Boolean; var len: Integer; L, R: string; begin L := AnsiLowerCase(Left); R := AnsiLowerCase(Right); len := Length(L); Result := (len - Length(R) = 0) and CompareMem(PChar(L), PChar(R), len * SizeOf(Char)); end; function TOrdinalIStringComparer.GetHashCode(const Value: string): Integer; var S: string; begin S := AnsiLowerCase(Value); Result := BobJenkinsHash(PChar(S)^, SizeOf(Char) * Length(S), 0); end; { TIStringComparer } class function TIStringComparer.Ordinal: TStringComparer; begin if FOrdinal = nil then FOrdinal := TOrdinalIStringComparer.Create; Result := TStringComparer(FOrdinal); end; function ExtendedHashImpl(Value: Extended): Integer; var m: Extended; e: Integer; begin // Denormalized floats and positive/negative 0.0 complicate things. Frexp(Value, m, e); if m = 0 then m := Abs(m); Result := BobJenkinsHash(m, SizeOf(m), 0); Result := BobJenkinsHash(e, SizeOf(e), Result); end; function ExtendedHash(Value: Pointer; Size: Integer): Integer; begin Result := ExtendedHashImpl(PExtended(Value)^); end; function DoubleHash(Value: Pointer; Size: Integer): Integer; begin Result := ExtendedHashImpl(PDouble(Value)^); end; function SingleHash(Value: Pointer; Size: Integer): Integer; begin Result := ExtendedHashImpl(PSingle(Value)^); end; { TComparer<T> } class function TComparer<T>.Default: IComparer<T>; begin Result := IComparer<T>(_LookupVtableInfo(giComparer, TypeInfo(T), SizeOf(T))); end; class function TComparer<T>.Construct(const Comparison: TComparison<T>): IComparer<T>; begin Result := TDelegatedComparer<T>.Create(Comparison); end; { TEqualityComparer<T> } class function TEqualityComparer<T>.Default: IEqualityComparer<T>; begin Result := IEqualityComparer<T>(_LookupVtableInfo(giEqualityComparer, TypeInfo(T), SizeOf(T))); end; class function TEqualityComparer<T>.Construct( const EqualityComparison: TEqualityComparison<T>; const Hasher: THasher<T>): IEqualityComparer<T>; begin Result := TDelegatedEqualityComparer<T>.Create( EqualityComparison, Hasher); end; { BobJenkinsHash } function Rot(x, k: Cardinal): Cardinal; inline; begin Result := (x shl k) or (x shr (32 - k)); end; procedure Mix(var a, b, c: Cardinal); inline; begin Dec(a, c); a := a xor Rot(c, 4); Inc(c, b); Dec(b, a); b := b xor Rot(a, 6); Inc(a, c); Dec(c, b); c := c xor Rot(b, 8); Inc(b, a); Dec(a, c); a := a xor Rot(c,16); Inc(c, b); Dec(b, a); b := b xor Rot(a,19); Inc(a, c); Dec(c, b); c := c xor Rot(b, 4); Inc(b, a); end; procedure Final(var a, b, c: Cardinal); inline; begin c := c xor b; Dec(c, Rot(b,14)); a := a xor c; Dec(a, Rot(c,11)); b := b xor a; Dec(b, Rot(a,25)); c := c xor b; Dec(c, Rot(b,16)); a := a xor c; Dec(a, Rot(c, 4)); b := b xor a; Dec(b, Rot(a,14)); c := c xor b; Dec(c, Rot(b,24)); end; {$POINTERMATH ON} // http://burtleburtle.net/bob/c/lookup3.c function HashLittle(const Data; Len, InitVal: Integer): Integer; var pb: PByte; pd: PCardinal absolute pb; a, b, c: Cardinal; label case_1, case_2, case_3, case_4, case_5, case_6, case_7, case_8, case_9, case_10, case_11, case_12; begin a := Cardinal($DEADBEEF) + Cardinal(Len shl 2) + Cardinal(InitVal); b := a; c := a; pb := @Data; // 4-byte aligned data if (Cardinal(pb) and 3) = 0 then begin while Len > 12 do begin Inc(a, pd[0]); Inc(b, pd[1]); Inc(c, pd[2]); Mix(a, b, c); Dec(Len, 12); Inc(pd, 3); end; case Len of 0: Exit(Integer(c)); 1: Inc(a, pd[0] and $FF); 2: Inc(a, pd[0] and $FFFF); 3: Inc(a, pd[0] and $FFFFFF); 4: Inc(a, pd[0]); 5: begin Inc(a, pd[0]); Inc(b, pd[1] and $FF); end; 6: begin Inc(a, pd[0]); Inc(b, pd[1] and $FFFF); end; 7: begin Inc(a, pd[0]); Inc(b, pd[1] and $FFFFFF); end; 8: begin Inc(a, pd[0]); Inc(b, pd[1]); end; 9: begin Inc(a, pd[0]); Inc(b, pd[1]); Inc(c, pd[2] and $FF); end; 10: begin Inc(a, pd[0]); Inc(b, pd[1]); Inc(c, pd[2] and $FFFF); end; 11: begin Inc(a, pd[0]); Inc(b, pd[1]); Inc(c, pd[2] and $FFFFFF); end; 12: begin Inc(a, pd[0]); Inc(b, pd[1]); Inc(c, pd[2]); end; end; end else begin // Ignoring rare case of 2-byte aligned data. This handles all other cases. while Len > 12 do begin Inc(a, pb[0] + pb[1] shl 8 + pb[2] shl 16 + pb[3] shl 24); Inc(b, pb[4] + pb[5] shl 8 + pb[6] shl 16 + pb[7] shl 24); Inc(c, pb[8] + pb[9] shl 8 + pb[10] shl 16 + pb[11] shl 24); Mix(a, b, c); Dec(Len, 12); Inc(pb, 12); end; case Len of 0: Exit(c); 1: goto case_1; 2: goto case_2; 3: goto case_3; 4: goto case_4; 5: goto case_5; 6: goto case_6; 7: goto case_7; 8: goto case_8; 9: goto case_9; 10: goto case_10; 11: goto case_11; 12: goto case_12; end; case_12: Inc(c, pb[11] shl 24); case_11: Inc(c, pb[10] shl 16); case_10: Inc(c, pb[9] shl 8); case_9: Inc(c, pb[8]); case_8: Inc(b, pb[7] shl 24); case_7: Inc(b, pb[6] shl 16); case_6: Inc(b, pb[5] shl 8); case_5: Inc(b, pb[4]); case_4: Inc(a, pb[3] shl 24); case_3: Inc(a, pb[2] shl 16); case_2: Inc(a, pb[1] shl 8); case_1: Inc(a, pb[0]); end; Final(a, b, c); Result := Integer(c); end; function BobJenkinsHash(const Data; Len, InitData: Integer): Integer; begin Result := HashLittle(Data, Len, InitData); end; end.
Unit RemDiskDll; {$MINENUMSIZE 4} Interface Uses Windows; Const REMDISK_FLAG_WRITABLE = $1; REMDISK_FLAG_COPY_ON_WRITE = $2; REMDISK_FLAG_ALLOCATED = $4; REMDISK_FLAG_SAVE_ON_STOP = $8; REMDISK_FLAG_ENCRYPTED = $10; REMDISK_FLAG_OFFLINE = $20; REMDISK_FLAG_FILE_SOURCE = $80; REMDISK_FLAG_SPARSE_FILE = $100; REMBUS_FLAG_SUPPORTS_PLAIN_RAM_DISKS = $1; REMBUS_FLAG_SUPPORTS_PLAIN_FILE_DISKS = $2; REMBUS_FLAG_SUPPORTS_ENCRYPTED_RAM_DISKS = $4; REMBUS_FLAG_SUPPORTS_ENCRYPTED_FILE_DISKS = $8; REMBUS_FLAG_SUPPORTS_EF_RAM_DISKS = $10; REMBUS_FLAG_SUPPORTS_EF_FILE_DISKS = $20; Type _REM_DRIVERS_INFO = Record Flags : Cardinal; BusMajorVersion : Cardinal; BusMinorVersion : Cardinal; DiskMajorVersion : Cardinal; DiskMinorVersion : Cardinal; end; REM_DRIVERS_INFO = _REM_DRIVERS_INFO; PREM_DRIVERS_INFO = ^REM_DRIVERS_INFO; _ERemBusConnectionMode = (rbcmReadOnly, rbcmReadWrite); ERemBusConnectionMode = _ERemBusConnectionMode; PERemBusConnectionMode = ^ERemBusConnectionMode; _EREmDiskInfoState = ( rdisInitialized, rdisWorking, rdisEncrypting, rdisDecrypting, rdisLoading, rdisSaving, rdisPasswordChange, rdisRemoved, rdisSurpriseRemoval ); EREmDiskInfoState = _EREmDiskInfoState; PEREmDiskInfoState = ^EREmDiskInfoState; _EREMDiskType = (rdtRAMDisk, rdtFileDisk); EREMDiskType = _EREMDiskType; PEREMDiskType = ^EREMDiskType; _REMDISK_INFO = Record DiskNumber : Cardinal; DiskType : EREMDiskType; DiskSize : UInt64; Flags : Cardinal; State : EREmDiskInfoState; FileName : PWideChar; end; REMDISK_INFO = _REMDISK_INFO; PREMDISK_INFO = ^REMDISK_INFO; Function DllRemDiskInstall(ABusDriverINFPath:PWideChar):Cardinal; StdCall; Function DllRemDiskCreate(ADiskNumber:Cardinal; ADiskType:EREMDiskType; ADiskSize:UInt64; AFileName:PWideChar; AShareMode:Cardinal; AFlags:Cardinal; APassword:Pointer; APasswordLength:NativeUInt):Cardinal; StdCall; Function DllRemDiskOpen(ADiskNumber:Cardinal; ADiskType:EREMDiskType; AFileName:PWideChar; AShareMode:Cardinal; AFlags:Cardinal; APassword:PWideChar; APasswordLength:NativeUInt):Cardinal; StdCall; Function DllRemDiskChangePassword(ADiskNumber:Cardinal; ANewPassword:Pointer; ANewPasswordLength:NativeUInt; AOldPassword:Pointer; AOldPasswordLength:NativeUInt):Cardinal; StdCall; Function DllRemDiskEncrypt(ADiskNumber:Cardinal; APassword:Pointer; APasswordLength:NativeUInt; AFooter:ByteBool):Cardinal; StdCall; Function DllRemDiskDecrypt(ADiskNumber:Cardinal; APassword:Pointer; APasswordLength:NativeUInt):Cardinal; StdCall; Function DllRemDiskFree(ADiskNumber:Cardinal):Cardinal; StdCall; Function DllRemDiskEnumerate(Var AArray:PREMDISK_INFO; Var ACount:Cardinal):Cardinal; StdCall; Procedure DllRemDiskEnumerationFree(AArray:PREMDISK_INFO; ACount:Cardinal); StdCall; Function DllRemDiskGetInfo(ADiskNumber:Cardinal; Var AInfo:REMDISK_INFO):Cardinal; StdCall; Procedure DllRemDiskInfoFree(Var AInfo:REMDISK_INFO); StdCall; Function DllRemDiskLoadFile(ADiskNumber:Cardinal; AFileName:PWideChar; AShareMode:Cardinal):Cardinal; StdCall; Function DllRemDiskSaveFile(ADiskNumber:cardinal; AFileName:PWideChar; AShareMode:Cardinal):Cardinal; StdCall; Function DllRemBusConnect(AMode:ERemBusConnectionMode; Var ADriversInfo:REM_DRIVERS_INFO):Cardinal; StdCall; Procedure DllRemBusDisconnect; StdCall; Implementation Const LibraryName = 'remdisk.dll'; {$IFNDEF WIN32} Function DllRemDiskInstall(ABusDriverINFPath:PWideChar):Cardinal; StdCall; External LibraryName; Function DllRemDiskCreate(ADiskNumber:Cardinal; ADiskType:EREMDiskType; ADiskSize:UInt64; AFileName:PWideChar; AShareMode:Cardinal; AFlags:Cardinal; APassword:Pointer; APasswordLength:NativeUInt):Cardinal; StdCall; External LibraryName; Function DllRemDiskOpen(ADiskNumber:Cardinal; ADiskType:EREMDiskType; AFileName:PWideChar; AShareMode:Cardinal; AFlags:Cardinal; APassword:PWideChar; APasswordLength:NativeUInt):Cardinal; StdCall; External LibraryName; Function DllRemDiskChangePassword(ADiskNumber:Cardinal; ANewPassword:Pointer; ANewPasswordLength:NativeUInt; AOldPassword:Pointer; AOldPasswordLength:NativeUInt):Cardinal; StdCall; External LibraryName; Function DllRemDiskEncrypt(ADiskNumber:Cardinal; APassword:Pointer; APasswordLength:NativeUInt; AFooter:ByteBool):Cardinal; StdCall; External LibraryName; Function DllRemDiskDecrypt(ADiskNumber:Cardinal; APassword:Pointer; APasswordLength:NativeUInt):Cardinal; StdCall; External LibraryName; Function DllRemDiskFree(ADiskNumber:Cardinal):Cardinal; StdCall; External LibraryName; Function DllRemDiskEnumerate(Var AArray:PREMDISK_INFO; Var ACount:Cardinal):Cardinal; StdCall; External LibraryName; Procedure DllRemDiskEnumerationFree(AArray:PREMDISK_INFO; ACount:Cardinal); StdCall; External LibraryName; Function DllRemDiskGetInfo(ADiskNumber:Cardinal; Var AInfo:REMDISK_INFO):Cardinal; StdCall; External LibraryName; Procedure DllRemDiskInfoFree(Var AInfo:REMDISK_INFO); StdCall; External LibraryName; Function DllRemDiskLoadFile(ADiskNumber:Cardinal; AFileName:PWideChar; AShareMode:Cardinal):Cardinal; StdCall; External LibraryName; Function DllRemDiskSaveFile(ADiskNumber:cardinal; AFileName:PWideChar; AShareMode:Cardinal):Cardinal; StdCall; External LibraryName; Function DllRemBusConnect(AMode:ERemBusConnectionMode; Var ADriversInfo:REM_DRIVERS_INFO):Cardinal; StdCall; External LibraryName; Procedure DllRemBusDisconnect; StdCall; External LibraryName; {$ELSE} Function DllRemDiskInstall(ABusDriverINFPath:PWideChar):Cardinal; StdCall; External LibraryName name '_DllRemDiskInstall@4'; Function DllRemDiskCreate(ADiskNumber:Cardinal; ADiskType:EREMDiskType; ADiskSize:UInt64; AFileName:PWideChar; AShareMode:Cardinal; AFlags:Cardinal; APassword:Pointer; APasswordLength:NativeUInt):Cardinal; StdCall; External LibraryName name '_DllRemDiskCreate@36'; Function DllRemDiskOpen(ADiskNumber:Cardinal; ADiskType:EREMDiskType; AFileName:PWideChar; AShareMode:Cardinal; AFlags:Cardinal; APassword:PWideChar; APasswordLength:NativeUInt):Cardinal; StdCall; External LibraryName name '_DllRemDiskOpen@28'; Function DllRemDiskChangePassword(ADiskNumber:Cardinal; ANewPassword:Pointer; ANewPasswordLength:NativeUInt; AOldPassword:Pointer; AOldPasswordLength:NativeUInt):Cardinal; StdCall; External LibraryName name '_DllRemDiskChangePassword@20'; Function DllRemDiskEncrypt(ADiskNumber:Cardinal; APassword:Pointer; APasswordLength:NativeUInt; AFooter:ByteBool):Cardinal; StdCall; External LibraryName name '_DllRemDiskEncrypt@16'; Function DllRemDiskDecrypt(ADiskNumber:Cardinal; APassword:Pointer; APasswordLength:NativeUInt):Cardinal; StdCall; External LibraryName name '_DllRemDiskDecrypt@12'; Function DllRemDiskFree(ADiskNumber:Cardinal):Cardinal; StdCall; External LibraryName name '_DllRemDiskFree@4'; Function DllRemDiskEnumerate(Var AArray:PREMDISK_INFO; Var ACount:Cardinal):Cardinal; StdCall; External LibraryName name '_DllRemDiskEnumerate@8'; Procedure DllRemDiskEnumerationFree(AArray:PREMDISK_INFO; ACount:Cardinal); StdCall; External LibraryName name '_DllRemDiskEnumerationFree@8'; Function DllRemDiskGetInfo(ADiskNumber:Cardinal; Var AInfo:REMDISK_INFO):Cardinal; StdCall; External LibraryName name '_DllRemDiskGetInfo@8'; Procedure DllRemDiskInfoFree(Var AInfo:REMDISK_INFO); StdCall; External LibraryName name '_DllRemDiskInfoFree@4'; Function DllRemDiskLoadFile(ADiskNumber:Cardinal; AFileName:PWideChar; AShareMode:Cardinal):Cardinal; StdCall; External LibraryName name '_DllRemDiskLoadFile@12'; Function DllRemDiskSaveFile(ADiskNumber:cardinal; AFileName:PWideChar; AShareMode:Cardinal):Cardinal; StdCall; External LibraryName name '_DllRemDiskSaveFile@12'; Function DllRemBusConnect(AMode:ERemBusConnectionMode; Var ADriversInfo:REM_DRIVERS_INFO):Cardinal; StdCall; External LibraryName name '_DllRemBusConnect@8'; Procedure DllRemBusDisconnect; StdCall; External LibraryName name '_DllRemBusDisconnect@0'; {$ENDIF} End.
unit xProtocolDev; interface uses System.Types, xTypes, xConsts, System.Classes, xFunction, system.SysUtils, xVCL_FMX, System.DateUtils; type /// <summary> /// 通讯设备基类 /// </summary> TProtocolDevBase = class private FControlAdd: Integer; FSN: String; FVersion: string; FOwnerDEV: TObject; protected procedure SetSN(const Value: String); virtual; procedure SetControlAdd(const Value: Integer); virtual; public constructor Create; virtual; procedure Assign(Source: TObject); virtual; /// <summary> /// 设备序号 /// </summary> property SN : String read FSN write SetSN; /// <summary> /// 控制地址 /// </summary> property ControlAdd : Integer read FControlAdd write SetControlAdd; /// <summary> /// 版本 /// </summary> property Version : string read FVersion write FVersion; /// <summary> /// 所有者 /// </summary> property OwnerDEV : TObject read FOwnerDEV write FOwnerDEV; end; type /// <summary> /// 语音对象 /// </summary> TVoice = class(TProtocolDevBase) private FVoiceType: Integer; public constructor Create; override; /// <summary> /// 语音提示类型 /// 考试时间开始 01 /// 考试时间到 02 /// 考试时间还剩十分钟 03 /// 考试时间还剩五分钟 04 /// </summary> property VoiceType : Integer read FVoiceType write FVoiceType; end; type TMinuteLeftEvent = procedure(nMinuteLeft: Integer) of object; type /// <summary> /// 时钟类型 /// </summary> TWorkTimerType = ( ttClock, // 时钟 ttPosTimer, // 正计时 ttRevTimer // 倒计时 ); /// <summary> /// 获取计时类型名称 /// </summary> function GetTimerTypeName( AType : TWorkTimerType ) : string; type /// <summary> /// 计时器 /// </summary> TPDTimer = class( TProtocolDevBase ) private FEnabled: Boolean; FWorkType: TWorkTimerType; FOnMinuteLeft: TMinuteLeftEvent; FCurrentTime: TDateTime; FStartTime : TDateTime; // 开始时间 FPauseTimeStart : TDateTime; // 暂停开始时间 FPauseTimeValue : TDateTime; // 暂停总时间 FPaused: Boolean; procedure SetEnabled(const Value: Boolean); procedure SetWorkType(const Value: TWorkTimerType); procedure SetPaused(const Value: Boolean); /// <summary> /// 清除计时临时对象 /// </summary> procedure ClearTime; function GetCurrentTime: TDateTime; procedure SetCurrentTime(const Value: TDateTime); protected /// <summary> /// 内部定时器 /// </summary> Timer : TMyTimer; /// <summary> /// 内部定时器计时 /// </summary> procedure OnTimer( Sender : TObject ); /// <summary> /// 更新时间 /// </summary> procedure UpdateTime; public constructor Create; override; destructor Destroy; override; public /// <summary> /// 计时方式 /// </summary> property WorkType : TWorkTimerType read FWorkType write SetWorkType; /// <summary> /// 是否启动计时 /// </summary> property Enabled : Boolean read FEnabled write SetEnabled; /// <summary> /// 当前的时间 /// </summary> property CurrentTime : TDateTime read GetCurrentTime write SetCurrentTime; /// <summary> /// 暂停 /// </summary> property Paused : Boolean read FPaused write SetPaused; /// <summary> /// 剩余时间提示 只有倒计时才有 /// </summary> property OnSecLeft: TMinuteLeftEvent read FOnMinuteLeft write FOnMinuteLeft; end; implementation { TProtocolDevBase } procedure TProtocolDevBase.Assign(Source: TObject); begin Assert(Source is TProtocolDevBase); FControlAdd := TProtocolDevBase(Source).ControlAdd; FSN := TProtocolDevBase(Source).SN; FVersion := TProtocolDevBase(Source).Version; end; constructor TProtocolDevBase.Create; begin FControlAdd := -1; end; procedure TProtocolDevBase.SetControlAdd(const Value: Integer); begin FControlAdd := Value; end; procedure TProtocolDevBase.SetSN(const Value: String); begin FSN := Value; end; { TVoice } constructor TVoice.Create; begin inherited; FVoiceType := 0; end; { TPDTimer } function GetTimerTypeName( AType : TWorkTimerType ) : string; begin case AType of ttClock: Result := '时钟'; ttPosTimer: Result := '正计时'; ttRevTimer: Result := '倒计时'; else Result := '未定义'; end; end; procedure TPDTimer.ClearTime; begin FStartTime := 0; FPauseTimeStart := 0; FPauseTimeValue := 0; end; constructor TPDTimer.Create; begin inherited; Timer := TMyTimer.Create( nil ); Timer.Enabled := False; Timer.OnTimer := OnTimer; FEnabled := False; FWorkType := ttClock; FCurrentTime := 0; ClearTime; end; destructor TPDTimer.Destroy; begin Timer.Free; inherited; end; function TPDTimer.GetCurrentTime: TDateTime; begin if FEnabled then begin case FWorkType of ttClock: Result := Now; ttPosTimer: begin if FPaused then begin Result := FPauseTimeStart - FStartTime - FPauseTimeValue + FCurrentTime; end else begin Result := Now - FStartTime - FPauseTimeValue + FCurrentTime; end; end; ttRevTimer: begin if FPaused then begin Result := FCurrentTime - (FPauseTimeStart - FStartTime - FPauseTimeValue); end else begin Result := FCurrentTime - (Now - FStartTime - FPauseTimeValue); end; end; else Result := FCurrentTime; end; end else begin Result := FCurrentTime; end; end; procedure TPDTimer.OnTimer(Sender: TObject); begin UpdateTime; end; procedure TPDTimer.SetCurrentTime(const Value: TDateTime); begin if not FEnabled then begin FCurrentTime := Value; end; end; procedure TPDTimer.SetEnabled(const Value: Boolean); begin FEnabled := Value; Timer.Enabled := FEnabled; if FEnabled then begin ClearTime; FStartTime := Now; end; end; procedure TPDTimer.SetPaused(const Value: Boolean); begin if FWorkType <> ttClock then begin if FEnabled then begin FPaused := Value; if FPaused then begin FPauseTimeStart := now; end else begin FPauseTimeValue := FPauseTimeValue + Now - FPauseTimeStart; end; end; end; end; procedure TPDTimer.SetWorkType(const Value: TWorkTimerType); begin FWorkType := Value; end; procedure TPDTimer.UpdateTime; var dtTemp : TDateTime; begin if not Enabled then Exit; if FWorkType = ttRevTimer then begin dtTemp := CurrentTime; if SecondOf(dtTemp) = 0 then begin if Assigned(FOnMinuteLeft) then begin FOnMinuteLeft(MinuteOfTheDay(dtTemp)); end; end; end; end; end.
{*********************************************} { TeeBI Software Library } { Expression Editor } { Copyright (c) 2015-2016 by Steema Software } { All Rights Reserved } {*********************************************} unit VCLBI.Editor.Expression; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Buttons, VCLBI.DataControl, VCLBI.Tree, BI.Expression, VCLBI.Editor.Completion; type TExpressionEditor = class(TForm) PanelFunctions: TPanel; BITree1: TBITree; Panel2: TPanel; Splitter1: TSplitter; PanelButtons: TPanel; Panel9: TPanel; BOK: TButton; BCancel: TButton; PageControl1: TPageControl; TabExpression: TTabSheet; PanelError: TPanel; LError: TLabel; EditExp: TMemo; TabTree: TTabSheet; BITree2: TBITree; Panel4: TPanel; Label2: TLabel; LValue: TLabel; BDelete: TButton; Panel1: TPanel; Label1: TLabel; SBToogle: TSpeedButton; procedure Panel2Resize(Sender: TObject); procedure EditExpChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BITree2DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure BITree2DragDrop(Sender, Source: TObject; X, Y: Integer); procedure FormDestroy(Sender: TObject); procedure BDeleteClick(Sender: TObject); procedure BITree2Change(Sender: TObject); procedure EditExpKeyPress(Sender: TObject; var Key: Char); procedure PageControl1Change(Sender: TObject); procedure SBToogleClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure EditExpKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } FOnChange : TNotifyEvent; FOnGetFields : TCompleteEvent; IChanging : Boolean; NilReference, IExp : TExpression; Old : TPoint; Completion : TExpressionCompletion; CompletionHandled : Boolean; procedure AddCompletionItems; procedure AddPredefined; procedure Complete(Sender:TObject; const Text:String); procedure CompletionGetFields(Sender: TObject; const Text: String); procedure CompletionResized(Sender:TObject); procedure DeletedNode(Sender: TObject); procedure FillTree(const ATree:TBITree; const AExpression:TExpression); function IsValid(const AExpression:TExpression):Boolean; procedure NilReferences(const AExpression: TExpression); function ParseExpression(const S:String):TExpression; procedure RefreshEdit(const AExpression: TExpression); procedure RefreshTree; procedure RefreshValue(const AExpression:TExpression); procedure SetupCompletionSize; public { Public declarations } Resolver : TResolveProc; procedure AddFields(const AItems:Array of String); class function Edit(const AOwner:TComponent; var AExpression:TExpression; const AResolver:TResolveProc=nil):Boolean; static; class function Embedd(const AOwner:TComponent; const AParent:TWinControl):TExpressionEditor; static; function ParseError(const APos:Integer; const AMessage:String):Boolean; procedure Refresh(const AExpression:TExpression); property Expression:TExpression read IExp; property OnChange:TNotifyEvent read FOnChange write FOnChange; property OnGetFields:TCompleteEvent read FOnGetFields write FOnGetFields; end; implementation
{*******************************************************} { } { Borland Delphi Visual Component Library } { Interface RTTI Support } { } { Copyright (c) 2001 Borland Software Corporation } { } {*******************************************************} Unit IntfInfo; interface uses TypInfo, SysUtils; type PIntfParamEntry = ^TIntfParamEntry; TIntfParamEntry = record Flags: TParamFlags; Name: string; Info: PTypeInfo; end; TIntfParamEntryArray = array of TIntfParamEntry; TCallConv = (ccReg, ccCdecl, ccPascal, ccStdCall, ccSafeCall); PIntfMethEntry = ^TIntfMethEntry; TIntfMethEntry = record Name: string; CC: TCallConv; Pos: Integer; ParamCount: Integer; ResultInfo: PTypeInfo; SelfInfo: PTypeInfo; Params: TIntfParamEntryArray; HasRTTI: Boolean; end; TIntfMethEntryArray = array of TIntfMethEntry; TPIntfMethEntryArray = array of PIntfMethEntry; PIntfMetaData = ^TIntfMetaData; TIntfMetaData = record Name: string; UnitName: string; MDA: TIntfMethEntryArray; IID: TGUID; Info: PTypeInfo; AncInfo: PTypeInfo; NumAnc: Integer; end; EInterfaceRTTIException = class(Exception); procedure GetIntfMetaData(Info: PTypeInfo; var IntfMD: TIntfMetaData; IncludeAncMethods: Boolean = False); function GetMethNum(const IntfMD: TIntfMetaData; const MethName: string): Integer; procedure GetDynArrayElTypeInfo(typeInfo: PTypeInfo; var EltInfo: PTypeInfo; var Dims: Integer); function GetDynArrayNextInfo(typeInfo: PTypeInfo): PTypeInfo; const CallingConventionName: array[ccReg..ccSafeCall] of string = ('REGISTER', 'CDECL', 'PASCAL', 'STDCALL', 'SAFECALL'); { do not localize } function GetDynArrayNextInfo2(typeInfo: PTypeInfo; var Name: string): PTypeInfo; resourcestring SNoRTTI = 'Interface %s has no RTTI'; SNoRTTIParam = 'Parameter %s on Method %s of Interface %s has no RTTI'; implementation const CCMap: array[0..4] of TCallConv = (ccReg, ccCdecl, ccPascal, ccStdCall, ccSafeCall); function GetMethNum(const IntfMD: TIntfMetaData; const MethName: string): Integer; var I, NumNames: Integer; begin NumNames := 0; Result := -1; for I := 0 to Length(IntfMD.MDA) - 1 do begin if CompareText(IntfMD.MDA[I].Name, MethName) = 0 then begin Result := I; Inc(NumNames); end; end; if NumNames > 1 then Result := -1; end; function ReadString(var P: Pointer): String; var B: Byte; begin B := Byte(P^); SetLength(Result, B); P := Pointer( Integer(P) + 1); Move(P^, Result[1], Integer(B)); P := Pointer( Integer(P) + B ); end; function ReadByte(var P: Pointer): Byte; begin Result := Byte(P^); P := Pointer( Integer(P) + 1); end; function ReadWord(var P: Pointer): Word; begin Result := Word(P^); P := Pointer( Integer(P) + 2); end; function ReadLong(var P: Pointer): Integer; begin Result := Integer(P^); P := Pointer( Integer(P) + 4); end; procedure FillMethodArray(P: Pointer; IntfMD: PIntfMetaData; Offset, Methods: Integer); var S: string; I, J, K, L: Integer; ParamCount: Integer; Kind, Flags: Byte; ParamInfo: PTypeInfo; ParamName: string; begin for I := 0 to Methods -1 do begin IntfMD.MDA[Offset].Name := ReadString(P); Kind := ReadByte(P); // kind IntfMd.MDA[Offset].CC := CCMap[ReadByte(P)]; ParamCount := ReadByte(P); // param count including self IntfMd.MDA[Offset].ParamCount := ParamCount - 1; IntfMd.MDA[Offset].Pos := I; IntfMd.MDA[Offset].HasRTTI := True; SetLength(IntfMD.MDA[Offset].Params, ParamCount); K := 0; for J := 0 to ParamCount - 1 do begin Flags := ReadByte(P); // flags ParamName := ReadString(P); // param name S := ReadString(P); // param type name L := ReadLong(P); if L <> 0 then ParamInfo := PPTypeInfo(L)^ else raise EInterfaceRTTIException.CreateFmt(SNoRTTIParam, [ParamName, IntfMD.MDA[Offset].Name, IntfMD.UnitName + '.' + IntfMd.Name]); if J = 0 then IntfMd.MDA[Offset].SelfInfo := ParamInfo else begin IntfMd.MDA[Offset].Params[K].Flags := TParamFlags(Flags); IntfMd.MDA[Offset].Params[K].Name := ParamName; IntfMd.MDA[Offset].Params[K].Info := ParamInfo; Inc(K); end; end; if Kind = Byte(mkFunction) then begin S := ReadString(P); IntfMd.MDA[Offset].ResultInfo := PPTypeInfo(ReadLong(P))^; end; Inc(Offset); end; end; function WalkAncestors(PP: PPTypeInfo; AddMeths: Boolean; IntfMD: PIntfMetaData; Offset, Methods: Integer): Integer; var S: string; AncTP: Pointer; P: Pointer; B: Byte; NumMethods, NumAncMeths: Integer; HasRTTI: Integer; begin P := Pointer(PP^); Result := 0; ReadByte(P); // Kind S := ReadString(P); AncTP := Pointer(ReadLong(P)); if AncTP <> nil then begin NumAncMeths := WalkAncestors(AncTP, False, nil, 0, 0); Result := Result + NumAncMeths; end else NumAncMeths := 0; P := Pointer(Integer(P) + 17); // intf.flags and guid B := Byte(P^); // str len P := Pointer(Integer(P) + B + 1); // skip unit name and count NumMethods := ReadWord(P); // # methods Result := Result + NumMethods; if AddMeths then begin HasRTTI := ReadWord(P); // $FFFF if no RTTI, # methods again if has RTTI if HasRTTI <> $FFFF then begin FillMethodArray(P, IntfMD, Offset + NumAncMeths, NumMethods); Dec(Offset, NumMethods); if Offset > 0 then WalkAncestors(AncTP, True, IntfMD, Offset, NumMethods); end; end; end; function GetNumAncMeths(P: Pointer): Integer; var B: Byte; Anc: Pointer; begin Result := 0; ReadByte(P); // kind B := Byte(P^); // str len P := Pointer(Integer(P) + B + 1); // skip sym name and count Anc := Pointer(ReadLong(P)); if Anc <> nil then Result := WalkAncestors(Anc, False, nil, 0, 0); end; procedure GetIntfMetaData(Info: PTypeInfo; var IntfMD: TIntfMetaData; IncludeAncMethods: Boolean = False); var I, Offset: Integer; Methods: Integer; HasRTTI: Integer; PP: PPTypeInfo; P: Pointer; SelfMethCount: Integer; begin P := Pointer(Info); IntfMD.NumAnc := GetNumAncMeths(P); IntfMD.Info := Info; ReadByte(P); // kind IntfMD.Name := ReadString(P); PP := PPTypeInfo(ReadLong(P)); if PP <> nil then IntfMD.AncInfo := PP^; // ancestor typeinfo ReadByte(P); // interface flags IntfMD.IID.D1 := ReadLong(P); IntfMD.IID.D2 := ReadWord(P); IntfMD.IID.D3 := ReadWord(P); for I := 0 to 7 do IntfMD.IID.D4[I] := ReadByte(P); IntfMD.UnitName := ReadString(P); Methods := ReadWord(P); // # methods HasRTTI := ReadWord(P); // $FFFF if no RTTI, # methods again if has RTTI if HasRTTI = $FFFF then raise EInterfaceRTTIException.CreateFmt(SNoRTTI, [IntfMD.UnitName + '.' + IntfMd.Name]); SelfMethCount := Methods; if IncludeAncMethods then begin Methods := Methods + IntfMD.NumAnc; Offset := IntfMD.NumAnc; end else begin Offset := 0; end; SetLength(IntfMD.MDA, Methods); FillMethodArray(P, @IntfMD, Offset, SelfMethCount); if IncludeAncMethods then begin if PP <> nil then WalkAncestors(PP, True, @IntfMD, Offset - IntfMD.NumAnc, IntfMD.NumAnc); IntfMD.NumAnc := 0; for I := 0 to Length(IntfMD.MDA) - 1 do begin if not IntfMD.MDA[I].HasRTTI then Inc(IntfMD.NumAnc) else break; end; end; end; procedure GetDynArrayElTypeInfo(typeInfo: PTypeInfo; var EltInfo: PTypeInfo; var Dims: Integer); var L: Integer; S: string; P: Pointer; Info: PTypeInfo; begin Dims := 0; P := Pointer(typeInfo); ReadByte(P); // kind S := ReadString(P); // symname ReadLong(P); // elsize L := ReadLong(P); if (L <> 0) then begin Info := PPTypeInfo(L)^; if Info.Kind = tkDynArray then begin GetDynArrayElTypeInfo(Info, EltInfo, Dims); end; end; ReadLong(P); // vartype L := ReadLong(P); // elttype, even if not destructable, 0 if type has no RTTI if L <> 0 then EltInfo := PPTypeInfo(L)^; Inc(Dims); end; function GetDynArrayNextInfo(typeInfo: PTypeInfo): PTypeInfo; var S: string; P: Pointer; L: Integer; begin Result := nil; P := Pointer(typeInfo); ReadByte(P); // kind S := ReadString(P); // symname ReadLong(P); // elsize L := ReadLong(P); if L <> 0 then Result := PPTypeInfo(L)^; // eltype or 0 if not destructable end; function GetDynArrayNextInfo2(typeInfo: PTypeInfo; var Name: string): PTypeInfo; var P: Pointer; L: Integer; begin Result := nil; P := Pointer(typeInfo); ReadByte(P); // kind Name := ReadString(P); // symname ReadLong(P); // elsize L := ReadLong(P); if L <> 0 then Result := PPTypeInfo(L)^; // eltype or 0 if not destructable end; end.
unit fODRadApproval; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ORCtrls, ORfn, ExtCtrls, fBase508Form, VA508AccessibilityManager; type TfrmODRadApproval = class(TfrmBase508Form) cmdOK: TButton; cmdCancel: TButton; cboRadiologist: TORComboBox; SrcLabel: TLabel; pnlBase: TORAutoPanel; procedure cmdOKClick(Sender: TObject); procedure cmdCancelClick(Sender: TObject); private FRadiologist: string ; FChanged: Boolean; end; procedure SelectApprovingRadiologist(FontSize: Integer; var Radiologist: string) ; implementation {$R *.DFM} uses rODRad, rCore, uCore; const TX_RAD_TEXT = 'Select radiologist or press Cancel.'; TX_RAD_CAP = 'No Radiologist Selected'; procedure SelectApprovingRadiologist(FontSize: Integer; var Radiologist: string); { displays radiologist selection form and returns a record of the selection } var frmODRadApproval: TfrmODRadApproval; W, H: Integer; begin frmODRadApproval := TfrmODRadApproval.Create(Application); try with frmODRadApproval do begin Font.Size := FontSize; W := ClientWidth; H := ClientHeight; ResizeToFont(FontSize, W, H); ClientWidth := W; pnlBase.Width := W; ClientHeight := H; pnlBase.Height := H; FChanged := False; FastAssign(SubsetOfRadiologists, cboRadiologist.Items); ShowModal; Radiologist := FRadiologist ; end; {with frmODRadApproval} finally frmODRadApproval.Release; end; end; procedure TfrmODRadApproval.cmdCancelClick(Sender: TObject); begin Close; end; procedure TfrmODRadApproval.cmdOKClick(Sender: TObject); begin if cboRadiologist.ItemIEN = 0 then begin InfoBox(TX_RAD_TEXT, TX_RAD_CAP, MB_OK or MB_ICONWARNING); FChanged := False ; Exit; end; FChanged := True; FRadiologist := cboRadiologist.Items[cboRadiologist.ItemIndex] ; Close; end; end.
unit Neslib.SysUtils; {< Sytem utilities } {$INCLUDE 'Neslib.inc'} interface uses System.SysUtils; { Checks two string references for equality. Parameters: AString1: first string AString2: second string Returns: True if AString1 and AString2 are references to the same string. This function is useful with string interning to quickly check two interned strings for equality. Instead of comparing the contents of the two strings, it just checks their references, which is just a single pointer comparison. See Neslib.Collections.TStringInternPool for a class you can use for string interning. } function SameStringRef(const AString1, AString2: String): Boolean; overload; inline; function SameStringRef(const AString1, AString2: UTF8String): Boolean; overload; inline; var { A TFormatSettings record configured for US number settings. It uses a period (.) as a decimal separator and comma (,) as thousands separator. Can be used to convert strings to floating-point values in cases where the strings are always formatted to use periods as decimal separators (regardless of locale). } USFormatSettings: TFormatSettings; implementation function SameStringRef(const AString1, AString2: String): Boolean; begin Result := (Pointer(AString1) = Pointer(AString2)); end; function SameStringRef(const AString1, AString2: UTF8String): Boolean; begin Result := (Pointer(AString1) = Pointer(AString2)); end; initialization USFormatSettings := TFormatSettings.Create('en-US'); USFormatSettings.DecimalSeparator := '.'; USFormatSettings.ThousandSeparator := ','; end.
{ Questa unit e' stata importata esternamente da altre fonti } { e non fa parte del sorgente pascal scritto dall'autore. } unit mouse; { and other interesting stuff } {$F+} interface procedure hidemouse; procedure memcpy(source,destination : pointer; size : word); procedure memzerocpy(source,destination : pointer; size : word); procedure mousecoords(var x,y : integer); procedure mousemove(x,y : integer); procedure mousereset; procedure mouse_x_limit(mn,mx : integer); procedure mouse_y_limit(mn,mx : integer); procedure showmouse; procedure mydelay(time : longint); function mouseclick:integer; function longtime : longint; implementation uses dos; (* Copies "size" bytes from "source" to "destination". *) (* The operator addr may be used to pass the correct adress. *) (* Example: memcpy(addr(source),addr(destination),200) *) (* where: source,destination : array[...] of bytes; *) (* 200 is the number of bytes to be copied *) procedure memcpy(source,destination : pointer; size : word); label LP; begin asm push ds push si mov cx,size lds si,source les di,destination LP: lodsb stosb loop LP pop si pop ds end; end; (* Does exactly the same as memcpy except that it does not copies *) (* those bytes whose value is 0. It's useful to put on the screen *) (* drawings using color 0 as trasparent. *) procedure memzerocpy(source,destination : pointer; size : word); label LP,L1,L2,L3; begin asm push ds push si mov cx,size mov dx,0 lds si,source les di,destination LP: lodsb cmp al,dl je L2 L1: stosb jmp L3 L2: inc di L3: loop LP pop si pop ds end; end; (* Return a value between 0 and 8640000 depending on current time *) function longtime : longint; var h,m,s,c : word; h1,m1, s1,c1 : longint; begin gettime(h,m,s,c); h1:=h; m1:=m; s1:=s; c1:=c; longtime:=c1+s1*100+m1*6000+h1*360000; end; (* It's the equivalent of DELAY except that it's based on hardware time *) (* and not on clock ticks. If some one alters the CPU speed using the TURBO *) (* button MYDELAY is not affected. This is not the same for DELAY. *) procedure mydelay(time : longint); var h,m,s,c : word; a,b, h1,m1, s1,c1 : longint; begin gettime(h,m,s,c); h1:=h; m1:=m; s1:=s; c1:=c; a:=c1+s1*100+m1*6000+h1*360000; repeat gettime(h,m,s,c); h1:=h; m1:=m; s1:=s; c1:=c; b:=((c1+s1*100+m1*6000+h1*360000)+8640000-a) mod 8640000; until (b>time); end; (* Follow the common procedures based on interrupt $33 *) procedure mousereset; var regs : REGISTERS; begin regs.ax:=0; intr($33,regs); end; procedure showmouse; var regs : REGISTERS; begin regs.ax:=1; intr($33,regs); end; procedure hidemouse; var regs : REGISTERS; begin regs.ax:=2; intr($33,regs); end; function mouseclick:integer; var regs : REGISTERS; begin regs.ax:=3; regs.bx:=0; intr($33,regs); mouseclick:=regs.bx; end; procedure mousecoords(var x,y : integer); var regs : REGISTERS; begin regs.ax:=3; regs.bx:=0; intr($33,regs); x:=regs.cx shr 1; y:=regs.dx; end; procedure mouse_x_limit(mn,mx : integer); var regs : REGISTERS; begin regs.ax:=7; regs.cx:=mn; regs.dx:=mx; intr($33,regs); end; procedure mouse_y_limit(mn,mx : integer); var regs : REGISTERS; begin regs.ax:=8; regs.cx:=mn; regs.dx:=mx; intr($33,regs); end; procedure mousemove(x,y : integer); var regs : REGISTERS; begin regs.ax:=4; regs.cx:=x; regs.dx:=y; intr($33,regs); end; end.
unit CashWork; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, CashInterface, DB, Buttons, Gauges, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxCurrencyEdit, cxClasses, cxPropertiesStore, dsdAddOn, dxSkinsCore, dxSkinsDefaultPainters; type TCashWorkForm = class(TForm) ceInputOutput: TcxCurrencyEdit; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; BitBtn1: TBitBtn; laRest: TLabel; Button5: TButton; btDeleteAllArticul: TButton; Gauge: TGauge; Button6: TButton; UserSettingsStorageAddOn: TdsdUserSettingsStorageAddOn; cxPropertiesStore: TcxPropertiesStore; Button7: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Button5Click(Sender: TObject); procedure btDeleteAllArticulClick(Sender: TObject); procedure Button6Click(Sender: TObject); private m_Cash: ICash; m_DataSet: TDataSet; public constructor Create(Cash: ICash; DataSet: TDataSet); end; implementation {$R *.dfm} { TCashWorkForm } constructor TCashWorkForm.Create(Cash: ICash; DataSet: TDataSet); begin inherited Create(nil); m_Cash:= Cash; m_DataSet:= DataSet; end; procedure TCashWorkForm.Button1Click(Sender: TObject); begin if ceInputOutput.Value <= 0 then begin ShowMessage('Сумма должна быть больше нуля...'); Exit; end; if TButton(Sender).Tag = 0 then m_Cash.CashInputOutput(ceInputOutput.Value) else m_Cash.CashInputOutput(- ceInputOutput.Value); end; procedure TCashWorkForm.Button2Click(Sender: TObject); begin if MessageDlg('Вы уверены в снятии Z-отчета?', mtInformation, mbOKCancel, 0) = mrOk then m_Cash.ClosureFiscal; end; procedure TCashWorkForm.Button3Click(Sender: TObject); begin m_Cash.OpenReceipt; m_Cash.SubTotal(true, true, 0, 0); m_Cash.TotalSumm(0, 0, ptMoney); m_Cash.CloseReceipt; end; procedure TCashWorkForm.Button4Click(Sender: TObject); var i: integer; RecordCountStr: string; CategoriesId: string; begin with m_DataSet do begin First; i:=1; RecordCountStr:= IntToStr(RecordCount); while not EOF do begin try m_Cash.DeleteArticules(FieldByName('Code').AsInteger); except end; m_Cash.ProgrammingGoods(FieldByName('Code').AsInteger, FieldByName('FullName').asString, FieldByName('LastPrice').asFloat, FieldByName('NDS').asFloat); Application.ProcessMessages; laRest.Caption:=IntToStr(i)+' из '+RecordCountStr; inc(i); Next; end; end; end; procedure TCashWorkForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree end; procedure TCashWorkForm.Button5Click(Sender: TObject); begin if MessageDlg('Вы уверены в снятии X-отчета?', mtInformation, mbOKCancel, 0) = mrOk then m_Cash.XReport; end; procedure TCashWorkForm.Button6Click(Sender: TObject); begin m_Cash.SetTime end; procedure TCashWorkForm.btDeleteAllArticulClick(Sender: TObject); var i: integer; begin m_Cash.DeleteArticules(0); { Gauge.MinValue:=1; Gauge.MaxValue:=14000; for i:=1 to 14000 do begin Gauge.Progress:=i; end;} m_Cash.ClearArticulAttachment; ShowMessage('Артикулы удалены') {} end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit DSAzureQueue; interface uses AzureUI, System.Classes, Vcl.ComCtrls, Vcl.Controls, System.Generics.Collections, Vcl.ImgList, Vcl.Menus; type ///<summary> The possible types of Azure queue nodes. ///</summary> TNodeType = (azqUnknown, azqQueues, azqQueue, azqMessage, azqLoading, azqTruncated); ///<summary> /// Data to store with a node which holds its value, and type. ///</summary> TNodeData = class protected FValue: String; FNodeType: TNodeType; public constructor Create; Virtual; ///<summary> The value associated with the node. </summary> ///<remarks> May be the same as the Node's text, although this value will never be truncated. </remarks> property Value: String read FValue write FValue; ///<summary> The node's type. </summary> property NodeType: TNodeType read FNodeType write FNodeType; end; ///<summary> /// Extension of TNodeData adding Queue Message specific information. ///</summary> TMessageNodeData = class(TNodeData) protected FMessageId: String; FInsertTime: String; FExpireTime: String; FDequeueCount: Integer; FMessageText: String; public constructor Create; Override; property MessageId: String read FMessageId write FMessageId; property InsertTime: String read FInsertTime write FInsertTime; property ExpireTime: String read FExpireTime write FExpireTime; property DequeueCount: Integer read FDequeueCount write FDequeueCount; property MessageText: String read FMessageText write FMessageText; end; ///<summary> /// Event for a message node in the tree being 'activated' (double-click or ENTER) ///</summary> TMessageActiveEvent = procedure(MessageData: TMessageNodeData) of object; ///<summary> /// Component for managing Queues and their messages on Microsoft Azure. ///</summary> ///<remarks> /// A tree component for viewing all of the queues stored for the given Microsoft Azure connection. /// Each queue has messages as child nodes, with a limitation of showing a maximum of 32 messages. /// From the tree you are able to add or remove queues, and for each queue you are able to pop the /// top message or add a new message to any queue. ///</remarks> TAzureQueueManagement = class(TAzureManagement) protected FMessageActivate: TMessageActiveEvent; FActive: Boolean; FCustomImages: TCustomImageList; FMessageLength: Integer; FMenuNode: TTreeNode; FForceCollapse: Boolean; procedure SetMessageLength(Length: Integer); procedure SetCustomImages(Value: TCustomImageList); function Activate: Boolean; procedure SetActive(Active: Boolean); function CreatePopupMenu: TPopupMenu; procedure UpdatePopupMenu(Sender: TObject); function CreateImageList: TCustomImageList; //Context Menu actions procedure ActivateAction(Sender: TObject); procedure AddQueueAction(Sender: TObject); procedure RemoveQueueAction(Sender: TObject); procedure ClearMessagesAction(Sender: TObject); procedure AddMessageAction(Sender: TObject); procedure RemoveMessageAction(Sender: TObject); procedure RefreshQueueAction(Sender: TObject); procedure RefreshListAction(Sender: TObject); procedure OpenQueueMetadata(Sender: TObject); //Checks given node and recursivly searches all child nodes //to see if any node is expanded and has a loading node as its child. function HasLoadingNode(Node: TTreeNode): Boolean; function isNodeLoading(Node: TTreeNode): Boolean; procedure ForceCollapse(Node: TTreeNode; FullCollapse: Boolean = True); procedure InitializeTree; procedure HandleNodeExpanded(Sender: TObject; Node: TTreeNode); procedure HandleNodeCollapsing(Sender: TObject; Node: TTreeNode; var AllowCollapse: Boolean); procedure OnImageIndex(Sender: TObject; Node: TTreeNode); procedure OnGetHint(Sender: TObject; const Node: TTreeNode; var Hint: string); procedure HandleCreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass); procedure HandleDoubleClick(Sender: TObject); procedure HandleKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); //Callbacks for action threads (refresh/add/remove) procedure PopulateQueues(Node: TTreeNode; QueueNames: TStringList; ForceExpand: Boolean; ErrorMessage: String); procedure PopulateMessages(Node: TTreeNode; Messages: TList<TMessageNodeData>; TotalMessages: Integer; ForceExpand: Boolean = True); procedure QueueCreated(QueueName: String; Success: Boolean; ForceExpand: Boolean); procedure QueueDeleted(QueueName: String; Success: Boolean; ForceExpand: Boolean); procedure MessageCreated(QueueNode: TTreeNode; Success: Boolean; ForceExpand: Boolean); procedure MessageRemoved(QueueNode: TTreeNode; Success: Boolean; ForceExpand: Boolean); //Helper functions for managing nodes function CreateLoadingNode(ParentNode: TTreeNode): TTreeNode; procedure PopulateForNode(Node: TTreeNode; ForceExpand: Boolean = True); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Align; property Anchors; property AutoExpand; property BevelEdges; property BevelInner; property BevelOuter; property BevelKind default bkNone; property BevelWidth; property BiDiMode; property BorderStyle; property BorderWidth; property ChangeDelay; property Color; property Ctl3D; property Constraints; property DoubleBuffered; property DragKind; property DragCursor; property DragMode; property Enabled; property Font; property RowSelect; property Touch; property Visible; property ToolTips; property ConnectionInfo; /// <summary> Display length for a Queue message in the tree </summary> /// <remarks> Must be between 5 and 400. /// If a message is truncated its node will have a tooltip showing more of the message. /// </remarks> property MessageLength: Integer read FMessageLength write SetMessageLength; /// <summary> Images to use instead of the default tree node images </summary> /// <remarks> In the (index) order of: Queues, Queue, Message </remarks> property CustomImages: TCustomImageList read FCustomImages write SetCustomImages; /// <summary> Callback to use for displaying a Queue message. </summary> /// <remarks> If set this replaces the message dialog which shows up by default. </remarks> property OnMessageActivate: TMessageActiveEvent read FMessageActivate write FMessageActivate; /// <summary> Set to True to be able to connect to azure and populate the tree. </summary> property Active: Boolean read FActive write SetActive; end; const ADD_QUEUE = 'AddQueue'; REMOVE_QUEUE = 'RemoveQueue'; ADD_MESSAGE = 'AddMessage'; CLEAR_MESSAGES = 'ClearMessages'; REMOVE_MESSAGE = 'RemoveMessage'; REFRESH_QUEUE = 'RefreshQueue'; REFRESH_LIST = 'RefreshList'; ACTIVATE_ITEM = 'Activate'; QUEUE_METADATA = 'QueueMetadata'; NODE_QUEUES = 'Queues'; NODE_QUEUE = 'Queue'; NODE_QUEUE_NAME = 'Name'; implementation uses Winapi.ActiveX, Data.DBXClientResStrs, Vcl.Dialogs, DSAzure, DSAzureMessageDialog, DSAzureQueueMetadataDialog, Vcl.ExtCtrls, Vcl.Graphics, System.SysUtils, Winapi.Windows, Xml.XMLDoc, Xml.XMLIntf, System.StrUtils, System.UITypes; type TQueuesPopulatedCallback = procedure(Node: TTreeNode; QueueNames: TStringList; ForceExpand: Boolean; ErrorMessage: String) of object; TMessagesPopulatedCallback = procedure(Node: TTreeNode; Messages: TList<TMessageNodeData>; TotalMessages: Integer; ForceExpand: Boolean) of object; TQueueCreatedCallback = procedure(QueueName: String; Success: Boolean; ForceExpand: Boolean) of object; TQueueDeletedCallback = procedure(QueueName: String; Success: Boolean; ForceExpand: Boolean) of object; TMessageCreatedCallback = procedure(QueueNode: TTreeNode; Success: Boolean; ForceExpand: Boolean) of object; TMessageRemovedCallback = procedure(QueueNode: TTreeNode; Success: Boolean; ForceExpand: Boolean) of object; TQueuePopulator = class(TThread) protected FNode: TTreeNode; FConnectionInfo: TAzureConnectionString; FCallback: TQueuesPopulatedCallback; FQueueService: TAzureQueueService; FForceExpand: Boolean; public constructor Create(Node: TTreeNode; ConnectionInfo: TAzureConnectionString; Callback: TQueuesPopulatedCallback; ForceExpand: Boolean); Virtual; destructor Destroy; override; procedure Execute; override; end; TMessagePopulator = class(TThread) protected FNode: TTreeNode; FConnectionInfo: TAzureConnectionString; FCallback: TMessagesPopulatedCallback; FQueueService: TAzureQueueService; FForceExpand: Boolean; function GetMessageCount(QueueName: String): Integer; public constructor Create(Node: TTreeNode; ConnectionInfo: TAzureConnectionString; Callback: TMessagesPopulatedCallback; ForceExpand: Boolean); Virtual; destructor Destroy; override; procedure Execute; override; end; TQueueMetadataUpdater = class(TThread) protected FQueueName: String; FConnectionInfo: TAzureConnectionString; FQueueService: TAzureQueueService; FParent: TAzureQueueManagement; public constructor Create(QueueName: String; ConnectionInfo: TAzureConnectionString; Parent: TAzureQueueManagement); Virtual; destructor Destroy; override; procedure Execute; override; end; TQueueCreator = class(TThread) protected FQueueName: String; FConnectionInfo: TAzureConnectionString; FCallback: TQueueCreatedCallback; FQueueService: TAzureQueueService; FForceExpand: Boolean; public constructor Create(QueueName: String; ConnectionInfo: TAzureConnectionString; Callback: TQueueCreatedCallback; ForceExpand: Boolean); Virtual; destructor Destroy; override; procedure Execute; override; end; TQueueDeletor = class(TThread) protected FQueueName: String; FConnectionInfo: TAzureConnectionString; FCallback: TQueueDeletedCallback; FQueueService: TAzureQueueService; FForceExpand: Boolean; public constructor Create(QueueName: String; ConnectionInfo: TAzureConnectionString; Callback: TQueueDeletedCallback; ForceExpand: Boolean); Virtual; destructor Destroy; override; procedure Execute; override; end; TMessageCreator = class(TThread) protected FQueueNode: TTreeNode; FMessage: String; FConnectionInfo: TAzureConnectionString; FCallback: TMessageCreatedCallback; FQueueService: TAzureQueueService; FForceExpand: Boolean; public constructor Create(QueueNode: TTreeNode; MessageText: String; ConnectionInfo: TAzureConnectionString; Callback: TMessageCreatedCallback; ForceExpand: Boolean); Virtual; destructor Destroy; override; procedure Execute; override; end; TMessageDeletor = class(TThread) protected FQueueNode: TTreeNode; FConnectionInfo: TAzureConnectionString; FCallback: TMessageRemovedCallback; FQueueService: TAzureQueueService; FForceExpand: Boolean; FClearAll: Boolean; public constructor Create(QueueNode: TTreeNode; ConnectionInfo: TAzureConnectionString; Callback: TMessageRemovedCallback; ForceExpand: Boolean; ClearAll: Boolean); Virtual; destructor Destroy; override; procedure Execute; override; end; function GetNodeData(Node: TTreeNode; NodeType: TNodeType = azqUnknown): TNodeData; begin //NodeType should only be unknown if the data is already assigned and not being created here Assert((NodeType <> azqUnknown) or Assigned(Node.Data)); if not Assigned(Node.Data) then begin if NodeType = azqMessage then Node.Data := Pointer(TMessageNodeData.Create) else Node.Data := Pointer(TNodeData.Create); TNodeData(Node.Data).NodeType := NodeType; end; Result := TNodeData(Node.Data); end; { TAzureQueueManagement } procedure TAzureQueueManagement.ActivateAction(Sender: TObject); begin SetActive(True); end; procedure TAzureQueueManagement.AddMessageAction(Sender: TObject); var Data: TNodeData; Msg: String; begin if (FMenuNode <> nil) and not IsNodeLoading(FMenuNode) then begin Data := FMenuNode.Data; Assert(Data.NodeType = azqQueue); Msg := InputBox(SAddMsgTitle, SAddMsgMessage, EmptyStr); if Msg <> EmptyStr then begin TMessageCreator.Create(FMenuNode, Msg, FConnectionInfo, MessageCreated, True); end; end; end; procedure TAzureQueueManagement.AddQueueAction(Sender: TObject); var QueueName: String; begin if not IsNodeLoading(GetNodeAt(0, 0)) then begin QueueName := InputBox(SAddQueueTitle, SAddQueueMessage, EmptyStr); if QueueName <> EmptyStr then begin QueueName := AnsiLowerCase(QueueName); TQueueCreator.Create(QueueName, FConnectionInfo, QueueCreated, True); end; end; end; procedure TAzureQueueManagement.ClearMessagesAction(Sender: TObject); var Data: TNodeData; begin if (FMenuNode <> nil) and not IsNodeLoading(FMenuNode) and ConfirmDeleteItem(True) then begin Data := FMenuNode.Data; Assert(Data.NodeType = azqQueue); TMessageDeletor.Create(FMenuNode, FConnectionInfo, MessageRemoved, True, True); end; end; constructor TAzureQueueManagement.Create(AOwner: TComponent); begin inherited; FMessageLength := 20; FActive := False; ReadOnly := True; OnExpanded := HandleNodeExpanded; OnCollapsing := HandleNodeCollapsing; OnGetImageIndex := OnImageIndex; OnCreateNodeClass := HandleCreateNodeClass; OnDblClick := HandleDoubleClick; OnKeyUp := HandleKeyUp; PopupMenu := CreatePopupMenu; FMessageActivate := nil; Images := CreateImageList; OnHint := OnGetHint; RightClickSelect := True; FMenuNode := nil; TAzureService.SetUp; end; function TAzureQueueManagement.CreateImageList: TCustomImageList; var Images: TCustomImageList; BMP: Vcl.Graphics.TBitmap; begin Images := TCustomImageList.Create(Self); BMP := GetAzureImage('IMG_AZUREQUEUES'); Images.Add(BMP, nil); BMP.Free; BMP := GetAzureImage('IMG_AZUREQUEUE'); Images.Add(BMP, nil); BMP.Free; BMP := GetAzureImage('IMG_AZUREMESSAGE'); Images.Add(BMP, nil); BMP.Free; Result := Images; end; function TAzureQueueManagement.CreateLoadingNode(ParentNode: TTreeNode): TTreeNode; var Node: TTreeNode; Nodedata: TNodeData; begin Node := Items.AddChild(ParentNode, SNodeLoading); NodeData := GetNodeData(Node, azqLoading); NodeData.Value := Node.Text; Result := Node; end; function TAzureQueueManagement.CreatePopupMenu: TPopupMenu; var Menu: TPopupMenu; Item: TMenuItem; begin Menu := TPopupMenu.Create(Self); Menu.OnPopup := UpdatePopupMenu; Item := Menu.CreateMenuItem; Item.Name := ACTIVATE_ITEM; Item.Caption := SActivate; Item.OnClick := ActivateAction; Menu.Items.Add(Item); Item := Menu.CreateMenuItem; Item.Name := ADD_QUEUE; Item.Caption := SAddQueue; Item.OnClick := AddQueueAction; Menu.Items.Add(Item); Item := Menu.CreateMenuItem; Item.Name := REMOVE_QUEUE; Item.Caption := SRemoveQueue; Item.OnClick := RemoveQueueAction; Menu.Items.Add(Item); Item := Menu.CreateMenuItem; Item.Name := QUEUE_METADATA; Item.Caption := SQueueMetadata; Item.OnClick := OpenQueueMetadata; Menu.Items.Add(Item); Item := Menu.CreateMenuItem; Item.Name := CLEAR_MESSAGES; Item.Caption := SClearQueueMessages; Item.OnClick := ClearMessagesAction; Menu.Items.Add(Item); Item := Menu.CreateMenuItem; Item.Name := 'N1'; Item.Caption := cLineCaption; Menu.Items.Add(Item); Item := Menu.CreateMenuItem; Item.Name := ADD_MESSAGE; Item.Caption := SAddMessage; Item.OnClick := AddMessageAction; Menu.Items.Add(Item); Item := Menu.CreateMenuItem; Item.Name := REMOVE_MESSAGE; Item.Caption := SRemoveMessage; Item.OnClick := RemoveMessageAction; Menu.Items.Add(Item); Item := Menu.CreateMenuItem; Item.Name := 'N2'; Item.Caption := cLineCaption; Menu.Items.Add(Item); Item := Menu.CreateMenuItem; Item.Name := REFRESH_QUEUE; Item.Caption := SRefresh; Item.OnClick := RefreshQueueAction; Menu.Items.Add(Item); Item := Menu.CreateMenuItem; Item.Name := REFRESH_LIST; Item.Caption := SRefresh; Item.OnClick := RefreshListAction; Menu.Items.Add(Item); Result := Menu; end; procedure TAzureQueueManagement.UpdatePopupMenu(Sender: TObject); var Data: TNodeData; MenuItem: TMenuItem; begin FMenuNode := Selected; Data := nil; if FMenuNode <> nil then Data := FMenuNode.Data; for MenuItem in PopupMenu.Items do begin if not FActive then MenuItem.Visible := MenuItem.Name = ACTIVATE_ITEM else begin if MenuItem.Name = REMOVE_QUEUE then MenuItem.Visible := (Data <> nil) and (Data.NodeType = azqQueue) else if MenuItem.Name = QUEUE_METADATA then MenuItem.Visible := (Data <> nil) and (Data.NodeType = azqQueue) else if MenuItem.Name = ADD_MESSAGE then MenuItem.Visible := (Data <> nil) and (Data.NodeType = azqQueue) else if MenuItem.Name = CLEAR_MESSAGES then MenuItem.Visible := (Data <> nil) and (Data.NodeType = azqQueue) else if MenuItem.Name = REMOVE_MESSAGE then MenuItem.Visible := (Data <> nil) and (Data.NodeType = azqMessage) and (FMenuNode.GetPrevSibling = nil) else if MenuItem.Name = REFRESH_QUEUE then MenuItem.Visible := (Data <> nil) and (Data.NodeType = azqQueue) else if MenuItem.Name = REFRESH_LIST then MenuItem.Visible := (Data = nil) or (Data.NodeType = azqQueues) else if MenuItem.Name = ACTIVATE_ITEM then MenuItem.Visible := False else MenuItem.Visible := True; end; end; end; destructor TAzureQueueManagement.Destroy; begin if not Assigned(CustomImages) and Assigned(Images) then begin Images.Clear; Images.Free; Images := nil; end; inherited; end; procedure TAzureQueueManagement.ForceCollapse(Node: TTreeNode; FullCollapse: Boolean); begin FForceCollapse := True; try if Node = nil then Node := Items.GetFirstNode; if Node <> nil then Node.Collapse(FullCollapse); finally FForceCollapse := False; end; end; procedure TAzureQueueManagement.HandleCreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass); begin NodeClass := TAzureTreeNode; end; procedure TAzureQueueManagement.HandleDoubleClick(Sender: TObject); var Dialog: TAzureMsgDialog; Data: TMessageNodeData; begin if (Selected <> nil) then begin if GetNodeData(Selected).NodeType = azqMessage then begin Data := TMessageNodeData(GetNodeData(Selected)); if Assigned(FMessageActivate) then FMessageActivate(Data) else begin Dialog := TAzureMsgDialog.Create(Self); Dialog.SetMessage(TMessageNodeData(GetNodeData(Selected))); Dialog.ShowModal; Dialog.Free; end; end; end; end; procedure TAzureQueueManagement.HandleKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var NodeData: TNodeData; IsDelete: Boolean; IsRefresh: Boolean; begin IsDelete := Key = VK_DELETE; IsRefresh := Key = VK_F5; if (Selected <> nil) and (IsDelete or IsRefresh) then begin NodeData := Selected.Data; FMenuNode := Selected; if (NodeData.NodeType = azqQueues) and IsRefresh then RefreshListAction(Sender) else if NodeData.NodeType = azqQueue then begin if IsDelete then RemoveQueueAction(Sender) else RefreshQueueAction(Sender); end else if IsDelete and (NodeData.NodeType = azqMessage) and (Selected.getPrevSibling = nil) then RemoveMessageAction(Sender); end else if (Key = VK_RETURN) then while ssShift in Shift do begin HandleDoubleClick(Sender); Break; end; end; procedure TAzureQueueManagement.HandleNodeCollapsing(Sender: TObject; Node: TTreeNode; var AllowCollapse: Boolean); begin AllowCollapse := FForceCollapse or not isNodeLoading(Node); end; procedure TAzureQueueManagement.HandleNodeExpanded(Sender: TObject; Node: TTreeNode); var NodeData: TNodeData; LoadingNode: TTreeNode; begin if isNodeLoading(Node) then begin LoadingNode := Node.getFirstChild; NodeData := GetNodeData(LoadingNode); Assert(NodeData.NodeType = azqLoading); PopulateForNode(Node); end; end; function TAzureQueueManagement.HasLoadingNode(Node: TTreeNode): Boolean; var ChildNode: TTreeNode; begin if Node = nil then Exit(False); Result := False; if Node.Expanded and isNodeLoading(Node) then Exit(True); if Node.HasChildren then begin ChildNode := Node.getFirstChild; while ChildNode <> nil do begin if HasLoadingNode(ChildNode) then Exit(True); ChildNode := ChildNode.getNextSibling; end; end; end; procedure TAzureQueueManagement.InitializeTree; var Node: TTreeNode; NodeData: TNodeData; begin Items.Clear; Node := Items.AddChild(nil, SNodeAzureQueueRoot); NodeData := GetNodeData(Node, azqQueues); NodeData.Value := Node.Text; CreateLoadingNode(Node); end; function TAzureQueueManagement.isNodeLoading(Node: TTreeNode): Boolean; var LoadingNode: TTreeNode; begin Result := False; //is only loading if the loading node is exposed if (Node <> nil) and (Node.Count = 1) and Node.Expanded then begin LoadingNode := Node.getFirstChild; Result := (GetNodeData(LoadingNode).NodeType = azqLoading); end; end; procedure TAzureQueueManagement.OnGetHint(Sender: TObject; const Node: TTreeNode; var Hint: string); var Data: TNodeData; begin Hint := EmptyStr; Data := GetNodeData(Node); if Data.NodeType = azqMessage then begin if TMessageNodeData(Data).MessageText <> Node.Text then Hint := TMessageNodeData(Data).MessageText; end; end; procedure TAzureQueueManagement.OnImageIndex(Sender: TObject; Node: TTreeNode); var Data: TNodeData; Indx: Integer; begin Data := GetNodeData(Node); case Data.NodeType of azqQueues: Indx := 0; azqQueue: Indx := 1; azqMessage: Indx := 2; else Indx := -1; end; Node.ImageIndex := Indx; Node.SelectedIndex := Indx; end; procedure TAzureQueueManagement.OpenQueueMetadata(Sender: TObject); var Data: TNodeData; QueueName: String; begin if (FMenuNode <> nil) then begin Data := GetNodeData(FMenuNode); if Data.NodeType = azqQueue then begin QueueName := Data.Value; TQueueMetadataUpdater.Create(QueueName, FConnectionInfo, Self); end; end; end; procedure TAzureQueueManagement.PopulateForNode(Node: TTreeNode; ForceExpand: Boolean); var NodeData: TNodeData; begin NodeData := GetNodeData(Node); if (NodeData.NodeType = azqQueues) then TQueuePopulator.Create(Node, FConnectionInfo, PopulateQueues, ForceExpand) else if (NodeData.NodeType = azqQueue) then TMessagePopulator.Create(Node, FConnectionInfo, PopulateMessages, ForceExpand); end; procedure TAzureQueueManagement.PopulateMessages(Node: TTreeNode; Messages: TList<TMessageNodeData>; TotalMessages: Integer; ForceExpand: Boolean); var NodeData: TMessageNodeData; NewChild: TTreeNode; MoreData: TNodeData; ShortMessage: String; begin if not FActive then Exit; if Messages = nil then begin Node.Collapse(False); Exit; end; Assert(TotalMessages > -1); Items.BeginUpdate; try Node.DeleteChildren; for NodeData in Messages do begin ShortMessage := NodeData.MessageText; if Length(ShortMessage) > FMessageLength then ShortMessage := Format('%s...', [Copy(ShortMessage, 0, FMessageLength)]); NewChild := Items.AddChild(Node, ShortMessage); NewChild.Data := Pointer(NodeData); end; if TotalMessages > Messages.Count then begin NewChild := Items.AddChild(Node, Format(SMoreMessages,[(TotalMessages - Messages.Count)])); MoreData := GetNodeData(NewChild, azqTruncated); MoreData.Value := NewChild.Text; end; finally if ForceExpand and not Node.Expanded then Node.Expand(False); Items.EndUpdate; FreeAndNil(Messages); end; end; procedure TAzureQueueManagement.PopulateQueues(Node: TTreeNode; QueueNames: TStringList; ForceExpand: Boolean; ErrorMessage: String); var QueueName: String; QueueNode: TTreeNode; QueueNodeData: TNodeData; begin if not FActive or (Node = nil) then begin ForceCollapse(nil); Exit; end; if (QueueNames = nil) or (ErrorMessage <> EmptyStr) then begin if (ErrorMessage <> EmptyStr) then MessageDlg(ErrorMessage, mtError, [mbOK], 0); ForceCollapse(nil); Exit; end; Items.BeginUpdate; try Node.DeleteChildren; for QueueName in QueueNames do begin QueueNode := Items.AddChild(Node, QueueName); QueueNodeData := GetNodeData(QueueNode, azqQueue); QueueNodeData.Value := QueueNode.Text; CreateLoadingNode(QueueNode); end; finally if ForceExpand and not Node.Expanded then Node.Expand(False); Items.EndUpdate; FreeAndNil(QueueNames); end; end; procedure TAzureQueueManagement.QueueCreated(QueueName: String; Success: Boolean; ForceExpand: Boolean); begin if not FActive then Exit; if Success then PopulateForNode(GetNodeAt(0, 0), ForceExpand) else MessageDlg(Format(SAddQueueError, [QueueName]), mtError, [mbOK], 0); end; procedure TAzureQueueManagement.QueueDeleted(QueueName: String; Success, ForceExpand: Boolean); begin if not FActive then Exit; if Success then PopulateForNode(GetNodeAt(0, 0), ForceExpand) else MessageDlg(Format(SDeleteQueueError, [QueueName]), mtError, [mbOK], 0); end; procedure TAzureQueueManagement.MessageCreated(QueueNode: TTreeNode; Success, ForceExpand: Boolean); begin if not FActive or (QueueNode = nil) then Exit; if Success then PopulateForNode(QueueNode, ForceExpand) else MessageDlg(Format(SAddQueueMessageError, [QueueNode.Text]), mtError, [mbOK], 0); end; procedure TAzureQueueManagement.MessageRemoved(QueueNode: TTreeNode; Success, ForceExpand: Boolean); begin if not FActive or (QueueNode = nil) then Exit; if Success then PopulateForNode(QueueNode, ForceExpand) else MessageDlg(Format(SRemoveQueueMessageError, [QueueNode.Text]), mtError, [mbOK], 0); end; procedure TAzureQueueManagement.RefreshListAction(Sender: TObject); var RootNode: TTreeNode; begin RootNode := GetNodeAt(0, 0); if not HasLoadingNode(RootNode) then begin //add a loading node when refreshing queues Items.BeginUpdate; RootNode.DeleteChildren; CreateLoadingNode(RootNode); RootNode.Expand(False); Items.EndUpdate; PopulateForNode(RootNode, True); end; end; procedure TAzureQueueManagement.RefreshQueueAction(Sender: TObject); var Data: TNodeData; begin if (FMenuNode <> nil) and not IsNodeLoading(FMenuNode) then begin Data := FMenuNode.Data; Assert(Data.NodeType = azqQueue); //add a loading node when refreshing queue Items.BeginUpdate; FMenuNode.DeleteChildren; CreateLoadingNode(FMenuNode); FMenuNode.Expand(False); Items.EndUpdate; PopulateForNode(FMenuNode, True); end; end; procedure TAzureQueueManagement.RemoveMessageAction(Sender: TObject); var Data: TNodeData; begin if (FMenuNode <> nil) and not IsNodeLoading(FMenuNode) and ConfirmDeleteItem then begin Data := FMenuNode.Data; Assert(Data.NodeType = azqMessage); TMessageDeletor.Create(FMenuNode.Parent, FConnectionInfo, MessageRemoved, True, False); end; end; procedure TAzureQueueManagement.RemoveQueueAction(Sender: TObject); var Data: TNodeData; begin if (FMenuNode <> nil) and not IsNodeLoading(FMenuNode) then begin if ConfirmDeleteItem then begin Data := FMenuNode.Data; Assert(Data.NodeType = azqQueue); TQueueDeletor.Create(FMenuNode.Text, FConnectionInfo, QueueDeleted, True); end; end; end; function TAzureQueueManagement.Activate: Boolean; begin Result := False; if FConnectionInfo <> nil then begin InitializeTree; Result := True; end; end; procedure TAzureQueueManagement.SetActive(Active: Boolean); begin if (FActive <> Active) then begin if not Active then begin FActive := False; Items.Clear; end else FActive := Activate; end; end; procedure TAzureQueueManagement.SetCustomImages(Value: TCustomImageList); begin if Value <> nil then begin //If the current Images are ones made internally, not set through CustomImages property, Free them if FCustomImages <> Images then begin Images.Free; end; Images := Value; end else Images := CreateImageList; FCustomImages := Value; end; procedure TAzureQueueManagement.SetMessageLength(Length: Integer); begin if Length < 5 then FMessageLength := 5 else if Length > 400 then FMessageLength := 400 else FMessageLength := Length; end; { TQueuePopulator } constructor TQueuePopulator.Create(Node: TTreeNode; ConnectionInfo: TAzureConnectionString; Callback: TQueuesPopulatedCallback; ForceExpand: Boolean); begin inherited Create; Assert(Node <> nil); Assert(ConnectionInfo <> nil); FNode := Node; FConnectionInfo := ConnectionInfo; FCallback := Callback; FForceExpand := ForceExpand; end; destructor TQueuePopulator.Destroy; begin FreeAndNil(FQueueService); inherited; end; procedure TQueuePopulator.Execute; var xml: String; xmlDoc: IXMLDocument; QueueNames: TStringList; QueuesXMLNode: IXMLNode; QueueNode: IXMLNode; NameNode: IXMLNode; ErrorMessage: String; begin inherited; FreeOnTerminate := True; CoInitialize(nil); QueueNames := nil; xmlDoc := nil; ErrorMessage := EmptyStr; try try FQueueService := TAzureQueueService.Create(FConnectionInfo); xml := FQueueService.ListQueues([],[]); xmlDoc := TXMLDocument.Create(nil); xmlDoc.LoadFromXML(xml); QueueNames := TStringList.Create; QueuesXMLNode := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_QUEUES); if (QueuesXMLNode <> nil) and (QueuesXMLNode.HasChildNodes) then begin QueueNode := QueuesXMLNode.ChildNodes.FindNode(NODE_QUEUE); while (QueueNode <> nil) do begin if QueueNode.NodeName = NODE_QUEUE then begin NameNode := QueueNode.ChildNodes.FindNode(NODE_QUEUE_NAME); QueueNames.Add(NameNode.Text); end; QueueNode := QueueNode.NextSibling; end; end; except on E : Exception do begin FreeAndNil(QueueNames); if (FQueueService <> nil) and (FQueueService.ResponseText <> EmptyStr) then ErrorMessage := SErrorGeneric + FQueueService.ResponseText else ErrorMessage := E.Message; end; end; finally CoUnInitialize(); TThread.Synchronize(nil, procedure begin FCallback(FNode, QueueNames, FForceExpand, ErrorMessage); end); end; end; { TMessageNodeData } constructor TMessageNodeData.Create; begin FDequeueCount := -1; FNodeType := azqMessage; end; { TNodeData } constructor TNodeData.Create; begin FNodeType := azqUnknown; end; { TMessagePopulator } constructor TMessagePopulator.Create(Node: TTreeNode; ConnectionInfo: TAzureConnectionString; Callback: TMessagesPopulatedCallback; ForceExpand: Boolean); begin inherited Create; Assert(Node <> nil); Assert(ConnectionInfo <> nil); FNode := Node; FConnectionInfo := ConnectionInfo; FCallback := Callback; FForceExpand := ForceExpand; end; destructor TMessagePopulator.Destroy; begin FreeAndNil(FQueueService); inherited; end; procedure TMessagePopulator.Execute; const MsgRetrieveNum = 32; var QueueName: String; Messages: TList<TMessageNodeData>; xml: String; xmlDoc: IXMLDocument; RootNode: IXMLNode; MessageNode: IXMLNode; AuxNode: IXMLNode; MessageData: TMessageNodeData; Added: Boolean; MsgCount: Integer; begin inherited; FreeOnTerminate := True; CoInitialize(nil); Messages := nil; xmlDoc := nil; QueueName := FNode.Text; MsgCount := -1; try try FQueueService := TAzureQueueService.Create(FConnectionInfo); try MsgCount := GetMessageCount(QueueName); except end; xml := FQueueService.PeekMessages(QueueName, MsgRetrieveNum); xmlDoc := TXMLDocument.Create(nil); xmlDoc.LoadFromXML(xml); Messages := TList<TMessageNodeData>.Create; RootNode := xmlDoc.DocumentElement; if (RootNode <> nil) and (RootNode.HasChildNodes) then begin MessageNode := RootNode.ChildNodes.FindNode('QueueMessage'); while (MessageNode <> nil) do begin Added := False; //making sure to only add the message if all of its values are valid if MessageNode.NodeName = 'QueueMessage' then begin MessageData := TMessageNodeData.Create; AuxNode := MessageNode.ChildNodes.FindNode('MessageId'); if AuxNode <> nil then begin MessageData.MessageId := AuxNode.Text; AuxNode := MessageNode.ChildNodes.FindNode('InsertionTime'); if AuxNode <> nil then begin MessageData.InsertTime := AuxNode.Text; AuxNode := MessageNode.ChildNodes.FindNode('ExpirationTime'); if AuxNode <> nil then begin MessageData.ExpireTime := AuxNode.Text; AuxNode := MessageNode.ChildNodes.FindNode('DequeueCount'); if AuxNode <> nil then begin try MessageData.DequeueCount := StrToInt(AuxNode.Text); AuxNode := MessageNode.ChildNodes.FindNode('MessageText'); if AuxNode <> nil then begin MessageData.MessageText := AuxNode.Text; Messages.Add(MessageData); Added := True; end; except end; end; end; end; end; end; if not Added then FreeAndNil(MessageData); MessageNode := MessageNode.NextSibling; end; end; except FreeAndNil(Messages); end; finally CoUninitialize; TThread.Synchronize(nil, procedure begin FCallback(FNode, Messages, MsgCount, FForceExpand); end); end; end; function TMessagePopulator.GetMessageCount(QueueName: String): Integer; var ValS: String; begin Result := -1; Assert(FQueueService <> nil); if FQueueService.GetQueueMetadata(QueueName) then begin ValS := FQueueService.ResponseHeader['x-ms-approximate-messages-count']; try Result := StrToInt(ValS); except end; end; end; { TQueueCreator } constructor TQueueCreator.Create(QueueName: String; ConnectionInfo: TAzureConnectionString; Callback: TQueueCreatedCallback; ForceExpand: Boolean); begin inherited Create; Assert(ConnectionInfo <> nil); FQueueName := QueueName; FConnectionInfo := ConnectionInfo; FCallback := Callback; FForceExpand := ForceExpand; end; destructor TQueueCreator.Destroy; begin FreeAndNil(FQueueService); inherited; end; procedure TQueueCreator.Execute; var Success: Boolean; begin inherited; FreeOnTerminate := True; CoInitialize(nil); try try FQueueService := TAzureQueueService.Create(FConnectionInfo); Success := FQueueService.CreateQueue(AnsiLowerCase(FQueueName)); except Success := False; end; finally CoUninitialize; TThread.Synchronize(nil, procedure begin FCallback(FQueueName, Success, FForceExpand); end); end; end; { TQueueDeletor } constructor TQueueDeletor.Create(QueueName: String; ConnectionInfo: TAzureConnectionString; Callback: TQueueDeletedCallback; ForceExpand: Boolean); begin inherited Create; Assert(ConnectionInfo <> nil); FQueueName := QueueName; FConnectionInfo := ConnectionInfo; FCallback := Callback; FForceExpand := ForceExpand; end; destructor TQueueDeletor.Destroy; begin FreeAndNil(FQueueService); inherited; end; procedure TQueueDeletor.Execute; var Success: Boolean; begin inherited; FreeOnTerminate := True; CoInitialize(nil); try try FQueueService := TAzureQueueService.Create(FConnectionInfo); Success := FQueueService.DeleteQueue(AnsiLowerCase(FQueueName)); except Success := False; end; finally CoUninitialize; TThread.Synchronize(nil, procedure begin FCallback(FQueueName, Success, FForceExpand); end); end; end; { TMessageCreator } constructor TMessageCreator.Create(QueueNode: TTreeNode; MessageText: String; ConnectionInfo: TAzureConnectionString; Callback: TMessageCreatedCallback; ForceExpand: Boolean); begin inherited Create; Assert(ConnectionInfo <> nil); FQueueNode := QueueNode; FMessage := MessageText; FConnectionInfo := ConnectionInfo; FCallback := Callback; FForceExpand := ForceExpand; end; destructor TMessageCreator.Destroy; begin FreeAndNil(FQueueService); inherited; end; procedure TMessageCreator.Execute; var Success: Boolean; begin inherited; FreeOnTerminate := True; CoInitialize(nil); try try FQueueService := TAzureQueueService.Create(FConnectionInfo); Success := FQueueService.PutMessage(AnsiLowerCase(FQueueNode.Text), FMessage); except Success := False; end; finally CoUninitialize; TThread.Synchronize(nil, procedure begin FCallback(FQueueNode, Success, FForceExpand); end); end; end; { TMessageDeletor } constructor TMessageDeletor.Create(QueueNode: TTreeNode; ConnectionInfo: TAzureConnectionString; Callback: TMessageRemovedCallback; ForceExpand: Boolean; ClearAll: Boolean); begin inherited Create; Assert(ConnectionInfo <> nil); Assert(QueueNode <> nil); Assert(GetNodeData(QueueNode).NodeType = azqQueue); FQueueNode := QueueNode; FConnectionInfo := ConnectionInfo; FCallback := Callback; FForceExpand := ForceExpand; FClearAll := ClearAll; end; destructor TMessageDeletor.Destroy; begin FreeAndNil(FQueueService); inherited; end; procedure TMessageDeletor.Execute; var Success: Boolean; xml: String; popReceipt: String; MessageNode: TTreeNode; MessageData: TMessageNodeData; begin inherited; FreeOnTerminate := True; CoInitialize(nil); Success := False; try try FQueueService := TAzureQueueService.Create(FConnectionInfo); if FClearAll then begin Success := FQueueService.ClearMessages(FQueueNode.Text); end else begin xml := FQueueService.GetMessages(FQueueNode.Text, 1); popReceipt := FQueueService.GetPopReceipt(xml); if popReceipt <> EmptyStr then begin Assert(FQueueNode.HasChildren); MessageNode := FQueueNode.getFirstChild; Assert(GetNodeData(MessageNode).NodeType = azqMessage); MessageData := TMessageNodeData(GetNodeData(MessageNode)); Success := FQueueService.DeleteMessage(FQueueNode.Text, MessageData.MessageId, popReceipt); end; end; except Success := False; end; finally CoUninitialize; TThread.Synchronize(nil, procedure begin FCallback(FQueueNode, Success, FForceExpand); end); end; end; { TQueueMetadataUpdater } constructor TQueueMetadataUpdater.Create(QueueName: String; ConnectionInfo: TAzureConnectionString; Parent: TAzureQueueManagement); begin inherited Create; Assert(ConnectionInfo <> nil); FQueueName := QueueName; FConnectionInfo := ConnectionInfo; FParent := Parent; end; destructor TQueueMetadataUpdater.Destroy; begin FreeAndNil(FQueueService); inherited; end; procedure TQueueMetadataUpdater.Execute; var Dialog: TAzureQueueMetadataDialog; Metadata, ModMetadata: TStringList; Count, I: Integer; AKey, AVal: String; Success: Boolean; begin inherited; FreeOnTerminate := True; Metadata := nil; ModMetadata := nil; Success := False; try try FQueueService := TAzureQueueService.Create(FConnectionInfo); if FQueueService.GetQueueMetadata(FQueueName) then begin Metadata := TStringList.Create; FQueueService.PopulateContainer('x-ms-meta-', Metadata, True); TThread.Synchronize(nil, procedure begin Dialog := TAzureQueueMetadataDialog.Create(FParent); try Dialog.SetActiveQueue(FQueueName, Metadata); FreeAndNil(MetaData); //Will reuse the variable lower down if Dialog.ShowModal = mrOK then begin Metadata := Dialog.GetMetadata; ModMetadata := TStringList.Create; end else Success := True; //Closed the dialog, so finished successfully finally FreeAndNil(Dialog); end; end); if Metadata <> nil then begin Count := Metadata.Count; for I := 0 to Count - 1 do begin AKey := Metadata.Names[I]; if AKey <> EmptyStr then begin AVal := Metadata.ValueFromIndex[I]; if not AnsiStartsText('x-ms-meta-', AKey) then AKey := 'x-ms-meta-' + AKey; ModMetadata.Values[AKey] := AVal; end; end; Success := FQueueService.PutQueueMetadata(FQueueName, ModMetadata); end; end; except Success := False; end; finally FreeAndNil(Metadata); FreeAndNil(ModMetadata); if not Success then begin TThread.Queue(nil, procedure begin MessageDlg(Format(SQueueMetadataError, [FQueueName]), mtError, [mbOK], 0); end); end; end; end; end.
unit MainUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Interpolation, IntervalArithmetic; type TMainForm = class(TForm) HeaderLabel: TLabel; DataPointsEdit: TEdit; DataPointsLabel: TLabel; InputGroupBox: TGroupBox; EvaluationPointLabel: TLabel; EvaluationPointEdit: TEdit; CalculationModeLabel: TLabel; NormalArithmeticsRadioButton: TRadioButton; IntervalArithmeticsRadioButton: TRadioButton; CalculateButton: TButton; OutputGroupBox: TGroupBox; LagrangePolynomialSolutionLabel: TLabel; LagrangeCoefficientsSolutionEdit: TEdit; LagrangeValueSolutionLabel: TLabel; LagrangeValueSolutionEdit: TEdit; NevilleValueSolutionLabel: TLabel; NevilleValueSolutionEdit: TEdit; DoubleEndIntervalArithmeticsRadioButton: TRadioButton; procedure CalculateButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} procedure ResetOutputFields; begin MainForm.LagrangeCoefficientsSolutionEdit.Clear; MainForm.LagrangeValueSolutionEdit.Clear; MainForm.NevilleValueSolutionEdit.Clear; end; function ArrayToString(ary : TExtendedArray) : string; overload; var i : Integer; begin result := ' '; for i := 0 to Length(ary)-1 do result := result + ' ' + FloatToStr(ary[i]); end; function ArrayToString(ary : TIntervalArray) : string; overload; var i : Integer; begin result := ' '; for i := 0 to Length(ary)-1 do result := result + ' ' + IntervalToString(ary[i]); end; procedure DisplayValueSolutions(lagrangeValueSolution: Extended; nevilleValueSolution: Extended); overload; begin MainForm.LagrangeValueSolutionEdit.Text := FloatToStr(lagrangeValueSolution); MainForm.NevilleValueSolutionEdit.Text := FloatToStr(nevilleValueSolution); end; procedure DisplayValueSolutions(lagrangeValueSolution: Interval; nevilleValueSolution: Interval); overload; begin MainForm.LagrangeValueSolutionEdit.Text := IntervalToString(lagrangeValueSolution); MainForm.NevilleValueSolutionEdit.Text := IntervalToString(nevilleValueSolution); end; procedure DisplayCoefficientsSolution(lagrangeCoefficients : TExtendedArray); overload; begin MainForm.LagrangeCoefficientsSolutionEdit.Text := ArrayToString(lagrangeCoefficients); end; procedure DisplayCoefficientsSolution(lagrangeCoefficients : TIntervalArray); overload; begin MainForm.LagrangeCoefficientsSolutionEdit.Text := ArrayToString(lagrangeCoefficients); end; function SplitString(input : string) : TStrings; begin result := TStringList.Create; ExtractStrings([' '], [], PChar(input), result); end; function ExtractDataPoints(input: string) : TExtendedArray; var tmp: TStrings; var i : Integer; begin tmp := SplitString(input); SetLength(result, tmp.Count); for i := 0 to tmp.Count - 1 do result[i] := StrToFloat(tmp[i]); end; function ExtractIntervalDataPoints(input: string; doubleEnd : boolean) : TIntervalArray; var tmp: TStrings; var i : Integer; begin tmp := SplitString(input); if(doubleEnd) then begin SetLength(result, tmp.Count div 2); for i := 0 to tmp.Count - 1 do begin if(i mod 2 = 0) then result[i div 2].a := left_read(tmp[i]) else result[i div 2].b := right_read(tmp[i]) end end else begin SetLength(result, tmp.Count); for i := 0 to tmp.Count - 1 do result[i] := int_read(tmp[i]); end end; function ExtractIntervalDataPoint(input : string; doubleEnd : boolean) : Interval; var tmp : TStrings; begin if(doubleEnd) then begin tmp := SplitString(input); result.a := left_read(tmp[0]); result.b := right_read(tmp[1]); end else result := int_read(input); end; procedure CalculateNormalArithmetics(evaluationPointText, dataPointsText: string); var evaluationPoint: Extended; var dataPoints, dataArguments, dataValues : TExtendedArray; var lagrangeValueSolution: Extended; var lagrangeCoefficients : TExtendedArray; var nevilleValueSolution: Extended; var problemDegree : Integer; var tmp, i : Integer; begin evaluationPoint := StrToFloat(evaluationPointText); dataPoints := ExtractDataPoints(dataPointsText); if (Length(dataPoints) mod 2) <> 0 then ShowMessage('Invalid data points format.') else begin problemDegree := Trunc(Length(dataPoints) / 2); SetLength(dataArguments, problemDegree); SetLength(dataValues, problemDegree); for i := 0 to Length(dataPoints) - 1 do begin if i mod 2 = 0 then dataArguments[Trunc(i/2)] := dataPoints[i] else dataValues[Trunc(i/2)] := dataPoints[i]; end; lagrangeValueSolution := Interpolation.Lagrange(problemDegree - 1, dataArguments, dataValues, evaluationPoint, tmp); lagrangeCoefficients := Interpolation.LagrangeCoefficients(problemDegree - 1, dataArguments, dataValues, tmp); nevilleValueSolution := Interpolation.Neville(problemDegree - 1, dataArguments, dataValues, evaluationPoint, tmp); DisplayValueSolutions(lagrangeValueSolution, nevilleValueSolution); DisplayCoefficientsSolution(lagrangeCoefficients); end; end; procedure CalculateIntervalArithmetics(evaluationPointText, dataPointsText: string; doubleEnd : boolean); var evaluationPoint: Interval; var dataPoints, dataArguments, dataValues : TIntervalArray; var lagrangeValueSolution: Interval; var nevilleValueSolution: Interval; var lagrangeCoefficientsSolution : TIntervalArray; var problemDegree : Integer; var tmp, i : Integer; begin evaluationPoint := ExtractIntervalDataPoint(evaluationPointText, doubleEnd); dataPoints := ExtractIntervalDataPoints(dataPointsText, doubleEnd); if (Length(dataPoints) mod 2) <> 0 then ShowMessage('Invalid data points format.') else begin problemDegree := Trunc(Length(dataPoints) / 2); SetLength(dataArguments, problemDegree); SetLength(dataValues, problemDegree); for i := 0 to Length(dataPoints) - 1 do begin if i mod 2 = 0 then dataArguments[Trunc(i/2)] := dataPoints[i] else dataValues[Trunc(i/2)] := dataPoints[i]; end; lagrangeValueSolution := Interpolation.Lagrange(problemDegree - 1, dataArguments, dataValues, evaluationPoint, tmp); lagrangeCoefficientsSolution := Interpolation.LagrangeCoefficients(problemDegree - 1, dataArguments, dataValues, tmp); nevilleValueSolution := Interpolation.Neville(problemDegree - 1, dataArguments, dataValues, evaluationPoint, tmp); DisplayValueSolutions(lagrangeValueSolution, nevilleValueSolution); DisplayCoefficientsSolution(lagrangeCoefficientsSolution); end; end; procedure TMainForm.CalculateButtonClick(Sender: TObject); begin ResetOutputFields(); if Length(MainForm.DataPointsEdit.Text) = 0 then begin MainForm.DataPointsEdit.SetFocus; ShowMessage('Data Points are required.'); end else if Length(MainForm.EvaluationPointEdit.Text) = 0 then begin MainForm.EvaluationPointEdit.SetFocus; ShowMessage('Evaluation Point is required.'); end else begin try if MainForm.NormalArithmeticsRadioButton.Checked then CalculateNormalArithmetics(MainForm.EvaluationPointEdit.Text, MainForm.DataPointsEdit.Text) else if MainForm.IntervalArithmeticsRadioButton.Checked then CalculateIntervalArithmetics(MainForm.EvaluationPointEdit.Text, MainForm.DataPointsEdit.Text, false) else if MainForm.DoubleEndIntervalArithmeticsRadioButton.Checked then CalculateIntervalArithmetics(MainForm.EvaluationPointEdit.Text, MainForm.DataPointsEdit.Text, true) except MainForm.DataPointsEdit.SelectAll; MainForm.DataPointsEdit.SetFocus; ShowMessage('Invalid input data.') end; end; end; end.
unit BrickCamp.Repositories.TUser; interface uses System.JSON, Spring.Container, Spring.Container.Injection, Spring.Container.Common, BrickCamp.IDB, BrickCamp.Model.TUser, BrickCamp.Repositories.IUser; type TUserRepository = class(TInterfacedObject, IUserRepository) protected [Inject] FDb: IBrickCampDb; public function GetOne(const Id: Integer): TUser; function GetOneByName(const Name: string): TUser; function GetList: TJSONArray; procedure Insert(const User: TUser); procedure Update(const User: TUser); procedure Delete(const Id: Integer); end; implementation uses Spring.Collections, Spring.Persistence.Criteria.Interfaces, Spring.Persistence.Criteria.Properties, MARS.Core.Utils; { TUserRepository } procedure TUserRepository.Delete(const Id: Integer); var User: TUser; begin User := FDb.GetSession.FindOne<TUser>(Id); if Assigned(User) then FDb.GetSession.Delete(User); end; function TUserRepository.GetList: TJSONArray; var LList: IList<TUser>; LItem: TUser; begin LList := FDb.GetSession.FindAll<TUser>; result := TJSONArray.Create; for LItem in LList do Result.Add(ObjectToJson(LItem)); end; function TUserRepository.GetOne(const Id: Integer): TUser; begin result := FDb.GetSession.FindOne<TUser>(Id); end; function TUserRepository.GetOneByName(const Name: string): TUser; var NameCriteria: Prop; List: IList<TUser>; begin NameCriteria := Prop.Create('NAME'); List := FDb.GetSession.FindWhere<TUser>(NameCriteria = Name); if List.Count>=1 then Result := List.Extract(List.Last) else begin Result := GlobalContainer.Resolve<TUser>; Result.Name := Name; FDb.GetSession.Insert(Result); Result := GetOneByName(Name); end; end; procedure TUserRepository.Insert(const User: TUser); begin FDb.GetSession.Insert(User); end; procedure TUserRepository.Update(const User: TUser); begin FDb.GetSession.Update(User); end; end.
{*******************************************************} { } { Модуль Гауссово размытие } { Copyright (c) 2015 } { } { } { Раработчик: Ророт Евгений } { Создан: 20.10.2015 } { Модифицирован: 20.10.2015 } { } {*******************************************************} unit GausUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls; type TGausForm = class(TForm) Label1: TLabel; TrackBar: TTrackBar; Edit: TEdit; UpDown: TUpDown; ButtonOK: TButton; ButtonCancel: TButton; procedure TrackBarChange(Sender: TObject); procedure EditChange(Sender: TObject); procedure ButtonCancelClick(Sender: TObject); procedure ButtonOKClick(Sender: TObject); procedure ButtonOKKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var GausForm: TGausForm; image:TBitmap; implementation {$R *.dfm} Uses MainUnit; type PRGBTriple = ^TRGBTriple; TRGBTriple = packed record b: byte; //легче для использования чем типа rgbtBlue... g: byte; r: byte; end; PRow = ^TRow; TRow = array[0..1000000] of TRGBTriple; PPRows = ^TPRows; TPRows = array[0..1000000] of PRow; const MaxKernelSize = 100; type TKernelSize = 1..MaxKernelSize; TKernel = record Size: TKernelSize; Weights: array[-MaxKernelSize..MaxKernelSize] of single; end; //идея заключается в том, что при использовании TKernel мы игнорируем //Weights (вес), за исключением Weights в диапазоне -Size..Size. procedure MakeGaussianKernel(var K: TKernel; radius: double; MaxData, DataGranularity: double); //Делаем K (гауссово зерно) со среднеквадратичным отклонением = radius. //Для текущего приложения мы устанавливаем переменные MaxData = 255, //DataGranularity = 1. Теперь в процедуре установим значение //K.Size так, что при использовании K мы будем игнорировать Weights (вес) //с наименее возможными значениями. (Малый размер нам на пользу, //поскольку время выполнения напрямую зависит от //значения K.Size.) var j: integer; temp, delta: double; KernelSize: TKernelSize; begin for j := Low(K.Weights) to High(K.Weights) do begin temp := j / radius; K.Weights[j] := exp(-temp * temp / 2); end; //делаем так, чтобы sum(Weights) = 1: temp := 0; for j := Low(K.Weights) to High(K.Weights) do temp := temp + K.Weights[j]; for j := Low(K.Weights) to High(K.Weights) do K.Weights[j] := K.Weights[j] / temp; //теперь отбрасываем (или делаем отметку "игнорировать" //для переменной Size) данные, имеющие относительно небольшое значение - //это важно, в противном случае смазавание происходим с малым радиусом и //той области, которая "захватывается" большим радиусом... KernelSize := MaxKernelSize; delta := DataGranularity / (2 * MaxData); temp := 0; while (temp < delta) and (KernelSize > 1) do begin temp := temp + 2 * K.Weights[KernelSize]; dec(KernelSize); end; K.Size := KernelSize; //теперь для корректности возвращаемого результата проводим ту же //операцию с K.Size, так, чтобы сумма всех данных была равна единице: temp := 0; for j := -K.Size to K.Size do temp := temp + K.Weights[j]; for j := -K.Size to K.Size do K.Weights[j] := K.Weights[j] / temp; end; function TrimInt(Lower, Upper, theInteger: integer): integer; begin if (theInteger <= Upper) and (theInteger >= Lower) then result := theInteger else if theInteger > Upper then result := Upper else result := Lower; end; function TrimReal(Lower, Upper: integer; x: double): integer; begin if (x < upper) and (x >= lower) then result := trunc(x) else if x > Upper then result := Upper else result := Lower; end; procedure BlurRow(var theRow: array of TRGBTriple; K: TKernel; P: PRow); var j, n, LocalRow: integer; tr, tg, tb: double; //tempRed и др. w: double; begin for j := 0 to High(theRow) do begin tb := 0; tg := 0; tr := 0; for n := -K.Size to K.Size do begin w := K.Weights[n]; //TrimInt задает отступ от края строки... with theRow[TrimInt(0, High(theRow), j - n)] do begin tb := tb + w * b; tg := tg + w * g; tr := tr + w * r; end; end; with P[j] do begin b := TrimReal(0, 255, tb); g := TrimReal(0, 255, tg); r := TrimReal(0, 255, tr); end; end; Move(P[0], theRow[0], (High(theRow) + 1) * Sizeof(TRGBTriple)); end; procedure GBlur(theBitmap: TBitmap; radius: double); var Row, Col: integer; theRows: PPRows; K: TKernel; ACol: PRow; P: PRow; begin if (theBitmap.HandleType <> bmDIB) or (theBitmap.PixelFormat <> pf24Bit) then raise exception.Create('GBlur может работать только с 24-битными изображениями'); MakeGaussianKernel(K, radius, 255, 1); GetMem(theRows, theBitmap.Height * SizeOf(PRow)); GetMem(ACol, theBitmap.Height * SizeOf(TRGBTriple)); //запись позиции данных изображения: for Row := 0 to theBitmap.Height - 1 do theRows[Row] := theBitmap.Scanline[Row]; //размываем каждую строчку: P := AllocMem(theBitmap.Width * SizeOf(TRGBTriple)); for Row := 0 to theBitmap.Height - 1 do BlurRow(Slice(theRows[Row]^, theBitmap.Width), K, P); //теперь размываем каждую колонку ReAllocMem(P, theBitmap.Height * SizeOf(TRGBTriple)); for Col := 0 to theBitmap.Width - 1 do begin //- считываем первую колонку в TRow: for Row := 0 to theBitmap.Height - 1 do ACol[Row] := theRows[Row][Col]; BlurRow(Slice(ACol^, theBitmap.Height), K, P); //теперь помещаем обработанный столбец на свое место в данные изображения: for Row := 0 to theBitmap.Height - 1 do theRows[Row][Col] := ACol[Row]; end; FreeMem(theRows); FreeMem(ACol); ReAllocMem(P, 0); end; procedure TGausForm.ButtonCancelClick(Sender: TObject); begin buffer.Assign(img); GausForm.Close; end; procedure TGausForm.ButtonOKClick(Sender: TObject); begin img.Assign(buffer); GausForm.Close; end; procedure TGausForm.ButtonOKKeyPress(Sender: TObject; var Key: Char); begin if key=#13 then ButtonOK.Click; if key=#27 then ButtonCancel.Click; end; procedure TGausForm.EditChange(Sender: TObject); begin buffer.Assign(img); TrackBar.Position:=StrToInt(Edit.Text); GBlur(buffer, TrackBar.Position); MainForm.PaintBox.Visible:=false; MainForm.PaintBox.Visible:=true; end; procedure TGausForm.TrackBarChange(Sender: TObject); begin Edit.Text:=IntToStr(TrackBar.Position); end; end.
unit AccountTitlesList; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseGridDetail, Data.DB, RzButton, Vcl.StdCtrls, Vcl.Mask, RzEdit, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzLabel, Vcl.ExtCtrls, RzPanel, RzDBEdit, Vcl.DBCtrls, RzDBCmbo, RzCmboBx, RzRadChk, RzDBChk; type TfrmAccountTitlesList = class(TfrmBaseGridDetail) Label2: TLabel; edCode: TRzDBEdit; edName: TRzDBEdit; Label3: TLabel; Label4: TLabel; mmDescription: TRzDBMemo; Label9: TLabel; dbluLineItem: TRzDBLookupComboBox; Label5: TLabel; cmbCostType: TRzDBComboBox; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } protected function EntryIsValid: boolean; override; function NewIsAllowed: boolean; override; function EditIsAllowed: boolean; override; procedure SearchList; override; procedure BindToObject; override; end; implementation {$R *.dfm} uses AccountingAuxData, IFinanceDialogs; { TfrmAccountTitlesList } procedure TfrmAccountTitlesList.BindToObject; begin inherited; end; function TfrmAccountTitlesList.EditIsAllowed: boolean; begin end; function TfrmAccountTitlesList.EntryIsValid: boolean; var error: string; begin if Trim(edCode.Text) = '' then error := 'Please enter code.' else if Trim(edName.Text) = '' then error := 'Please enter name.' else if Trim(dbluLineItem.Text) = '' then error := 'Please select a line item.'; if error <> '' then ShowErrorBox(error); Result := error = ''; end; procedure TfrmAccountTitlesList.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; dmAccountingAux.Free; end; procedure TfrmAccountTitlesList.FormCreate(Sender: TObject); begin dmAccountingAux := TdmAccountingAux.Create(self); inherited; end; function TfrmAccountTitlesList.NewIsAllowed: boolean; begin end; procedure TfrmAccountTitlesList.SearchList; begin grList.DataSource.DataSet.Locate('acct_title_name',edSearchKey.Text, [loPartialKey,loCaseInsensitive]); end; end.
(** * Crab Cups parts 1 and 2 in Pascal (derived from C solution). * * Build with 'fpc -Mdelphi puzzle.pas' to have 32 bits Integer type. Reduce * MaxCups, MaxRounds and Progress constants to compile with Turbo Pascal 3. *) program CrabCups; type MyString = String[9]; (* To make Turbo Pascal happy. *) const MaxCups = 1000000; (* Number of cups in part 2. *) MaxRounds = 10000000; (* Number of rounds in part 2. *) Progress = 10000; (* Progress indicator steps. *) var Total: Integer; (* Total number of cups. *) Current: Integer; (* Number of current cup. *) Next: Array[1..MaxCups] of Integer; (* Neighbors of each cup. *) (** * Sets neighbor of cup i to j. *) procedure SetNext(I, J: Integer); begin Next[I] := J; end; (** * Gets neighbor of cup i. *) function GetNext(I: Integer): Integer; begin GetNext := Next[I]; end; (** * Starts a new game with the given start configuration and a given total number * of cups. *) procedure Init(Start: MyString; Cups: Integer); var I, J, K: Integer; begin Total := Cups; Current := Ord(Start[1]) - Ord('0'); (* Link start cups with each other. *) J := Current; for I := 2 to Length(Start) do begin K := Ord(Start[I]) - Ord('0'); WriteLn(J, ' -> ', K); SetNext(J, K); J := K; end; (* Link remaining cups (if any). *) WriteLn('[....]'); for I := Length(Start) + 1 to Cups do begin (* WriteLn(J, ' -> ', K); *) SetNext(J, I); J := I; end; (* Link last cup with first in start configuration. *) WriteLn(Cups, ' -> ', Current); SetNext(J, Current); WriteLn; end; (** * Plays the given number of rounds, wildly shuffling and swapping our cups. *) procedure Play(Rounds: Integer); var Hand, Dest: Integer; begin while Rounds > 0 do begin Rounds := Rounds - 1; (* Pick *) Hand := GetNext(Current); SetNext(Current, GetNext(GetNext(GetNext(Hand)))); (* Place *) Dest := Current; repeat Dest := Dest - 1; if Dest = 0 then Dest := Total; until (Dest <> Hand) and (Dest <> GetNext(Hand)) and (Dest <> GetNext(GetNext(Hand))); SetNext(GetNext(GetNext(Hand)), GetNext(Dest)); SetNext(Dest, Hand); (* Rotate *) Current := GetNext(Current); if Rounds mod Progress = 0 then Write('#'); end; WriteLn; WriteLn; end; (** * Prints the solution (neighbors of cup 1, product of first and second). *) procedure Done; var Cup1, Cup2, I: Integer; Product: Real; begin Cup1 := GetNext(1); Cup2 := GetNext(Cup1); Product := Cup1 * Cup2; (* Caution: Large value! *) Write('Neighbors of 1 = '); for I := 1 to 9 do begin Write(Cup1, ' '); Cup1 := GetNext(Cup1); end; WriteLn; WriteLn('First * second = ', product:0:0); WriteLn; end; begin WriteLn('*** AoC 2020.23 Crab Cups ***'); WriteLn; WriteLn('--- Part 1 ---'); WriteLn; Init('398254716', 9); Play(100); Done; WriteLn('--- Part 2 ---'); WriteLn; Init('398254716', MaxCups); Play(MaxRounds); Done; end.
unit ORSplitter; interface uses Controls, Graphics, ExtCtrls, Classes, Types, Windows; type TSplitOrientation = (soHorizontal, soVertical); TORSplitter = class(TGraphicControl) private FActiveControl: TWinControl; FAutoSnap: Boolean; FBeveled: Boolean; FBrush: TBrush; FDownPos: TPoint; FLineDC: HDC; FLineVisible: Boolean; FMinSize: NaturalNumber; FMaxSize: Integer; FNewSize: Integer; FOldKeyDown: TKeyEvent; FOldSize: Integer; FPrevBrush: HBrush; FResizeStyle: TResizeStyle; FSplit: Integer; FOnCanResize: TCanResizeEvent; FOnMoved: TNotifyEvent; FOnPaint: TNotifyEvent; fSplitOrientation: TSplitOrientation; procedure AllocateLineDC; procedure CalcSplitSize(X, Y: Integer; var NewSize, Split: Integer); procedure DrawLine; procedure FocusKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ReleaseLineDC; procedure SetBeveled(Value: Boolean); procedure UpdateSize(X, Y: Integer); procedure SetSplitOrientation(const Value: TSplitOrientation); function GetSplitOrientation: TSplitOrientation; protected function CanResize(var NewSize: Integer): Boolean; reintroduce; virtual; function DoCanResize(var NewSize: Integer): Boolean; virtual; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; procedure RequestAlign; override; procedure StopSizing; dynamic; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Canvas; published property Align default alNone; property AutoSnap: Boolean read FAutoSnap write FAutoSnap default True; property Beveled: Boolean read FBeveled write SetBeveled default False; property Color; property Cursor; property Constraints; property MinSize: NaturalNumber read FMinSize write FMinSize; property ParentColor; property ResizeStyle: TResizeStyle read FResizeStyle write FResizeStyle; property Visible; property Width; property Height; property OnCanResize: TCanResizeEvent read FOnCanResize write FOnCanResize; property OnMoved: TNotifyEvent read FOnMoved write FOnMoved; property OnPaint: TNotifyEvent read FOnPaint write FOnPaint; property SplitOrientation: TSplitOrientation read GetSplitOrientation write SetSplitOrientation; end; implementation uses Themes, Forms; { TORSplitter } type TWinControlAccess = class(TWinControl); constructor TORSplitter.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle - [csGestures]; FOldSize := -1; end; destructor TORSplitter.Destroy; begin FBrush.Free; inherited Destroy; end; procedure TORSplitter.AllocateLineDC; begin FLineDC := GetDCEx(Parent.Handle, 0, DCX_CACHE or DCX_CLIPSIBLINGS or DCX_LOCKWINDOWUPDATE); if ResizeStyle = rsPattern then begin if FBrush = nil then begin FBrush := TBrush.Create; if TStyleManager.IsCustomStyleActive then with StyleServices do FBrush.Bitmap := AllocPatternBitmap(clBlack, GetStyleColor(scSplitter)) else FBrush.Bitmap := AllocPatternBitmap(clBlack, clWhite); end; FPrevBrush := SelectObject(FLineDC, FBrush.Handle); end; end; procedure TORSplitter.DrawLine; var P: TPoint; begin FLineVisible := not FLineVisible; P := Point(Left, Top); if (SplitOrientation = soVertical) then P.X := Left + FSplit else P.Y := Top + FSplit; PatBlt(FLineDC, p.X, p.Y, Width, Height, PATINVERT); end; procedure TORSplitter.ReleaseLineDC; begin if FPrevBrush <> 0 then SelectObject(FLineDC, FPrevBrush); ReleaseDC(Parent.Handle, FLineDC); if FBrush <> nil then begin FBrush.Free; FBrush := nil; end; end; procedure TORSplitter.RequestAlign; begin inherited RequestAlign; if (Cursor <> crVSplit) and (Cursor <> crHSplit) then Exit; if SplitOrientation = soVertical then Cursor := crHSplit else Cursor := crVSplit; end; procedure TORSplitter.Paint; const XorColor = $00FFD8CE; var FrameBrush: HBRUSH; R: TRect; begin R := ClientRect; if TStyleManager.IsCustomStyleActive then Canvas.Brush.Color := StyleServices.GetSystemColor(clBtnFace) else Canvas.Brush.Color := Color; Canvas.FillRect(ClientRect); if Beveled then begin if (SplitOrientation = soVertical) then InflateRect(R, -1, 2) else InflateRect(R, 2, -1); OffsetRect(R, 1, 1); FrameBrush := CreateSolidBrush(ColorToRGB(StyleServices.GetSystemColor(clBtnHighlight))); FrameRect(Canvas.Handle, R, FrameBrush); DeleteObject(FrameBrush); OffsetRect(R, -2, -2); FrameBrush := CreateSolidBrush(ColorToRGB(StyleServices.GetSystemColor(clBtnShadow))); FrameRect(Canvas.Handle, R, FrameBrush); DeleteObject(FrameBrush); end; if csDesigning in ComponentState then { Draw outline } with Canvas do begin Pen.Style := psDot; Pen.Mode := pmXor; Pen.Color := XorColor; Brush.Style := bsClear; Rectangle(0, 0, ClientWidth, ClientHeight); end; if Assigned(FOnPaint) then FOnPaint(Self); end; function TORSplitter.DoCanResize(var NewSize: Integer): Boolean; begin Result := CanResize(NewSize); if Result and (NewSize <= MinSize) and FAutoSnap then NewSize := 0; end; function TORSplitter.CanResize(var NewSize: Integer): Boolean; begin Result := True; if Assigned(FOnCanResize) then FOnCanResize(Self, NewSize, Result); end; procedure TORSplitter.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); if Button = mbLeft then begin FDownPos := Point(X, Y); UpdateSize(X, Y); AllocateLineDC; with ValidParentForm(Self) do if ActiveControl <> nil then begin FActiveControl := ActiveControl; FOldKeyDown := TWinControlAccess(FActiveControl).OnKeyDown; TWinControlAccess(FActiveControl).OnKeyDown := FocusKeyDown; end; if ResizeStyle in [rsLine, rsPattern] then DrawLine; end; end; procedure TORSplitter.CalcSplitSize(X, Y: Integer; var NewSize, Split: Integer); var S: Integer; begin if (SplitOrientation = soVertical) then Split := X - FDownPos.X else Split := Y - FDownPos.Y; S := 0; NewSize := S; if S < FMinSize then NewSize := FMinSize else if S > FMaxSize then NewSize := FMaxSize; if S <> NewSize then begin if Align in [alRight, alBottom] then S := S - NewSize else S := NewSize - S; Inc(Split, S); end; end; procedure TORSplitter.UpdateSize(X, Y: Integer); begin CalcSplitSize(X, Y, FNewSize, FSplit); end; procedure TORSplitter.MouseMove(Shift: TShiftState; X, Y: Integer); var NewSize, Split: Integer; begin inherited; if (ssLeft in Shift) and (Align = alNone) then begin CalcSplitSize(X, Y, NewSize, Split); if DoCanResize(NewSize) then begin if ResizeStyle in [rsLine, rsPattern] then DrawLine; FNewSize := NewSize; FSplit := Split; if ResizeStyle in [rsLine, rsPattern] then DrawLine; end; end; end; procedure TORSplitter.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if ResizeStyle in [rsLine, rsPattern] then DrawLine; StopSizing; end; procedure TORSplitter.FocusKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then StopSizing else if Assigned(FOldKeyDown) then FOldKeyDown(Sender, Key, Shift); end; function TORSplitter.GetSplitOrientation: TSplitOrientation; begin case Align of alLeft, alRight: Result := soVertical; alTop, alBottom: Result := soHorizontal; else Result := fSplitOrientation; end; end; procedure TORSplitter.SetBeveled(Value: Boolean); begin FBeveled := Value; Repaint; end; procedure TORSplitter.SetSplitOrientation(const Value: TSplitOrientation); begin fSplitOrientation := Value; RequestAlign; end; procedure TORSplitter.StopSizing; begin if FLineVisible then DrawLine; ReleaseLineDC; if Assigned(FActiveControl) then begin TWinControlAccess(FActiveControl).OnKeyDown := FOldKeyDown; FActiveControl := nil; end; if SplitOrientation = soVertical then Left := Left + FSplit else Top := Top + FSplit; if Assigned(FOnMoved) then FOnMoved(Self); end; end.
unit UFrmGoodsSelect; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmModal, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, ActnList, StdCtrls, cxButtons, ExtCtrls, cxControls, cxContainer, cxEdit, dxSkinsCore, dxSkinsDefaultPainters, cxTextEdit, cxStyles, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, DB, cxDBData, cxCurrencyEdit, cxDBLookupComboBox, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, DBClient; type TFrmGoodsSelect = class(TFrmModal) pnlTop: TPanel; lbl1: TLabel; edtFilter: TcxTextEdit; btnFilter: TcxButton; GrdData: TcxGrid; GrdbtblvwData: TcxGridDBTableView; ClmnDataGoodsID: TcxGridDBColumn; ClmnDataGoodsName: TcxGridDBColumn; ClmnDataGoodsPYM: TcxGridDBColumn; ClmnDataGoodsType: TcxGridDBColumn; ClmnDataGoodsUnit: TcxGridDBColumn; ClmnDataGoodsPrice: TcxGridDBColumn; ClmnDataClassGuid: TcxGridDBColumn; GrdlvlData: TcxGridLevel; ClmnDataGoodsBarCode: TcxGridDBColumn; procedure FormShow(Sender: TObject); procedure GrdbtblvwDataDblClick(Sender: TObject); procedure GrdbtblvwDataKeyPress(Sender: TObject; var Key: Char); procedure btnOkClick(Sender: TObject); procedure edtFilterKeyPress(Sender: TObject; var Key: Char); procedure btnFilterClick(Sender: TObject); private public { Public declarations } end; var FrmGoodsSelect: TFrmGoodsSelect; implementation uses UDBAccess, UMsgBox, UDmBillBase; {$R *.dfm} procedure TFrmGoodsSelect.btnFilterClick(Sender: TObject); begin inherited; DmBillBase.DoGoodsFilter(Trim(edtFilter.Text)); GrdData.SetFocus; end; procedure TFrmGoodsSelect.btnOkClick(Sender: TObject); begin inherited; if not DmBillBase.CdsGoods.Active or DmBillBase.CdsGoods.IsEmpty then begin ShowMsg('请选择商品信息!'); Exit; end; ModalResult := mrOk; end; procedure TFrmGoodsSelect.edtFilterKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key = #13 then btnFilter.Click; end; procedure TFrmGoodsSelect.FormShow(Sender: TObject); begin inherited; GrdData.SetFocus; end; procedure TFrmGoodsSelect.GrdbtblvwDataDblClick(Sender: TObject); begin inherited; btnOk.Click; end; procedure TFrmGoodsSelect.GrdbtblvwDataKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key = #13 then btnOk.Click; end; end.
{ This sample application demonstrates the following features of the TOLEContainer: - Toolbar negotiation - Status bar hints while inplace editing - Using the TOLEContainer's dialogs including InsertObject, ObjectProperties and PasteSpecial. - Using the TOLEContainer's constructors CreateLinkToFile, CreateObjectFromFile. - Menu merging during in-place activation } unit sdimain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, Buttons, ExtCtrls, Menus, OleCtnrs, StdCtrls; type TMainForm = class(TForm) MainMenu1: TMainMenu; File1: TMenuItem; Exit1: TMenuItem; Help1: TMenuItem; About1: TMenuItem; Toolbar: TPanel; SpeedButton1: TSpeedButton; LinkButton: TSpeedButton; CopyButton: TSpeedButton; CutButton: TSpeedButton; PasteButton: TSpeedButton; OpenButton: TSpeedButton; OpenDialog1: TOpenDialog; StatusPanel: TPanel; StatusBar: TStatusBar; Save1: TMenuItem; SaveAs1: TMenuItem; SaveDialog1: TSaveDialog; Open1: TMenuItem; N2: TMenuItem; SaveButton: TSpeedButton; Edit1: TMenuItem; Object1: TMenuItem; N4: TMenuItem; PasteSpecial1: TMenuItem; Paste1: TMenuItem; Copy1: TMenuItem; Cut1: TMenuItem; New1: TMenuItem; Panel1: TPanel; OleContainer1: TOleContainer; procedure Exit1Click(Sender: TObject); procedure Copy1Click(Sender: TObject); procedure Paste1Click(Sender: TObject); procedure Object2Click(Sender: TObject); procedure LinkButtonClick(Sender: TObject); procedure About1Click(Sender: TObject); procedure Save1Click(Sender: TObject); procedure File1Click(Sender: TObject); procedure Open1Click(Sender: TObject); procedure CutButtonClick(Sender: TObject); procedure New1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Object1Click(Sender: TObject); procedure Cut1Click(Sender: TObject); procedure PasteSpecial1Click(Sender: TObject); procedure Edit1Click(Sender: TObject); private ObjectFileName: TFileName; InsertCanceled: Boolean; procedure ShowHint(Sender: TObject); end; var MainForm: TMainForm; implementation uses about; {$R *.dfm} procedure TMainForm.ShowHint(Sender: TObject); begin Statusbar.Panels[0].Text := Application.Hint; end; procedure TMainForm.Exit1Click(Sender: TObject); begin Close; end; procedure TMainForm.Copy1Click(Sender: TObject); begin OleContainer1.Copy; PasteButton.Enabled := True; end; procedure TMainForm.Paste1Click(Sender: TObject); begin if (OleContainer1.State = osEmpty) or (MessageDlg('Replace existing object?', mtConfirmation, mbOkCancel, 0) = mrOk) then begin OleContainer1.Paste; CopyButton.Enabled := True; CutButton.Enabled := True; end; end; procedure TMainForm.Object2Click(Sender: TObject); begin if OleContainer1.State <> osEmpty then OleContainer1.ObjectPropertiesDialog; end; procedure TMainForm.LinkButtonClick(Sender: TObject); begin if (OleContainer1.State = osEmpty) or (MessageDlg('Replace existing object?', mtConfirmation, mbOkCancel, 0) = mrOk) then with OpenDialog1 do if OpenDialog1.Execute then begin OleContainer1.CreateLinkToFile(FileName, False); ObjectFileName := FileName; CutButton.Enabled := True; CopyButton.Enabled := True; PasteButton.Enabled := OleContainer1.CanPaste; end; end; procedure TMainForm.About1Click(Sender: TObject); begin AboutBox := TAboutBox.Create(Self); try AboutBox.ShowModal; finally AboutBox.Free; end; end; procedure TMainForm.Save1Click(Sender: TObject); begin with SaveDialog1 do begin SaveDialog1.FileName := ObjectFileName; if (Length(FileName) = 0) or (Sender = SaveAs1) then begin if Execute then begin OleContainer1.SaveToFile(FileName); ObjectFileName := FileName; end end else OleContainer1.SaveToFile(FileName); end; end; procedure TMainForm.File1Click(Sender: TObject); begin with OleContainer1 do begin Save1.Enabled := Modified; SaveAs1.Enabled := Modified; end; end; procedure TMainForm.Open1Click(Sender: TObject); begin with OpenDialog1 do if Execute then begin OleContainer1.CreateObjectFromFile(FileName, False); ObjectFileName := FileName; CutButton.Enabled := True; CopyButton.Enabled := True; PasteButton.Enabled := True; end; end; procedure TMainForm.CutButtonClick(Sender: TObject); begin if OleContainer1.State <> osEmpty then with OleContainer1 do begin Copy; DestroyObject; CopyButton.Enabled := False; PasteButton.Enabled := OleContainer1.CanPaste; ObjectFilename := ''; end; end; procedure TMainForm.New1Click(Sender: TObject); begin if (OleContainer1.State = osEmpty) or (MessageDlg('Delete existing object?', mtConfirmation, mbOkCancel, 0) = mrOk) then begin InsertCanceled := false; with OleContainer1 do begin DestroyObject; Object1Click(Sender); if not InsertCanceled then begin DoVerb(PrimaryVerb); ObjectFileName := ''; end; end end; end; procedure TMainForm.FormCreate(Sender: TObject); begin ObjectFileName := ''; Application.OnHint := ShowHint; end; procedure TMainForm.Object1Click(Sender: TObject); begin if (OleContainer1.State = osEmpty) or (MessageDlg('Delete current OLE object?', mtConfirmation, mbOkCancel, 0) = mrOk) then if OleContainer1.InsertObjectDialog then begin CutButton.Enabled := True; CopyButton.Enabled := True; PasteButton.Enabled := OleContainer1.CanPaste; with OleContainer1 do DoVerb(PrimaryVerb); end else InsertCanceled := true; end; procedure TMainForm.Cut1Click(Sender: TObject); begin OleContainer1.Copy; OleContainer1.DestroyObject; CutButton.Enabled := False; CopyButton.Enabled := False; PasteButton.Enabled := OleContainer1.CanPaste; end; procedure TMainForm.PasteSpecial1Click(Sender: TObject); begin if (OleContainer1.State = osEmpty) or (MessageDlg('Delete current OLE object?', mtConfirmation, mbOkCancel, 0) = mrOk) then begin if OleContainer1.PasteSpecialDialog then begin CutButton.Enabled := True; CopyButton.Enabled := True; PasteButton.Enabled := OleContainer1.CanPaste; end; end; end; procedure TMainForm.Edit1Click(Sender: TObject); begin with OleContainer1 do begin Cut1.Enabled := State <> osEmpty; Copy1.Enabled := State <> osEmpty; Paste1.Enabled := CanPaste; PasteSpecial1.Enabled := CanPaste; end; end; end.
unit ncaFramePagamento; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxLabel, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, LMDGraph, cxPCdxBarPopupMenu, cxPC, ncEspecie, Menus, StdCtrls, cxButtons; type TFramePagamento = class(TFrame) panPri: TLMDSimplePanel; panValores: TLMDSimplePanel; private { Private declarations } FOnClicouPagamento : TNotifyEvent; procedure _OnClicouPag(Sender: TObject); public procedure Clear; procedure Add(aPrompt: String; aValor: Currency; aCorFonte, aCor: TColor; aHeight: Byte; aTraco: Boolean; aBold: Boolean=False); procedure Load(aPagEsp: TncPagEspecies; aTotal, aDesconto, aTroco, aCredUsado, aCreditado: Currency); property OnClicouPagamento: TNotifyEvent read FOnClicouPagamento write FOnClicouPagamento; { Public declarations } end; implementation uses ncClassesBase; {$R *.dfm} resourcestring rsSubTotal = 'Sub-Total'; rsDesconto = 'Desconto'; rsTotalPagar = 'Total à pagar'; rsTroco = 'Troco'; rsCredUsado = 'Crédito Usado'; rsSalvarCred = 'Salvar crédito em conta'; rsEditarPag = 'Editar Pagamento (F2)'; { TFrame1 } procedure TFramePagamento.Add(aPrompt: String; aValor: Currency; aCorFonte, aCor: TColor; aHeight: Byte; aTraco: Boolean; aBold: Boolean = False); var P : TLMDSimplePanel; L : TcxLabel; begin P := TLMDSimplePanel.Create(panValores); P.Height := aHeight; P.Color := aCor; if aTraco then begin P.Bevel.Mode := bmEdge; P.Bevel.EdgeStyle := etEtched; P.Bevel.BorderSides := [fsBottom]; end; P.Align := alTop; P.Parent := panValores; P.Top := (panValores.ComponentCount-1) * 40; P.Margins.Top := 0; P.Margins.Left := 0; P.Margins.Right := 0; P.Margins.Bottom := 1; P.AlignWithMargins := True; L := TcxLabel.Create(panValores); L.Parent := P; L.Align := alClient; L.Properties.Alignment.Vert := taVCenter; L.Caption := aPrompt; if aBold then L.Style.TextColor := aCorFonte; L := TcxLabel.Create(panValores); L.Parent := P; L.Align := alRight; L.Properties.Alignment.Vert := taVCenter; L.Caption := CurrencyToStr(aValor); L.Style.TextColor := aCorFonte; if aBold then L.Style.TextStyle := [fsBold]; end; procedure TFramePagamento.Clear; begin while panValores.ComponentCount>0 do panValores.Components[0].Free; end; procedure TFramePagamento.Load(aPagEsp: TncPagEspecies; aTotal, aDesconto, aTroco, aCredUsado, aCreditado: Currency); var I: Integer; B: TcxButton; begin LockWindowUpdate(panPri.Handle); try Clear; if aDesconto>0 then begin Add(rsSubTotal, aTotal, clBlack, clBtnFace, 30, False); Add(rsDesconto, aDesconto*-1, clRed, clBtnFace, 30, False); end; Add(rsTotalPagar, aTotal-aDesconto, clAzulNEX, clBtnFace, 30, False, True); if aCredUsado>0 then Add(rsCredUsado, aCredUsado, clGreen, clBtnFace, 30, False); for i := 0 to aPagEsp.Count - 1 do with aPagEsp.Items[i] do Add(Nome, peValor, clBlack, clBtnFace, 30, False, True); if aTroco>0 then Add(rsTroco, aTroco, clGreen, clBtnFace, 30, False, True); if aPagEsp.Credito>0 then Add(rsSalvarCred, aPagEsp.Credito, clGreen, clBtnFace, 30, False, True); with TcxButton.Create(panValores) do begin Parent := panValores; Align := alTop; LookAndFeel.Kind := lfFlat; LookAndFeel.NativeStyle := False; Top := 1000; Margins.Top := 1; Margins.Left := 0; Margins.Right := 0; margins.Bottom := 0; Caption := rsEditarPag; Font.Name := 'Segoe UI Semibold'; Font.Size := 10; Font.Style := []; OnClick := OnClicouPagamento; end; finally LockWindowUpdate(0); end; end; procedure TFramePagamento._OnClicouPag(Sender: TObject); begin if Assigned(FOnClicouPagamento) then FOnClicouPagamento(Self); end; end.
UNIT PersonUnit; INTERFACE TYPE MoodType = (happy, excited, funny, angry, tired); Person = ^PersonObj; PersonObj = OBJECT name: STRING; age: INTEGER; mood: MoodType; CONSTRUCTOR Init(name: STRING); CONSTRUCTOR Init2(name: STRING; mood: MoodType); DESTRUCTOR Done; PROCEDURE SaySomething; FUNCTION ToString: STRING; END; (* PERSON *) IMPLEMENTATION FUNCTION MoodTypeToString(mood: MoodType): STRING; BEGIN (* MoodTypeToString *) CASE (mood) OF happy: MoodTypeToString := 'happy'; excited: MoodTypeToString := 'excited'; funny: MoodTypeToString := 'funny'; angry: MoodTypeToString := 'angry'; tired: MoodTypeToString := 'tired'; END; END; (* MoodTypeToString *) CONSTRUCTOR PersonObj.Init(name: STRING); BEGIN (* CONSTRUCTOR *) self.name := name; age := 0; mood := excited; END; (* CONSTRUCTOR *) CONSTRUCTOR PersonObj.Init2(name: STRING; mood: MoodType); BEGIN (* CONSTRUCTOR *) self.name := name; age := 0; self.mood := mood; END; (* CONSTRUCTOR *) DESTRUCTOR PersonObj.Done; BEGIN (* DESTRUCTOR *) END; (* DESTRUCTOR *) PROCEDURE PersonObj.SaySomething; BEGIN (* Person.SaySomething *) WriteLn('Hello, my name is ', name); END; (* Person.SaySomething *) FUNCTION PersonObj.ToString: STRING; BEGIN (* Person.ToString *) ToString := name + '(' + MoodTypeToString(mood) + ')'; END; (* Person.ToString *) BEGIN (* PersonUnit *) END. (* PersonUnit *)
{=============================================================================== TIntegerList Based on FPC RTL TList and TStringList License: Modified LGPL (same as FPC RTL) ===============================================================================} unit IntegerList; {$MODE DELPHI} {$DEFINE UseRTLMessages} interface uses Classes, SysUtils {$IFDEF UseRTLMessages}, RtlConsts{$ENDIF}; //--------------------------- Integer List ------------------------------------- type TIntListItem = Integer; PIntList = ^TIntList; TIntList = array[0..MaxListSize - 1] of TIntListItem; TIntListSortCompare = function (Item1, Item2: TIntListItem): Integer; const IntItemEmptyValue = 0; IntItemWordRatio = SizeOf(TIntListItem) div SizeOf(Word); type TIntegerList = class(TObject) private FList: PIntList; FCount: Integer; FCapacity: Integer; FDuplicates: TDuplicates; FSorted: Boolean; procedure CopyMove (AList: TIntegerList); procedure MergeMove (AList: TIntegerList); procedure DoCopy(ListA, ListB: TIntegerList); procedure DoSrcUnique(ListA, ListB: TIntegerList); procedure DoAnd(ListA, ListB: TIntegerList); procedure DoDestUnique(ListA, ListB: TIntegerList); procedure DoOr(ListA, ListB: TIntegerList); procedure DoXOr(ListA, ListB: TIntegerList); procedure QuickSort(FList: PIntList; L, R : Longint; Compare: TIntListSortCompare); procedure SetSorted(const Value: Boolean); protected function Get(Index: Integer): TIntListItem; procedure Put(Index: Integer; Item: TIntListItem); procedure SetCapacity(NewCapacity: Integer); function GetCapacity: Integer; procedure SetCount(NewCount: Integer); function GetCount: Integer; function GetList: PIntList; procedure InsertItem(Index: Integer; Item: TIntListItem); public procedure AddList(AList: TIntegerList); function Add(Item: TIntListItem): Integer; procedure Clear; virtual; procedure Delete(Index: Integer); class procedure Error(const Msg: string; Data: PtrInt); virtual; procedure Exchange(Index1, Index2: Integer); function Expand: TIntegerList; function Extract(Item: TIntListItem): TIntListItem; function First: TIntListItem; function Find(const Item: TIntListItem; var Index: Integer): Boolean; virtual; function IndexOf(Item: TIntListItem): Integer; procedure Insert(Index: Integer; Item: TIntListItem); function Last: TIntListItem; procedure Move(CurIndex, NewIndex: Integer); procedure Assign (ListA: TIntegerList; AOperator: TListAssignOp = laCopy; ListB: TIntegerList = nil); function Remove(Item: TIntListItem): Integer; procedure Sort; virtual; procedure CustomSort(Compare: TIntListSortCompare); property Duplicates: TDuplicates read FDuplicates write FDuplicates; property Sorted: Boolean read FSorted write SetSorted; property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount write SetCount; property Items[Index: Integer]: TIntListItem read Get write Put; default; property List: PIntList read GetList; end; implementation const {$IFNDEF UseRTLMessages} SListIndexError = 'List index (%d) out of bounds'; SListCapacityError = 'List capacity (%d) exceeded'; SListCountError = 'List count (%d) out of bounds'; SSortedListError = 'Operation not allowed on sorted list'; {$ENDIF} SDuplicateItem = 'List does not allow duplicates'; function IntListCompare(Item1, Item2: TIntListItem): Integer; begin if Item1 > Item2 then Exit(1) else if Item1 = Item2 then Exit(0) else Result := -1; end; { TIntegerList } procedure TIntegerList.CopyMove(AList: TIntegerList); var I: Integer; begin Clear; for I := 0 to AList.Count - 1 do Add(AList[I]); end; procedure TIntegerList.MergeMove(AList: TIntegerList); var I: Integer; begin for I := 0 to AList.Count - 1 do if IndexOf(AList[I]) < 0 then Add(AList[I]); end; procedure TIntegerList.DoCopy(ListA, ListB: TIntegerList); begin if Assigned(ListB) then CopyMove(ListB) else CopyMove(ListA); end; procedure TIntegerList.DoSrcUnique(ListA, ListB: TIntegerList); var I: Integer; begin if Assigned(ListB) then begin Clear; for I := 0 to ListA.Count-1 do if ListB.IndexOf(ListA[I]) < 0 then Add(ListA[I]); end else begin for I := Count-1 downto 0 do if ListA.IndexOf(Self[I]) >= 0 then Delete(I); end; end; procedure TIntegerList.DoAnd(ListA, ListB: TIntegerList); var I: Integer; begin if Assigned (ListB) then begin Clear; for I := 0 to ListA.Count-1 do if ListB.IndexOf (ListA[I]) >= 0 then Add(ListA[I]); end else begin for I := Count - 1 downto 0 do if ListA.IndexOf(Self[I]) < 0 then Delete(I); end; end; procedure TIntegerList.DoDestUnique(ListA, ListB: TIntegerList); procedure MoveElements (Src, Dest : TIntegerList); var I: Integer; begin Clear; for I := 0 to Src.Count-1 do if Dest.IndexOf(Src[I]) < 0 then Add(Src[I]); end; var Dest : TIntegerList; begin if Assigned (ListB) then MoveElements (ListB, ListA) else try Dest := TIntegerList.Create; Dest.CopyMove(Self); MoveElements(ListA, Dest) finally FreeAndNil(Dest); end; end; procedure TIntegerList.DoOr(ListA, ListB: TIntegerList); begin if Assigned(ListB) then begin CopyMove(ListA); MergeMove(ListB); end else MergeMove(ListA); end; procedure TIntegerList.DoXOr(ListA, ListB: TIntegerList); var I: Integer; List: TIntegerList; begin if assigned (ListB) then begin Clear; for I := 0 to ListA.Count - 1 do if ListB.IndexOf(ListA[I]) < 0 then Add(ListA[I]); for I := 0 to ListB.Count - 1 do if ListA.IndexOf(ListB[I]) < 0 then Add(ListB[I]); end else try List := TIntegerList.Create; List.CopyMove(Self); for I := Count - 1 downto 0 do if listA.IndexOf(Self[I]) >= 0 then Delete(I); for I := 0 to ListA.Count - 1 do if List.IndexOf(ListA[I]) < 0 then Add(ListA[I]); finally List.Free; end; end; procedure TIntegerList.QuickSort(FList: PIntList; L, R: Longint; Compare: TIntListSortCompare); var I, J: Longint; P, Q: TIntListItem; begin repeat I := L; J := R; P := FList^[ (L + R) div 2 ]; repeat while Compare(P, FList^[i]) > 0 do I := I + 1; while Compare(P, FList^[J]) < 0 do J := J - 1; If I <= J then begin Q := FList^[I]; FList^[I] := FList^[J]; FList^[J] := Q; I := I + 1; J := J - 1; end; until I > J; if L < J then QuickSort(FList, L, J, Compare); L := I; until I >= R; end; procedure TIntegerList.SetSorted(const Value: Boolean); begin if FSorted <> Value then begin if Value then Sort; FSorted := Value; end; end; function TIntegerList.Get(Index: Integer): TIntListItem; begin if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); Result := FList^[Index]; end; procedure TIntegerList.Put(Index: Integer; Item: TIntListItem); begin if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); FList^[Index] := Item; end; procedure TIntegerList.SetCapacity(NewCapacity: Integer); begin if (NewCapacity < FCount) or (NewCapacity > MaxListSize) then Error(SListCapacityError, NewCapacity); if NewCapacity = FCapacity then Exit; ReallocMem(FList, SizeOf(TIntListItem) * NewCapacity); FCapacity := NewCapacity; end; function TIntegerList.GetCapacity: Integer; begin Result := FCapacity; end; procedure TIntegerList.SetCount(NewCount: Integer); begin if NewCount < FCount then begin while NewCount < FCount do Delete(FCount - 1) end else begin if (NewCount < 0) or (NewCount > MaxListSize)then Error(SListCountError, NewCount); if NewCount > FCount then begin if NewCount > FCapacity then SetCapacity(NewCount); if FCount < NewCount then FillWord(FList^[FCount], (NewCount-FCount) * IntItemWordRatio, 0); end; FCount := Newcount; end; end; function TIntegerList.GetCount: Integer; begin Result := FCount; end; function TIntegerList.GetList: PIntList; begin Result := FList; end; procedure TIntegerList.AddList(AList: TIntegerList); var I: Integer; begin if (Capacity < Count + AList.Count) then Capacity := Count + AList.Count; for I := 0 to AList.Count - 1 do Add(AList[I]); end; function TIntegerList.Add(Item: TIntListItem): Integer; begin if not Sorted then Result := FCount else if Find(Item, Result) then case Duplicates of DupIgnore : Exit; DupError : Error(SDuplicateItem, 0); end; InsertItem(Result, Item); end; procedure TIntegerList.Clear; begin while (Count > 0) do Delete(Count-1); end; procedure TIntegerList.Delete(Index: Integer); begin if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); FCount := FCount-1; System.Move(FList^[Index+1], FList^[Index], (FCount - Index) * SizeOf(Pointer)); // Shrink the list if appropriate if (FCapacity > 256) and (FCount < FCapacity shr 2) then begin FCapacity := FCapacity shr 1; ReallocMem(FList, SizeOf(Pointer) * FCapacity); end; end; class procedure TIntegerList.Error(const Msg: string; Data: PtrInt); begin raise EListError.CreateFmt(Msg,[Data]) at get_caller_addr(get_frame); end; procedure TIntegerList.Exchange(Index1, Index2: Integer); var Temp: TIntListItem; begin if ((Index1 >= FCount) or (Index1 < 0)) then Error(SListIndexError, Index1); if ((Index2 >= FCount) or (Index2 < 0)) then Error(SListIndexError, Index2); Temp := FList^[Index1]; FList^[Index1] := FList^[Index2]; FList^[Index2] := Temp; end; function TIntegerList.Expand: TIntegerList; var IncSize: Integer; begin if FCount < FCapacity then exit; IncSize := 4; if FCapacity > 3 then IncSize := IncSize + 4; if FCapacity > 8 then IncSize := IncSize+8; if FCapacity > 127 then Inc(IncSize, FCapacity shr 2); SetCapacity(FCapacity + IncSize); Result := Self; end; function TIntegerList.Extract(Item: TIntListItem): TIntListItem; var I: Integer; begin I := IndexOf(Item); if I >= 0 then begin Result := Item; Delete(I); end else Result := IntItemEmptyValue; end; function TIntegerList.First: TIntListItem; begin if FCount = 0 then Result := IntItemEmptyValue else Result := Items[0]; end; function TIntegerList.Find(const Item: TIntListItem; var Index: Integer): Boolean; var L, R, I: Integer; CompareRes: Integer; begin Result := false; // Use binary search. L := 0; R := Count - 1; while (L <= R) do begin I := L + (R - L) div 2; CompareRes := IntListCompare(Item, FList^[I]); if (CompareRes > 0) then L := I + 1 else begin R := I - 1; if (CompareRes = 0) then begin Result := true; if (Duplicates <> dupAccept) then L := I; // forces end of while loop end; end; end; Index := L; end; function TIntegerList.IndexOf(Item: TIntListItem): Integer; begin Result := 0; while (Result < FCount) and (FList^[Result] <> Item) do Result := Result + 1; if Result = FCount then Result := -1; end; procedure TIntegerList.Insert(Index: Integer; Item: TIntListItem); begin if Sorted then Error(SSortedListError,0) else if (Index < 0) or (Index > FCount) then Error(SListIndexError, Index) else InsertItem(Index, Item); end; procedure TIntegerList.InsertItem(Index: Integer; Item: TIntListItem); begin if FCount = FCapacity then Self.Expand; if Index < FCount then System.Move(FList^[Index], FList^[Index+1], (FCount - Index) * SizeOf(TIntListItem)); FList^[Index] := Item; Inc(FCount); end; function TIntegerList.Last: TIntListItem; begin if FCount = 0 then Result := IntItemEmptyValue else Result := Items[FCount - 1]; end; procedure TIntegerList.Move(CurIndex, NewIndex: Integer); var Temp: TIntListItem; begin if ((CurIndex < 0) or (CurIndex > Count - 1)) then Error(SListIndexError, CurIndex); if ((NewIndex < 0) or (NewIndex > Count -1)) then Error(SlistIndexError, NewIndex); Temp := FList^[CurIndex]; FList^[CurIndex] := IntItemEmptyValue; Self.Delete(CurIndex); Self.InsertItem(NewIndex, IntItemEmptyValue); FList^[NewIndex] := Temp; end; procedure TIntegerList.Assign(ListA: TIntegerList; AOperator: TListAssignOp; ListB: TIntegerList); begin case AOperator of laCopy : DoCopy (ListA, ListB); // replace dest with src laSrcUnique : DoSrcUnique (ListA, ListB); // replace dest with src that are not in dest laAnd : DoAnd (ListA, ListB); // remove from dest that are not in src laDestUnique : DoDestUnique (ListA, ListB); // remove from dest that are in src laOr : DoOr (ListA, ListB); // add to dest from src and not in dest laXOr : DoXOr (ListA, ListB); // add to dest from src and not in dest, remove from dest that are in src end; end; function TIntegerList.Remove(Item: TIntListItem): Integer; begin Result := IndexOf(Item); if Result <> -1 then Delete(Result); end; procedure TIntegerList.Sort; begin CustomSort(IntListCompare); end; procedure TIntegerList.CustomSort(Compare: TIntListSortCompare); begin if not Assigned(FList) or (FCount < 2) then Exit; QuickSort(FList, 0, FCount-1, Compare); end; end.
unit PaymentMain; interface uses System.SysUtils, System.Classes, BaseDocked, Vcl.Controls, Vcl.StdCtrls, RzLabel, Vcl.ExtCtrls, RzPanel, Vcl.Mask, RzEdit, RzBtnEdt, Vcl.Grids, RzGrids, RzDBEdit, SaveIntf, System.UITypes, PaymentIntf, Vcl.Imaging.pngimage, Payment, StrUtils, Vcl.Graphics, System.Types, RzCmboBx, Data.DB, Vcl.DBGrids, RzDBGrid; type TfrmPaymentMain = class(TfrmBaseDocked, ISave, IPayment) pnlDetail: TRzPanel; grDetailStringGrid: TRzStringGrid; pnlAddPayment: TRzPanel; imgAddPayment: TImage; edClient: TRzEdit; pnlDeletePayment: TRzPanel; imgDeletePayment: TImage; dtePaymentDate: TRzDBDateTimeEdit; edReceipt: TRzDBEdit; cmbPaymentMethod: TRzComboBox; grDetail: TRzDBGrid; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; lblAdvancePayment: TLabel; Label5: TLabel; Label6: TLabel; lblReferenceNo: TLabel; lblPosted: TLabel; lblWithdrawn: TLabel; lblTotalAmount: TLabel; lblChange: TLabel; pnlCancelPayment: TRzPanel; imgCancelPayment: TImage; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure imgAddPaymentClick(Sender: TObject); procedure imgAddPaymentMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure imgAddPaymentMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormShow(Sender: TObject); procedure imgDeletePaymentClick(Sender: TObject); procedure grDetailStringGridResize(Sender: TObject); procedure grDetailStringGridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure dtePaymentDateChange(Sender: TObject); private { Private declarations } function SelectActiveClient: TModalResult; function SelectActiveLoan: TModalResult; function PaymentIsValid: boolean; procedure ShowPaymentDetail; procedure SetAmounts; procedure PopulateDetail; procedure AddRow(const detail: TPaymentDetail); procedure RemoveRow(const row: integer); procedure SetUnboundControls; procedure Retrieve; procedure ChangeControlState; procedure DeletePayment; procedure BindControlToObject; public { Public declarations } function Save: boolean; procedure Cancel; procedure AddActiveLoan; end; implementation {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} uses PaymentData, IFinanceDialogs, ActiveClientsSearch, ActiveClient, ActiveLoans, FormsUtil, PaymentDetail, PaymentMethod, IFinanceGlobal; function TfrmPaymentMain.PaymentIsValid: boolean; var error: string; begin BindControlToObject; if pmt.Date < ifn.AppDate then error := 'Payment date is set in the past.' else if not Assigned(pmt.PaymentMethod) then error := 'No payment method selected.' else if not Assigned(pmt.Client) then error := 'Please select a client.' else if pmt.DetailCount = 0 then error := 'Please add at least one payment detail.' else if pmt.PaymentMethod.Method = mdBankWithdrawal then begin if pmt.TotalAmount > pmt.Withdrawn then error := 'Total amount paid is greater than amount withdrawn.'; end; if error <> '' then ShowErrorBox(error); Result := error = '' end; function TfrmPaymentMain.Save: boolean; begin Result := false; if (pmt.IsNew) and (PaymentIsValid) then begin try if (Trim(edReceipt.Text) = '') and (ShowWarningBox('Receipt number has NOT been entered. ' + 'Do you want to continue saving this entry?') <> mrYes) then begin Result := false; Exit; end; pmt.Save; SetUnboundControls; ChangeControlState; Result := true; except on E: Exception do begin Result := false; ShowErrorBox(E.Message); end; end; end; end; function TfrmPaymentMain.SelectActiveClient: TModalResult; begin Result := mrCancel; with TfrmActiveClientsSearch.Create(self) do begin try try ShowModal; Result := ModalResult; except on e: Exception do ShowErrorBox(e.Message); end; finally Free; end; end; end; function TfrmPaymentMain.SelectActiveLoan: TModalResult; begin Result := mrCancel; with TfrmActiveLoans.Create(self) do begin try try ShowModal; Result := ModalResult; except on e: Exception do ShowErrorBox(e.Message); end; finally Free; end; end; end; procedure TfrmPaymentMain.ShowPaymentDetail; begin with TfrmPaymentDetail.Create(self) do begin try try ShowModal; if ModalResult = mrOK then begin AddRow(pmt.Details[pmt.DetailCount-1]); SetAmounts; end; except on e: Exception do ShowErrorBox(e.Message); end; finally Free; end; end; end; procedure TfrmPaymentMain.Cancel; begin end; procedure TfrmPaymentMain.FormClose(Sender: TObject; var Action: TCloseAction); begin dmPayment.Destroy; pmt.Destroy; inherited; end; procedure TfrmPaymentMain.FormCreate(Sender: TObject); begin dmPayment := TdmPayment.Create(self); try if (not Assigned(pmt)) or (pmt.IsNew) then begin if not Assigned(pmt) then pmt := TPayment.Create; pmt.Add; if pmt.IsWithdrawal then begin edClient.Text := pmt.Client.Name; SetAmounts; end; end else Retrieve; PopulatePaymentMethodComboBox(cmbPaymentMethod,pmt.PaymentMethod.Method = mdBankWithdrawal); except on E: Exception do ShowErrorBox(E.Message); end; ChangeControlState; inherited; end; procedure TfrmPaymentMain.FormShow(Sender: TObject); begin inherited; PopulateDetail; end; procedure TfrmPaymentMain.grDetailStringGridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var cellStr: string; begin with grDetailStringGrid do begin cellStr := Cells[ACol,ARow]; if ARow = 0 then Canvas.Font.Style := [fsBold] else Canvas.Font.Style := []; Canvas.Font.Size := Font.Size; Canvas.Font.Name := Font.Name; if ARow = 0 then Canvas.TextRect(Rect,Rect.Left + (ColWidths[ACol] div 2) - (Canvas.TextWidth(cellStr) div 2), Rect.Top + 2, cellStr) else if (ACol in [3,4,5,6]) and (ARow > 0) then Canvas.TextRect(Rect,Rect.Left - Canvas.TextWidth(cellStr) + ColWidths[3] - 20,Rect.Top + 2,cellStr) else Canvas.TextOut(Rect.Left + 2, Rect.Top + 2, cellStr); end; end; procedure TfrmPaymentMain.grDetailStringGridResize(Sender: TObject); begin inherited; ExtendLastColumn(grDetailStringGrid); end; procedure TfrmPaymentMain.AddActiveLoan; begin if pmt.IsNew then begin // check if a client has been selected if not Assigned(pmt.Client) then begin if SelectActiveClient = mrOk then begin pmt.Client := activeCln; edClient.Text := activeCln.Name; end else Exit; end; pmt.Client.RetrieveActiveLoans; // show active loans of selected client if SelectActiveLoan = mrOk then ShowPaymentDetail; end else ShowErrorBox('Adding a NEW payment has been restricted.'); end; procedure TfrmPaymentMain.SetAmounts; begin lblWithdrawn.Caption := 'Amount withdrawn: ' + FormatCurr('###,##0.00',pmt.Withdrawn); lblTotalAmount.Caption := 'Total amount paid: ' + FormatCurr('###,###,##0.00',pmt.TotalAmount); lblChange.Caption := 'Change: ' + FormatCurr('###,###,##0.00',pmt.ChangeAmount); lblChange.Visible := pmt.IsWithdrawal; end; procedure TfrmPaymentMain.imgAddPaymentClick(Sender: TObject); begin inherited; AddActiveLoan; end; procedure TfrmPaymentMain.imgAddPaymentMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; ButtonDown(Sender); end; procedure TfrmPaymentMain.imgAddPaymentMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; ButtonUp(Sender); end; procedure TfrmPaymentMain.imgDeletePaymentClick(Sender: TObject); begin DeletePayment; end; procedure TfrmPaymentMain.DeletePayment; begin if pmt.IsNew then begin if pmt.DetailCount > 0 then begin if ShowDecisionBox('Are you sure you want to delete the selected payment?') = mrYes then begin pmt.RemoveDetail(TPaymentDetail(grDetailStringGrid.Objects[0,grDetailStringGrid.Row]).Loan); RemoveRow(grDetailStringGrid.Row); grDetail.DataSource.DataSet.Delete; SetAmounts; end; end; end else ShowErrorBox('Deleting a payment has been restricted.'); end; procedure TfrmPaymentMain.dtePaymentDateChange(Sender: TObject); begin inherited; pmt.Date := dtePaymentDate.Date; end; procedure TfrmPaymentMain.RemoveRow(const row: Integer); var rw, cl: integer; begin with grDetailStringGrid do begin // clear the object in the deleted row Objects[0,row] := nil; // move up all rows for rw := row + 1 to RowCount - 1 do begin for cl := 0 to ColCount - 1 do Cells[cl,rw-1] := Cells[cl,rw]; if Assigned(Objects[0,rw]) then Objects[0,rw-1] := Objects[0,rw]; end; // decrease row count or clear if details is empty if pmt.DetailCount = 0 then begin for cl := 0 to ColCount - 1 do Cells[cl,row] := ''; end else RowCount := RowCount - 1 end; end; procedure TfrmPaymentMain.PopulateDetail; var i, cnt: integer; begin with grDetailStringGrid do begin RowCount := RowCount + 1; FixedRows := 1; // headers Cells[0,0] := 'Loan ID'; Cells[1,0] := 'Type'; Cells[2,0] := 'Account'; Cells[3,0] := 'Principal'; Cells[4,0] := 'Interest'; Cells[5,0] := 'Penalty'; Cells[6,0] := 'Total amount'; Cells[7,0] := 'Remarks'; // widths ColWidths[0] := 120; ColWidths[1] := 120; ColWidths[2] := 120; ColWidths[3] := 80; ColWidths[4] := 80; ColWidths[5] := 80; ColWidths[6] := 100; ColWidths[7] := 200; cnt := pmt.DetailCount - 1; for i := 0 to cnt do AddRow(pmt.Details[i]); end; end; procedure TfrmPaymentMain.AddRow(const detail: TPaymentDetail); var r: integer; begin with grDetailStringGrid do begin if not FirstRow(grDetailStringGrid) then RowCount := RowCount + 1; r := RowCount - FixedRows; Cells[0,r] := detail.Loan.Id; Cells[1,r] := detail.Loan.LoanTypeName; Cells[2,r] := detail.Loan.AccountTypeName; Cells[3,r] := FormatCurr('###,###,##0.00',detail.Principal); Cells[4,r] := FormatCurr('###,###,##0.00',detail.Interest); Cells[5,r] := FormatCurr('###,###,##0.00',detail.Penalty); Cells[6,r] := FormatCurr('###,###,##0.00',detail.TotalAmount); Objects[0,r] := detail; end; // add to memory table with grDetail.DataSource.DataSet, detail do begin if not Active then Open; Append; FieldByName('LoanId').AsString := Loan.Id; FieldByName('LoanType').AsString := Loan.LoanTypeName; FieldByName('AccountType').AsString := Loan.AccountTypeName; FieldByName('Principal').AsString := FormatCurr('###,###,##0.00',Principal); FieldByName('Interest').AsString := FormatCurr('###,###,##0.00',Interest); FieldByName('Penalty').AsString := FormatCurr('###,###,##0.00',Penalty); FieldByName('TotalAmount').AsString := FormatCurr('###,###,##0.00',TotalAmount); grDetail.DataSource.DataSet.Post; end; end; procedure TfrmPaymentMain.BindControlToObject; begin // payment method pmt.PaymentMethod := TPaymentMethod(cmbPaymentMethod.Items.Objects[cmbPaymentMethod.ItemIndex]); end; procedure TfrmPaymentMain.SetUnboundControls; begin edClient.Text := pmt.Client.Name; cmbPaymentMethod.ItemIndex := Integer(pmt.PaymentMethod.Method) - 1; lblReferenceNo.Caption := pmt.ReferenceNo; lblPosted.Caption := IfThen(pmt.IsPosted,'Yes','No'); lblAdvancePayment.Visible := pmt.IsAdvance; end; procedure TfrmPaymentMain.Retrieve; begin pmt.Retrieve; SetUnboundControls; SetAmounts; end; procedure TfrmPaymentMain.ChangeControlState; var new: boolean; begin new := pmt.IsNew; // dtePaymentDate.ReadOnly := not new; edReceipt.ReadOnly := not new; cmbPaymentMethod.ReadOnly := not new; end; end.
unit AMostraErrosExportacaoDados; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, ExtCtrls, PainelGradiente, Componentes1, Grids, CGrades, StdCtrls, Buttons, UnDados; type TFMostraErrosExportacaoDados = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; GErrosExportacao: TRBStringGridColor; PanelColor1: TPanelColor; BFechar: TBitBtn; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BFecharClick(Sender: TObject); procedure GErrosExportacaoCarregaItemGrade(Sender: TObject; VpaLinha: Integer); procedure GErrosExportacaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure GErrosExportacaoMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); private { Private declarations } VprDErroExportacao: TRBDExportacadoDadosErros; VprDExportacao: TRBDExportacaoDados; procedure CarTitulosGrade; public { Public declarations } procedure MostraErro(VpaDErroExportacao: TRBDExportacaoDados); end; var FMostraErrosExportacaoDados: TFMostraErrosExportacaoDados; implementation uses APrincipal; {$R *.DFM} { **************************************************************************** } procedure TFMostraErrosExportacaoDados.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } CarTitulosGrade; end; { *************************************************************************** } procedure TFMostraErrosExportacaoDados.GErrosExportacaoCarregaItemGrade(Sender: TObject; VpaLinha: Integer); begin VprDErroExportacao := TRBDExportacadoDadosErros(VprDExportacao.ErrosExportacao.Items[VpaLinha-1]); GErrosExportacao.Cells[1,VpaLinha] := VprDErroExportacao.NomTabela; GErrosExportacao.Cells[2,VpaLinha]:= VprDErroExportacao.DesRegistro; GErrosExportacao.Cells[3,VpaLinha]:= VprDErroExportacao.DesErro; end; { *************************************************************************** } procedure TFMostraErrosExportacaoDados.GErrosExportacaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin key := 0; end; { *************************************************************************** } procedure TFMostraErrosExportacaoDados.GErrosExportacaoMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); begin if VprDExportacao.ErrosExportacao.Count > 0 then begin VprDErroExportacao := TRBDExportacadoDadosErros(VprDExportacao.ErrosExportacao.Items[VpaLinhaAtual-1]); end; end; { *************************************************************************** } procedure TFMostraErrosExportacaoDados.MostraErro(VpaDErroExportacao: TRBDExportacaoDados); begin VprDExportacao := VpaDErroExportacao; GErrosExportacao.ADados := VprDExportacao.ErrosExportacao; GErrosExportacao.CarregaGrade; if VpaDErroExportacao.ErrosExportacao.Count > 0 then showmodal; end; { *************************************************************************** } procedure TFMostraErrosExportacaoDados.BFecharClick(Sender: TObject); begin close; end; { *************************************************************************** } procedure TFMostraErrosExportacaoDados.CarTitulosGrade; begin GErrosExportacao.Cells[1,0] := 'Tabela'; GErrosExportacao.Cells[2,0] := 'Registro'; GErrosExportacao.Cells[3,0] := 'Erro'; end; procedure TFMostraErrosExportacaoDados.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFMostraErrosExportacaoDados]); end.
unit FHIRAuthMap; interface uses FHIRResources; type TTokenCategory = (tcClinical, tcData, tcMeds, tcSchedule, tcAudit, tcDocuments, tcFinancial, tcOther); const CODES_TTokenCategory : array [TTokenCategory] of String = ('Clinical', 'Data', 'Meds', 'Schedule', 'Audit', 'Documents', 'Financial', 'Other'); // categories for web login // tcClinical, tcData, tcMeds, tcSchedule, tcAudit, tcDocuments, tcFinancial, tcOther RESOURCE_CATEGORY : array [TFHIRResourceType] of TTokenCategory = ( tcOther, // frtNull tcFinancial , // frtAccount Account frtAccount tcOther, // ActivityDefinition ActivityDefinition frtActivityDefinition tcClinical , // frtAllergyIntolerance AllergyIntolerance tcSchedule , // frtAppointment Appointment tcSchedule , // frtAppointmentResponse AppointmentResponse tcAudit , // frtAuditEvent AuditEvent tcOther , // frtBasic Basic tcDocuments , // frtBinary Binary tcOther , // frtBodySite BodySite tcOther , // frtBundle Bundle tcClinical , // frtCarePlan CarePlan tcClinical , // frtCareTeam CareTeam tcFinancial , // frtClaim Claim tcFinancial , // frtClaimResponse ClaimResponse tcClinical , // frtClinicalImpression ClinicalImpression tcOther , // frtCodeSystem CodeSystem tcOther , // frtCommunication Communication tcOther , // frtCommunicationRequest CommunicationRequest tcOther , // frtCompartmentDefinition CompartmentDefinition tcDocuments , // frtComposition Composition tcOther , // frtConceptMap ConceptMap tcClinical , // frtCondition Condition (aka Problem) tcOther , // frtConformance Conformance tcOther, // frtConsent tcFinancial , // frtContract Contract tcFinancial , // frtCoverage Coverage tcOther , // frtDataElement DataElement tcOther , // frtDecisionSupportRule DecisionSupportServiceModule tcClinical, // frtDetectedIssue DetectedIssue tcOther , // frtDevice Device tcOther , // frtDeviceComponent DeviceComponent tcOther , // frtDeviceMetric DeviceMetric tcOther , // frtDeviceUseRequest DeviceUseRequest tcClinical, // frtDeviceUseStatement DeviceUseStatement tcClinical, // frtDiagnosticReport DiagnosticRequest tcClinical , // frtDiagnosticOrder DiagnosticReport tcDocuments , // frtDocumentManifest DocumentManifest tcDocuments, // frtDocumentReference DocumentReference tcFinancial , // frtEligibilityRequest EligibilityRequest tcFinancial, // frtEligibilityResponse tcSchedule , // frtEncounter Encounter tcOther, // frtEndpoint Endpoint tcFinancial, // frtEnrollmentRequest EnrollmentRequest tcFinancial , // frtEnrollmentResponse EnrollmentResponse tcSchedule, // frtEpisodeOfCare EpisodeOfCare tcOther, // frtExpansionProfile ExpansionProfile tcFinancial , // frtExplanationOfBenefit ExplanationOfBenefit tcClinical, // frtFamilyMemberHistory FamilyMemberHistory tcClinical , // frtFlag Flag tcClinical , // frtGoal Goal tcOther , // frtGroup Group tcClinical , // frtGuidanceResponse GuidanceResponse tcSchedule , // frtHealthcareService HealthcareService tcData , // frtImagingStudy ImagingManifest tcData , // frtImagingStudy ImagingStudy tcMeds , // frtImmunization Immunization tcMeds , // frtImmunizationRecommendation ImmunizationRecommendation tcOther , // frtImplemnetationGuide ImplementationGuide tcOther, // frtLibrary Library tcClinical , // frtLinkage Linkage tcOther , // frtList List tcOther , // frtLocation Location tcOther, // frtMeasure Measure tcOther , // frtMedia MeasureReport tcOther , // frtMedia Media tcMeds , // frtMedication Medication tcMeds , // frtMedicationAdministration MedicationAdministration tcMeds , // frtMedicationDispense MedicationDispense tcMeds , // frtMedicationPrescription MedicationOrder tcMeds , // frtMedicationStatement MedicationStatement tcOther , // frtMessageHeader MessageHeader tcOther , // frtNamingSystem NamingSystem tcMeds , // frtNutritionOrder NutritionRequest tcData , // frtObservation Observation tcOther , // frtOperationDefinition OperationDefinition tcOther , // frtOperationOutcome OperationOutcome tcOther , // frtOrganization Organization tcOther , // frtParameters tcSchedule , // frtPatient Patient tcFinancial , // frtPaymentNotice PaymentNotice tcFinancial , // frtPaymentReconciliation PaymentReconciliation tcOther , // frtPerson Person tcOther , // frtPlanDefinition PlanDefinition tcOther , // frtPractitioner Practitioner tcOther , // frtPractitionerRole PractitionerRole tcClinical , // frtProcedure Procedure tcOther , // frtProcedureRequest ProcedureRequest tcOther , // frtProcessRequest ProcessRequest tcOther , // frtProcessResponse ProcessResponse tcAudit , // frtProvenance Provenance tcOther , // frtQuestionnaire Questionnaire tcOther, // frtQuestionnaireResponse QuestionnaireResponse tcClinical , // frtReferralRequest, ReferralRequest tcOther , // frtRelatedPerson, RelatedPerson tcOther , // frtRiskAssessment, RiskAssessment tcSchedule , // frtSchedule, Schedule tcOther , // frtSearchParameter, SearchParameter tcData, // frtSequence Sequence tcOther , // frtSearchParameter, tcSchedule , // frtSlot, tcData , // frtSpecimen, tcOther , // frtStructureDefinition, tcOther , // frtStructureMap[, tcOther , // frtSubscription, tcOther , // frtSubstance, tcOther , // frtSupplyDelivery, tcOther , // frtSupplyRequest, tcOther , // frtTask, tcOther , // frtTestReport, tcOther , // frtTestScript, tcOther , // frtValueSet, tcClinical,// frtVisionPrescription, tcOther); // frtCustom implementation end.
unit UProduto; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { Produto } TProduto = class private FCodigo: integer; FDescricao: string; FValorUnitario: double; procedure setCodigo(Value: integer); procedure setDescricao(Value: string); procedure setValorUnitario(Value: double); public property Codigo: integer read FCodigo write setCodigo; property Descricao: string read FDescricao write setDescricao; property Valor: double read FValorUnitario write setValorUnitario; constructor Create; end; implementation { Produto } procedure TProduto.setCodigo(Value: integer); begin FCodigo := Value; end; procedure TProduto.setDescricao(Value: string); begin FDescricao := Value; end; procedure TProduto.setValorUnitario(Value: double); begin FValorUnitario := Value; end; constructor TProduto.Create; begin inherited Create; end; end.
unit unit_ws_container; {$mode objfpc}{$H+} interface uses {$IFDEF UNIX}cthreads,{$ENDIF} Classes, SysUtils,log_core, wsutils, wsmessages, wsstream, ssockets, WebsocketsClient; type { TRecieverThread } TRecieverThread = class(TThread) private FCommunicator: TWebsocketCommunincator; protected procedure Execute; override; public constructor Create(ACommunicator: TWebsocketCommunincator); end; type { TSimpleChat } TSimpleChat = class private FReciever: TRecieverThread; //Thread for Reciving Msg FCommunicator: TWebsocketCommunincator; //Handels connection l:tlog; procedure RecieveMessage(Sender: TObject); procedure StreamClosed(Sender: TObject); public procedure send(msg:string); constructor Create(ACommunicator: TWebsocketCommunincator); destructor Destroy; override; end; implementation uses unitmain; { TSimpleChat } procedure TSimpleChat.StreamClosed(Sender: TObject); begin //WriteLn('Connection to ', FCommunicator.SocketStream.RemoteAddress.Address, ' closed'); // l.print('Connection to '+FCommunicator.SocketStream.RemoteAddress.Address+' closed'); l.print('Connection (STREAM) closed'); end; procedure TSimpleChat.RecieveMessage(Sender: TObject); var MsgList: TWebsocketMessageOwnerList; m: TWebsocketMessage; begin MsgList := TWebsocketMessageOwnerList.Create(True); try FCommunicator.GetUnprocessedMessages(MsgList); //Nachrichten abrufen for m in MsgList do if m is TWebsocketStringMessage then begin //WriteLn('Message from ', FCommunicator.SocketStream.RemoteAddress.Address, ': ', TWebsocketStringMessage(m).Data) l.inp('Message from '+ FCommunicator.SocketStream.RemoteAddress.Address+ ': '+ TWebsocketStringMessage(m).Data); end else if m is TWebsocketPongMessage then begin //WriteLn('Pong from ', FCommunicator.SocketStream.RemoteAddress.Address, ': ', TWebsocketPongMessage(m).Data); l.inp('Pong from '+ FCommunicator.SocketStream.RemoteAddress.Address+ ': '+ TWebsocketPongMessage(m).Data); end; finally MsgList.Free; //Destroys MsgList (better: freeandnil() ) end; end; procedure TSimpleChat.send(msg:string); //sends a msg var str:string; begin str:=msg; if FCommunicator.Open then begin //ReadLn(str); if not FCommunicator.Open then Exit; {with FCommunicator.WriteMessage do try WriteRaw(str); finally Free; end;} try fcommunicator.WriteMessage.WriteRaw(msg) finally fcommunicator.WriteMessage.Free; end; end; {if FCommunicator.Open then begin try //fcommunicator.WriteMessage.WriteRaw(msg); fcommunicator.WriteMessage.WriteAnsiString(msg); fcommunicator.WriteMessage.DispatchStr(msg); //fcommunicator.Free; l.print('SENDING: '+msg); except //freeandnil(fcommunicator); //fcommunicator.Free; l.print('ERROR while sending this msg: '+msg); end; end;} end; constructor TSimpleChat.Create(ACommunicator: TWebsocketCommunincator); begin //l:=tlog.create(1,formmain.e_log); //l.enable_line_nr; FCommunicator := ACommunicator; //Communicator zuweisen FCommunicator.OnClose:=@StreamClosed; //Event zuweisung FCommunicator.OnRecieveMessage:=@RecieveMessage; FReciever := TRecieverThread.Create(ACommunicator); //Reciver erstellen end; destructor TSimpleChat.Destroy; begin while not FReciever.Finished do begin Sleep(10); end; FReciever.Free; FCommunicator.Free; inherited Destroy; end; { TRecieverThread } procedure TRecieverThread.Execute; begin while not Terminated and FCommunicator.Open do begin FCommunicator.RecieveMessage; Sleep(100); //polling of messages every 100ms 1/10s end; end; constructor TRecieverThread.Create(ACommunicator: TWebsocketCommunincator); begin FCommunicator := ACommunicator; //Communicator (Verbindungs Handler ) wird durchgereicht inherited Create(False); //? end; end.
unit Test.ReqCreator; interface uses Windows, TestFrameWork, GMGlobals, GM485, ArchIntervalBuilder, Generics.Collections, GMConst; type ArrayOfCardinal = array of Cardinal; ArchIntervalBuilderForTest = class(TArchIntervalBuilder) private FArray: ArrayOfCardinal; FArrayIndex: int; protected function GetNextHole(): LongWord; override; function IsAllProcessed: bool; override; procedure OpenQuery(); override; public constructor Create(lst: ArrayOfCardinal); end; TReqCreatorTest = class(TTestCase) private builder: ArchIntervalBuilderForTest; lst: TList<ArchReqInterval>; arr: ArrayOfCardinal; procedure CheckInterval(ut: LongWord; dt: TDateTime; err: string); protected procedure SetUp; override; procedure TearDown; override; published procedure ArchIntervalBuilder; end; implementation uses DateUtils, SysUtils; { TReqCreatorTest } procedure TReqCreatorTest.CheckInterval(ut: LongWord; dt: TDateTime; err: string); begin Check(ut = LocalToUTC(dt), err + ': ' + DateTimeToStr(UTCtoLocal(ut)) + ' <> ' + DateTimeToStr(dt)); end; procedure TReqCreatorTest.ArchIntervalBuilder; begin Check(lst.Count = 4, 'Count ' + IntToStr(lst.Count) + ' <> 4'); CheckInterval(lst[0].UTime1, EncodeDate(2014, 03, 01), '1-1'); CheckInterval(lst[0].UTime2, EncodeDate(2014, 03, 05), '1-2'); CheckInterval(lst[1].UTime1, EncodeDate(2014, 03, 06), '2-1'); CheckInterval(lst[1].UTime2, EncodeDate(2014, 03, 06), '2-2'); CheckInterval(lst[2].UTime1, EncodeDate(2014, 03, 11), '3-1'); CheckInterval(lst[2].UTime2, EncodeDate(2014, 03, 13), '3-2'); CheckInterval(lst[3].UTime1, EncodeDate(2014, 03, 24), '4-1'); CheckInterval(lst[3].UTime2, EncodeDate(2014, 03, 26), '4-2'); end; procedure TReqCreatorTest.SetUp; begin inherited; SetLength(arr, 12); arr[0] := LocalToUTC(EncodeDate(2014, 03, 01)); arr[1] := LocalToUTC(EncodeDate(2014, 03, 02)); arr[2] := LocalToUTC(EncodeDate(2014, 03, 03)); arr[3] := LocalToUTC(EncodeDate(2014, 03, 04)); arr[4] := LocalToUTC(EncodeDate(2014, 03, 05)); arr[5] := LocalToUTC(EncodeDate(2014, 03, 06)); arr[6] := LocalToUTC(EncodeDate(2014, 03, 11)); arr[7] := LocalToUTC(EncodeDate(2014, 03, 12)); arr[8] := LocalToUTC(EncodeDate(2014, 03, 13)); arr[9] := LocalToUTC(EncodeDate(2014, 03, 24)); arr[10] := LocalToUTC(EncodeDate(2014, 03, 25)); arr[11] := LocalToUTC(EncodeDate(2014, 03, 26)); builder := ArchIntervalBuilderForTest.Create(arr); lst := builder.BuildIntervalList(UTC_DAY, 5); end; procedure TReqCreatorTest.TearDown; begin inherited; builder.Free(); lst.Free(); end; { ArchIntervalBuilderForTest } constructor ArchIntervalBuilderForTest.Create(lst: ArrayOfCardinal); begin inherited Create(nil); FArrayIndex := 0; FArray := lst; end; function ArchIntervalBuilderForTest.GetNextHole: LongWord; begin Result := FArray[FArrayIndex]; inc(FArrayIndex); end; function ArchIntervalBuilderForTest.IsAllProcessed: bool; begin Result := FArrayIndex > High(FArray); end; procedure ArchIntervalBuilderForTest.OpenQuery; begin end; initialization RegisterTest('GMIOPSrv/Devices/Common', TReqCreatorTest.Suite); end.
{***********************************<_INFO>************************************} { <Проект> Видеосервер } { } { <Область> 16:Медиа-контроль } { } { <Задача> Конфигурация видеосервера } { } { <Автор> Фадеев Р.В. } { } { <Дата> 10.12.2008 } { } { <Примечание> Нет примечаний. } { } { <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" } { } {***********************************</_INFO>***********************************} unit MediaServer.Configuration; interface uses Windows,SysUtils, Classes, IniFiles, ActiveX, ComObj, Contnrs,ExtCtrls, Generics.Collections, HHCommon, MediaProcessing.Definitions; type TBufferOverflowAction = (boaDoNotWriting,boaWriteIFramesOnly); TPhysicalDeviceType = (dtInPointsMultiplexer, dtIpCameraBeward,dtFile,dtRecordStorageSource,dtCompressionCardHikvision,dtDesktop,dtWebCamera,dtMediaServer,dtRTSP, dtInPointsRetransmitter); const PhysicalDeviceTypeNamesLong: array [TPhysicalDeviceType] of string = ('Мультиплексор','Ip камера "Beward"','Файл','Файловое хранилище','Компрессионная карта "Hikvision"','Рабочий стол','Web-камера','Медиа-сервер','RTSP','Ретранслятор'); PhysicalDeviceTypeNamesShort: array [TPhysicalDeviceType] of string = ('Мультиплексор','Ip камера "Beward"','Файл','ФХ','Компр. карта "Hikvision"','Раб. стол','Web-камера','Медиа-сервер','RTSP','Ретранслятор'); PhysicalDeviceTypeNamesSignature: array [TPhysicalDeviceType] of string = ('Multiplexer','IpCamBeward','File','FileStorage','CompCardHikvision','Desktop','WebCam','MediaServer','RTSP','Retransmitter'); type TPtzPoint = record DeviceId: integer; Name: string; Description: string; end; TPtzPointArray = array of TPtzPoint; TPtzProtocol = record Enabled: boolean; ProtocolClassName: string; Port: Word; UserName: string; UserPassword: string; procedure LoadFromIni(aIniFile: TCustomIniFile; const aSection,aPrefix: string); procedure SaveToIni(aIniFile: TCustomIniFile; const aSection,aPrefix: string); end; TPtzStopTranslationWhileMoving = record Enabled: boolean; Period: integer; //мс procedure LoadFromIni(aIniFile: TCustomIniFile; const aSection,aPrefix: string); procedure SaveToIni(aIniFile: TCustomIniFile; const aSection,aPrefix: string); end; TPhysicalDeviceParameters = record DeviceType: TPhysicalDeviceType; ServerIP: string; ServerPort: Integer; Protocol: Integer; //HHNet Protocol, TRecordStorageTransportType ChannelNo: Integer; //Как правило, что-то одно из двух: channel или Name ChannelProfile: Integer; SourceName: string; UserName: string; UserPassword: string; TransmitAudio : boolean; PeriodStart,PeriodEnd: TDateTime; //Для архивных записей KeepPersistentConnection: boolean; PtzCustomProtocol: TPtzProtocol; PtzStopTranslationWhileMoving: TPtzStopTranslationWhileMoving; PtzPoints:TPtzPointArray; function GetDisplayDescription(aLongFormat: boolean): string; procedure LoadFromIni(aIniFile: TCustomIniFile; const aSection,aPrefix: string); procedure SaveToIni(aIniFile: TCustomIniFile; const aSection,aPrefix: string); end; TClientAuthorizationProvider = (apBuiltIn,apDatabase); TClientConnectionParameters = record //Идентификация устройства, как к нему буду обращаться внешние клиенты Name: string; Description: string; AuthorizationProvider: TClientAuthorizationProvider; UserName: string; Password: string; //Если пусто, значит не нужен end; TRecordStorageTransportType = (ttNetworkPath,ttFileServer); TArchiveSource = record Text: string; //Наименование (для пользователя) ConnectionString: string; SourceName: string; RecordStorageTransport: TRecordStorageTransportType; //Медиа-процессоры MediaProcessors: TAllMediaStreamBytes; function GetUrl: string; end; TArchiveParameters = record Sources: TArray<TArchiveSource>; function IsEnabled: boolean; function ToString: string; end; //TArchiveParametersArray = array of TArchiveParameters; //.TOverqueueDetectMode = (oqdmConstantBitrate, oqdmPercent) TProcessingQueueParams = record //макс. кол-во кадров, хранящихся в очереди обработки MaxSize: integer; //максимально допустимая длина в мсек первого и последнего кадра, хранящегося в очереди //для оценки используется системный поток MaxDuration: integer; //процент отдаваемого потока относительно входящего потока OverqueueBitrateTresholdPercent: integer; //период для измерения скорости потока OverqueueBitrateMeasureIntervalMs: integer; procedure Initialize; procedure LoadFromIni(aIniFile: TCustomIniFile; const aSection: string); procedure SaveToIni(aIniFile: TCustomIniFile; const aSection: string); end; TInPointConfig = class Id: string; Name: string; Folder: string; //Только для информации Info_OriginalStreamType: TAllMediaStreamTypes; Info_ResultStreamType: TAllMediaStreamTypes; //Настройки физического поключения к камере DeviceParams:TPhysicalDeviceParameters; //Медиа-процессоры MediaProcessors: TAllMediaStreamBytes; //Extensions Extensions: TBytes; //Настройки очереди обработки ProcessingQueueParams: TProcessingQueueParams; //Использовать очсередь обработки только при наличии клиентских соединений к этой точке UseProcessingQueueOnlyIfNeeded: boolean; //надо ли при таком режиме очищать предбуфер (иначе туда пойдут необработанные кадры) UseProcessingQueueOnlyIfNeededAndClearPrebuffer: boolean; //максимальный размер пред. буфера PrebufferMaxSize: integer; constructor Create; procedure LoadFromIni(aIniFile: TCustomIniFile; const aSection: string); procedure SaveToIni(aIniFile: TCustomIniFile; const aSection: string); end; TBackingParams = record //Подложка ImagePath: string; //Положение камеры на карте DevicePosition: TPoint; //Угол камеры, соответствующий "северу" на подложке DeviceZeroAngle: integer; end; TOutPointConfig = class Id: string; //Включен Enabled: Boolean; //Разрешать управление объектом (масштаб, поворот и проч), при наличии такой возможности у устройства UserInteractiveControlAllowed: boolean; //Группа Folder : string; SourceId:string; SourceIdForUnauthorizedUser:string; SourceIdForBlockedUser:string; SourceIdForInsufficientPrivileges:string; SourceIdForDisconnectedState: string; SourceIdForOverQueue: string; //Настройки подложки BackingParams: TBackingParams; //Настройки очереди обработки ProcessingQueueParams: TProcessingQueueParams; //Настройки для внешнего подключения ClientParams:TClientConnectionParameters; //Медиа-процессоры MediaProcessors: TAllMediaStreamBytes; //Параметы архива для источника ArchiveParams: TArchiveParameters; constructor Create; procedure LoadFromIni(aIniFile: TCustomIniFile; const aSection: string); procedure SaveToIni(aIniFile: TCustomIniFile; const aSection: string); end; //Замещение одного сетевого адреса другим TNetAddressSubstitution = class private FSourceAddress: string; FDestAddress: string; public property SourceAddress: string read FSourceAddress write FSourceAddress; property DestAddress: string read FDestAddress write FDestAddress; end; TMediaServerConfig = class; TOnModifiedExternallyEvent = procedure (aSender: TMediaServerConfig) of object; TMediaServerConfig = class private FFileName : string; FFileData : AnsiString; FFileModificationDate : integer; FFileCheckTimer: TTimer; FUpdateLock: integer; FInPoints : TObjectList<TInPointConfig>; FOutPoints : TObjectList<TOutPointConfig>; FNetAddressSubstitutions: TObjectList<TNetAddressSubstitution>; FRestartAppEnabled: boolean; FRestartAppTime: TDateTime; FShowBaloonMessagesWhenMinimized: boolean; FOnModifiedExternally: TOnModifiedExternallyEvent; FMaxBufferSize: Integer; FBufferOverflowAction: TBufferOverflowAction; FProxyUsingPolicy: THHNetProxyUsingPolicy; FRtspPort: Word; FRtpPort: Word; F3sCommandPort: Word; F3sStreamPort: Word; FUserDataBaseUDL: string; FRtpTcpEnabled: boolean; FRtpUdpEnabled: boolean; FMscpPort: Word; FMsepPort: Word; F3sStreamSyncPeriod: cardinal; FNetRegistrationServerIp: string; FNetRegistrationName: string; FNetRegistrationEnabled: boolean; FRelayStartPort: Word; FRestartIfPageFileTooLargeEnabled: boolean; FRestartIfPageFileTooLargeMB: integer; class var FWatchingLock: integer; function GetInPointCount: Integer; function GetInPoint(i: Integer): TInPointConfig; function GetOutPointCount: Integer; function GetOutPoint(i: Integer): TOutPointConfig; procedure OnCheckFileTimer(Sender: TObject); procedure DoOnChangeFileExternally; procedure StartChangeWatching; procedure Load; function AddInPointInternal: TInPointConfig; function AddOutPointInternal: TOutPointConfig; function GetNetAddressSubsitution(index: integer): TNetAddressSubstitution; public constructor Create(const aFilePath: string='');overload; destructor Destroy; override; function FileName_: string; class function DefaultFileName: string; procedure Reload; procedure Save; function AddInPoint(aInPointType: TPhysicalDeviceType; aCreateAutoName: boolean): TInPointConfig; function IsInPointNameUnique(aInPoint: TInPointConfig):boolean; function AddOutPoint(aCreateAutoName: boolean): TOutPointConfig; function IsOutPointNameUnique(aOutPoint: TOutPointConfig):boolean; procedure DeleteInPoint(aInPoint: TInPointConfig); procedure ClearInPoints; property InPoints[i: Integer]: TInPointConfig read GetInPoint; property InPointCount: Integer read GetInPointCount; function FindInPoint(const aIP: string; aPort: integer; aChannelNo: integer) : TInPointConfig; overload; function FindInPoint(const aID: string) : TInPointConfig; overload; procedure DeleteOutPoint(aOutPoint: TOutPointConfig); procedure ClearOutPoints; property OutPoints[i: Integer]: TOutPointConfig read GetOutPoint; property OutPointCount: Integer read GetOutPointCount; // Максимальный размер буфера записи, МБ (для типа буфера btCommonDynamic) property MaxBufferSizeMB: Integer read FMaxBufferSize write FMaxBufferSize; property BufferOverflowAction : TBufferOverflowAction read FBufferOverflowAction write FBufferOverflowAction; property RtspPort: Word read FRtspPort write FRtspPort; property RtpPort: Word read FRtpPort write FRtpPort; property RtpUdpEnabled: boolean read FRtpUdpEnabled write FRtpUdpEnabled; property RtpTcpEnabled: boolean read FRtpTcpEnabled write FRtpTcpEnabled; property Ms3sCommandPort: Word read F3sCommandPort write F3sCommandPort; property Ms3sStreamPort: Word read F3sStreamPort write F3sStreamPort; property Ms3sStreamSyncPeriod: cardinal read F3sStreamSyncPeriod write F3sStreamSyncPeriod; property MscpPort: Word read FMscpPort write FMscpPort; property MsepPort: Word read FMsepPort write FMsepPort; property UserDataBaseUDL: string read FUserDataBaseUDL write FUserDataBaseUDL; //протокол для получения удаленных файлов property ShowBaloonMessagesWhenMinimized: boolean read FShowBaloonMessagesWhenMinimized write FShowBaloonMessagesWhenMinimized; property RestartAppEnabled: boolean read FRestartAppEnabled write FRestartAppEnabled; property RestartAppTime: TDateTime read FRestartAppTime write FRestartAppTime; property RestartIfPageFileTooLargeEnabled: boolean read FRestartIfPageFileTooLargeEnabled write FRestartIfPageFileTooLargeEnabled; property RestartIfPageFileTooLargeMB: integer read FRestartIfPageFileTooLargeMB write FRestartIfPageFileTooLargeMB; property RelayStartPort: Word read FRelayStartPort write FRelayStartPort; function NetAddressSubsitutionCount: integer; property NetAddressSubsitutions[index:integer]: TNetAddressSubstitution read GetNetAddressSubsitution; function AddNetAddressSubsitution(const aSourceAddress,aDestAddress: string):TNetAddressSubstitution; procedure ClearNetAddressSubsitutions; //регистрация в сети property NetRegistrationEnabled: boolean read FNetRegistrationEnabled write FNetRegistrationEnabled; property NetRegistrationServerIp: string read FNetRegistrationServerIp write FNetRegistrationServerIp; property NetRegistrationName: string read FNetRegistrationName write FNetRegistrationName; function SuperUserPassword: string; property ProxyUsingPolicy: THHNetProxyUsingPolicy read FProxyUsingPolicy write FProxyUsingPolicy; property OnModifiedExternally: TOnModifiedExternallyEvent read FOnModifiedExternally write FOnModifiedExternally; class procedure LockWatching; class procedure UnlockWatching; end; EConfigError = class (Exception); function RecordStorageTransportTypeToString(const aType: TRecordStorageTransportType): string; implementation uses Generics.Defaults, uBaseUtils, MediaServer.Net.Definitions,IdHashMessageDigest; const DefaultProcessingQueueMaxSize = 120; DefaultPrebufferMaxSize = 120; DefaultMediaProcessingQueueMaxDuration = 3000; DefaultOverqueueBitrateMeasureIntervalMs = 25000; DefaultOverqueueBitrateTresholdPercent=50; function RecordStorageTransportTypeToString(const aType: TRecordStorageTransportType): string; const Names : array [TRecordStorageTransportType] of string = ('NetworkPath','FileServer'); begin if not (integer(aType) in [0..Length(Names)-1]) then result:='' else result:=Names[aType]; end; function MaskString(const aString: string): string; var i: integer; begin result:=aString; for i := 1 to Length(aString) do result[i]:=char(integer(aString[i]) XOR (Length(aString)-i+1)); end; { TInPointConfig } { TMediaServerConfig } constructor TMediaServerConfig.Create(const aFilePath: string=''); var s: string; begin s:=aFilePath; if s='' then s:=DefaultFileName; FFileName:=s; FInPoints := TObjectList<TInPointConfig>.Create(TComparer<TInPointConfig>.Default); FOutPoints := TObjectList<TOutPointConfig>.Create(TComparer<TOutPointConfig>.Default); FNetAddressSubstitutions:=TObjectList<TNetAddressSubstitution>.Create(TComparer<TNetAddressSubstitution>.Default); FFileCheckTimer:=TTimer.Create(nil); //на объекте была какая-то странная ситуация, когда стандартные функции Windows по обнаружению изменений работали неправильно. Пришлось переделать на таймер со сравнением даты файлов FFileCheckTimer.OnTimer:=OnCheckFileTimer; FFileCheckTimer.Interval:=1000; FFileCheckTimer.Enabled:=false; Load; end; //------------------------------------------------------------------------------ procedure TMediaServerConfig.Load; var aSection: string; aIndex: Integer; aInPointConfig: TInPointConfig; aOutPointConfig: TOutPointConfig; aIniFile: TMemIniFile; FStream: TStream; x: integer; begin Assert(FFileName<>''); FFileCheckTimer.Enabled:=false; if FileExists(FFileName) then begin //Читаем полностью содержимое исходного файла FStream:=TFileStream.Create(FFileName,fmOpenRead or fmShareDenyWrite); try SetLength(FFileData,FStream.Size); FStream.Read(FFileData[1],Length(FFileData)); finally FreeAndNil(FStream); end; end; aIniFile:=TMemIniFile.Create(FFileName); try FInPoints.Clear; FOutPoints.Clear; FNetAddressSubstitutions.Clear; FBufferOverflowAction := TBufferOverflowAction(aIniFile.ReadInteger('General', 'BufferOverflowAction', integer(boaWriteIFramesOnly))); FMaxBufferSize := aIniFile.ReadInteger('General', 'MaxBufferSize', 200); FRestartAppEnabled:=aIniFile.ReadBool('General', 'RestartAppEnabled', true); FRestartAppTime:=aIniFile.ReadTime('General', 'RestartAppTime', EncodeTime(6,0,0,0)); FRestartIfPageFileTooLargeEnabled:=aIniFile.ReadBool('General', 'RestartIfPageFileTooLargeEnabled', true); FRestartIfPageFileTooLargeMB:=aIniFile.ReadInteger('General', 'RestartIfPageFileTooLargeMB', 2500); FShowBaloonMessagesWhenMinimized:=aIniFile.ReadBool('General', 'ShowBaloonMessagesWhenMinimized', false); FRtspPort:=aIniFile.ReadInteger('General','RtspPort',icRtspServerPort); FRtpPort:=aIniFile.ReadInteger('General','RtpPort',6700); FRtpTcpEnabled:=aIniFile.ReadBool('General','RtpTcpEnabled',true); FRtpUdpEnabled:=aIniFile.ReadBool('General','RtpUdpEnabled',true); F3sCommandPort:=aIniFile.ReadInteger('General','3SCommandPort',icCommandServerPort); F3sStreamPort:=aIniFile.ReadInteger('General','3SStreamPort',icStreamServerPort); F3sStreamSyncPeriod:=aIniFile.ReadInteger('General','3SStreamSyncPeriod',25000); if F3sStreamSyncPeriod<5000 then F3sStreamSyncPeriod:=5000; //04.07.2012 Слишком маленький период дает большую нагрузку на сеть FMscpPort:=aIniFile.ReadInteger('General','MscpPort',icMSCPServerPort); FMsepPort:=aIniFile.ReadInteger('General','MsepPort',icMsepServerPort); FRelayStartPort:=aIniFile.ReadInteger('General','RelayStartPort',18700); FUserDataBaseUDL:=aIniFile.ReadString('General','UserDataBaseUDL',''); x:=aIniFile.ReadInteger('General','ProxyUsingPolicy',0); if (x>integer(High(FProxyUsingPolicy))) or (x<integer(Low(FProxyUsingPolicy))) then x:=integer(Low(FProxyUsingPolicy)); FProxyUsingPolicy:=THHNetProxyUsingPolicy(x); FNetRegistrationEnabled:=aIniFile.ReadBool('NetRegistration','Enabled',false); FNetRegistrationServerIp:=aIniFile.ReadString('NetRegistration','ServerIp',''); FNetRegistrationName:=aIniFile.ReadString('NetRegistration','Name',''); aIndex := 0; while true do begin aSection := Format('InPoint %d', [aIndex]); if not aIniFile.SectionExists(aSection) then break; aInPointConfig := AddInPointInternal; aInPointConfig.LoadFromIni(aIniFile,aSection);; Inc(aIndex); end; aIndex := 0; while true do begin aSection := Format('OutPoint %d', [aIndex]); if not aIniFile.SectionExists(aSection) then break; aOutPointConfig := AddOutPointInternal; aOutPointConfig.LoadFromIni(aIniFile,aSection); Inc(aIndex); end; aIndex := 0; while true do begin aSection := Format('NetAddressSubstitution %d', [aIndex]); if not aIniFile.SectionExists(aSection) then break; AddNetAddressSubsitution( aIniFile.ReadString(aSection, 'Source', ''), aIniFile.ReadString(aSection, 'Destination','') ); Inc(aIndex); end; finally aIniFile.Free; end; StartChangeWatching; end; //------------------------------------------------------------------------------ class procedure TMediaServerConfig.LockWatching; begin InterlockedIncrement(FWatchingLock); end; //------------------------------------------------------------------------------ function TMediaServerConfig.NetAddressSubsitutionCount: integer; begin result:=FNetAddressSubstitutions.Count; end; //------------------------------------------------------------------------------ procedure TMediaServerConfig.Save; var aSection: string; i,j: Integer; aInPointConfig: TInPointConfig; aOutPointConfig: TOutPointConfig; aNetAddressSubstitution: TNetAddressSubstitution; aIniFile : TMemIniFile; begin Assert(FFileName<>''); if FRtpPort mod 2 <>0 then raise EConfigError.Create('RTP порт должен быть четным'); for i := 0 to FInPoints.Count - 1 do begin if (FInPoints[i].Name='') then raise EConfigError.Create('Не задано имя для устройства'); for j:=i+1 to FInPoints.Count - 1 do begin if (AnsiSameText(FInPoints[i].Name, FInPoints[j].Name)) then raise EConfigError.CreateFmt('Имя "%s" повторяется несколько раз. Не допускается одинаковое описание для двух или более камер.',[FInPoints[i].Name]); end; end; for i := 0 to FOutPoints.Count - 1 do begin if (FOutPoints[i].ClientParams.Name='') then raise EConfigError.Create('Не задано имя для исходящей точки подключения'); if (FOutPoints[i].SourceId='') then raise EConfigError.CreateFmt('Для исходящей точки подключения "%s" не указан источник',[FOutPoints[i].ClientParams.Name]); if (fsiBaseUtils.StrPosOneOf(['/','@','\'],FOutPoints[i].ClientParams.Name)>0) then raise EConfigError.CreateFmt('В имени исходящей точки подключения "%s" присутствуют недопустимые символы',[FOutPoints[i].ClientParams.Name]); if FindInPoint(FOutPoints[i].SourceId)=nil then raise EConfigError.CreateFmt('Для исходящей точки подключения "%s" не найден указанный источник',[FOutPoints[i].ClientParams.Name]); for j:=i+1 to FOutPoints.Count - 1 do begin if (AnsiSameText(FOutPoints[i].ClientParams.Name, FOutPoints[j].ClientParams.Name)) then raise EConfigError.CreateFmt('Имя "%s" повторяется несколько раз. Не допускается одинаковое описание для двух или более камер.',[FOutPoints[i].ClientParams.Name]); end; if FOutPoints[i].ClientParams.AuthorizationProvider=apDatabase then begin if FUserDataBaseUDL='' then raise EConfigError.CreateFmt('Исходящая точка подключения "%s" использует авторизацию из внешней БД, но параметры подключения к БД не указаны.',[FOutPoints[i].ClientParams.Name]); if not FileExists(FUserDataBaseUDL) then raise EConfigError.CreateFmt('Исходящая точка подключения "%s" использует авторизацию из внешней БД, но параметры подключения к БД не корректны.',[FOutPoints[i].ClientParams.Name]); end; end; FFileCheckTimer.Enabled:=false; DeleteFile(FFileName); if FileExists(FFileName) then raise Exception.Create('Не удается получить доступ на запись к файлу конфигурации'); aIniFile:=TMemIniFile.Create(FFileName); try // общие параметры aIniFile.WriteInteger('General', 'BufferOverflowAction', Integer(FBufferOverflowAction)); aIniFile.WriteInteger('General', 'MaxBufferSize', FMaxBufferSize); aIniFile.WriteBool ('General', 'RestartAppEnabled', FRestartAppEnabled); aIniFile.WriteTime ('General', 'RestartAppTime', FRestartAppTime); aIniFile.WriteBool ('General', 'RestartIfPageFileTooLargeEnabled', FRestartIfPageFileTooLargeEnabled); aIniFile.WriteInteger('General', 'RestartIfPageFileTooLargeMB', FRestartIfPageFileTooLargeMB); aIniFile.WriteBool ('General', 'ShowBaloonMessagesWhenMinimized', FShowBaloonMessagesWhenMinimized); aIniFile.WriteInteger('General','ProxyUsingPolicy',integer(FProxyUsingPolicy)); aIniFile.WriteInteger('General','RtspPort',FRtspPort); aIniFile.WriteInteger('General','RtpPort',FRtpPort); aIniFile.WriteBool('General','RtpTcpEnabled',FRtpTcpEnabled); aIniFile.WriteBool('General','RtpUdpEnabled',FRtpUdpEnabled); aIniFile.WriteInteger('General','3SCommandPort',F3sCommandPort); aIniFile.WriteInteger('General','3SStreamPort',F3sStreamPort); aIniFile.WriteInteger('General','3SStreamSyncPeriod',F3sStreamSyncPeriod); aIniFile.WriteInteger('General','MscpPort',FMscpPort); aIniFile.WriteInteger('General','MsepPort',FMsepPort); aIniFile.WriteString('General','UserDataBaseUDL',FUserDataBaseUDL); aIniFile.WriteBool('NetRegistration','Enabled',FNetRegistrationEnabled); aIniFile.WriteString('NetRegistration','ServerIp',FNetRegistrationServerIp); aIniFile.WriteString('NetRegistration','Name',FNetRegistrationName); aIniFile.WriteInteger('General','RelayStartPort',FRelayStartPort); // список устройств for i := 0 to FInPoints.Count - 1 do begin aSection := Format('InPoint %d', [i]); aInPointConfig := FInPoints[i]; aInPointConfig.SaveToIni(aIniFile,aSection); end; // список устройств for i := 0 to FOutPoints.Count - 1 do begin aSection := Format('OutPoint %d', [i]); aOutPointConfig := FOutPoints[i]; aOutPointConfig.SaveToIni(aIniFile,aSection); end; // список устройств for i := 0 to FNetAddressSubstitutions.Count - 1 do begin aSection := Format('NetAddressSubstitution %d', [i]); aNetAddressSubstitution := FNetAddressSubstitutions[i]; aIniFile.WriteString(aSection, 'Source', aNetAddressSubstitution.SourceAddress); aIniFile.WriteString(aSection, 'Destination', aNetAddressSubstitution.DestAddress); end; aIniFile.UpdateFile; finally aIniFile.Free; end; StartChangeWatching; end; //------------------------------------------------------------------------------ function TMediaServerConfig.AddInPoint(aInPointType: TPhysicalDeviceType; aCreateAutoName: boolean): TInPointConfig; var i,j: integer; s: string; aPrefix: string; begin result:=AddInPointInternal; Result.DeviceParams.DeviceType:=aInPointType; aPrefix:=PhysicalDeviceTypeNamesShort[aInPointType]; s:=''; if aCreateAutoName then begin //Подбираем имя по умолчанию for j:=1 to 512 do begin s := Format('%s_%d', [aPrefix,j]); for i:=0 to InPointCount-1 do if AnsiSameText(FInPoints[i].Name,s) then begin s:=''; break; end; if s<>'' then break; end; end; s:=StringReplace(s,'"','',[rfReplaceAll]); Result.Name:=s; case aInPointType of dtIpCameraBeward: begin Result.DeviceParams.UserName:='admin'; Result.DeviceParams.UserPassword:='admin'; Result.DeviceParams.ServerIP := '192.168.1.1'; Result.DeviceParams.ServerPort := 5000; end; dtFile: begin Result.DeviceParams.ChannelNo:=-1; end; dtRecordStorageSource: begin Result.DeviceParams.ChannelNo:=-1; end; dtCompressionCardHikvision: begin end; dtMediaServer: begin Result.DeviceParams.ServerIP := '192.168.1.1'; Result.DeviceParams.ServerPort := icCommandServerPort; Result.DeviceParams.UserName:='root'; Result.DeviceParams.UserPassword:='root'; end; end; result.ProcessingQueueParams.Initialize; result.PrebufferMaxSize:=DefaultPrebufferMaxSize; end; //------------------------------------------------------------------------------ function TMediaServerConfig.AddOutPoint(aCreateAutoName: boolean): TOutPointConfig; var i,j: integer; s: string; begin result:=AddOutPointInternal; s:=''; if aCreateAutoName then begin //Подбираем имя по умолчанию for j:=1 to 512 do begin s := Format('Out_%d', [j]); for i:=0 to OutPointCount-1 do if AnsiSameText(FOutPoints[i].ClientParams.Name,s) then begin s:=''; break; end; if s<>'' then break; end; end; s:=StringReplace(s,'"','',[rfReplaceAll]); Result.ClientParams.UserName:='root'; Result.ClientParams.Name:=s; Result.ArchiveParams.Sources:=nil; result.ProcessingQueueParams.Initialize; // по умолчанию устройство включено Result.Enabled := True; end; //------------------------------------------------------------------------------ function TMediaServerConfig.AddOutPointInternal: TOutPointConfig; begin Result := TOutPointConfig.Create; Result.ClientParams.Description:=''; Result.ProcessingQueueParams.Initialize; FOutPoints.Add(Result); end; //------------------------------------------------------------------------------ procedure TMediaServerConfig.DeleteInPoint(aInPoint: TInPointConfig); var aFoundIndex: Integer; begin aFoundIndex := FInPoints.IndexOf(aInPoint); if aFoundIndex <> -1 then FInPoints.Delete(aFoundIndex); end; //------------------------------------------------------------------------------ destructor TMediaServerConfig.Destroy; begin FreeAndNil(FInPoints); FreeAndNil(FOutPoints); FreeAndNil(FNetAddressSubstitutions); FreeAndNil(FFileCheckTimer); inherited; end; //------------------------------------------------------------------------------ function TMediaServerConfig.GetInPointCount: Integer; begin Result := FInPoints.Count; end; //------------------------------------------------------------------------------ function TMediaServerConfig.GetNetAddressSubsitution(index: integer): TNetAddressSubstitution; begin result:=FNetAddressSubstitutions[index]; end; //------------------------------------------------------------------------------ function TMediaServerConfig.GetInPoint(i: Integer): TInPointConfig; begin Result := TInPointConfig(FInPoints[i]); end; //------------------------------------------------------------------------------ function TMediaServerConfig.AddInPointInternal: TInPointConfig; begin Result := TInPointConfig.Create; Result.DeviceParams.Protocol := 0; Result.DeviceParams.ChannelNo := 0; Result.DeviceParams.KeepPersistentConnection:=true; Result.DeviceParams.PtzCustomProtocol.Port:=80; Result.DeviceParams.PtzStopTranslationWhileMoving.Period:=200; Result.ProcessingQueueParams.Initialize; FInPoints.Add(Result); end; //------------------------------------------------------------------------------ function TMediaServerConfig.AddNetAddressSubsitution(const aSourceAddress, aDestAddress: string): TNetAddressSubstitution; begin result:=TNetAddressSubstitution.Create; result.SourceAddress:=aSourceAddress; result.DestAddress:=aDestAddress; FNetAddressSubstitutions.Add(result); end; //------------------------------------------------------------------------------ procedure TMediaServerConfig.ClearInPoints; begin FInPoints.Clear; end; //------------------------------------------------------------------------------ procedure TMediaServerConfig.ClearNetAddressSubsitutions; begin FNetAddressSubstitutions.Clear; end; //------------------------------------------------------------------------------ function TMediaServerConfig.FindInPoint(const aIP: string; aPort: integer; aChannelNo: integer): TInPointConfig; var i: integer; begin result:=nil; for i:=0 to InPointCount-1 do begin if AnsiSameText(FInPoints[i].DeviceParams.ServerIP, aIP) and (FInPoints[i].DeviceParams.ServerPort=aPort) and (FInPoints[i].DeviceParams.ChannelNo=aChannelNo) then begin result:=FInPoints[i]; break; end; end; end; //------------------------------------------------------------------------------ function TMediaServerConfig.FindInPoint(const aID: string): TInPointConfig; var i: integer; begin result:=nil; for i:=0 to InPointCount-1 do begin if FInPoints[i].Id=aID then begin result:=FInPoints[i]; break; end; end; end; //------------------------------------------------------------------------------ procedure TMediaServerConfig.ClearOutPoints; begin FOutPoints.Clear; end; //------------------------------------------------------------------------------ function TMediaServerConfig.GetOutPointCount: Integer; begin Result := FOutPoints.Count; end; //------------------------------------------------------------------------------ function TMediaServerConfig.GetOutPoint(i: Integer): TOutPointConfig; begin Result := TOutPointConfig(FOutPoints[i]); end; //------------------------------------------------------------------------------ procedure TMediaServerConfig.DeleteOutPoint(aOutPoint: TOutPointConfig); var aFoundIndex: Integer; begin aFoundIndex := FOutPoints.IndexOf(aOutPoint); if aFoundIndex <> -1 then FOutPoints.Delete(aFoundIndex); end; //------------------------------------------------------------------------------ function TMediaServerConfig.FileName_: string; begin result:=FFileName; end; //------------------------------------------------------------------------------ procedure TMediaServerConfig.OnCheckFileTimer(Sender: TObject); const aMethodName = 'TMediaServerConfig.OnCheckFileTimer'; var aTmp: integer; begin if (FUpdateLock>0) or (FWatchingLock>0) then exit; aTmp:=FileAge(FFileName); if (aTmp<>-1) and (aTmp<>FFileModificationDate) then begin FFileCheckTimer.Enabled:=false; try if FWatchingLock=0 then DoOnChangeFileExternally; except on E:Exception do ;//?? end; end; end; //------------------------------------------------------------------------------ procedure TMediaServerConfig.Reload; begin Load; end; //------------------------------------------------------------------------------ procedure TMediaServerConfig.DoOnChangeFileExternally; var FStream: TStream; aData: AnsiString; begin if FUpdateLock>0 then exit; //Читаем полностью содержимое исходного файла FStream:=TFileStream.Create(FFileName,fmOpenRead or fmShareDenyWrite); try SetLength(aData,FStream.Size); FStream.Read(aData[1],Length(aData)); finally FreeAndNil(FStream); end; //ничего не изменилось if aData=FFileData then begin StartChangeWatching; exit; end; Load; if Assigned(FOnModifiedExternally) then FOnModifiedExternally(self); end; //------------------------------------------------------------------------------ function TMediaServerConfig.IsInPointNameUnique(aInPoint: TInPointConfig):boolean; var i: integer; begin for i:=0 to InPointCount-1 do if FInPoints[i]<>aInPoint then if AnsiSameText(FInPoints[i].Name,aInPoint.Name) then exit(false); result:=true; end; //------------------------------------------------------------------------------ function TMediaServerConfig.IsOutPointNameUnique(aOutPoint: TOutPointConfig): boolean; var i: integer; begin for i:=0 to OutPointCount-1 do if FOutPoints[i]<>aOutPoint then if AnsiSameText(FOutPoints[i].ClientParams.Name, aOutPoint.ClientParams.Name) then exit(false); result:=true; end; //------------------------------------------------------------------------------ procedure TMediaServerConfig.StartChangeWatching; var FStream: TStream; begin Assert(FFileName<>''); FFileModificationDate:=FileAge(FFileName); if FileExists(FFileName) then begin //Читаем полностью содержимое исходного файла FStream:=TFileStream.Create(FFileName,fmOpenRead or fmShareDenyWrite); try SetLength(FFileData,FStream.Size); FStream.Read(FFileData[1],Length(FFileData)); finally FreeAndNil(FStream); end; end; FFileCheckTimer.Enabled:=true; end; //------------------------------------------------------------------------------ function TMediaServerConfig.SuperUserPassword: string; begin result:=DefaultSuperUserPassword; end; //------------------------------------------------------------------------------ class procedure TMediaServerConfig.UnlockWatching; begin InterlockedDecrement(FWatchingLock); end; //------------------------------------------------------------------------------ class function TMediaServerConfig.DefaultFileName: string; begin result:=ExtractFileDir(ParamStr(0)) + '\MediaServer.cfg'; end; { TPhysicalDeviceParameters } function TPhysicalDeviceParameters.GetDisplayDescription(aLongFormat: boolean): string; var aAddress: string; aChannel : string; i: integer; begin if aLongFormat then aAddress:=PhysicalDeviceTypeNamesLong[DeviceType] else aAddress:=PhysicalDeviceTypeNamesShort[DeviceType]; if DeviceType=dtInPointsMultiplexer then begin if ServerIP='' then i:=0 else i:=fsiBaseUtils.CharCount(ServerIP,';')+1; result:=aAddress+ ', '+IntToStr(i); exit; end; if ServerPort<>0 then aAddress:=aAddress+Format(' %s:%d',[ServerIP,ServerPort]) else aAddress:=aAddress+' '+ServerIP; if ChannelNo>=0 then begin aChannel:=Format(', канал %d',[ChannelNo+1]); if ChannelProfile>0 then aChannel:=Format('%s/%d',[aChannel,ChannelProfile+1]); end; result:=Trim(aAddress)+Trim(aChannel); end; procedure TPhysicalDeviceParameters.LoadFromIni(aIniFile: TCustomIniFile;const aSection,aPrefix: string); var i: integer; begin self.DeviceType:= TPhysicalDeviceType(aIniFile.ReadInteger(aSection, aPrefix+'Type', 0)); self.ServerIP := aIniFile.ReadString(aSection, aPrefix+'ServerIP', ''); self.ServerPort := aIniFile.ReadInteger(aSection, aPrefix+'ServerPort', 0); self.Protocol := aIniFile.ReadInteger(aSection, aPrefix+'Protocol', 0); self.ChannelNo := aIniFile.ReadInteger(aSection, aPrefix+'ChannelNum', 0); self.ChannelProfile := aIniFile.ReadInteger(aSection, aPrefix+'ChannelProfile', 0); self.SourceName:=aIniFile.ReadString(aSection, aPrefix+'SourceName', ''); self.UserName := aIniFile.ReadString(aSection, aPrefix+'UserName', ''); self.UserPassword := MaskString(fsiBaseUtils.CodesToString(aIniFile.ReadString(aSection, aPrefix+'UserPassword', ''))); self.KeepPersistentConnection := aIniFile.ReadBool(aSection, aPrefix+'KeepPersistentConnection', false); self.TransmitAudio := aIniFile.ReadBool(aSection, aPrefix+'TransmitAudio', false); PtzCustomProtocol.LoadFromIni(aIniFile,aSection,aPrefix+'PtzCustomProtocol.'); PtzStopTranslationWhileMoving.LoadFromIni(aIniFile,aSection,aPrefix+'PtzStopTranslationWhileMoving.'); SetLength(self.PtzPoints,aIniFile.ReadInteger(aSection, aPrefix+'PtzPoints.Count', 0)); for i := 0 to High(self.PtzPoints) do begin self.PtzPoints[i].DeviceId:=aIniFile.ReadInteger(aSection, Format(aPrefix+'PtzPoints.%d.DeviceId',[i]), 0); self.PtzPoints[i].Name:=aIniFile.ReadString(aSection, Format(aPrefix+'PtzPoints.%d.Name',[i]), ''); self.PtzPoints[i].Description:=aIniFile.ReadString(aSection, Format(aPrefix+'PtzPoints.%d.Description',[i]), ''); end; self.PeriodStart:=aIniFile.ReadDateTime(aSection, aPrefix+'PeriodStart', 0); self.PeriodEnd:=aIniFile.ReadDateTime(aSection, aPrefix+'PeriodEnd', 0); end; procedure TPhysicalDeviceParameters.SaveToIni(aIniFile: TCustomIniFile;const aSection,aPrefix: string); var j: integer; begin aIniFile.WriteInteger(aSection, aPrefix+'Type', integer(self.DeviceType)); aIniFile.WriteString(aSection, aPrefix+'ServerIP', self.ServerIP); aIniFile.WriteInteger(aSection, aPrefix+'ServerPort', self.ServerPort); aIniFile.WriteInteger(aSection, aPrefix+'Protocol', self.Protocol); aIniFile.WriteInteger(aSection, aPrefix+'ChannelNum', self.ChannelNo); aIniFile.WriteInteger(aSection, aPrefix+'ChannelProfile', self.ChannelProfile); aIniFile.WriteString(aSection, aPrefix+'SourceName', self.SourceName); aIniFile.WriteString(aSection, aPrefix+'UserName', self.UserName); aIniFile.WriteString(aSection, aPrefix+'UserPassword', fsiBaseUtils.StringToCodes(MaskString(self.UserPassword))); aIniFile.WriteBool(aSection, aPrefix+'KeepPersistentConnection', self.KeepPersistentConnection); aIniFile.WriteDateTime(aSection, aPrefix+'PeriodStart', self.PeriodStart); aIniFile.WriteDateTime(aSection, aPrefix+'PeriodEnd', self.PeriodEnd); aIniFile.WriteBool(aSection, aPrefix+'TransmitAudio', self.TransmitAudio); PtzCustomProtocol.SaveToIni(aIniFile,aSection,aPrefix+'PtzCustomProtocol.'); PtzStopTranslationWhileMoving.SaveToIni(aIniFile,aSection,aPrefix+'PtzStopTranslationWhileMoving.'); aIniFile.WriteInteger(aSection, aPrefix+'PtzPoints.Count', Length(self.PtzPoints)); for j := 0 to High(self.PtzPoints) do begin aIniFile.WriteInteger(aSection, Format(aPrefix+'PtzPoints.%d.DeviceId',[j]), self.PtzPoints[j].DeviceId); aIniFile.WriteString(aSection, Format(aPrefix+'PtzPoints.%d.Name',[j]), self.PtzPoints[j].Name); aIniFile.WriteString(aSection, Format(aPrefix+'PtzPoints.%d.Description',[j]), self.PtzPoints[j].Description); end; end; { TInPointConfig } constructor TInPointConfig.Create; var aGUID: TGUID; begin CoCreateGuid(aGUID); UseProcessingQueueOnlyIfNeeded:=false; UseProcessingQueueOnlyIfNeededAndClearPrebuffer:=true; Id:=GUIDToString(aGUID); end; procedure TInPointConfig.LoadFromIni(aIniFile: TCustomIniFile;const aSection: string); var aMediaType: TMediaType; s: AnsiString; begin self.Id := aIniFile.ReadString(aSection, 'ID', ''); self.ProcessingQueueParams.LoadFromIni(aIniFile, aSection); self.PrebufferMaxSize:=aIniFile.ReadInteger(aSection, 'PrebufferMaxSize', DefaultPrebufferMaxSize); self.UseProcessingQueueOnlyIfNeeded:=aIniFile.ReadBool(aSection, 'UsesProcessingQueueOnlyIfNeeded',false); self.UseProcessingQueueOnlyIfNeededAndClearPrebuffer:=aIniFile.ReadBool(aSection, 'UseProcessingQueueOnlyIfNeededAndClearPrebuffer',true); //self.Enabled := aIniFile.ReadBool(aSection, 'Enabled', True); //Physical Device self.Name := aIniFile.ReadString(aSection, 'Name', ''); self.Folder := aIniFile.ReadString(aSection, 'Folder', ''); Self.DeviceParams.LoadFromIni(aIniFile,aSection,'DeviceParams.'); //Media Processors for aMediaType := Low(TMediaType) to High(TMediaType) do begin s:=aIniFile.ReadString(aSection,'MediaProcessors.'+MediaTypeNames[aMediaType],''); self.MediaProcessors[aMediaType]:=fsiBaseUtils.AnsiStringToBytes(fsiBaseUtils.CodesToString(s)); self.Info_OriginalStreamType[aMediaType]:=aIniFile.ReadInteger(aSection,'Info.OriginalStreamType.'+MediaTypeNames[aMediaType],0); self.Info_ResultStreamType[aMediaType]:=aIniFile.ReadInteger(aSection,'Info.ResultStreamType.'+MediaTypeNames[aMediaType],0); end; //Extensions s:=aIniFile.ReadString(aSection,'Extensions',''); self.Extensions:=fsiBaseUtils.AnsiStringToBytes(fsiBaseUtils.CodesToString(s)); end; procedure TInPointConfig.SaveToIni(aIniFile: TCustomIniFile; const aSection: string); var aMediaType: TMediaType; s: AnsiString; begin aIniFile.WriteString(aSection, 'ID', self.Id); aIniFile.WriteString(aSection, 'Name', self.Name); aIniFile.WriteString(aSection, 'Folder', self.Folder); aIniFile.WriteInteger(aSection, 'PrebufferMaxSize', self.PrebufferMaxSize); aIniFile.WriteBool(aSection, 'UsesProcessingQueueOnlyIfNeeded', self.UseProcessingQueueOnlyIfNeeded); aIniFile.WriteBool(aSection, 'UseProcessingQueueOnlyIfNeededAndClearPrebuffer', self.UseProcessingQueueOnlyIfNeededAndClearPrebuffer); self.ProcessingQueueParams.SaveToIni(aIniFile,aSection); //Physical Device self.DeviceParams.SaveToIni(aIniFile,aSection,'DeviceParams.'); for aMediaType:=Low(aMediaType) to High(aMediaType) do begin //Медиа-процессоры s:=fsiBaseUtils.BytesToAnsiString(self.MediaProcessors[aMediaType]); s:=fsiBaseUtils.StringToCodes(s); Assert(Length(s)=2*Length(self.MediaProcessors[aMediaType])); aIniFile.WriteString(aSection,'MediaProcessors.'+MediaTypeNames[aMediaType],s); aIniFile.WriteInteger(aSection,'Info.OriginalStreamType.'+MediaTypeNames[aMediaType],self.Info_OriginalStreamType[aMediaType]); aIniFile.WriteInteger(aSection,'Info.ResultStreamType.'+MediaTypeNames[aMediaType],self.Info_ResultStreamType[aMediaType]); end; //Extensions s:=fsiBaseUtils.BytesToAnsiString(self.Extensions); s:=fsiBaseUtils.StringToCodes(s); aIniFile.WriteString(aSection,'Extensions',s); end; { TOutPointConfig } constructor TOutPointConfig.Create; var aGUID: TGUID; begin CoCreateGuid(aGUID); Id:=GUIDToString(aGUID); end; procedure TOutPointConfig.LoadFromIni(aIniFile: TCustomIniFile; const aSection: string); var aName: string; i: Integer; aMediaType: TMediaType; s: AnsiString; b: boolean; begin self.Id := aIniFile.ReadString(aSection, 'ID', ''); self.Folder := aIniFile.ReadString(aSection, 'Folder', ''); self.ProcessingQueueParams.LoadFromIni(aIniFile,aSection); self.SourceId := aIniFile.ReadString(aSection, 'SourceID', ''); self.SourceIdForBlockedUser := aIniFile.ReadString(aSection, 'SourceIdForBlockedUser', ''); self.SourceIdForUnauthorizedUser := aIniFile.ReadString(aSection, 'SourceIdForUnauthorizedUser', ''); self.SourceIdForInsufficientPrivileges := aIniFile.ReadString(aSection, 'SourceIdForInsufficientPrivileges', ''); self.SourceIdForDisconnectedState := aIniFile.ReadString(aSection, 'SourceIdForDisconnectedState', ''); self.SourceIdForOverQueue := aIniFile.ReadString(aSection, 'SourceIdForOverQueue', ''); self.BackingParams.ImagePath := aIniFile.ReadString(aSection, 'BackingParams.ImagePath', ''); self.BackingParams.DeviceZeroAngle := aIniFile.ReadInteger(aSection, 'BackingParams.DeviceZeroAngle', 0); self.BackingParams.DevicePosition.X:=aIniFile.ReadInteger(aSection, 'BackingParams.DevicePosition.X', 0); self.BackingParams.DevicePosition.Y:=aIniFile.ReadInteger(aSection, 'BackingParams.DevicePosition.Y', 0); self.Enabled := aIniFile.ReadBool(aSection, 'Enabled', True); self.UserInteractiveControlAllowed:= aIniFile.ReadBool(aSection, 'UserInteractiveControlAllowed', True); //Client Connections self.ClientParams.Name:=aIniFile.ReadString(aSection, 'ClientParams.Name', ''); self.ClientParams.Description:=aIniFile.ReadString(aSection, 'ClientParams.Description', ''); //self.ClientParams.PasswordNeeded:=aIniFile.ReadBool(aSection,'ClientParams.PasswordNeeded',false); s:=fsiBaseUtils.StringToCodes(MaskString('root')); self.ClientParams.UserName:=MaskString(fsiBaseUtils.CodesToString(aIniFile.ReadString(aSection,'ClientParams.UserName',s))); self.ClientParams.Password:=MaskString(fsiBaseUtils.CodesToString(aIniFile.ReadString(aSection,'ClientParams.Password',''))); self.ClientParams.AuthorizationProvider:=TClientAuthorizationProvider(aIniFile.ReadInteger(aSection,'ClientParams.AuthorizationProvider',0)); //Archive Settings b:=aIniFile.ReadBool(aSection, 'ArchiveParams.Name', false); if b then //old format begin SetLength(self.ArchiveParams.Sources,1); self.ArchiveParams.Sources[0].ConnectionString:=aIniFile.ReadString(aSection, 'ArchiveParams.ConnectionString',''); self.ArchiveParams.Sources[0].SourceName:=aIniFile.ReadString(aSection, 'ArchiveParams.SourceName', ''); self.ArchiveParams.Sources[0].RecordStorageTransport:=TRecordStorageTransportType(aIniFile.ReadInteger(aSection, 'ArchiveParams.RecordStorageTransport', 0)); //Media Processors for archive for aMediaType := Low(TMediaType) to High(TMediaType) do begin s:=aIniFile.ReadString(aSection,'ArchiveParams.MediaProcessors.'+MediaTypeNames[aMediaType],''); self.ArchiveParams.Sources[0].MediaProcessors[aMediaType]:=fsiBaseUtils.AnsiStringToBytes(fsiBaseUtils.CodesToString(s)); end; end //Actual format else begin i:=aIniFile.ReadInteger(aSection,'ArchiveParams.Sources.Count',0); SetLength(self.ArchiveParams.Sources,i); for i := 0 to High(self.ArchiveParams.Sources) do begin aName:=Format('ArchiveParams.Sources.%d',[i]); self.ArchiveParams.Sources[i].ConnectionString:=aIniFile.ReadString(aSection, aName+'ConnectionString',self.ArchiveParams.Sources[i].ConnectionString); self.ArchiveParams.Sources[i].SourceName:=aIniFile.ReadString(aSection, aName+'SourceName', self.ArchiveParams.Sources[i].SourceName); self.ArchiveParams.Sources[i].RecordStorageTransport:=TRecordStorageTransportType(aIniFile.ReadInteger(aSection, aName+'RecordStorageTransport', integer(self.ArchiveParams.Sources[i].RecordStorageTransport))); self.ArchiveParams.Sources[i].Text:=aIniFile.ReadString(aSection, aName+'Text',self.ArchiveParams.Sources[i].Text); //Media Processors for archive for aMediaType := Low(TMediaType) to High(TMediaType) do begin s:=aIniFile.ReadString(aSection,aName+'MediaProcessors.'+MediaTypeNames[aMediaType],''); self.ArchiveParams.Sources[i].MediaProcessors[aMediaType]:=fsiBaseUtils.AnsiStringToBytes(fsiBaseUtils.CodesToString(s)); end; end; end; //Media Processors for aMediaType := Low(TMediaType) to High(TMediaType) do begin s:=aIniFile.ReadString(aSection,'MediaProcessors.'+MediaTypeNames[aMediaType],''); self.MediaProcessors[aMediaType]:=fsiBaseUtils.AnsiStringToBytes(fsiBaseUtils.CodesToString(s)); end; end; procedure TOutPointConfig.SaveToIni(aIniFile: TCustomIniFile; const aSection: string); var aName: string; j: Integer; aMediaType: TMediaType; s: AnsiString; begin aIniFile.WriteString(aSection, 'ID', self.Id); aIniFile.WriteString(aSection, 'Folder', self.Folder); aIniFile.WriteBool(aSection, 'Enabled', self.Enabled); aIniFile.WriteString(aSection, 'SourceID', self.SourceID); aIniFile.WriteString(aSection, 'SourceIdForBlockedUser', self.SourceIdForBlockedUser); aIniFile.WriteBool(aSection, 'UserInteractiveControlAllowed', self.UserInteractiveControlAllowed); aIniFile.WriteString(aSection, 'SourceIdForUnauthorizedUser', self.SourceIdForUnauthorizedUser); aIniFile.WriteString(aSection, 'SourceIdForInsufficientPrivileges', self.SourceIdForInsufficientPrivileges); aIniFile.WriteString(aSection, 'SourceIdForDisconnectedState', self.SourceIdForDisconnectedState); aIniFile.WriteString(aSection, 'SourceIdForOverQueue', self.SourceIdForOverQueue); self.ProcessingQueueParams.SaveToIni(aIniFile,aSection); aIniFile.WriteString(aSection, 'BackingParams.ImagePath', self.BackingParams.ImagePath); aIniFile.WriteInteger(aSection,'BackingParams.DeviceZeroAngle', self.BackingParams.DeviceZeroAngle); aIniFile.WriteInteger(aSection,'BackingParams.DevicePosition.X', self.BackingParams.DevicePosition.X); aIniFile.WriteInteger(aSection,'BackingParams.DevicePosition.Y', self.BackingParams.DevicePosition.Y); //Client Connections aIniFile.WriteString(aSection, 'ClientParams.Name', self.ClientParams.Name); aIniFile.WriteString(aSection, 'ClientParams.Description',self.ClientParams.Description); //aIniFile.WriteBool(aSection, 'ClientParams.PasswordNeeded', self.ClientParams.PasswordNeeded); aIniFile.WriteString(aSection, 'ClientParams.UserName', fsiBaseUtils.StringToCodes(MaskString(self.ClientParams.UserName))); aIniFile.WriteString(aSection, 'ClientParams.Password', fsiBaseUtils.StringToCodes(MaskString(self.ClientParams.Password))); aIniFile.WriteInteger(aSection,'ClientParams.AuthorizationProvider',integer(self.ClientParams.AuthorizationProvider)); //Archive Settings aIniFile.WriteInteger(aSection,'ArchiveParams.Sources.Count',Length(self.ArchiveParams.Sources)); for j := 0 to High(self.ArchiveParams.Sources) do begin aName:=Format('ArchiveParams.Sources.%d',[j]); aIniFile.WriteString(aSection, aName+'ConnectionString',self.ArchiveParams.Sources[j].ConnectionString); aIniFile.WriteString(aSection, aName+'SourceName', self.ArchiveParams.Sources[j].SourceName); aIniFile.WriteInteger(aSection, aName+'RecordStorageTransport', integer(self.ArchiveParams.Sources[j].RecordStorageTransport)); aIniFile.WriteString(aSection, aName+'Text',self.ArchiveParams.Sources[j].Text); //Media Processors for archive for aMediaType := Low(TMediaType) to High(TMediaType) do begin s:=fsiBaseUtils.BytesToAnsiString(self.ArchiveParams.Sources[j].MediaProcessors[aMediaType]); s:=fsiBaseUtils.StringToCodes(s); Assert(Length(s)=2*Length(self.ArchiveParams.Sources[j].MediaProcessors[aMediaType])); aIniFile.WriteString(aSection,aName+'MediaProcessors.'+MediaTypeNames[aMediaType],s); end; end; //Медиа-процессоры for aMediaType:=Low(aMediaType) to High(aMediaType) do begin //Медиа-процессоры s:=fsiBaseUtils.BytesToAnsiString(self.MediaProcessors[aMediaType]); s:=fsiBaseUtils.StringToCodes(s); Assert(Length(s)=2*Length(self.MediaProcessors[aMediaType])); aIniFile.WriteString(aSection,'MediaProcessors.'+MediaTypeNames[aMediaType],s); end; end; { TArchiveParameters } function TArchiveParameters.IsEnabled: boolean; var k: integer; begin result:=false; for k := 0 to High(Sources) do if (Sources[k].SourceName<>'') and (Sources[k].ConnectionString<>'') then begin result:=true; break; end; end; function TArchiveParameters.ToString: string; var k: integer; begin result:=''; for k := 0 to High(Sources) do if (Sources[k].SourceName<>'') and (Sources[k].ConnectionString<>'') then begin if result<>'' then result:=result+'; '; result:=result+Format('%s/%s, %s',[ Sources[k].ConnectionString, Sources[k].SourceName, RecordStorageTransportTypeToString(Sources[k].RecordStorageTransport)]); end; end; { TArchiveSource } function MD5Encode(const aData: string): String; var md5indy: TIdHashMessageDigest; begin md5indy:=TIdHashMessageDigest5.Create;//создаем экземпляр объекта try result:=LowerCase(md5indy.HashStringAsHex(aData));//тот же хэш, но в HEX-форме finally md5indy.Free; end; end; function TArchiveSource.GetUrl: string; begin if (ConnectionString<>'') and (SourceName<>'') then result:=MD5Encode(ConnectionString)+'/'+SourceName; end; { TProcessingQueueParams } procedure TProcessingQueueParams.Initialize; begin MaxSize:=DefaultProcessingQueueMaxSize; MaxDuration:=DefaultMediaProcessingQueueMaxDuration; OverqueueBitrateTresholdPercent:=DefaultOverqueueBitrateTresholdPercent; OverqueueBitrateMeasureIntervalMs:=DefaultOverqueueBitrateMeasureIntervalMs; end; procedure TProcessingQueueParams.LoadFromIni(aIniFile: TCustomIniFile;const aSection: string); begin self.MaxSize:=aIniFile.ReadInteger(aSection, 'ProcessingQueue.MaxSize', MaxSize); self.MaxDuration:=aIniFile.ReadInteger(aSection, 'ProcessingQueue.MaxDuration', MaxDuration); self.OverqueueBitrateTresholdPercent:=aIniFile.ReadInteger(aSection, 'ProcessingQueue.OverqueueBitrateTresholdPercent', OverqueueBitrateTresholdPercent); self.OverqueueBitrateMeasureIntervalMs:=aIniFile.ReadInteger(aSection, 'ProcessingQueue.OverqueueBitrateMeasureIntervalMs', OverqueueBitrateMeasureIntervalMs); end; procedure TProcessingQueueParams.SaveToIni(aIniFile: TCustomIniFile; const aSection: string); begin aIniFile.WriteInteger(aSection, 'ProcessingQueue.MaxSize', MaxSize); aIniFile.WriteInteger(aSection, 'ProcessingQueue.MaxDuration', MaxDuration); aIniFile.WriteInteger(aSection, 'ProcessingQueue.OverqueueBitrateTresholdPercent', OverqueueBitrateTresholdPercent); aIniFile.WriteInteger(aSection, 'ProcessingQueue.OverqueueBitrateMeasureIntervalMs', OverqueueBitrateMeasureIntervalMs); end; { TPtzProtocol } procedure TPtzProtocol.LoadFromIni(aIniFile: TCustomIniFile; const aSection, aPrefix: string); begin self.Enabled:=aIniFile.ReadBool(aSection, aPrefix+'Enabled', false); self.ProtocolClassName:=aIniFile.ReadString(aSection, aPrefix+'Implementor', ''); self.UserName:=aIniFile.ReadString(aSection, aPrefix+'UserName', ''); self.UserPassword:=aIniFile.ReadString(aSection, aPrefix+'UserPassword', ''); self.Port:=aIniFile.ReadInteger(aSection, aPrefix+'Port', 80); end; procedure TPtzProtocol.SaveToIni(aIniFile: TCustomIniFile; const aSection,aPrefix: string); begin aIniFile.WriteBool(aSection, aPrefix+'Enabled', self.Enabled); aIniFile.WriteString(aSection, aPrefix+'Implementor', self.ProtocolClassName); aIniFile.WriteString(aSection, aPrefix+'UserName', self.UserName); aIniFile.WriteString(aSection, aPrefix+'UserPassword', self.UserPassword); aIniFile.WriteInteger(aSection, aPrefix+'Port', self.Port); end; { TPtzStopTranslationWhileMoving } procedure TPtzStopTranslationWhileMoving.LoadFromIni(aIniFile: TCustomIniFile; const aSection, aPrefix: string); begin self.Enabled:=aIniFile.ReadBool(aSection, aPrefix+'Enabled', false); self.Period:=aIniFile.ReadInteger(aSection, aPrefix+'Period', 200); end; procedure TPtzStopTranslationWhileMoving.SaveToIni(aIniFile: TCustomIniFile;const aSection, aPrefix: string); begin aIniFile.WriteBool(aSection, aPrefix+'Enabled', self.Enabled); aIniFile.WriteInteger(aSection, aPrefix+'Period', self.Period); end; end.
unit BrickCamp.TSettings; interface uses BrickCamp.ISettings, System.IniFiles; type TCbdSettings = class(TInterfacedObject, IBrickCampSettings) protected const CONFIG_INI = 'config.ini'; protected function GetConfigFile: TIniFile; function GetValueAsString(Section, Key: String): String; function GetValueAsInteger(Section, Key: String): Integer; public function GetDBStringConnection: String; function GetRedisIpAddress: String; function GetRedisIpPort: String; end; implementation uses System.SysUtils; const DB_SEC = 'DB'; DB_KEY_CONSTR = 'ConnectionString'; REDIS_SEC = 'Redis'; REDIS_ADDRESS_IPV4 = 'Address_IpV4'; REDIS_PORT_IPV4 = 'Port'; { TCbdSettings } function TCbdSettings.GetConfigFile: TIniFile; begin //TODO - renamed athe config file to the name of exe, and use an after build event to leave it in target folder from project folder Result := TIniFile.Create(ExtractFilePath(ParamStr(0)) + CONFIG_INI); end; function TCbdSettings.GetDBStringConnection: String; begin Result := GetValueAsString(DB_SEC, DB_KEY_CONSTR); end; function TCbdSettings.GetRedisIpAddress: String; begin Result := GetValueAsString(REDIS_SEC, REDIS_ADDRESS_IPV4); end; function TCbdSettings.GetRedisIpPort: String; begin Result := GetValueAsString(REDIS_SEC, REDIS_PORT_IPV4); end; function TCbdSettings.GetValueAsString(Section, Key: String): String; var Config: TIniFile; begin Config := GetConfigFile; try Result := Config.ReadString(Section, Key, ''); finally Config.Free; end; end; function TCbdSettings.GetValueAsInteger(Section, Key: String): Integer; var Config: TIniFile; begin Config := GetConfigFile; try Result := Config.ReadInteger(Section, Key, -1); finally Config.Free; end; end; end.
unit RecordsWithForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.Memo, FMX.Controls.Presentation, FMX.ScrollBox; type TForm1 = class(TForm) Memo1: TMemo; Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public procedure Show (const msg: string); end; var Form1: TForm1; implementation {$R *.fmx} type TMyDate = packed record Year: Integer; Month: Byte; Day: Byte; end; function MyDateToString (MyDate: TMyDate): string; begin Result := MyDate.Year.ToString + '.' + MyDate.Month.ToString + '.' + MyDate.Day.ToString; end; procedure IncreaseYear (var MyDate: TMyDate); begin Inc (MyDate.Year); end; procedure TForm1.Button1Click(Sender: TObject); var BirthDay: TMyDate; begin with BirthDay do begin Year := 1997; Month := 2; Day := 14; Show ('Born in year ' + Year.ToString); end; Show ('Record size is ' + SizeOf (BirthDay).ToString); end; type TMyRecord = record MyName: string; MyValue: Integer; end; procedure TForm1.Button2Click(Sender: TObject); var Record1: TMyRecord; begin with Record1 do begin Name := 'Joe'; MyValue := 22; end; with Record1 do Show (MyName + ': ' + MyValue.ToString); end; procedure TForm1.Show(const msg: string); begin Memo1.Lines.Add(msg); end; initialization Randomize; end.
unit typename_4; interface implementation uses System; type TC1 = class function GetName: string; end; TC2 = class(TC1) end; function TC1.GetName: string; begin Result := typename(self); end; var S: string; procedure Test; var Obj: TC1; begin Obj := TC2.Create(); S := Obj.GetName(); end; initialization Test(); finalization Assert(S = 'TC1'); end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995,2001 Inprise Corporation } { } {*******************************************************} unit RootEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DesignIntf, DesignEditors, StdCtrls, ShellCtrls; type TRootPathEditDlg = class(TForm) Button1: TButton; Button2: TButton; rbUseFolder: TRadioButton; GroupBox1: TGroupBox; cbFolderType: TComboBox; GroupBox2: TGroupBox; ePath: TEdit; rbUsePath: TRadioButton; OpenDialog1: TOpenDialog; btnBrowse: TButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Button2Click(Sender: TObject); procedure rbUseFolderClick(Sender: TObject); procedure rbUsePathClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btnBrowseClick(Sender: TObject); private procedure UpdateState; public end; TRootProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; TRootEditor = class(TComponentEditor) public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): String; override; function GetVerbCount: Integer; override; end; implementation {$R *.dfm} uses TypInfo, FileCtrl; resourcestring SPickRootPath = 'Please select a root path'; SEditRoot = 'E&dit Root'; const NTFolders = [rfCommonDesktopDirectory, rfCommonPrograms, rfCommonStartMenu, rfCommonStartup]; function PathIsCSIDL(Value: string): Boolean; begin Result := GetEnumValue(TypeInfo(TRootFolder), Value) >= 0; end; function RootPathEditor(Value : string): string; begin Result := Value; with TRootPathEditDlg.Create(Application) do try rbUseFolder.Checked := PathIsCSIDL(Result); rbUsePath.Checked := not rbUseFolder.Checked; if not PathIsCSIDL(Result) then begin cbFolderType.ItemIndex := 0; ePath.Text := Result; end else cbFolderType.ItemIndex := cbFolderType.Items.IndexOf(Result); UpdateState; ShowModal; if ModalResult = mrOK then begin if rbUsePath.Checked then Result := ePath.Text else Result := cbFolderType.Items[cbFolderType.ItemIndex]; end; finally Free; end; end; procedure TRootProperty.Edit; begin SetStrValue(RootPathEditor(GetStrValue)); end; function TRootProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog]; end; procedure TRootPathEditDlg.FormCreate(Sender: TObject); var FT: TRootFolder; begin for FT := Low(TRootFolder) to High(TRootFolder) do if not ((Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and (FT in NTFolders)) then cbFolderType.Items.Add(GetEnumName(TypeInfo(TRootFolder), Ord(FT))); cbFolderType.ItemIndex := 0; end; procedure TRootPathEditDlg.UpdateState; begin cbFolderType.Enabled := rbUseFolder.Checked; ePath.Enabled := not rbUseFolder.Checked; btnBrowse.Enabled := ePath.Enabled; end; procedure TRootPathEditDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TRootPathEditDlg.Button2Click(Sender: TObject); begin ModalResult := mrCancel; Close; end; procedure TRootPathEditDlg.rbUseFolderClick(Sender: TObject); begin rbUsePath.Checked := not rbUseFolder.Checked; UpdateState; end; procedure TRootPathEditDlg.rbUsePathClick(Sender: TObject); begin rbUseFolder.Checked := not rbUsePath.Checked; UpdateState; end; procedure TRootPathEditDlg.Button1Click(Sender: TObject); begin ModalResult := mrOK; end; procedure TRootPathEditDlg.btnBrowseClick(Sender: TObject); var Path : widestring; Dir : string; begin Path := ePath.Text; Dir := ePath.Text; if SelectDirectory( SPickRootPath, '', Dir ) then ePath.Text := Dir; end; { TRootEditor } procedure TRootEditor.ExecuteVerb(Index: Integer); procedure EditRoot; const SRoot = 'root'; var Path : string; begin Path := RootPathEditor(GetPropValue(Component, SRoot, True)); SetPropValue(Component, SRoot, Path); Designer.Modified; end; begin case Index of 0 : EditRoot; end; end; function TRootEditor.GetVerb(Index: Integer): String; begin case Index of 0 : Result := SEditRoot; end; end; function TRootEditor.GetVerbCount: Integer; begin Result := 1; end; end.
unit ReleaseSessionsCmd; interface procedure ReleaseSessions(databaseName : String; userId, password : String; hostName : String; hostPort : Integer); implementation uses Classes, sysUtils, strUtils, edbcomps, SessionManager; procedure ReleaseSessions(databaseName : String; userId, password : String; hostName : String; hostPort : Integer); var sessionMgr : TSessionManager; db : TEDBDatabase; ds : TEDBQuery; Sessions : TStringList; i: Integer; begin sessionMgr := TSessionManager.Create(userId, password, hostName, hostPort); try db := TEDBDatabase.Create(nil); ds := TEDBQuery.Create(nil); Sessions := TStringList.Create; try db.SessionName := sessionMgr.session.Name; // This is extra setup that is needed for Remove Server Session to work. db.Session.SessionType := stRemote; db.session.LoginUser := userId; db.session.LoginPassword := password; db.session.CharacterSet := csAnsi; if AnsiLeftStr(hostName, 2) = '\\' then db.session.RemoteHost := AnsiRightStr(hostName, length(hostName) - 2) else db.session.RemoteAddress := hostName; db.session.RemotePort := hostPort; //12010; db.Database := 'Configuration' ; //databaseName; db.DatabaseName := databaseName + DateTimeToStr(now); ds.SessionName := sessionMgr.session.SessionName; ds.DatabaseName := 'Configuration'; // db.Database; ds.SQL.Add('Select Distinct SessionId From Configuration.ServerSessionLocks ' + 'Where DatabaseName = ''' + databaseName + ''' and ObjectType=''Database'''); ds.ExecSQL; while not ds.EOF do begin if ds.FieldByName('SessionId').AsInteger <> sessionMgr.session.CurrentRemoteID then Sessions.Add(ds.FieldByName('SessionId').AsString); ds.Next; end; ds.Close; for i := 0 to Sessions.Count - 1 do db.Execute('Remove Server Session ' + Sessions[i]); finally FreeAndNil(db); FreeAndNil(ds); FreeAndNil(Sessions); end; finally sessionMgr.Free; end; end; end.
unit TeeSlovak; {$I TeeDefs.inc} interface Uses Classes; Var TeeSlovakLanguage:TStringList=nil; Procedure TeeSetSlovak; Procedure TeeCreateSlovak; implementation Uses SysUtils, TeeConst, TeeProCo {$IFNDEF D5},TeCanvas{$ENDIF}; Procedure TeeSlovakConstants; begin TeeMsg_Copyright :='© 1995-2004 by David Berneda'; TeeMsg_LegendFirstValue :='Prvá hodnota legendy musí byť > 0'; TeeMsg_LegendColorWidth :='Šírka farby legendy musí byť > 0%'; TeeMsg_SeriesSetDataSource:='Nie je rodičovský graf pre overenie zdroja dát'; TeeMsg_SeriesInvDataSource:='Neplatný zdroj dát: %s'; TeeMsg_FillSample :='FillSampleValues NumValues musí byť > 0'; TeeMsg_AxisLogDateTime :='Dátumová a časová os nemôže byť logaritmická'; TeeMsg_AxisLogNotPositive :='Min a max hodnoty logaritmickej osi musia byť >= 0'; TeeMsg_AxisLabelSep :='% vzdialenosť štítkov musí byť väčšia ako 0'; TeeMsg_AxisIncrementNeg :='Prírastok osi musí byť >= 0'; TeeMsg_AxisMinMax :='Minimálna hodnota osi musí byť <= ako maximálna'; TeeMsg_AxisMaxMin :='Maximálna hodnota osi musí byť >= ako minimálna'; TeeMsg_AxisLogBase :='Logaritmický základ osi musí byť >= 2'; TeeMsg_MaxPointsPerPage :='MaxPointsPerPage musí byť >= 0'; TeeMsg_3dPercent :='Percento 3D efektu musí byť medzi %d a %d'; TeeMsg_CircularSeries :='Krížové závislosti sérií nie sú prípustné'; TeeMsg_WarningHiColor :='Je požadovaná 16k farebná hĺbka kvôli lepšiemu vzhľadu'; TeeMsg_DefaultPercentOf :='%s / %s'; TeeMsg_DefaultPercentOf2 :='%s'+#13+'/ %s'; TeeMsg_DefPercentFormat :='##0.## %'; TeeMsg_DefValueFormat :='#,##0.###'; TeeMsg_DefLogValueFormat :='#.0 "x10" E+0'; TeeMsg_AxisTitle :='Nadpis osi'; TeeMsg_AxisLabels :='Štítky osi'; TeeMsg_RefreshInterval :='Interval obnovovania musí byť medzi 0 a 60'; TeeMsg_SeriesParentNoSelf :='Nie som Series.ParentChart !'; TeeMsg_GalleryLine :='Čiarový'; TeeMsg_GalleryPoint :='Bodový'; TeeMsg_GalleryArea :='Povrchový'; TeeMsg_GalleryBar :='Stĺpcový'; TeeMsg_GalleryHorizBar :='Horizontálny'#13'stĺpcový'; TeeMsg_Stack :='Hromada'; TeeMsg_GalleryPie :='Koláčový'; TeeMsg_GalleryCircled :='Kruhový'; TeeMsg_GalleryFastLine :='Rýchly čiarový'; TeeMsg_GalleryHorizLine :='Horizontálny'#13'čiarový'; TeeMsg_PieSample1 :='Automobily'; TeeMsg_PieSample2 :='Telefóny'; TeeMsg_PieSample3 :='Stoly'; TeeMsg_PieSample4 :='Monitory'; TeeMsg_PieSample5 :='Lampy'; TeeMsg_PieSample6 :='Klávesnice'; TeeMsg_PieSample7 :='Bicykle'; TeeMsg_PieSample8 :='Stoličky'; TeeMsg_GalleryLogoFont :='Courier New'; TeeMsg_Editing :='Upravujem %s'; TeeMsg_GalleryStandard :='Štandardné'; TeeMsg_GalleryExtended :='Rozšírené'; TeeMsg_GalleryFunctions :='Funkcie'; TeeMsg_EditChart :='&Upraviť graf...'; TeeMsg_PrintPreview :='U&kážka pred tlačou...'; TeeMsg_ExportChart :='E&xport grafu...'; TeeMsg_CustomAxes :='Špeciálne osi...'; TeeMsg_InvalidEditorClass :='%s: Neplatná trieda editora: %s'; TeeMsg_MissingEditorClass :='%s: nemá žiadne okno editora'; TeeMsg_GalleryArrow :='Šípka'; TeeMsg_ExpFinish :='&Dokončiť'; TeeMsg_ExpNext :='Ď&alej >'; TeeMsg_GalleryGantt :='Gantt'; TeeMsg_GanttSample1 :='Design'; TeeMsg_GanttSample2 :='Modelovanie'; TeeMsg_GanttSample3 :='Vývoj'; TeeMsg_GanttSample4 :='Predaj'; TeeMsg_GanttSample5 :='Marketing'; TeeMsg_GanttSample6 :='Testovanie'; TeeMsg_GanttSample7 :='Výroba'; TeeMsg_GanttSample8 :='Ladenie'; TeeMsg_GanttSample9 :='Nová verzia'; TeeMsg_GanttSample10 :='Bankovníctvo'; TeeMsg_ChangeSeriesTitle :='Zmena nadpisu série'; TeeMsg_NewSeriesTitle :='Nový nadpis série:'; TeeMsg_DateTime :='Dátum / čas'; TeeMsg_TopAxis :='Horná os'; TeeMsg_BottomAxis :='Spodná os'; TeeMsg_LeftAxis :='Ľavá os'; TeeMsg_RightAxis :='Pravá os'; TeeMsg_SureToDelete :='Vymazať %s ?'; TeeMsg_DateTimeFormat :='For&mát dátumu a času:'; TeeMsg_Default :='Implicitné: '; TeeMsg_ValuesFormat :='For&mát hodnôt:'; TeeMsg_Maximum :='Maximum'; TeeMsg_Minimum :='Minimum'; TeeMsg_DesiredIncrement :='Žiadúci %s inkrement'; TeeMsg_IncorrectMaxMinValue:='Nekorektná hodnota. Dôvod: %s'; TeeMsg_EnterDateTime :='Vlož [Počet dní] '+TeeMsg_HHNNSS; TeeMsg_SureToApply :='Použiť zmeny ?'; TeeMsg_SelectedSeries :='(Vybrané série)'; TeeMsg_RefreshData :='&Obnoviť dáta'; TeeMsg_DefaultFontSize :={$IFDEF LINUX}'10'{$ELSE}'8'{$ENDIF}; TeeMsg_DefaultEditorSize :='414'; TeeMsg_DefaultEditorHeight:='347'; TeeMsg_FunctionAdd :='Sčítať'; TeeMsg_FunctionSubtract :='Odčítať'; TeeMsg_FunctionMultiply :='Násobiť'; TeeMsg_FunctionDivide :='Deliť'; TeeMsg_FunctionHigh :='Vysoko'; TeeMsg_FunctionLow :='Nízko'; TeeMsg_FunctionAverage :='Priemer'; TeeMsg_GalleryShape :='Tvary'; TeeMsg_GalleryBubble :='Bubliny'; TeeMsg_FunctionNone :='Kopírovať'; TeeMsg_None :='(nič)'; TeeMsg_PrivateDeclarations:='{ Súkromné deklarácie }'; TeeMsg_PublicDeclarations :='{ Verejné deklarácie }'; TeeMsg_DefaultFontName :=TeeMsg_DefaultEngFontName; TeeMsg_CheckPointerSize :='Veľkosť ukazateľa musí byť väčšia ako nula'; TeeMsg_About :='&O TeeChart-e...'; tcAdditional :='Additional'; tcDControls :='Data Controls'; tcQReport :='QReport'; TeeMsg_DataSet :='Súbor dát'; TeeMsg_AskDataSet :='&Súbor dát:'; TeeMsg_SingleRecord :='Jeden záznam'; TeeMsg_AskDataSource :='&Zdroj dát:'; TeeMsg_Summary :='Súhrn'; TeeMsg_FunctionPeriod :='Perióda funkcie musí byť >= 0'; TeeMsg_WizardTab :='Business'; TeeMsg_TeeChartWizard :='Sprievodca TeeChart'; TeeMsg_ClearImage :='Odst&rániť'; TeeMsg_BrowseImage :='&Vyhľadať...'; TeeMsg_WizardSureToClose :='Ste si istý, že chcete zatvoriť sprievodcu TeeChart ?'; TeeMsg_FieldNotFound :='Pole %s neexistuje'; TeeMsg_DepthAxis :='Hĺbková os'; TeeMsg_PieOther :='Ostatné'; TeeMsg_ShapeGallery1 :='abc'; TeeMsg_ShapeGallery2 :='123'; TeeMsg_ValuesX :='X'; TeeMsg_ValuesY :='Y'; TeeMsg_ValuesPie :='Koláč'; TeeMsg_ValuesBar :='Stĺpec'; TeeMsg_ValuesAngle :='Uhol'; TeeMsg_ValuesGanttStart :='Začiatok'; TeeMsg_ValuesGanttEnd :='Koniec'; TeeMsg_ValuesGanttNextTask:='NextTask'; TeeMsg_ValuesBubbleRadius :='Polomer'; TeeMsg_ValuesArrowEndX :='KoniecX'; TeeMsg_ValuesArrowEndY :='KoniecY'; TeeMsg_Legend :='Legenda'; TeeMsg_Title :='Nadpis'; TeeMsg_Foot :='Spodok'; TeeMsg_Period :='Perióda'; TeeMsg_PeriodRange :='Rozsah periódy'; TeeMsg_CalcPeriod :='Počítať %s každý:'; TeeMsg_SmallDotsPen :='Malé body'; TeeMsg_InvalidTeeFile :='Neplatný graf v súbore *.'+TeeMsg_TeeExtension; TeeMsg_WrongTeeFileFormat :='Chybný formát súboru *.'+TeeMsg_TeeExtension; TeeMsg_EmptyTeeFile :='Prázdny súbor *.'+TeeMsg_TeeExtension; { 5.01 } {$IFDEF D5} TeeMsg_ChartAxesCategoryName := 'Osi grafu'; TeeMsg_ChartAxesCategoryDesc := 'Vlastnosti a udalosti os grafu'; TeeMsg_ChartWallsCategoryName := 'Steny grafu'; TeeMsg_ChartWallsCategoryDesc := 'Vlastnosti a udalosti stien grafu'; TeeMsg_ChartTitlesCategoryName := 'Nadpisy grafu'; TeeMsg_ChartTitlesCategoryDesc := 'Vlastnosti a udalosti nadpisov grafu'; TeeMsg_Chart3DCategoryName := '3D graf'; TeeMsg_Chart3DCategoryDesc := 'Vlastnosti a udalosti 3D grafu'; {$ENDIF} TeeMsg_CustomAxesEditor :='Zvláštne '; TeeMsg_Series :='Série'; TeeMsg_SeriesList :='Série...'; TeeMsg_PageOfPages :='Strana %d / %d'; TeeMsg_FileSize :='%d bytov'; TeeMsg_First :='Prvá'; TeeMsg_Prior :='Predchádzajúca'; TeeMsg_Next :='Nasledujúca'; TeeMsg_Last :='Posledná'; TeeMsg_Insert :='Vložiť'; TeeMsg_Delete :='Vymazať'; TeeMsg_Edit :='Upraviť'; TeeMsg_Post :='Uložiť'; TeeMsg_Cancel :='Storno'; TeeMsg_All :='(všetko)'; TeeMsg_Index :='Index'; TeeMsg_Text :='Text'; TeeMsg_AsBMP :='ako &Bitová mapa'; TeeMsg_BMPFilter :='Bitové mapy (*.bmp)|*.bmp'; TeeMsg_AsEMF :='ako &Metafile'; TeeMsg_EMFFilter :='Enhanced Metafiles (*.emf)|*.emf|Metafiles (*.wmf)|*.wmf'; TeeMsg_ExportPanelNotSet := 'Vlastnosť Panel vo formáte exportu nie je nastavená'; TeeMsg_Normal :='Normálne'; TeeMsg_NoBorder :='Bez okraja'; TeeMsg_Dotted :='Bodkované'; TeeMsg_Colors :='Farby'; TeeMsg_Filled :='Vyplnené'; TeeMsg_Marks :='Značky'; TeeMsg_Stairs :='Schody'; TeeMsg_Points :='Body'; TeeMsg_Height :='Výška'; TeeMsg_Hollow :='Dutina'; TeeMsg_Point2D :='Bod 2D'; TeeMsg_Triangle :='Trojuholník'; TeeMsg_Star :='Hviezda'; TeeMsg_Circle :='Kruh'; TeeMsg_DownTri :='Dole troj.'; TeeMsg_Cross :='Kríž'; TeeMsg_Diamond :='Diamant'; TeeMsg_NoLines :='Bez čiar'; TeeMsg_Stack100 :='Sklad 100%'; TeeMsg_Pyramid :='Pyramída'; TeeMsg_Ellipse :='Elipsa'; TeeMsg_InvPyramid:='Inv. pyramída'; TeeMsg_Sides :='Strany'; TeeMsg_SideAll :='Strana všet.'; TeeMsg_Patterns :='Vzory'; TeeMsg_Exploded :='Výbuch'; TeeMsg_Shadow :='Tieň'; TeeMsg_SemiPie :='Polokoláč'; TeeMsg_Rectangle :='Obdĺžnik'; TeeMsg_VertLine :='Vert. čiara'; TeeMsg_HorizLine :='Horiz. čiara'; TeeMsg_Line :='Čiara'; TeeMsg_Cube :='Kocka'; TeeMsg_DiagCross :='Diag. kríž'; TeeMsg_CanNotFindTempPath :='Nemôžem nájsť dočasný adresár'; TeeMsg_CanNotCreateTempChart :='Nemôžem vytvoriť dočasný súbor'; TeeMsg_CanNotEmailChart :='Nemôžem poslať graf e-mailom. Chyba MAPI: %d'; TeeMsg_SeriesDelete :='Mazanie série: ValueIndex %d mimo hranice (0 do %d).'; TeeMsg_NoSeriesSelected :='Nie sú vybrané žiadne série'; TeeMsg_CannotLoadChartFromURL:='Chybový kód: %d pri sťahovaní grafu z URL: %s'; TeeMsg_CannotLoadSeriesDataFromURL:='Chybový kód: %d pri sťahovaní dát série z URL: %s'; { 5.02 } { Moved from TeeImageConstants.pas unit } TeeMsg_AsJPEG :='ako &JPEG'; TeeMsg_JPEGFilter :='JPEG súbory (*.jpg)|*.jpg'; TeeMsg_AsGIF :='ako &GIF'; TeeMsg_GIFFilter :='GIF súbory (*.gif)|*.gif'; TeeMsg_AsPNG :='ako &PNG'; TeeMsg_PNGFilter :='PNG súbory (*.png)|*.png'; TeeMsg_AsPCX :='ako PC&X'; TeeMsg_PCXFilter :='PCX súbory (*.pcx)|*.pcx'; TeeMsg_AsVML :='ako &VML (HTM)'; TeeMsg_VMLFilter :='VML súbory (*.htm)|*.htm'; { 5.02 } TeeMsg_AskLanguage :='&Jazyk...'; { 5.03 } TeeMsg_Gradient :='Prechod'; TeeMsg_WantToSave :='Chcete uložiť %s?'; TeeMsg_NativeFilter :='Súbory TeeChart '+TeeDefaultFilterExtension; TeeMsg_Property :='Vlastnosť'; TeeMsg_Value :='Hodnota'; TeeMsg_Yes :='Áno'; TeeMsg_No :='Nie'; TeeMsg_Image :='(obrázok)'; {AX 5.0.4} TeeMsg_ActiveXVersion := 'ActiveX Release ' + AXVer; TeeMsg_ActiveXCannotImport := 'Nemôžem importovať TeeChart z %s'; TeeMsg_ActiveXVerbPrint := '&Ukážka pred tlačou...'; TeeMsg_ActiveXVerbExport := 'E&xport...'; TeeMsg_ActiveXVerbImport := '&Import...'; TeeMsg_ActiveXVerbHelp := '&Pomoc...'; TeeMsg_ActiveXVerbAbout := '&O TeeChart-e...'; TeeMsg_ActiveXError := 'TeeChart: Chybový kód: %d pri sťahovaní: %s'; TeeMsg_DatasourceError := 'TeeChart DataSource nie je Series alebo RecordSet'; TeeMsg_SeriesTextSrcError := 'Chybný typ série'; TeeMsg_AxisTextSrcError := 'Chybný typ osi'; TeeMsg_DelSeriesDatasource := 'Naozaj chcete vymazať %s ?'; TeeMsg_OCXNoPrinter := 'Nie je nainštalovaná žiadna tlačiareň.'; TeeMsg_ActiveXPictureNotValid :='Obrázok nie je platný'; { 6.0 } TeeMsg_FunctionCustom :='y = f(x)'; TeeMsg_AsPDF :='ako &PDF'; TeeMsg_PDFFilter :='PDF súbory (*.pdf)|*.pdf'; TeeMsg_AsPS :='ako PostScript'; TeeMsg_PSFilter :='PostScript súbory (*.eps)|*.eps'; TeeMsg_GalleryHorizArea :='Horizontálna'#13'oblasť'; TeeMsg_SelfStack :='Self Stacked'; TeeMsg_DarkPen :='Tmavý okraj'; TeeMsg_SelectFolder :='Vyberte databázový adresár'; TeeMsg_BDEAlias :='&Alias:'; TeeMsg_ADOConnection :='&Spojenie:'; { TeeProCo } TeeMsg_GalleryPolar :='Pólový'; TeeMsg_GalleryCandle :='Sviečkový'; TeeMsg_GalleryVolume :='Objemový'; TeeMsg_GallerySurface :='Povrchový'; TeeMsg_GalleryContour :='Obrysový'; TeeMsg_GalleryBezier :='Bezierový'; TeeMsg_GalleryPoint3D :='3D bodový'; TeeMsg_GalleryRadar :='Radar'; TeeMsg_GalleryDonut :='Donut'; TeeMsg_GalleryCursor :='Kurzorový'; TeeMsg_GalleryBar3D :='3D stĺpcový'; TeeMsg_GalleryBigCandle :='Veľké sviečky'; TeeMsg_GalleryLinePoint :='Čiary body'; TeeMsg_GalleryHistogram :='Histogram'; TeeMsg_GalleryWaterFall :='Vodopád'; TeeMsg_GalleryWindRose :='Veterná ruža'; TeeMsg_GalleryClock :='Hodiny'; TeeMsg_GalleryColorGrid :='Farebná mriežka'; TeeMsg_GalleryBoxPlot :='BoxPlot'; TeeMsg_GalleryHorizBoxPlot:='Horiz. boxplot'; TeeMsg_GalleryBarJoin :='Spojené stĺpce'; TeeMsg_GallerySmith :='Kováč'; TeeMsg_GalleryPyramid :='Pyramída'; TeeMsg_GalleryMap :='Mapa'; TeeMsg_PolyDegreeRange :='Polynomický stupeň musí byť medzi 1 a 20'; TeeMsg_AnswerVectorIndex :='Index vektora musí byť medzi 1 a %d'; TeeMsg_FittingError :='Nemôžem vykonať skúšku'; TeeMsg_PeriodRange :='Perióda musí byť >= 0'; TeeMsg_ExpAverageWeight :='ExpAverage Weight musí byť medzi 0 a 1'; TeeMsg_GalleryErrorBar :='Chybový stĺpec'; TeeMsg_GalleryError :='Chybový'; TeeMsg_GalleryHighLow :='Vysoký-nízky'; TeeMsg_FunctionMomentum :='Hybnosť'; TeeMsg_FunctionMomentumDiv :='Rozdelenie'#13'hybnosti'; TeeMsg_FunctionExpAverage :='Exponenciálny'#13'priemer'; TeeMsg_FunctionMovingAverage:='Pohyblivý'#13'priemer'; TeeMsg_FunctionExpMovAve :='Exp. pohyblivý'#13'priemer'; TeeMsg_FunctionRSI :='R.S.I.'; TeeMsg_FunctionCurveFitting:='Odpovedajúca'#13'krivka'; TeeMsg_FunctionTrend :='Trend'; TeeMsg_FunctionExpTrend :='Exp. Trend'; TeeMsg_FunctionLogTrend :='Log. Trend'; TeeMsg_FunctionCumulative :='Kumulatívny'; TeeMsg_FunctionStdDeviation:='Štandardná'#13'odchýlka'; TeeMsg_FunctionBollinger :='Skupiny'#13'deliteľov'; TeeMsg_FunctionRMS :='Root Mean'#13'Square'; TeeMsg_FunctionMACD :='MACD'; TeeMsg_FunctionStochastic :='Pravdepodobnosť'; TeeMsg_FunctionADX :='ADX'; TeeMsg_FunctionCount :='Počet'; TeeMsg_LoadChart :='Načítať TeeChart...'; TeeMsg_SaveChart :='Uložiť TeeChart...'; TeeMsg_TeeFiles :='Súbory TeeChart Pro'; TeeMsg_GallerySamples :='Ostatné'; TeeMsg_GalleryStats :='Štatistiky'; TeeMsg_CannotFindEditor :='Nemôžem nájsť formulár Editor sérií: %s'; TeeMsg_Test :='Test...'; TeeMsg_ValuesDate :='Dátum'; TeeMsg_ValuesOpen :='Otvoriť'; TeeMsg_ValuesHigh :='Vysoko'; TeeMsg_ValuesLow :='Nízko'; TeeMsg_ValuesClose :='Zatvoriť'; TeeMsg_ValuesOffset :='Offset'; TeeMsg_ValuesStdError :='Štand. chyba'; TeeMsg_Grid3D :='3D mriežka'; TeeMsg_LowBezierPoints :='Počet Bézierových bodov musí byť > 1'; { TeeCommander component... } TeeCommanMsg_Normal :='Normál'; TeeCommanMsg_Edit :='Upraviť'; TeeCommanMsg_Print :='Tlač'; TeeCommanMsg_Copy :='Kopírovať'; TeeCommanMsg_Save :='Uložiť'; TeeCommanMsg_3D :='3D'; TeeCommanMsg_Rotating :='Rotácia: %d° Výška: %d°'; TeeCommanMsg_Rotate :='Rotácia'; TeeCommanMsg_Moving :='Horiz.Offset: %d Vert.Offset: %d'; TeeCommanMsg_Move :='Presun'; TeeCommanMsg_Zooming :='Zoom: %d %%'; TeeCommanMsg_Zoom :='Zoom'; TeeCommanMsg_Depthing :='3D: %d %%'; TeeCommanMsg_Depth :='Hĺbka'; TeeCommanMsg_Chart :='Graf'; TeeCommanMsg_Panel :='Panel'; TeeCommanMsg_RotateLabel:='Pre rotáciu ťahajte %s'; TeeCommanMsg_MoveLabel :='Pre presun ťahajte %s'; TeeCommanMsg_ZoomLabel :='Pre zoom ťahajte %s'; TeeCommanMsg_DepthLabel :='Pre zmenu 3D ťahajte %s'; TeeCommanMsg_NormalLabel:='Ťahajte ľavým tlačítkom pre Zoom, pravým pre rolovanie'; TeeCommanMsg_NormalPieLabel:='Ťahajte časť koláča pre explodovanie'; TeeCommanMsg_PieExploding :='Časť: %d Explodovaná: %d %%'; TeeMsg_TriSurfaceLess :='Počet bodov musí byť >= 4'; TeeMsg_TriSurfaceAllColinear :='Všetky kolineárne dátové body'; TeeMsg_TriSurfaceSimilar :='Podobné body - nemôžem vykonať'; TeeMsg_GalleryTriSurface :='Troj.povrch'; TeeMsg_AllSeries :='Všetky série'; TeeMsg_Edit :='Upraviť'; TeeMsg_GalleryFinancial :='Finančné'; TeeMsg_CursorTool :='Kurzor'; TeeMsg_DragMarksTool :='Ťahajúce značky'; TeeMsg_AxisArrowTool :='Šípky osi'; TeeMsg_DrawLineTool :='Kreslenie čiary'; TeeMsg_NearestTool :='Najbližší bod'; TeeMsg_ColorBandTool :='Farebný pás'; TeeMsg_ColorLineTool :='Farebná čiara'; TeeMsg_RotateTool :='Rotácia'; TeeMsg_ImageTool :='Obrázok'; TeeMsg_MarksTipTool :='Tipy'; TeeMsg_AnnotationTool:='Poznámka'; TeeMsg_CantDeleteAncestor :='Nemôžem vymazať predchodcu'; TeeMsg_Load :='Načítať...'; { TeeChart Actions } TeeMsg_CategoryChartActions :='Graf'; TeeMsg_CategorySeriesActions :='Série grafu'; TeeMsg_Action3D := '&3D'; TeeMsg_Action3DHint := 'Zmena 2D / 3D'; TeeMsg_ActionSeriesActive := '&Aktívne'; TeeMsg_ActionSeriesActiveHint := 'Zobraziť / skryť série'; TeeMsg_ActionEditHint := 'Upraviť graf'; TeeMsg_ActionEdit := '&Upraviť...'; TeeMsg_ActionCopyHint := 'Kopírovať do schránky'; TeeMsg_ActionCopy := '&Kopírovať'; TeeMsg_ActionPrintHint := 'Ukážka grafu pred tlačou'; TeeMsg_ActionPrint := '&Tlač...'; TeeMsg_ActionAxesHint := 'Zobraziť / skryť osi'; TeeMsg_ActionAxes := '&Osi'; TeeMsg_ActionGridsHint := 'Zobraziť / skryť mriežky'; TeeMsg_ActionGrids := '&Mriežky'; TeeMsg_ActionLegendHint := 'Zobraziť / skryť legendu'; TeeMsg_ActionLegend := '&Legenda'; TeeMsg_ActionSeriesEditHint := 'Upraviť série'; TeeMsg_ActionSeriesMarksHint := 'Zobraziť / skryť značky sérií'; TeeMsg_ActionSeriesMarks := '&Značky'; TeeMsg_ActionSaveHint := 'Uložiť graf'; TeeMsg_ActionSave := '&Uložiť...'; TeeMsg_CandleBar := 'Stĺpec'; TeeMsg_CandleNoOpen := 'Neotvorený'; TeeMsg_CandleNoClose := 'Nezatvorený'; TeeMsg_NoLines := 'Žiadne čiary'; TeeMsg_NoHigh := 'Žiadny vrchol'; TeeMsg_NoLow := 'Žiadny spodok'; TeeMsg_ColorRange := 'Rozsah farieb'; TeeMsg_WireFrame := 'Drôtový model'; TeeMsg_DotFrame := 'Bodový model'; TeeMsg_Positions := 'Polohy'; TeeMsg_NoGrid := 'Žiadna mriežka'; TeeMsg_NoPoint := 'Žiadny bod'; TeeMsg_NoLine := 'Žiadna čiara'; TeeMsg_Labels := 'Štítky'; TeeMsg_NoCircle := 'Žiadny kruh'; TeeMsg_Lines := 'Čiary'; TeeMsg_Border := 'Okraj'; TeeMsg_SmithResistance := 'Odpor'; TeeMsg_SmithReactance := 'Jalový odpor'; TeeMsg_Column := 'Stĺpec'; { 5.01 } TeeMsg_Separator := 'Oddeľovač'; TeeMsg_FunnelSegment := 'Segment '; TeeMsg_FunnelSeries := 'Tunel'; TeeMsg_FunnelPercent := '0.00 %'; TeeMsg_FunnelExceed := 'Presiahnutá kvóta'; TeeMsg_FunnelWithin := ' v kvóte'; TeeMsg_FunnelBelow := ' alebo viac pod kvótou'; TeeMsg_CalendarSeries := 'Kalendár'; TeeMsg_DeltaPointSeries := 'Troj bod'; TeeMsg_ImagePointSeries := 'Obrazový bod'; TeeMsg_ImageBarSeries := 'Obrazový stĺpec'; TeeMsg_SeriesTextFieldZero := 'SeriesText: Index poľa musí byť väčší ako nula.'; { 5.02 } TeeMsg_Origin := 'Počiatok'; TeeMsg_Transparency := 'Transparentnosť'; TeeMsg_Box := 'Schránka'; TeeMsg_ExtrOut := 'ExtrOut'; TeeMsg_MildOut := 'MildOut'; TeeMsg_PageNumber := 'Číslo strany'; TeeMsg_TextFile := 'Textový súbor'; { 5.03 } TeeMsg_Gradient :='Prechod'; TeeMsg_WantToSave :='Uložiť %s?'; TeeMsg_Property :='Vlastnosť'; TeeMsg_Value :='Hodnota'; TeeMsg_Yes :='Áno'; TeeMsg_No :='Nie'; TeeMsg_Image :='(obrázok)'; { 5.03 } TeeMsg_DragPoint := 'Ťahový bod'; TeeMsg_OpportunityValues := 'Príležit.hodnoty'; TeeMsg_QuoteValues := 'Kvót.hodnoty'; { 6.0 } TeeMsg_FunctionSmooth :='Vyrovnanie'; TeeMsg_FunctionCross :='Krížové body'; TeeMsg_GridTranspose :='Transponovanie 3D mriežky'; TeeMsg_FunctionCompress :='Kompresia'; TeeMsg_ExtraLegendTool :='Extra Legenda'; TeeMsg_FunctionCLV :='Najbližšia'#13'hodnota'; TeeMsg_FunctionOBV :='On Balance'#13'Volume'; TeeMsg_FunctionCCI :='Commodity'#13'Channel Index'; TeeMsg_FunctionPVO :='Objemový'#13'Oscilátor'; TeeMsg_SeriesAnimTool :='Animácia sérií'; TeeMsg_GalleryPointFigure :='Bod a obrazec'; TeeMsg_Up :='Hore'; TeeMsg_Down :='Dole'; TeeMsg_GanttTool :='Gantt ťahanie'; TeeMsg_XMLFile :='XML súbor'; TeeMsg_GridBandTool :='Skupina mriežok'; TeeMsg_FunctionPerf :='Výkon'; TeeMsg_GalleryGauge :='Merítko'; TeeMsg_GalleryGauges :='Merítka'; TeeMsg_ValuesVectorEndZ :='KoniecZ'; TeeMsg_GalleryVector3D :='3D vektor'; TeeMsg_Gallery3D :='3D'; TeeMsg_GalleryTower :='Veža'; TeeMsg_SingleColor :='Jedna farba'; TeeMsg_Cover :='Pokrytie'; TeeMsg_Cone :='Kužeľ'; TeeMsg_PieTool :='Kúsky koláča'; end; Procedure TeeCreateSlovak; begin if not Assigned(TeeSlovakLanguage) then begin TeeSlovakLanguage:=TStringList.Create; TeeSlovakLanguage.Text:= 'GRADIENT EDITOR=Editor prechodov'#13+ 'GRADIENT=Prechod'#13+ 'DIRECTION=Smer'#13+ 'VISIBLE=Viditeľné'#13+ 'TOP BOTTOM=Hore Dole'#13+ 'BOTTOM TOP=Dole Hore'#13+ 'LEFT RIGHT=Vľavo Vpravo'#13+ 'RIGHT LEFT=Vpravo Vľavo'#13+ 'FROM CENTER=Od stredu'#13+ 'FROM TOP LEFT=Od ľava hore'#13+ 'FROM BOTTOM LEFT=Od ľava dole'#13+ 'OK=OK'#13+ 'CANCEL=Storno'#13+ 'COLORS=Farby'#13+ 'START=Začiatok'#13+ 'MIDDLE=Stred'#13+ 'END=Koniec'#13+ 'SWAP=Výmena'#13+ 'NO MIDDLE=Bez stredu'#13+ 'TEEFONT EDITOR=TeeFont editor'#13+ 'INTER-CHAR SPACING=Medzery medzi znakmi'#13+ 'FONT=Font'#13+ 'SHADOW=Tieň'#13+ 'HORIZ. SIZE=Horiz. veľkosť'#13+ 'VERT. SIZE=Vert. veľkosť'#13+ 'COLOR=Farba'#13+ 'OUTLINE=Obrys'#13+ 'OPTIONS=Možnosti'#13+ 'FORMAT=Formát'#13+ 'TEXT=Text'#13+ 'GRADIENT=Prechod'#13+ 'POSITION=Pozícia'#13+ 'LEFT=Vľavo'#13+ 'TOP=Hore'#13+ 'AUTO=Auto'#13+ 'CUSTOM=Vlastné'#13+ 'LEFT TOP=Vľavo hore'#13+ 'LEFT BOTTOM=Vľavo dole'#13+ 'RIGHT TOP=Vpravo hore'#13+ 'RIGHT BOTTOM=Vpravo dole'#13+ 'MULTIPLE AREAS=Viac povrchov'#13+ 'NONE=Nič'#13+ 'STACKED=Nakopené'#13+ 'STACKED 100%=Nakopené 100%'#13+ 'AREA=Povrch'#13+ 'PATTERN=Vzor'#13+ 'STAIRS=Schody'#13+ 'SOLID=Plný'#13+ 'CLEAR=Čistý'#13+ 'HORIZONTAL=Horizontálny'#13+ 'VERTICAL=Vertikálny'#13+ 'DIAGONAL=Diagonálny'#13+ 'B.DIAGONAL=B.Diagonálny'#13+ 'CROSS=Kríž'#13+ 'DIAG.CROSS=Diag. kríž'#13+ 'AREA LINES=Plošné čiary'#13+ 'BORDER=Okraj'#13+ 'INVERTED=Inverzné'#13+ 'INVERTED SCROLL=Inverzný posun'#13+ 'COLOR EACH=Ofarbi všetky'#13+ 'ORIGIN=Počiatok'#13+ 'USE ORIGIN=Použi počiatok'#13+ 'WIDTH=Šírka'#13+ 'HEIGHT=Výška'#13+ 'AXIS=Osi'#13+ 'LENGTH=Dĺžka'#13+ 'SCROLL=Rolovanie'#13+ 'PATTERN=Vzor'#13+ 'START=Začiatok'#13+ 'END=Koniec'#13+ 'BOTH=Oboje'#13+ 'AXIS INCREMENT=Prírastok osi'#13+ 'INCREMENT=Prírastok'#13+ 'STANDARD=Štandard'#13+ 'CUSTOM=Vlastné'#13+ 'ONE MILLISECOND=Jedna milisekunda'#13+ 'ONE SECOND=Jedna sekunda'#13+ 'FIVE SECONDS=Päť sekúnd'#13+ 'TEN SECONDS=Desať sekúnd'#13+ 'FIFTEEN SECONDS=Pätnásť sekúnd'#13+ 'THIRTY SECONDS=Tridsať sekúnd'#13+ 'ONE MINUTE=Jedna minúta'#13+ 'FIVE MINUTES=Päť minút'#13+ 'TEN MINUTES=Desať minút'#13+ 'FIFTEEN MINUTES=Pätnásť minút'#13+ 'THIRTY MINUTES=Tridsať minút'#13+ 'ONE HOUR=Jedna hodina'#13+ 'TWO HOURS=Dve hodiny'#13+ 'SIX HOURS=Šesť hodín'#13+ 'TWELVE HOURS=Dvanásť hodín'#13+ 'ONE DAY=Jeden deň'#13+ 'TWO DAYS=Dva dni'#13+ 'THREE DAYS=Tri dni'#13+ 'ONE WEEK=Jeden týždeň'#13+ 'HALF MONTH=Pol mesiaca'#13+ 'ONE MONTH=Jeden mesiac'#13+ 'TWO MONTHS=Dva mesiace'#13+ 'THREE MONTHS=Tri mesiace'#13+ 'FOUR MONTHS=Štyri mesiace'#13+ 'SIX MONTHS=Šesť mesiacov'#13+ 'ONE YEAR=Jeden rok'#13+ 'EXACT DATE TIME=Presný dátum a čas'#13+ 'AXIS MAXIMUM AND MINIMUM=Minimum a maximum osi'#13+ 'VALUE=Hodnota'#13+ 'TIME=Čas'#13+ 'LEFT AXIS=Ľavá os'#13+ 'RIGHT AXIS=Pravá os'#13+ 'TOP AXIS=Horná os'#13+ 'BOTTOM AXIS=Spodná os'#13+ '% BAR WIDTH=% Šírka stĺpca'#13+ 'STYLE=Štýl'#13+ '% BAR OFFSET=% Offset stĺpca'#13+ 'RECTANGLE=Obdĺžnik'#13+ 'PYRAMID=Pyramída'#13+ 'INVERT. PYRAMID=Inverzná pyramída'#13+ 'CYLINDER=Valec'#13+ 'ELLIPSE=Elipsa'#13+ 'ARROW=Šípka'#13+ 'RECT. GRADIENT=Prav. prechod'#13+ 'CONE=Kužeľ'#13+ 'DARK BAR 3D SIDES=Tmavý stĺpec 3D strany'#13+ 'BAR SIDE MARGINS=Okraje strany stĺpca'#13+ 'AUTO MARK POSITION=Automaticky označiť pozíciu'#13+ 'BORDER=Okraj'#13+ 'JOIN=Spojiť'#13+ 'BAR SIDE MARGINS=Okraje strany stĺpca'#13+ 'DATASET=Dataset'#13+ 'APPLY=Použiť'#13+ 'SOURCE=Zdroj'#13+ 'MONOCHROME=Monochrom'#13+ 'DEFAULT=Implicitné'#13+ '2 (1 BIT)=2 (1 bit)'#13+ '16 (4 BIT)=16 (4 bit)'#13+ '256 (8 BIT)=256 (8 bit)'#13+ '32768 (15 BIT)=32768 (15 bit)'#13+ '65536 (16 BIT)=65536 (16 bit)'#13+ '16M (24 BIT)=16M (24 bit)'#13+ '16M (32 BIT)=16M (32 bit)'#13+ 'LENGTH=Dĺžka'#13+ 'MEDIAN=Stred'#13+ 'WHISKER=Tykadlo'#13+ 'PATTERN COLOR EDITOR=Editor farby vzoru'#13+ 'IMAGE=Obrázok'#13+ 'NONE=Nič'#13+ 'BACK DIAGONAL=Spätná diagonála'#13+ 'CROSS=Kríž'#13+ 'DIAGONAL CROSS=Diagonálny kríž'#13+ 'FILL 80%=Vyplniť 80%'#13+ 'FILL 60%=Vyplniť 60%'#13+ 'FILL 40%=Vyplniť 40%'#13+ 'FILL 20%=Vyplniť 20%'#13+ 'FILL 10%=Vyplniť 10%'#13+ 'ZIG ZAG=Cik Cak'#13+ 'VERTICAL SMALL=Vertikálne malé'#13+ 'HORIZ. SMALL=Horizontálne malé'#13+ 'DIAG. SMALL=Diagonálne malé'#13+ 'BACK DIAG. SMALL=Spätné diag. malé'#13+ 'CROSS SMALL=Kríž malý'#13+ 'DIAG. CROSS SMALL=Diag. kríž malý'#13+ 'PATTERN COLOR EDITOR=Editor farby vzoru'#13+ 'OPTIONS=Možnosti'#13+ 'DAYS=Dni'#13+ 'WEEKDAYS=Dni v týždni'#13+ 'TODAY=Dnes'#13+ 'SUNDAY=Nedeľa'#13+ 'TRAILING=Sledované'#13+ 'MONTHS=Mesiace'#13+ 'LINES=Čiary'#13+ 'SHOW WEEKDAYS=Zobraz dni v týždni'#13+ 'UPPERCASE=Veľké písmená'#13+ 'TRAILING DAYS=Sledované dni'#13+ 'SHOW TODAY=Zobraz dnes'#13+ 'SHOW MONTHS=Zobraz mesiace'#13+ 'CANDLE WIDTH=Šírka sviečky'#13+ 'STICK=Palica'#13+ 'BAR=Stĺpec'#13+ 'OPEN CLOSE=Otvoriť Zatvoriť'#13+ 'UP CLOSE=Hore Zatvoriť'#13+ 'DOWN CLOSE=Dole Zatvoriť'#13+ 'SHOW OPEN=Otvoriť'#13+ 'SHOW CLOSE=Zatvoriť'#13+ 'DRAW 3D=Kresliť 3D'#13+ 'DARK 3D=Tmavé 3D'#13+ 'EDITING=Upravujem'#13+ 'CHART=Graf'#13+ 'SERIES=Série'#13+ 'DATA=Dáta'#13+ 'TOOLS=Nástroje'#13+ 'EXPORT=Export'#13+ 'PRINT=Tlač'#13+ 'GENERAL=Všeobecné'#13+ 'TITLES=Nadpisy'#13+ 'LEGEND=Legenda'#13+ 'PANEL=Panel'#13+ 'PAGING=Strany'#13+ 'WALLS=Steny'#13+ '3D=3D'#13+ 'ADD=Pridať'#13+ 'DELETE=Vymazať'#13+ 'TITLE=Nadpis'#13+ 'CLONE=Klon'#13+ 'CHANGE=Zmeniť'#13+ 'HELP=Pomoc'#13+ 'CLOSE=Zatvoriť'#13+ 'IMAGE=Obrázok'#13+ 'TEECHART PRINT PREVIEW=Ukážka pred tlačou'#13+ 'PRINTER=Tlačiareň'#13+ 'SETUP=Nastaviť'#13+ 'ORIENTATION=Orientácia'#13+ 'PORTRAIT=Portrét'#13+ 'LANDSCAPE=Naležato'#13+ 'MARGINS (%)=Okraje (%)'#13+ 'DETAIL=Detail'#13+ 'MORE=Viac'#13+ 'NORMAL=Normálne'#13+ 'RESET MARGINS=Obnoviť okraje'#13+ 'VIEW MARGINS=Zobraziť okraje'#13+ 'PROPORTIONAL=Proporcionálne'#13+ 'TEECHART PRINT PREVIEW=Ukážka pred tlačou'#13+ 'RECTANGLE=Obdĺžnik'#13+ 'CIRCLE=Kruh'#13+ 'VERTICAL LINE=Vert. čiara'#13+ 'HORIZ. LINE=Horiz. čiara'#13+ 'TRIANGLE=Trojuholník'#13+ 'INVERT. TRIANGLE=Inv. trojuholník'#13+ 'LINE=Čiara'#13+ 'DIAMOND=Diamant'#13+ 'CUBE=Kocka'#13+ 'DIAGONAL CROSS=Diagonálny kríž'#13+ 'STAR=Hviezda'#13+ 'TRANSPARENT=Transparentne'#13+ 'HORIZ. ALIGNMENT=Horiz. zarovnanie'#13+ 'LEFT=Vľavo'#13+ 'CENTER=Stred'#13+ 'RIGHT=Vpravo'#13+ 'ROUND RECTANGLE=Zaoblený obdĺžnik'#13+ 'ALIGNMENT=Zarovnanie'#13+ 'TOP=Hore'#13+ 'BOTTOM=Dole'#13+ 'RIGHT=Vpravo'#13+ 'BOTTOM=Dole'#13+ 'UNITS=Jednotky'#13+ 'PIXELS=Body'#13+ 'AXIS=Osi'#13+ 'AXIS ORIGIN=Počiatok osi'#13+ 'ROTATION=Rotácia'#13+ 'CIRCLED=Okrúhly'#13+ '3 DIMENSIONS=3 rozmery'#13+ 'RADIUS=Polomer'#13+ 'ANGLE INCREMENT=Inkrement uhla'#13+ 'RADIUS INCREMENT=Inkrement polomera'#13+ 'CLOSE CIRCLE=Blízky kríž'#13+ 'PEN=Pero'#13+ 'CIRCLE=Kruh'#13+ 'LABELS=Štítky'#13+ 'VISIBLE=Viditeľný'#13+ 'ROTATED=Zrotovaný'#13+ 'CLOCKWISE=V smere hod. ručičiek'#13+ 'INSIDE=Vnútri'#13+ 'ROMAN=Rímsky'#13+ 'HOURS=Hodiny'#13+ 'MINUTES=Minúty'#13+ 'SECONDS=Sekundy'#13+ 'START VALUE=Štartovacia hodnota'#13+ 'END VALUE=Koncová hodnota'#13+ 'TRANSPARENCY=Transparentnosť'#13+ 'DRAW BEHIND=Kresliť vzadu'#13+ 'COLOR MODE=Farebný mód'#13+ 'STEPS=Kroky'#13+ 'RANGE=Rozsah'#13+ 'PALETTE=Paleta'#13+ 'PALE=Svetlý'#13+ 'STRONG=Silný'#13+ 'GRID SIZE=Veľkosť mriežky'#13+ 'X=X'#13+ 'Z=Z'#13+ 'DEPTH=Hĺbka'#13+ 'IRREGULAR=Nepravidelne'#13+ 'GRID=Mriežka'#13+ 'VALUE=Hodnota'#13+ 'ALLOW DRAG=Povoliť ťahanie'#13+ 'VERTICAL POSITION=Vertikálna pozícia'#13+ 'PEN=Pero'#13+ 'LEVELS POSITION=Pozícia hladín'#13+ 'LEVELS=Hladiny'#13+ 'NUMBER=Číslo'#13+ 'LEVEL=Hladina'#13+ 'AUTOMATIC=Automaticky'#13+ 'BOTH=Oboje'#13+ 'SNAP=Snímok'#13+ 'FOLLOW MOUSE=Sledujte myš'#13+ 'STACK=Kopa'#13+ 'HEIGHT 3D=Výška 3D'#13+ 'LINE MODE=Čiarový mód'#13+ 'STAIRS=Schody'#13+ 'NONE=Nič'#13+ 'OVERLAP=Prekrývanie'#13+ 'STACK=Kopa'#13+ 'STACK 100%=Kopa 100%'#13+ 'CLICKABLE=Klikateľné'#13+ 'LABELS=Štítky'#13+ 'AVAILABLE=Dostupné'#13+ 'SELECTED=Označené'#13+ 'DATASOURCE=Zdroj dát'#13+ 'GROUP BY=Zoskupiť'#13+ 'CALC=Počítať'#13+ 'OF=/'#13+ 'SUM=Súčet'#13+ 'COUNT=Počet'#13+ 'HIGH=Vysoko'#13+ 'LOW=Nízko'#13+ 'AVG=Priemer'#13+ 'HOUR=Hodina'#13+ 'DAY=Deň'#13+ 'WEEK=Týždeň'#13+ 'WEEKDAY=Deň v týždni'#13+ 'MONTH=Mesiac'#13+ 'QUARTER=Kvartál'#13+ 'YEAR=Rok'#13+ 'HOLE %=Otvor %'#13+ 'RESET POSITIONS=Obnoviť pozície'#13+ 'MOUSE BUTTON=Tlačítko myši'#13+ 'ENABLE DRAWING=Sprístupniť kreslenie'#13+ 'ENABLE SELECT=Sprístupniť výber'#13+ 'ENHANCED=Rozšírené'#13+ 'ERROR WIDTH=Šírka chyby'#13+ 'WIDTH UNITS=Jednotky šírky'#13+ 'PERCENT=Percent'#13+ 'PIXELS=Body'#13+ 'LEFT AND RIGHT=Vľavo a vpravo'#13+ 'TOP AND BOTTOM=Hore a dole'#13+ 'BORDER=Okraj'#13+ 'BORDER EDITOR=Editor okraja'#13+ 'DASH=Čiarka'#13+ 'DOT=Bod'#13+ 'DASH DOT=Čiara bod'#13+ 'DASH DOT DOT=Čiara bod bod'#13+ 'CALCULATE EVERY=Spočítať každé'#13+ 'ALL POINTS=Všetky body'#13+ 'NUMBER OF POINTS=Počet bodov'#13+ 'RANGE OF VALUES=Rozsah hodnôt'#13+ 'FIRST=Prvý'#13+ 'CENTER=Stred'#13+ 'LAST=Posledný'#13+ 'TEEPREVIEW EDITOR=Editor ukážky'#13+ 'ALLOW MOVE=Umožniť presun'#13+ 'ALLOW RESIZE=Umožniť zmeniť veľkosť'#13+ 'DRAG IMAGE=Ťahať obrázok'#13+ 'AS BITMAP=Ako bitmapa'#13+ 'SHOW IMAGE=Zobraziť obrázok'#13+ 'DEFAULT=Implicitné'#13+ 'MARGINS=Okraje'#13+ 'SIZE=Veľkosť'#13+ '3D %=3D %'#13+ 'ZOOM=Zväčšenie'#13+ 'ROTATION=Rotácia'#13+ 'ELEVATION=Výška'#13+ '100%=100%'#13+ 'HORIZ. OFFSET=Horiz. Offset'#13+ 'VERT. OFFSET=Vert. Offset'#13+ 'PERSPECTIVE=Perspektíva'#13+ 'ANGLE=Uhol'#13+ 'ORTHOGONAL=Ortogonálny'#13+ 'ZOOM TEXT=Zväčšiť text'#13+ 'SCALES=Mierky'#13+ 'TITLE=Nadpis'#13+ 'TICKS=Tiky'#13+ 'MINOR=Menšie'#13+ 'MAXIMUM=Maximum'#13+ 'MINIMUM=Minimum'#13+ '(MAX)=(max)'#13+ '(MIN)=(min)'#13+ 'DESIRED INCREMENT=Žiadúci prírastok'#13+ '(INCREMENT)=(prírastok)'#13+ 'LOG BASE=Log základ'#13+ 'LOGARITHMIC=Logaritmický'#13+ 'TITLE=Nadpis'#13+ 'MIN. SEPARATION %=Min. medzera %'#13+ 'MULTI-LINE=Viacriadkový'#13+ 'LABEL ON AXIS=Štítok na osi'#13+ 'ROUND FIRST=Zaokrúhliť prvý'#13+ 'MARK=Značka.'#13+ 'LABELS FORMAT=Formát štítkov'#13+ 'EXPONENTIAL=Exponenciálny'#13+ 'DEFAULT ALIGNMENT=Implicitné zoradenie'#13+ 'LEN=Dĺžka'#13+ 'LENGTH=Dĺžka'#13+ 'AXIS=Os'#13+ 'INNER=Vnútorný'#13+ 'GRID=Mriežka'#13+ 'AT LABELS ONLY=Iba na štítkoch'#13+ 'CENTERED=Centrované'#13+ 'COUNT=Počet'#13+ 'TICKS=Tiky'#13+ 'POSITION %=Pozícia %'#13+ 'START %=Začiatok %'#13+ 'END %=Koniec %'#13+ 'OTHER SIDE=Druhá strana'#13+ 'AXES=Osi'#13+ 'BEHIND=Vzadu'#13+ 'CLIP POINTS=Orezané body'#13+ 'PRINT PREVIEW=Ukážka pred tlačou'#13+ 'MINIMUM PIXELS=Minimum bodov'#13+ 'MOUSE BUTTON=Tlačítko myši'#13+ 'ALLOW=Povoliť'#13+ 'ANIMATED=Animovaný'#13+ 'VERTICAL=Vertikálny'#13+ 'RIGHT=Vpravo'#13+ 'MIDDLE=Stred'#13+ 'ALLOW SCROLL=Povoliť rolovanie'#13+ 'TEEOPENGL EDITOR=TeeOpenGL Editor'#13+ 'AMBIENT LIGHT=Okolné svetlo'#13+ 'SHININESS=Osvetlenie'#13+ 'FONT 3D DEPTH=3D hĺbka fontu'#13+ 'ACTIVE=Aktívne'#13+ 'FONT OUTLINES=Obrysy fontu'#13+ 'SMOOTH SHADING=Jemné tieňovanie'#13+ 'LIGHT=Svetlo'#13+ 'Y=Y'#13+ 'INTENSITY=Intenzita'#13+ 'BEVEL=Plátno'#13+ 'FRAME=Rám'#13+ 'ROUND FRAME=Okrúhly rám'#13+ 'LOWERED=Znížený'#13+ 'RAISED=Zvýšený'#13+ 'POSITION=Pozícia'#13+ 'SYMBOLS=Symboly'#13+ 'TEXT STYLE=Štýl textu'#13+ 'LEGEND STYLE=Štýl legendy'#13+ 'VERT. SPACING=Vert. odstup'#13+ 'AUTOMATIC=Automaticky'#13+ 'SERIES NAMES=Názvy sérií'#13+ 'SERIES VALUES=Hodnoty sérií'#13+ 'LAST VALUES=Posledné hodnoty'#13+ 'PLAIN=Čistý'#13+ 'LEFT VALUE=Ľavá hodnota'#13+ 'RIGHT VALUE=Pravá hodnota'#13+ 'LEFT PERCENT=Ľavé percento'#13+ 'RIGHT PERCENT=Pravé percento'#13+ 'X VALUE=Hodnota X'#13+ 'VALUE=Hodnota'#13+ 'PERCENT=Percent'#13+ 'X AND VALUE=X a hodnota'#13+ 'X AND PERCENT=X a percento'#13+ 'CHECK BOXES=Zaškrtávacie políčka'#13+ 'DIVIDING LINES=Deliace čiary'#13+ 'FONT SERIES COLOR=Farba písma sérií'#13+ 'POSITION OFFSET %=Offset pozície %'#13+ 'MARGIN=Okraj'#13+ 'RESIZE CHART=Upraviť veľkosť grafu'#13+ 'CUSTOM=Špeciálny'#13+ 'WIDTH UNITS=Jednotky šírky'#13+ 'CONTINUOUS=Súvislý'#13+ 'POINTS PER PAGE=Bodov na stranu'#13+ 'SCALE LAST PAGE=Prispôsobiť poslednú stranu'#13+ 'CURRENT PAGE LEGEND=Legenda aktuálnej strany'#13+ 'PANEL EDITOR=Editor panelu'#13+ 'BACKGROUND=Pozadie'#13+ 'BORDERS=Okraje'#13+ 'BACK IMAGE=Obrázok v pozadí'#13+ 'STRETCH=Roztiahnuť'#13+ 'TILE=Vydláždiť'#13+ 'CENTER=Na stred'#13+ 'BEVEL INNER=Vnútorná hrana'#13+ 'LOWERED=Znížený'#13+ 'RAISED=Zvýšený'#13+ 'BEVEL OUTER=Vonkajšia hrana'#13+ 'MARKS=Značky'#13+ 'DATA SOURCE=Zdroj dát'#13+ 'SORT=Utriediť'#13+ 'CURSOR=Kurzor'#13+ 'SHOW IN LEGEND=Zobraziť v legende'#13+ 'FORMATS=Formáty'#13+ 'VALUES=Hodnoty'#13+ 'PERCENTS=Percentá'#13+ 'HORIZONTAL AXIS=Horizontálna os'#13+ 'TOP AND BOTTOM=Vrch a spodok'#13+ 'DATETIME=Dátum/Čas'#13+ 'VERTICAL AXIS=Vertikálna os'#13+ 'LEFT=Vľavo'#13+ 'RIGHT=Vpravo'#13+ 'LEFT AND RIGHT=Vľavo a vpravo'#13+ 'ASCENDING=Vzostupne'#13+ 'DESCENDING=Zostupne'#13+ 'DRAW EVERY=Kresli všetko'#13+ 'CLIPPED=Zrezaný'#13+ 'ARROWS=Šípky'#13+ 'MULTI LINE=Viac čiar'#13+ 'ALL SERIES VISIBLE=Všetky série viditeľné'#13+ 'LABEL=Štítok'#13+ 'LABEL AND PERCENT=Štítok a percento'#13+ 'LABEL AND VALUE=Štítok a hodnota'#13+ 'PERCENT TOTAL=Percent spolu'#13+ 'LABEL AND PERCENT TOTAL=Štítok a percent spolu'#13+ 'X VALUE=Hodnota X'#13+ 'X AND Y VALUES=Hodnoty X a Y'#13+ 'MANUAL=Manuálne'#13+ 'RANDOM=Náhodne'#13+ 'FUNCTION=Funkcia'#13+ 'NEW=Nové'#13+ 'EDIT=Upraviť'#13+ 'DELETE=Vymazať'#13+ 'PERSISTENT=Trvalý'#13+ 'ADJUST FRAME=Upraviť rám'#13+ 'SUBTITLE=Podnadpis'#13+ 'SUBFOOT=Podspodok'#13+ 'FOOT=Spodok'#13+ 'DELETE=Vymazať'#13+ 'VISIBLE WALLS=Viditeľné steny'#13+ 'BACK=Späť'#13+ 'DIF. LIMIT=Dif. limit'#13+ 'LINES=Čiary'#13+ 'ABOVE=Nad'#13+ 'WITHIN=Vnútri'#13+ 'BELOW=Pod'#13+ 'CONNECTING LINES=Spojené čiary'#13+ 'SERIES=Série'#13+ 'PALE=Bledý'#13+ 'STRONG=Silný'#13+ 'HIGH=Vysoký'#13+ 'LOW=Nízky'#13+ 'BROWSE=Vyhľadať'#13+ 'TILED=Vydláždený'#13+ 'INFLATE MARGINS=Zhustené okraje'#13+ 'SQUARE=Štvorec'#13+ 'DOWN TRIANGLE=Dolný trojuholník'#13+ 'SMALL DOT=Malý bod'#13+ 'DEFAULT=Implicitne'#13+ 'GLOBAL=Globálny'#13+ 'SHAPES=Telesá'#13+ 'BRUSH=Štetec'#13+ 'BRUSH=Štetec'#13+ 'BORDER=Okraj'#13+ 'COLOR=Farba'#13+ 'DELAY=Opozdenie'#13+ 'MSEC.=msec.'#13+ 'MOUSE ACTION=Akcia myšou'#13+ 'MOVE=Presun'#13+ 'CLICK=Klik'#13+ 'BRUSH=Štetec'#13+ 'DRAW LINE=Kresliť čiaru'#13+ 'BORDER EDITOR=Editor okraja'#13+ 'DASH=Pomlčka'#13+ 'DOT=Bod'#13+ 'DASH DOT=Pomlčka bod'#13+ 'DASH DOT DOT=Pomlčka bod bod'#13+ 'EXPLODE BIGGEST=Explodovať najväčší'#13+ 'TOTAL ANGLE=Celkový uhol'#13+ 'GROUP SLICES=Skupinové rezy'#13+ 'BELOW %=Pod %'#13+ 'BELOW VALUE=Spodná hodnota'#13+ 'OTHER=Ostatné'#13+ 'PATTERNS=Vzory'#13+ 'CLOSE CIRCLE=Zatvorený kruh'#13+ 'VISIBLE=Viditeľné'#13+ 'CLOCKWISE=V smere hodin. ručičiek'#13+ 'SIZE %=Veľkosť %'#13+ 'PATTERN=Vzor'#13+ 'DEFAULT=Implicitne'#13+ 'SERIES DATASOURCE TEXT EDITOR=Textový editor zdroja dát sérií'#13+ 'FIELDS=Polia'#13+ 'NUMBER OF HEADER LINES=Počet čiar záhlavia'#13+ 'SEPARATOR=Oddeľovač'#13+ 'COMMA=Čiarka'#13+ 'SPACE=Medzera'#13+ 'TAB=Tabulátor'#13+ 'FILE=Súbor'#13+ 'WEB URL=Webové URL'#13+ 'LOAD=Načítať'#13+ 'C LABELS=C štítky'#13+ 'R LABELS=R štítky'#13+ 'C PEN=C pero'#13+ 'R PEN=R pero'#13+ 'STACK GROUP=Skladová skupina'#13+ 'USE ORIGIN=Použiť počiatok'#13+ 'MULTIPLE BAR=Zložený stĺpec'#13+ 'SIDE=Strana'#13+ 'STACKED 100%=Uskladnené 100%'#13+ 'SIDE ALL=Straniť všetko'#13+ 'BRUSH=Štetec'#13+ 'DRAWING MODE=Kresliaci mód'#13+ 'SOLID=Plný'#13+ 'WIREFRAME=Drôtený model'#13+ 'DOTFRAME=Bodový model'#13+ 'SMOOTH PALETTE=Jemná paleta'#13+ 'SIDE BRUSH=Stranový štetec'#13+ 'ABOUT TEECHART PRO V7.0=O TeeChart Pro v7.0'#13+ 'ALL RIGHTS RESERVED.=Všetky práva vyhradené.'#13+ 'VISIT OUR WEB SITE !=Navštívte našu web stránku !'#13+ 'TEECHART WIZARD=Sprievodca TeeChart'#13+ 'SELECT A CHART STYLE=Vyberte štýl grafu'#13+ 'DATABASE CHART=Databázový graf'#13+ 'NON DATABASE CHART=Nedatabázový graf'#13+ 'SELECT A DATABASE TABLE=Vyberte databázovú tabuľku'#13+ 'ALIAS=Alias'#13+ 'TABLE=Tabuľka'#13+ 'SOURCE=Zdroj'#13+ 'BORLAND DATABASE ENGINE=Borland Database Engine'#13+ 'MICROSOFT ADO=Microsoft ADO'#13+ 'SELECT THE DESIRED FIELDS TO CHART=Vyberte požadované polia pre graf'#13+ 'SELECT A TEXT LABELS FIELD=Vyberte pole pre textové štítky'#13+ 'CHOOSE THE DESIRED CHART TYPE=Vyberte požadovaný typ grafu'#13+ '2D=2D'#13+ 'CHART PREVIEW=Ukážka grafu'#13+ 'SHOW LEGEND=Zobraziť legendu'#13+ 'SHOW MARKS=Zobraziť značky'#13+ '< BACK=< Späť'#13+ 'SELECT A CHART STYLE=Vyberte štýl grafu'#13+ 'NON DATABASE CHART=Nedatabázový graf'#13+ 'SELECT A DATABASE TABLE=Vyberte databázovú tabuľku'#13+ 'BORLAND DATABASE ENGINE=Borland Database Engine'#13+ 'SELECT THE DESIRED FIELDS TO CHART=Vyberte požadované polia pre graf'#13+ 'SELECT A TEXT LABELS FIELD=Vyberte pole pre textové štítky'#13+ 'CHOOSE THE DESIRED CHART TYPE=Vyberte požadovaný typ grafu'#13+ 'EXPORT CHART=Export grafu'#13+ 'PICTURE=Obrázok'#13+ 'NATIVE=Vlastný'#13+ 'KEEP ASPECT RATIO=Zachovať pomer strán'#13+ 'INCLUDE SERIES DATA=Zahrnúť dáta sérií'#13+ 'FILE SIZE=Veľkosť súboru'#13+ 'DELIMITER=Obmedzovač'#13+ 'XML=XML'#13+ 'HTML TABLE=HTML tabuľka'#13+ 'EXCEL=Excel'#13+ 'TAB=Tabulátor'#13+ 'COLON=Dvojbodka'#13+ 'INCLUDE=Vložiť'#13+ 'POINT LABELS=Štítky bodu'#13+ 'POINT INDEX=Index bodu'#13+ 'HEADER=Hlavička'#13+ 'COPY=Kopírovať'#13+ 'SAVE=Uložiť'#13+ 'SEND=Poslať'#13+ 'KEEP ASPECT RATIO=Zachovať pomer strán'#13+ 'INCLUDE SERIES DATA=Zahrnúť dáta sérií'#13+ 'FUNCTIONS=Funkcie'#13+ 'ADD=Pridať'#13+ 'ADX=ADX'#13+ 'AVERAGE=Priemer'#13+ 'BOLLINGER=Deliteľ'#13+ 'COPY=Kopírovať'#13+ 'DIVIDE=Deliť'#13+ 'EXP. AVERAGE=Exp. priemer'#13+ 'EXP.MOV.AVRG.=Exp. pohyb. priemer'#13+ 'HIGH=Vysoko'#13+ 'LOW=Nízko'#13+ 'MACD=MACD'#13+ 'MOMENTUM=Momentum'#13+ 'MOMENTUM DIV=Momentum Div'#13+ 'MOVING AVRG.=Pohyb. priemer'#13+ 'MULTIPLY=Násobiť'#13+ 'R.S.I.=R.S.I.'#13+ 'ROOT MEAN SQ.=Root Mean SQ.'#13+ 'STD.DEVIATION=Štandardná odchýlka'#13+ 'STOCHASTIC=Náhodný'#13+ 'SUBTRACT=Odčítať'#13+ 'APPLY=Použiť'#13+ 'SOURCE SERIES=Zdrojové série'#13+ 'TEECHART GALLERY=TeeChart galéria'#13+ 'FUNCTIONS=Funkcie'#13+ 'DITHER=Dither'#13+ 'REDUCTION=Redukcia'#13+ 'COMPRESSION=Kompresia'#13+ 'LZW=LZW'#13+ 'RLE=RLE'#13+ 'NEAREST=Najbližší'#13+ 'FLOYD STEINBERG=Floyd Steinberg'#13+ 'STUCKI=Stucki'#13+ 'SIERRA=Sierra'#13+ 'JAJUNI=JaJuNI'#13+ 'STEVE ARCHE=Steve Arche'#13+ 'BURKES=Burkes'#13+ 'WINDOWS 20=Windows 20'#13+ 'WINDOWS 256=Windows 256'#13+ 'WINDOWS GRAY=Windows šedé'#13+ 'MONOCHROME=Monochromatické'#13+ 'GRAY SCALE=Odtiene šedej'#13+ 'NETSCAPE=Netscape'#13+ 'QUANTIZE=Quantize'#13+ 'QUANTIZE 256=Quantize 256'#13+ '% QUALITY=% Kvalita'#13+ 'GRAY SCALE=Odtiene šedej'#13+ 'PERFORMANCE=Výkon'#13+ 'QUALITY=Kvalita'#13+ 'SPEED=Rýchlosť'#13+ 'COMPRESSION LEVEL=Stupeň kompresie'#13+ 'CHART TOOLS GALLERY=Galéria nástrojov grafu'#13+ 'ANNOTATION=Poznámka'#13+ 'AXIS ARROWS=Šípky osi'#13+ 'COLOR BAND=Farebná skupina'#13+ 'COLOR LINE=Farebná čiara'#13+ 'CURSOR=Kurzor'#13+ 'DRAG MARKS=Ťahanie značky'#13+ 'DRAW LINE=Kreslenie čiary'#13+ 'IMAGE=Obrázok'#13+ 'MARK TIPS=Značkové tipy'#13+ 'NEAREST POINT=Najbližší bod'#13+ 'ROTATE=Rotácia'#13+ 'CHART TOOLS GALLERY=Galéria nástrojov grafu'#13+ 'BRUSH=Štetec'#13+ 'DRAWING MODE=Kresliaci mód'#13+ 'WIREFRAME=Drôtený model'#13+ 'SMOOTH PALETTE=Jemná paleta'#13+ 'SIDE BRUSH=Stranový štetec'#13+ 'YES=Áno'#13+ 'PERIOD=Perióda'#13+ 'DOWN=Dole'#13+ 'ANIMATIONS=Animácie'#13+ 'ADD TEXT=Pridať text'#13+ 'FONT SIZE=Veľkosť písma'#13+ 'MOVE TEXT=Presun textu'#13+ 'MOVEMENT=Pohyb'#13+ 'NODE COLOR=Farba uzla'#13+ 'NODE ZOOM=Zväčšenie uzla'#13+ 'TEXT ANGLE=Uhol textu'#13+ 'TEXT COLOR=Farba textu'#13+ 'TEXT FLASH=Blikanie textu'#13+ 'TEXT TRANSP=Transp. text'#13+ 'TREE COLOR=Farba stromu'#13+ 'PREVIEW=Ukážka'#13+ 'SHADOW EDITOR=Editor tieňa'#13+ 'CALLOUT=Popis'#13+ 'TEXT ALIGNMENT=Zarovnanie textu'#13+ 'DISTANCE=Vzdialenosť'#13+ 'ARROW HEAD=Hlavička šípky'#13+ 'POINTER=Ukazateľ'#13+ 'AVAILABLE LANGUAGES=Dostupné jazyky'#13+ 'CHOOSE A LANGUAGE=Vyberte si jazyk'#13+ 'CALCULATE USING=Počítať použitím'#13+ 'EVERY NUMBER OF POINTS=Každý počet bodov'#13+ 'EVERY RANGE=Každý rozsah'#13+ 'INCLUDE NULL VALUES=Zahrnúť nulové hodnoty'#13+ 'DATE=Dátum'#13+ 'ENTER DATE=Vložte dátum'#13+ 'ENTER TIME=Vložte čas'#13+ 'BEVEL SIZE=Veľkosť skosenia'#13+ 'DEVIATION=Odchýlka'#13+ 'UPPER=Vyšší'#13+ 'LOWER=Nižší'#13+ 'NOTHING=Nič'#13+ 'LEFT TRIANGLE=Ľavý trojuholník'#13+ 'RIGHT TRIANGLE=Pravý trojuholník'#13+ 'SHOW PREVIOUS BUTTON=Zobraziť predch. tlačítko'#13+ 'SHOW NEXT BUTTON=Zobraziť nasled. tlačítko'#13+ 'CONSTANT=Konštanta'#13+ 'SHOW LABELS=Zobraziť štítky'#13+ 'SHOW COLORS=Zobraziť farby'#13+ 'XYZ SERIES=XYZ série'#13+ 'SHOW X VALUES=Zobraziť X hodnoty'#13+ 'DELETE ROW=Vymazať riadok'#13+ 'VOLUME SERIES=Objemové série'#13+ 'ACCUMULATE=Nazbierať'#13+ 'SINGLE=Jeden'#13+ 'REMOVE CUSTOM COLORS=Odstrániť zvyčajné farby'#13+ 'STEP=Krok'#13+ 'USE PALETTE MINIMUM=Použiť minimum palety'#13+ 'AXIS MAXIMUM=Maximum osi'#13+ 'AXIS CENTER=Centrovanie osi'#13+ 'AXIS MINIMUM=Minimum osi'#13+ 'DRAG REPAINT=Prekresliť ťah'#13+ 'NO LIMIT DRAG=Žiadny limit ťahu'#13+ 'DAILY (NONE)=Denne (nič)'#13+ 'WEEKLY=Týždenne'#13+ 'MONTHLY=Mesačne'#13+ 'BI-MONTHLY=Dvojmesačne'#13+ 'QUARTERLY=Štvrťročne'#13+ 'YEARLY=Ročne'#13+ 'DATETIME PERIOD=Perióda dátumu/času'#13+ 'TREE CONNECTION EDITOR=Editor spojenia stromu'#13+ 'ARROW FROM=Šípka od'#13+ 'ARROW TO=Šípka do'#13+ 'POINTS=Body'#13+ 'SIDES=Strany'#13+ 'INVERTED SIDES=Inverzné strany'#13+ 'CURVE=Krivka'#13+ 'POINT=Bod'#13+ 'ADD NEW POINT=Pridať nový bod'#13+ 'DELETE POINT=Vymazať bod'#13+ 'FIXED=Nemenný'#13+ 'RELATIVE FROM=Relatívne od'#13+ 'PREVIOUS POINT=Predchádzajúci bod'#13+ 'NEXT POINT=Ďalší bod'#13+ 'RELATIVE TO=Relatívne do'#13+ 'SMOOTH=Hladký'#13+ 'INTERPOLATE=Interpolovať'#13+ 'START X=Štart X'#13+ 'NUM. POINTS=Počet bodov'#13+ 'COLOR EACH LINE=Vyfarbiť každú čiaru'#13+ 'CASE SENSITIVE=Rozlišovať veľkosť písma'#13+ 'SORT BY=Triediť podľa'#13+ '(NONE)=(nič)'#13+ 'CALCULATION=Výpočet'#13+ 'GROUP=Skupina'#13+ 'DRAG STYLE=Štýl ťahania'#13+ 'WEIGHT=Váha'#13+ 'EDIT LEGEND=Upraviť legendu'#13+ 'ROUND=Oblý'#13+ 'FLAT=Plochý'#13+ 'DRAW ALL=Kresliť všetko'#13+ 'IGNORE NULLS=Ignorovať nuly'#13+ 'DATABASE TREE WIZARD=Sprievodca databáz. stromom'#13+ 'SAMPLE DATA=Ukážkové dáta'#13+ 'TREE PREVIEW=Ukážka stromu'#13+ 'CODE FIELD=Kódové pole'#13+ 'PARENT FIELD=Rodičovské pole'#13+ 'TEXT FIELDS=Textové polia'#13+ 'DETAIL DATASET=Detailný dataset'#13+ 'DETAIL FIELDS=Detailné polia'#13+ 'MULTI-LINE TEXT=Viacriadkový text'#13+ 'NEXT >=Ďalšie >'#13+ '< PREVIOUS=< Predch.'#13+ 'CHOOSE A SITUATION=Vyberte situáciu'#13+ 'LIGHT 0=Svetlo 0'#13+ 'LIGHT 1=Svetlo 1'#13+ 'LIGHT 2=Svetlo 2'#13+ 'DRAW STYLE=Štýl kreslenia'#13+ 'DEFAULT BORDER=Štandardný okraj'#13+ 'SQUARED=Štvorcový'#13+ 'SHOW PAGE NUMBER=Zobraziť číslo strany'#13+ 'SEPARATION=Oddelenie'#13+ 'ROUND BORDER=Okrúhly okraj'#13+ 'NUMBER OF SAMPLE VALUES=Počet ukážkových hodnôt'#13+ 'SPACING=Vzdialenosť'#13+ 'RESIZE PIXELS TOLERANCE=Tolerancia zmeny veľkosti bodov'#13+ 'FULL REPAINT=Plné prekreslenie'#13+ 'END POINT=Koncový bod'#13+ 'BAND 1=Skupina 1'#13+ 'BAND 2=Skupina 2'#13+ 'GRID 3D SERIES=3D mriežka sérií'#13+ 'TRANSPOSE NOW=Transponovať teraz'#13+ 'PERIOD 1=Perióda 1'#13+ 'PERIOD 2=Perióda 2'#13+ 'PERIOD 3=Perióda 3'#13+ 'HISTOGRAM=Histogram'#13+ 'EXP. LINE=Exp. čiara'#13+ 'DRAG TO RESIZE=Ťahajte pre zmenu veľkosti'#13+ 'MOVE UP=Presun nahor'#13+ 'MOVE DOWN=Presun nadol'#13+ 'SERIES MARKS=Značky sérií'#13+ 'WALL=Stena'#13+ 'TEXT LABELS=Textové štítky'#13+ 'X VALUES=X hodnoty'#13+ 'BOLD=Tučné'#13+ 'ITALIC=Šikmé'#13+ 'UNDERLINE=Podčiarknuté'#13+ 'STRIKE OUT=Prečiarknuté'#13+ 'LEFT JUSTIFY=Zarovnať vľavo'#13+ 'RIGHT JUSTIFY=Zarovnať vpravo'#13+ 'FONT COLOR=Farba písma'#13+ 'FONT NAME=Meno fontu'#13+ 'INTER-CHAR SIZE=Veľkosť medzi znakmi'#13+ 'ADD ANNOTATION=Pridať poznámku'#13+ 'ENABLE ZOOM=Povoliť zväčšenie'#13+ 'ENABLE SCROLL=Povoliť rolovanie'#13+ 'DRAW LINES=Kresliť čiary'#13+ 'SHOW HINTS=Zobraziť rady'#13+ 'COLOR EACH POINT=Vyfarbiť každý bod'#13+ 'SHOW AT LEGEND=Zobraziť v legende'#13+ 'SHOW SERIES MARKS=Zobraziť značky sérií'#13+ 'BORDER COLOR=Farba okraja'#13+ 'BORDER STYLE=Štýl okraja'#13+ 'BORDER WIDTH=Šírka okraja'#13+ 'NEW USING WIZARD=Nové použitím sprievodcu'#13+ 'OPEN=Otvoriť'#13+ 'SAVE AS=Uložiť ako'#13+ 'REOPEN=Znovu otvoriť'#13+ 'SEND BY E-MAIL=Poslať e-mailom'#13+ 'EXIT=Odchod'#13+ 'PROPERTIES=Vlastnosti'#13+ 'CHART TOOLS=Nástroje grafu'#13+ 'VIEW=Zobrazenie'#13+ 'OPEN GL=OpenGL'#13+ 'SERIES LIST=Zoznam sérií'#13+ 'INSPECTOR=Inšpektor'#13+ 'GALLERY=Galéria'#13+ 'STATUS BAR=Stavový riadok'#13+ 'AS TAB=Ako tab.'#13+ 'AS WINDOW=Ako okno'#13+ 'HIDE=Skryť'#13+ 'TOOLBARS=Nástrojové panely'#13+ 'PAGE=Strana'#13+ 'LANGUAGE=Jazyk'#13+ 'WEB CHARTS GALLERY=Galéria webových grafov'#13+ 'UPDATE VERSION=Aktualizovaná verzia'#13+ 'TEXT MODE=Textový mód'#13+ 'HELP INDEX=Index pomoci'#13+ 'TEECHART WEB=Web TeeChart'#13+ 'ONLINE SUPPORT=Online podpora'#13+ 'ABOUT=O programe'#13+ 'CONFIGURE=Konfigurácia'#13+ 'DUPLICATE=Duplikovať'#13+ 'SELECT ALL=Vybrať všetko'#13+ 'HIDE SERIES LIST=Skryť zoznam sérií'#13+ 'HIDE INSPECTOR=Skryť inšpektora'#13+ 'ALIGN TO TOP=Zarovnať na vrch'#13+ 'ALIGN TO BOTTOM=Zarovnať na spodok'#13+ 'VIEW 3D=Zobraziť 3D'#13+ 'RIGHT SIDE=Pravá strana'#13+ 'CHECK-BOXES=Zaškrtávacie políčka'#13+ 'SERIES COLOR=Farba sérií'#13+ 'CONTINOUS=Nepretržitý'#13+ 'AUTOSIZE=Auto-veľkosť'#13+ 'CUSTOM POSITION=Špeciálna pozícia'#13+ 'GRAY SCALE VISUAL=Vizuálne stupne šedi'#13+ 'INVERTED GRAY SCALE=Inverzné stupne šedi'#13+ 'AUTO SIZE=Auto-veľkosť'#13+ 'LABEL PERCENT=Štítok percento'#13+ 'LABEL VALUE=Štítok hodnota'#13+ 'LABEL PERCENT TOTAL=Štítok percento spolu'#13+ 'AXIS LINE=Čiara osi'#13+ 'MINOR GRID=Menšia mriežka'#13+ 'STAIRS INVERTED=Inverzné schody'#13+ 'SIDE MARGINS=Okraje na stranách'#13+ 'INVERTED PYRAMID=Inverzná pyramída'#13+ 'ALIGN GRID=Zarovnaná mriežka'#13+ 'WEIGHTED=Vážený'#13+ 'WEIGHTED BY INDEX=Vážený indexom'#13+ 'CREATE NEW DATASET=Vytvoriť nový súbor dát'#13+ 'BORLAND BDE=Borland BDE'#13+ 'DATASET STYLE=Štýl súboru dát'#13+ 'BDE ALIAS=BDE alias'#13+ 'SQL QUERY=SQL príkaz'#13+ 'SELECT * FROM=select * from'#13+ 'CONNECTION=Spojenie'#13+ 'BUILD=Stavba'#13+ 'TREE NODE EDITOR=Editor stromového uzla'#13+ 'CROSS-BOX=Krížový box'#13+ 'CHILDREN CONNECTIONS=Detské spojenia'#13+ 'HORIZONTAL LINE=Horizontálna čiara'#13+ 'INVERTED LINE=Inverzná čiara'#13+ 'TRIANGLE TOP=Trojuholník hore'#13+ 'TRIANGLE BOTTOM=Trojuholník dole'#13+ 'TRIANGLE LEFT=Trojuholník vľavo'#13+ 'TRIANGLE RIGHT=Trojuholník vpravo'#13+ 'ALWAYS=Vždy'#13+ 'NEVER=Nikdy'#13+ 'CLIP TEXT=Vystrihnúť text'#13+ 'ALIGN=Zarovnať'#13+ 'DEFAULT IMAGE=Štandardný obrázok'#13+ 'BUTTON5=Tlačítko5'#13+ 'CLOSED FOLDER=Zatvorený priečinok'#13+ 'OPEN FOLDER=Otvorený priečinok'#13+ 'DESKTOP=Pracovná plocha'#13+ 'MYPC=Moje PC'#13+ 'NETWORK=Sieť'#13+ 'FLOPPY 3=Disketa 3'#13+ 'RECYCLE BIN=Odpadkový kôš'#13+ 'HARD DISK=Pevný disk'#13+ 'NET SHARE=Sieťové zdieľanie'#13+ 'COMPUTER=Počítač'#13+ 'WORLD=Svet'#13+ 'FOLDER OPEN AND CLOSE=Priečinok otvoriť a zatvoriť'#13+ 'CHECKED CLOSED FOLDER=Vybraný zatvorený priečinok'#13+ 'UNCHECKED CLOSED FOLDER=Nevybraný zatvorený priečinok'#13+ 'CHECKED=Vybraný'#13+ 'UNCHECKED=Nevybraný'#13+ 'RADIO CHECKED=Radio vybraný'#13+ 'RADIO UNCHECKED=Radio nevybraný'#13+ 'RADIO CHECKED FOLDER=Radio vybraný priečinok'#13+ 'RADIO UNCHECKED FOLDER=Radio nevybraný priečinok'#13+ 'HORIZONTAL SIZE=Horizontálna veľkosť'#13+ 'VERTICAL SIZE=Vertikálna veľkosť'#13+ 'MOVE HORIZ=Presun horiz.'#13+ 'MOVE VERT=Presun vert.'#13+ 'DARK BORDER=Tmavý okraj'#13+ 'PIE SERIES=Koláčové série'#13+ 'FOCUS=Ohnisko'#13+ 'EXPLODE=Explodovať'#13+ 'BOX SIZE=Veľkosť políčka'#13+ 'REVERSAL AMOUNT=Obrátený rozsah'#13+ 'PERCENTAGE=Percento'#13+ 'COMPLETE R.M.S.=Kompletné R.M.S.'#13+ 'BUTTON=Tlačítko'#13+ 'ALL=Všetko'#13+ 'START AT MIN. VALUE=Štart pri minimálnej hodnote'#13+ 'EXECUTE !=Spustiť !'#13+ 'IMAG. SYMBOL=Obr. symbol'#13+ 'FACTOR=Faktor'#13+ 'SELF STACK=Samokopa'#13+ 'SIDE LINES=Čiary na strane'#13+ 'CHART FROM TEMPLATE (*.TEE FILE)=Graf zo šablóny (súbor *.tee)'#13+ 'OPEN TEECHART TEMPLATE FILE FROM=Otvoriť TeeChart šablónu zo súboru'#13+ 'EXPORT DIALOG=Okno exportu'#13+ 'BINARY=Binárny'#13+ 'POINT COLORS=Farby bodu'#13+ 'OUTLINE GRADIENT=Obrysový prechod'#13+ 'CLOSE LOCATION VALUE=Najbližšie položená hodnota'#13+ 'COMMODITY CHANNEL INDEX=Index tovarového kanála'#13 ; end; end; Procedure TeeSetSlovak; begin TeeCreateSlovak; TeeLanguage:=TeeSlovakLanguage; TeeSlovakConstants; TeeLanguageHotKeyAtEnd:=False; TeeLanguageCanUpper:=True; end; initialization finalization FreeAndNil(TeeSlovakLanguage); end.
unit configuration; {$mode objfpc}{$M+} interface uses Classes, SysUtils, Forms, StdCtrls, utils {$IFDEF unix} ,baseunix, unix {$endif} ; const ModeNormal: integer = 1; ModeFiltersDisabled: integer = 2; ModeTrackingDisabled: integer = 3; type TAComponents = array of TComponent; TOTConfig = Class private UserPreferences: TStringList; public FilePath: string; IconPath: string; LogPath: string; ReportsPath: string; StoragePath: string; DBPath: AnsiString; PHPPath: string; LangDir: string; ReportsHtmlDir: string; Mode: Integer; constructor Create(); function FileConfigExists: boolean; procedure SetPreference(Component: TComponent); function Get(PrefName: string):string; end; implementation constructor TOTConfig.Create(); var wpath: string; {$IFDEF unix} sharepath,uhpath: string; {$endif} begin UserPreferences := TStringList.Create; {$IFDEF Windows} wpath := ExtractFilePath(Application.EXEName); FilePath := wpath + 'preferences.xml'; LogPath := wpath + 'opentempus.log'; DBPath := wpath + 'opentempus.s3db'; IconPath := wpath + 'icons'; ReportsPath := wpath + 'reports'; StoragePath := wpath + 'storage'; ReportsHtmlDir:= wpath + 'reportshtml'; LangDir := wpath + 'languages'; PHPPath := wpath + 'bin'+DirectorySeparator+'php'; {$ENDIF} {$IFDEF unix} sharepath := '/usr/share/opentempus'; uhpath := GetEnvironmentVariable('HOME')+ DirectorySeparator + 'opentempus'; IF NOT DirectoryExists(uhpath) THEN CreateDir(uhpath); FilePath := uhpath + DirectorySeparator + 'preferences.xml'; LogPath := uhpath + DirectorySeparator + 'opentempus.log'; DBPath := uhpath + DirectorySeparator + 'opentempus.s3db'; ReportsHtmlDir:= uhpath + DirectorySeparator + 'reportshtml'; IF NOT DirectoryExists(ReportsHtmlDir) THEN CreateDir(ReportsHtmlDir); IF NOT FileExists(DBPath) THEN FileCopy(sharepath + DirectorySeparator + 'opentempus.s3db',DBPath); IconPath := sharepath + DirectorySeparator + 'icons'; ReportsPath := sharepath + DirectorySeparator + 'reports'; StoragePath := sharepath + DirectorySeparator + 'storage'; LangDir := sharepath + DirectorySeparator + 'languages'; PHPPath := 'php'; {$ENDIF} end; function TOTConfig.FileConfigExists: boolean; begin result := FileExists(FilePath); end; procedure TOTConfig.SetPreference(Component: TComponent); var NewName: string; begin IF Component is TCheckBox THEN BEGIN with Component as TCheckBox do begin NewName := StringReplace(Name, 'Check', '',[rfReplaceAll, rfIgnoreCase]); IF UserPreferences.IndexOfName(NewName) <> -1 THEN UserPreferences.Values[NewName] := booltostr(Checked,TRUE) ELSE UserPreferences.Add(NewName+'='+booltostr(Checked,TRUE)); end; END ELSE IF Component is TComboBox THEN BEGIN with Component as TComboBox do begin NewName := StringReplace(Name, 'Combo', '',[rfReplaceAll, rfIgnoreCase]); IF UserPreferences.IndexOfName(NewName) <> -1 THEN UserPreferences.Values[NewName] := Text ELSE UserPreferences.Add(NewName+'='+Text); end; END ELSE IF Component is TEdit THEN BEGIN with Component as TEdit do begin NewName := StringReplace(Name, 'Edit', '',[rfReplaceAll, rfIgnoreCase]); IF UserPreferences.IndexOfName(NewName) <> -1 THEN UserPreferences.Values[NewName] := Text ELSE UserPreferences.Add(NewName+'='+Text); end; END end; function TOTConfig.Get(PrefName: string):string; begin IF UserPreferences.IndexOfName(PrefName) <> -1 THEN begin result := UserPreferences.Values[PrefName]; end else begin result := ''; end end; end.
unit Amazon.Request; interface Uses Amazon.Interfaces; type TAmazonRequest = class(TInterfacedObject, IAmazonRequest) private fsAuthorization_header: UTF8String; fsamz_date: UTF8String; fsdate_stamp: UTF8String; fssecret_key: UTF8String; fsaccess_key: UTF8String; fsservice: UTF8String; fsendpoint: UTF8String; fstargetPrefix: UTF8String; fsregion: UTF8String; fsrequest_parameters: UTF8String; fshost: UTF8String; fsoperationName: UTF8String; protected function gettarget: UTF8String; function getsecret_key: UTF8String; procedure setsecret_key(value: UTF8String); function getaccess_key: UTF8String; procedure setaccess_key(value: UTF8String); function gettargetPrefix: UTF8String; procedure settargetPrefix(value: UTF8String); function getservice: UTF8String; procedure setservice(value: UTF8String); function getendpoint: UTF8String; procedure setendpoint(value: UTF8String); function getregion: UTF8String; procedure setregion(value: UTF8String); function getrequest_parameters: UTF8String; procedure setrequest_parameters(value: UTF8String); function gethost: UTF8String; procedure sethost(value: UTF8String); function getamz_date: UTF8String; procedure setamz_date(value: UTF8String); function getdate_stamp: UTF8String; procedure setdate_stamp(value: UTF8String); function getoperationName: UTF8String; procedure setoperationName(value: UTF8String); function getauthorization_header: UTF8String; procedure setauthorization_header(value: UTF8String); public property secret_key: UTF8String read getsecret_key write setsecret_key; property access_key: UTF8String read getaccess_key write setaccess_key; property targetPrefix: UTF8String read gettargetPrefix write settargetPrefix; property operationName: UTF8String read getoperationName write setoperationName; property service: UTF8String read getservice write setservice; property endpoint: UTF8String read getendpoint write setendpoint; property host: UTF8String read gethost write sethost; property region: UTF8String read getregion write setregion; property request_parameters: UTF8String read getrequest_parameters write setrequest_parameters; property amz_date: UTF8String read getamz_date write setamz_date; property date_stamp: UTF8String read getdate_stamp write setdate_stamp; property authorization_header: UTF8String read getauthorization_header write setauthorization_header; property target: UTF8String read gettarget; end; implementation function TAmazonRequest.getsecret_key: UTF8String; begin Result := fssecret_key; end; procedure TAmazonRequest.setsecret_key(value: UTF8String); begin fssecret_key := value; end; function TAmazonRequest.getrequest_parameters: UTF8String; begin Result := fsrequest_parameters; end; procedure TAmazonRequest.setrequest_parameters(value: UTF8String); begin fsrequest_parameters := value; end; function TAmazonRequest.getaccess_key: UTF8String; begin Result := fsaccess_key; end; procedure TAmazonRequest.setaccess_key(value: UTF8String); begin fsaccess_key := value; end; function TAmazonRequest.gettargetPrefix: UTF8String; begin Result := fstargetPrefix; end; procedure TAmazonRequest.settargetPrefix(value: UTF8String); begin fstargetPrefix := value; end; function TAmazonRequest.getservice: UTF8String; begin Result := fsservice; end; procedure TAmazonRequest.setservice(value: UTF8String); begin fsservice := value; end; function TAmazonRequest.getregion: UTF8String; begin Result := fsregion; end; procedure TAmazonRequest.setregion(value: UTF8String); begin fsregion := value; end; function TAmazonRequest.gethost: UTF8String; begin Result := fshost; end; procedure TAmazonRequest.sethost(value: UTF8String); begin fshost := value; end; function TAmazonRequest.getendpoint: UTF8String; begin Result := fsendpoint; end; procedure TAmazonRequest.setendpoint(value: UTF8String); begin fsendpoint := value; end; function TAmazonRequest.getamz_date: UTF8String; begin Result := fsamz_date; end; procedure TAmazonRequest.setamz_date(value: UTF8String); begin fsamz_date := value; end; function TAmazonRequest.getdate_stamp: UTF8String; begin Result := fsdate_stamp; end; procedure TAmazonRequest.setdate_stamp(value: UTF8String); begin fsdate_stamp := value; end; function TAmazonRequest.getoperationName: UTF8String; begin Result := fsoperationName; end; procedure TAmazonRequest.setoperationName(value: UTF8String); begin fsoperationName := value; end; procedure TAmazonRequest.setauthorization_header(value: UTF8String); begin fsAuthorization_header := value; end; function TAmazonRequest.getauthorization_header: UTF8String; begin Result := fsAuthorization_header; end; function TAmazonRequest.gettarget: UTF8String; begin Result := targetPrefix + '.' + operationName; end; end.
(* Files: MM, 2020-04-01 *) (* ------ *) (* Fun with Files *) (* ========================================================================= *) PROGRAM Files; TYPE MoodType = (happy, sad, angry, bored); Person = RECORD name: STRING; age: INTEGER; mood: MoodType; END; VAR textfile: TEXT; intfile: FILE OF INTEGER; personfile: FILE OF Person; p: Person; s: STRING; error: INTEGER; i: INTEGER; BEGIN (* Files *) ////// personfile ////////// Assign(personfile, 'personfile.dat'); Rewrite(personfile); p.name := 'Max Mustermann'; p.age := 24; p.mood := angry; Write(personfile, p); Close(personfile); Reset(personfile); Read(personfile, p); WriteLn(p.name, ' - '); WriteLn(p.age); WriteLn(p.mood); WriteLn; ////// intfile ////////// Assign(intfile, 'intfile.dat'); Rewrite(intfile); FOR i := 1 TO 10 DO BEGIN Write(intfile, i); END; (* FOR *) Close(intfile); Reset(intfile); REPEAT Read(intfile, i); Write(i, ' - '); UNTIL Eof(intfile); (* REPEAT *) ////// TextFile ///////// Assign(textfile, 'testfile.txt'); //Rewrite(textfile); (* Create File to write *) {$I-} Reset(textfile); (* Open File to read *) error := IOResult; IF (error <> 0) THEN BEGIN WriteLn('ERROR: Cannot open file.'); WriteLn('Code: ', IOResult); (* Is reset to 0 with each call *) WriteLn('Code: ', error); HALT; END; (* IF *) {$I+} REPEAT ReadLn(textfile, s); WriteLn(s); UNTIL Eof(textfile); (* REPEAT *) (* End of file *) Close(textfile); WriteLn('Done!'); END. (* Files *)
unit NumPageFrame; interface uses Windows, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, Buttons, ComCtrls, ExtCtrls, ItemsDef, Grids, ValEdit, ActnList, Menus, MainForm, Clipbrd, Core, IniFiles; type TfrmNumPageTemplate = class(TFrame) grpPreview: TGroupBox; imgPreview: TImage; grpTickets: TGroupBox; grpLabel: TGroupBox; lvTickets: TListView; lbedTicketName: TLabeledEdit; lbedTicketPosX: TLabeledEdit; lbedTicketPosY: TLabeledEdit; vleNLData: TValueListEditor; pmList: TPopupMenu; N1: TMenuItem; N2: TMenuItem; actlst: TActionList; actAddItem: TAction; actDelItem: TAction; edName: TEdit; lbName: TLabel; edWidth: TEdit; lbWidth: TLabel; edHeight: TEdit; lbHeight: TLabel; grpNumPageProps: TGroupBox; btnOK: TBitBtn; btnCancel: TBitBtn; actUpdateList: TAction; actSaveList: TAction; cbbTicketTpl: TComboBox; lbTicketTpl: TLabel; actImageFromFile: TAction; actImageFromClipboard: TAction; actImageClear: TAction; pmImage: TPopupMenu; N7: TMenuItem; N8: TMenuItem; actBtnOK: TAction; actBtnCancel: TAction; actAddLabel: TAction; miAddLabel: TMenuItem; procedure actlstExecute(Action: TBasicAction; var Handled: Boolean); procedure DummyAction(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure lbedTicketNameChange(Sender: TObject); procedure lvTicketsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure edWidthChange(Sender: TObject); procedure edHeightChange(Sender: TObject); procedure FrameResize(Sender: TObject); procedure lbedTicketPosXChange(Sender: TObject); procedure lbedTicketPosYChange(Sender: TObject); procedure lbedPosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure imgPreviewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure imgPreviewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); private { Private declarations } StopUpdate: Boolean; PreviewBgImage: TBitmap; PreviewParams: TPreviewParams; procedure ReadItem_NumPageTpl(ListOnly: Boolean = false); procedure ReadItem_Ticket(); procedure WriteItem_NumPageTpl(); procedure WriteItem_Ticket(); procedure TicketMod(Item: TListItem; Action: string); procedure UpdatePreview(); function GetTicketByPoint(Point: TPoint): TTicket; function GetNumlabelByPoint(Point: TPoint): TNumLabel; procedure SetPreviewParams(); public { Public declarations } Form: TForm; Page: TSomePage; NumPageTpl: TNumPageTpl; NumProject: TNumProject; CurTicket: TTicket; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ReadItem(); procedure ChangeLanguage(); end; var iImgIndexTicket: Integer = 24; iImgIndexNumlabel: Integer = 0; NumPageCreated: Boolean = False; sAskDeleteTicket: string = 'Удалить билет?'; implementation //uses MainForm; {$R *.dfm} constructor TfrmNumPageTemplate.Create(AOwner: TComponent); begin inherited Create(AOwner); StopUpdate:=False; PreviewBgImage:=nil; // NumPageCreated:= True; ChangeLanguage; end; destructor TfrmNumPageTemplate.Destroy; begin if Assigned(PreviewBgImage) then FreeAndNil(PreviewBgImage); StopUpdate:=True; NumPageCreated:= False; inherited Destroy(); end; procedure TfrmNumPageTemplate.ChangeLanguage(); var Part: string; begin if not Assigned(langFile) then Exit; if NumPageCreated then begin Part:= 'NumPage'; Self.grpNumPageProps.Caption:= LangFile.ReadString(Part, 'sgrpNumPageProps', Self.grpNumPageProps.Caption); Self.lbName.Caption:= LangFile.ReadString(Part, 'slbName', Self.lbName.Caption); Self.lbHeight.Caption:= LangFile.ReadString(Part, 'slbHeight', Self.lbHeight.Caption); Self.lbWidth.Caption:= LangFile.ReadString(Part, 'slbWidth', Self.lbWidth.Caption); Self.btnOK.Caption:= LangFile.ReadString(Part, 'sbtnOk', Self.btnOK.Caption); Self.btnCancel.Caption:= LangFile.ReadString(Part, 'sbtnCancel', Self.btnCancel.Caption); Self.grpPreview.Caption:= LangFile.ReadString(Part, 'sgrpPreview', Self.grpPreview.Caption); Self.grpTickets.Caption:= LangFile.ReadString(Part, 'sgrpTickets', Self.grpTickets.Caption); Self.lvTickets.Columns[0].Caption:= LangFile.ReadString(Part, 'slvTickets_0', Self.lvTickets.Columns[0].Caption); Self.lvTickets.Columns[1].Caption:= LangFile.ReadString(Part, 'slvTickets_1', Self.lvTickets.Columns[1].Caption); Self.N1.Caption:= LangFile.ReadString(Part, 'smiAddTicket', Self.N1.Caption); Self.miAddLabel.Caption:= LangFile.ReadString(Part, 'smiAddLabel', Self.miAddLabel.Caption); Self.N2.Caption:= LangFile.ReadString(Part, 'smiDelete', Self.N2.Caption); //Self.N6.Caption:= LangFile.ReadString(Part, 'smiImgFromFile', Self.N6.Caption); Self.N7.Caption:= LangFile.ReadString(Part, 'smiImgFromClipboard', Self.N7.Caption); Self.N8.Caption:= LangFile.ReadString(Part, 'smiClearImg', Self.N8.Caption); Self.grpLabel.Caption:= LangFile.ReadString(Part, 'sgrpLabel', Self.grpLabel.Caption); Self.lbedTicketName.EditLabel.Caption:= LangFile.ReadString(Part,'slbedTicketName', Self.lbedTicketName.EditLabel.Caption); Self.lbedTicketPosX.EditLabel.Caption:= LangFile.ReadString(Part, 'slbedTicketPosX', Self.lbedTicketPosX.EditLabel.Caption); Self.lbedTicketPosY.EditLabel.Caption:= LangFile.ReadString(Part, 'slbedTicketPosY', Self.lbedTicketPosY.EditLabel.Caption); Self.lbTicketTpl.Caption:= LangFile.ReadString(Part, 'slbTicketTpl', Self.lbTicketTpl.Caption); Self.vleNLData.TitleCaptions[0]:= LangFile.ReadString(Part, 'svleNLData_0', Self.vleNLData.TitleCaptions[0]); Self.vleNLData.TitleCaptions[1]:= LangFile.ReadString(Part, 'svleNLData_1', Self.vleNLData.TitleCaptions[1]); end; end; procedure TfrmNumPageTemplate.ReadItem_NumPageTpl(ListOnly: Boolean = false); var i: Integer; lvi: TListItem; nl: TNumLabel; begin if not Assigned(NumPageTpl) then Exit; NumPageTpl.Read(true); edName.Text:=NumPageTpl.Name; edWidth.Text:=IntToStr(NumPageTpl.Size.X); edHeight.Text:=IntToStr(NumPageTpl.Size.Y); TicketMod(nil, 'update_list'); end; procedure TfrmNumPageTemplate.WriteItem_NumPageTpl(); begin if not Assigned(NumPageTpl) then Exit; NumPageTpl.Name:=edName.Text; NumPageTpl.Size.X:=StrToIntDef(edWidth.Text, 0); NumPageTpl.Size.Y:=StrToIntDef(edHeight.Text, 0); StartTransaction(); NumPageTpl.Write(); TicketMod(nil, 'write_list'); CloseTransaction(); end; procedure TfrmNumPageTemplate.ReadItem_Ticket(); var Item: TTicket; i: Integer; begin if not Assigned(CurTicket) then Exit; Item:=CurTicket; lbedTicketName.Text:=Item.Name; lbedTicketPosX.Text:=IntToStr(Item.Position.X); lbedTicketPosY.Text:=IntToStr(Item.Position.Y); if Assigned(Item.Tpl) then begin //cbbTicketTpl.Text:=Item.Tpl.Name; i:=cbbTicketTpl.Items.IndexOfObject(Item.Tpl); cbbTicketTpl.ItemIndex:=i; end; vleNLData.Strings.Clear(); // vleNLData.InsertRow('Action', Item.Action, true); // vleNLData.InsertRow('ValueType', Item.ValueType, true); // vleNLData.InsertRow('BaseValue', Item.BaseValue, true); end; procedure TfrmNumPageTemplate.WriteItem_Ticket(); var i: Integer; Item: TTicket; begin if not Assigned(CurTicket) then Exit; Item:=CurTicket; Item.Name:=lbedTicketName.Text; Item.Position.X:=StrToIntDef(lbedTicketPosX.Text, 0); Item.Position.Y:=StrToIntDef(lbedTicketPosY.Text, 0); if cbbTicketTpl.Items.Count>0 then begin i:=cbbTicketTpl.ItemIndex; if i<0 then i:=0; Item.Tpl:=(cbbTicketTpl.Items.Objects[i] as TTicketTpl); end; //Item.Action:=vleNLData.Values['Action']; //Item.ValueType:=vleNLData.Values['ValueType']; //Item.BaseValue:=vleNLData.Values['BaseValue']; end; procedure TfrmNumPageTemplate.TicketMod(Item: TListItem; Action: string); var NewItem: TListItem; NewObject, ItemObject: TTicket; i: Integer; begin if not Assigned(NumPageTpl) then Exit; StopUpdate:=True; ItemObject:=nil; if Assigned(Item) then begin if Assigned(Item.Data) then begin ItemObject:=TTicket(Item.Data); end; end; if Action='add' then begin NewObject:=TTicket.Create(self.NumProject); NewObject.Name:='Билет '+IntToStr(NumPageTpl.Tickets.Count+1); if NumProject.TicketTplList.Count>0 then NewObject.Tpl:=NumProject.TicketTplList[0]; NewObject.NumPageTpl:=NumPageTpl; if Assigned(CurTicket) then begin NewObject.Tpl:=CurTicket.Tpl; NewObject.Position:=CurTicket.Position; //NewObject.BaseValue:=CurNumLabel.BaseValue; //NewObject.ValueType:=CurNumLabel.ValueType; //NewObject.Action:=CurNumLabel.Action; end; NumPageTpl.Tickets.Add(NewObject); NewItem:=lvTickets.Items.Add(); NewItem.Caption:=NewObject.Name; NewItem.SubItems.Add(PosToStr(NewObject.Position)); NewItem.Data:=NewObject; NewItem.ImageIndex:=iImgIndexTicket; end else if Action='del' then begin if Assigned(Item) then begin // Are you sure? if Application.MessageBox(PAnsiChar(sAskDeleteTicket), PAnsiChar(sAskDeleteCaption), MB_OKCANCEL) <> IDOK then Exit; i:=lvTickets.Items.IndexOf(Item); Item.Delete(); ItemObject.Delete(); NumPageTpl.Tickets.Remove(ItemObject); CurTicket:=nil; if NumPageTpl.Tickets.Count>0 then begin if i >= lvTickets.Items.Count then i:=lvTickets.Items.Count-1; lvTickets.ItemIndex:=i; end else begin lbedTicketName.Text:=''; lbedTicketPosX.Text:=''; lbedTicketPosY.Text:=''; //vleNLData end; end; end {else if Action='edit' then begin if Assigned(ItemObject) then begin end; end} else if Action='update_list' then begin //if not NumPageTpl.Tickets.LoadFromBase() then Exit; lvTickets.Items.BeginUpdate(); lvTickets.Items.Clear(); for i:=0 to NumPageTpl.Tickets.Count-1 do begin NewObject:=(NumPageTpl.Tickets[i] as TTicket); NewObject.Read(); NewItem:=lvTickets.Items.Add(); NewItem.Caption:=NewObject.Name; NewItem.Data:=NewObject; NewItem.ImageIndex:=iImgIndexTicket; NewItem.SubItems.Add(PosToStr(NewObject.Position)); end; lvTickets.Items.EndUpdate(); end else if Action='write_list' then begin //TicketTpl.NumLabels.SaveToBase(); for i:=0 to NumPageTpl.Tickets.Count-1 do begin (NumPageTpl.Tickets[i] as TTicket).Write(); end; end else if Action='select' then begin if Assigned(ItemObject) then begin if Assigned(CurTicket) then begin if CurTicket<>ItemObject then begin end; end; // Save previous item WriteItem_Ticket(); CurTicket:=ItemObject; // Read selected item ReadItem_Ticket(); //frmMain.Caption:=snProgramName+' - '+CurProject.Name; //memoProjectDesc.Lines.Text:=CurProject.Desc; end; end; StopUpdate:=False; end; procedure TfrmNumPageTemplate.actlstExecute(Action: TBasicAction; var Handled: Boolean); var ListItem: TListItem; begin ListItem:=lvTickets.Selected; if Action = actAddItem then begin TicketMod(ListItem, 'add'); end else if Action = actDelItem then begin TicketMod(ListItem, 'del'); end else if Action = actUpdateList then begin TicketMod(ListItem, 'update_list'); end else if Action = actSaveList then begin TicketMod(ListItem, 'write_list'); end else if Action = actImageFromFile then begin end else if Action = actImageFromClipboard then begin if not Assigned(PreviewBgImage) then PreviewBgImage:=TBitmap.Create(); PreviewBgImage.LoadFromClipboardFormat(cf_Bitmap, ClipBoard.GetAsHandle(cf_Bitmap), 0); UpdatePreview(); end else if Action = actImageClear then begin FreeAndNil(PreviewBgImage); UpdatePreview(); end; end; procedure TfrmNumPageTemplate.DummyAction(Sender: TObject); begin Exit; end; procedure TfrmNumPageTemplate.btnCancelClick(Sender: TObject); begin //if Assigned(Form) then Form.Release(); if (Parent is TSomePage) then begin Core.CmdQueue.AddCmd('CLOSE '+IntToStr((Parent as TSomePage).PageID)); end; if Assigned(Form) then Form.Close(); end; procedure TfrmNumPageTemplate.btnOKClick(Sender: TObject); begin WriteItem_Ticket(); WriteItem_NumPageTpl(); self.NumPageTpl.Write(); Core.CmdQueue.AddCmd('REFRESH PAGE_TPL_LIST'); if (Parent is TSomePage) then begin Core.CmdQueue.AddCmd('CLOSE '+IntToStr((Parent as TSomePage).PageID)); end; //if Assigned(Form) then Form.Release(); if Assigned(Form) then Form.Close(); end; procedure TfrmNumPageTemplate.ReadItem(); var i: integer; Item: TTicketTpl; begin cbbTicketTpl.Clear(); for i:=0 to NumProject.TicketTplList.Count-1 do begin Item:=NumProject.TicketTplList[i]; cbbTicketTpl.AddItem(Item.Name, Item); end; ReadItem_NumPageTpl(); UpdatePreview(); end; procedure TfrmNumPageTemplate.FormClose(Sender: TObject; var Action: TCloseAction); begin if Assigned(Form) then Form.Release(); end; procedure TfrmNumPageTemplate.lbedTicketNameChange(Sender: TObject); begin if Assigned(lvTickets.Selected) then lvTickets.Selected.Caption:=lbedTicketName.Text; end; procedure TfrmNumPageTemplate.lvTicketsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin TicketMod(Item, 'select'); UpdatePreview(); end; procedure TfrmNumPageTemplate.SetPreviewParams(); var Canvas: TCanvas; kx, ky: Real; PreviewSize: TSize; begin imgPreview.Picture.Bitmap.Height:=imgPreview.Height; imgPreview.Picture.Bitmap.Width:=imgPreview.Width; Canvas:=imgPreview.Canvas; // Compute ticket preview size in pixels with PreviewParams do begin SizeMm.cx:=StrToIntDef(edWidth.Text, 0); SizeMm.cy:=StrToIntDef(edHeight.Text, 0); CanvasSize.cx:=Canvas.ClipRect.Right-Canvas.ClipRect.Left; CanvasSize.cy:=Canvas.ClipRect.Bottom-Canvas.ClipRect.Top; PreviewSize.cx:=CanvasSize.cx-8; PreviewSize.cy:=CanvasSize.cy-8; kx:=0; if SizeMm.cx<>0 then kx:=PreviewSize.cx/SizeMm.cx; ky:=0; if SizeMm.cy<>0 then ky:=PreviewSize.cy/SizeMm.cy; if kx<ky then begin k:=kx; PreviewSize.cy:=Round(SizeMm.cy*k); end else begin k:=ky; PreviewSize.cx:=Round(SizeMm.cx*k); end; BordersRect.Left:=(CanvasSize.cx-PreviewSize.cx) div 2; BordersRect.Top:=(CanvasSize.cy-PreviewSize.cy) div 2; BordersRect.Right:=BordersRect.Left+PreviewSize.cx; BordersRect.Bottom:=BordersRect.Top+PreviewSize.cy; end; end; procedure TfrmNumPageTemplate.UpdatePreview(); var tr, r: TRect; x,y,sx,sy,i: Integer; Item: TTicket; Canvas: TCanvas; begin if not Assigned(NumPageTpl) then Exit; SetPreviewParams(); with PreviewParams do begin Canvas:=imgPreview.Canvas; // Clear canvas Canvas.Brush.Color:=clWhite; Canvas.FillRect(imgPreview.Canvas.ClipRect); Canvas.Pen.Width:=1; Canvas.Pen.Color:=clBlack; //Canvas.Brush.Color:=clInfoBk; //clYellow; //Canvas.FillRect(BordersRect); Canvas.Rectangle(BordersRect); // Draw background image if Assigned(PreviewBgImage) then begin Canvas.StretchDraw(BordersRect, PreviewBgImage); end; // Draw tickets for i:=0 to NumPageTpl.Tickets.Count-1 do begin Item:=NumPageTpl.Tickets[i]; if not Assigned(Item.Tpl) then Continue; x:=BordersRect.Left+Round(Item.Position.X*k); y:=BordersRect.Top+Round(Item.Position.Y*k); sx:=Round(Item.Tpl.Size.X*k); sy:=Round(Item.Tpl.Size.Y*k); r:=Rect(x, y, x+sx, y+sy); Canvas.Pen.Width:=1; if Assigned(CurTicket) then begin if CurTicket.ID = Item.ID then Canvas.Pen.Width:=3; end; Canvas.Pen.Color:=clBlack; Canvas.Brush.Color:=clInfoBk; //clYellow; Canvas.FillRect(r); Canvas.Rectangle(r); end; end; end; procedure TfrmNumPageTemplate.edWidthChange(Sender: TObject); begin UpdatePreview(); end; procedure TfrmNumPageTemplate.edHeightChange(Sender: TObject); begin UpdatePreview(); end; procedure TfrmNumPageTemplate.FrameResize(Sender: TObject); begin UpdatePreview(); end; procedure TfrmNumPageTemplate.lbedTicketPosXChange(Sender: TObject); begin if StopUpdate then Exit; WriteItem_Ticket(); TicketMod(nil, 'update_list'); UpdatePreview(); end; procedure TfrmNumPageTemplate.lbedTicketPosYChange(Sender: TObject); begin if StopUpdate then Exit; WriteItem_Ticket(); TicketMod(nil, 'update_list'); UpdatePreview(); end; procedure TfrmNumPageTemplate.lbedPosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var i, n: Integer; begin n:=0; if Key = VK_UP then begin n:=1; end else if Key = VK_DOWN then begin n:=-1; end; if (ssShift in Shift) then n:=n*5; if not (Sender is TLabeledEdit) then Exit; i:=StrToIntDef((Sender as TLabeledEdit).Text, 0); i:=i+n; (Sender as TLabeledEdit).Text:=IntToStr(i); end; function TfrmNumPageTemplate.GetNumlabelByPoint(Point: TPoint): TNumLabel; var LocalPoint: TPoint; Canvas: TCanvas; x,y, i: Integer; r: TRect; Item: TNumLabel; LogFont: TLogFont; TextSize: TSize; begin Result:=nil; //LocalPoint:=self.ScreenToClient(Point); LocalPoint:=Point; SetPreviewParams(); with PreviewParams do begin Canvas:=imgPreview.Canvas; // Test numlabels for i:=0 to NumPageTpl.NumLabels.Count-1 do begin Item:=NumPageTpl.NumLabels[i]; if not Assigned(Item.Font) then Continue; x:=BordersRect.Left+Round(Item.Position.X*k); y:=BordersRect.Top+Round(Item.Position.Y*k); Canvas.Font.Assign(Item.Font); // Пересчет размера шрифта //Canvas.Font.Height:=Round(Item.Size * Font.PixelsPerInch / 72 *k); Canvas.Font.Height:=-Round(Item.Size * k); GetObject(Canvas.Font.Handle, SizeOf(TLogFont), @LogFont); { Вывести текст 1/10 градуса против часовой стрелки } LogFont.lfEscapement := Item.Angle*10; Canvas.Font.Handle := CreateFontIndirect(LogFont); TextSize:=Canvas.TextExtent(Item.Name); r:=Rect(x, y, x+TextSize.cx, y+TextSize.cy); if PtInRect(r, LocalPoint) then begin Result:=Item; Exit; end; end; end; end; function TfrmNumPageTemplate.GetTicketByPoint(Point: TPoint): TTicket; var LocalPoint: TPoint; Canvas: TCanvas; x, y, sx, sy, i: Integer; r: TRect; Item: TTicket; LogFont: TLogFont; TextSize: TSize; begin Result:=nil; //LocalPoint:=self.ScreenToClient(Point); LocalPoint:=Point; SetPreviewParams(); with PreviewParams do begin Canvas:=imgPreview.Canvas; // Test tickets for i:=0 to NumPageTpl.Tickets.Count-1 do begin Item:=NumPageTpl.Tickets[i]; if not Assigned(Item.Tpl) then Continue; x:=BordersRect.Left+Round(Item.Position.X*k); y:=BordersRect.Top+Round(Item.Position.Y*k); sx:=Round(Item.Tpl.Size.X*k); sy:=Round(Item.Tpl.Size.Y*k); r:=Rect(x, y, x+sx, y+sy); if PtInRect(r, LocalPoint) then begin Result:=Item; Exit; end; end; end; end; function GetListItemByItemObject(lv: TListView; ItemObject: TObject): TListItem; var i: integer; begin Result:=nil; for i:=0 to lv.Items.Count-1 do begin if lv.Items[i].Data = ItemObject then begin Result:=lv.Items[i]; Exit; end; end; end; procedure TfrmNumPageTemplate.imgPreviewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Item1: TTicket; Item2: TNumLabel; ListItem: TListItem; begin if Button = mbLeft then begin // Ищем билет по координатам Item1:=GetTicketByPoint(Point(X, Y)); if Assigned(Item1) then begin ListItem:=GetListItemByItemObject(lvTickets, Item1); if not Assigned(ListItem) then Exit; lvTickets.Selected:=ListItem; PreviewParams.MouseOffset.X:=X-PreviewParams.BordersRect.Left-Round(Item1.Position.X*PreviewParams.k); PreviewParams.MouseOffset.Y:=Y-PreviewParams.BordersRect.Top-Round(Item1.Position.Y*PreviewParams.k); Exit; end; // Ищем нумератор по координатам Item2:=GetNumlabelByPoint(Point(X, Y)); if Assigned(Item2) then begin ListItem:=GetListItemByItemObject(lvTickets, Item2); if not Assigned(ListItem) then Exit; lvTickets.Selected:=ListItem; PreviewParams.MouseOffset.X:=X-PreviewParams.BordersRect.Left-Round(Item2.Position.X*PreviewParams.k); PreviewParams.MouseOffset.Y:=Y-PreviewParams.BordersRect.Top-Round(Item2.Position.Y*PreviewParams.k); Exit; end; //NumLabelMod(ListItem, 'select'); //UpdatePreview(); end; end; procedure TfrmNumPageTemplate.imgPreviewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var PointMM: TPoint; begin if (ssLeft in Shift) then begin if not Assigned(CurTicket) then Exit; if PreviewParams.k=0 then Exit; StopUpdate:=True; PointMM.X:=Round((X-PreviewParams.BordersRect.Left-PreviewParams.MouseOffset.X)/PreviewParams.k); PointMM.Y:=Round((Y-PreviewParams.BordersRect.Top-PreviewParams.MouseOffset.Y)/PreviewParams.k); CurTicket.Position.X:=PointMM.X; CurTicket.Position.Y:=PointMM.Y; lbedTicketPosX.Text:=IntToStr(PointMM.X); lbedTicketPosY.Text:=IntToStr(PointMM.Y); UpdatePreview(); StopUpdate:=False; end; end; end.
{ Oracle Deploy System ver.1.0 (ORDESY) by Volodymyr Sedler aka scribe 2016 Desc: wrap/deploy/save objects of oracle database. No warranty of using this program. Just Free. With bugs, suggestions please write to justscribe@yahoo.com On Github: github.com/justscribe/ORDESY As a part of project. Desc: saving/loading options to *.ini. Warning: there some problems with memory leaks, use carefuly and check with ReportMemoryLeaksOnShutdown := true;. } unit uOptions; interface uses // ORDESY Modules {$IFDEF Debug} uLog, {$ENDIF} Windows, Classes, SysUtils, IniFiles, Forms; type TOption = record Section: string; Name: string; Value: string; Procedure Clear; end; POption = ^TOption; TOptions = class private FOptions: array of TOption; FEmpty: boolean; FLastChange, FLastSave: TDateTime; function GetOptionsCount: integer; function GetSavedMark: boolean; public AppTitle: string; UserName: string; constructor Create; destructor Destroy; override; function SaveUserOptions(const aFileName: string = 'options.ini'): boolean; function LoadUserOptions(const aFileName: string = 'options.ini'): boolean; function GetOption(const aSection, aName: string): string; function SetOption(const aSection, aName, aValue: string): boolean; property IsEmpty: boolean read FEmpty; property Count: integer read GetOptionsCount; property Saved: boolean read GetSavedMark; end; implementation { TOptions } constructor TOptions.Create; begin inherited Create; FEmpty:= true; end; destructor TOptions.Destroy; var i: integer; begin for i := 0 to high(FOptions) do //Dispose(POption(@FOptions[i])); FOptions[i].Clear; SetLength(FOptions, 0); inherited Destroy; end; function TOptions.GetOption(const aSection, aName: string): string; var i: integer; begin Result:= ''; if FEmpty then raise Exception.Create('Options are empty, please load from file first!'); for i := 0 to high(FOptions) do begin if (FOptions[i].Section = aSection) and (FOptions[i].Name = aName) then begin Result:= FOptions[i].Value; Exit; end; end; //raise Exception.Create('No such value in [' + aSection + ']:[' + aName + ']'); end; function TOptions.GetOptionsCount: integer; var i: integer; begin Result:= 0; if FEmpty then Exit; Result:= length(FOptions); end; function TOptions.GetSavedMark: boolean; begin Result:= false; if FEmpty then Exit; if FLastChange <= FLastSave then Result:= true; end; function TOptions.LoadUserOptions(const aFileName: string = 'options.ini'): boolean; var iniFile: TIniFile; i, n: integer; Sections, Section, Values: TStringList; begin Result:= false; if not FileExists(ExtractFilePath(ParamStr(0)) + aFileName) then begin Result:= true; Exit; end; try SetLength(FOptions, 0); iniFile:= TIniFile.Create(ExtractFilePath(ParamStr(0)) + aFileName); Sections:= TStringList.Create; Section:= TStringList.Create; Values:= TStringList.Create; iniFile.ReadSections(Sections); for i := 0 to Sections.Count - 1 do begin iniFile.ReadSection(Sections.Strings[i], Section); for n := 0 to Section.Count - 1 do begin SetLength(FOptions, length(FOptions) + 1); FOptions[high(FOptions)].Section:= Sections.Strings[i]; FOptions[high(FOptions)].Name:= Section.Strings[n]; FOptions[high(FOptions)].Value:= iniFile.ReadString(Sections.Strings[i], Section.Strings[n], ''); end; end; if Length(FOptions) <> 0 then FEmpty:= false; FLastChange:= GetTime; FLastSave:= FLastChange; Result:= true; finally Sections.Free; Section.Free; Values.Free; iniFile.Free; end; end; function TOptions.SaveUserOptions(const aFileName: string = 'options.ini'): boolean; var iniFile: TIniFile; i: integer; begin Result:= false; if FEmpty then raise Exception.Create('No options added, nothing to save!'); try iniFile:= TIniFile.Create(ExtractFilePath(ParamStr(0)) + aFileName); for i := 0 to high(FOptions) do begin iniFile.WriteString(FOptions[i].Section, FOptions[i].Name, FOptions[i].Value); end; FLastSave:= GetTime; Result:= true; finally iniFile.Free; end; end; function TOptions.SetOption(const aSection, aName, aValue: string): boolean; var i: integer; Founded: boolean; iItem: TOption; begin Result:= False; try Founded:= false; if (aSection = '') or (aName = '') or (aValue = '') then raise Exception.Create('Some of option agrument is empty!'); for i := 0 to high(FOptions) do begin if (FOptions[i].Section = aSection) and (FOptions[i].Name = aName) then begin FOptions[i].Value:= aValue; Founded:= true; end; end; if not Founded then begin SetLength(FOptions, length(FOptions) + 1); iItem.Section:= aSection; iItem.Name:= aName; iItem.Value:= aValue; FOptions[high(FOptions)]:= iItem; iItem.Clear; end; FLastChange:= GetTime; FEmpty:= false; Result:= true; except on E: Exception do begin {$IFDEF Debug} AddToLog(ClassName + ' | WrapItem | ' + E.Message); MessageBox(Application.Handle, PChar(ClassName + ' | WrapItem | ' + E.Message), PChar(Application.Title + ' - Error'), 48); {$ELSE} MessageBox(Application.Handle, PChar(E.Message), PChar(Application.Title + ' - Error'), 48); {$ENDIF} end; end; end; { TOption } procedure TOption.Clear; begin Self:= Default(TOption); end; end.
unit UFrmStockInfoEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmModal, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxControls, cxContainer, cxEdit, dxSkinsCore, dxSkinsDefaultPainters, cxTextEdit, StdCtrls, ActnList, cxButtons, ExtCtrls, DBClient; type TFrmStockInfoEdit = class(TFrmModal) lbl1: TLabel; edtStockID: TcxTextEdit; lbl2: TLabel; edtStockName: TcxTextEdit; lbl3: TLabel; edtLinkMan: TcxTextEdit; lbl4: TLabel; edtPhone: TcxTextEdit; lbl5: TLabel; edtAddress: TcxTextEdit; lbl10: TLabel; edtRemark: TcxTextEdit; procedure FormShow(Sender: TObject); procedure btnOkClick(Sender: TObject); private FAction: string; FDataSet: TClientDataSet; procedure ClearControls; function BeforeExecute: Boolean; function DoExecute: Boolean; public class function ShowStockInfoEdit(DataSet: TClientDataSet; AAction: string): Boolean; end; var FrmStockInfoEdit: TFrmStockInfoEdit; implementation uses UDBAccess, UMsgBox, UPubFunLib; {$R *.dfm} { TFrmStockInfoEdit } function TFrmStockInfoEdit.BeforeExecute: Boolean; const cCheckIDExistsSQL = 'select * from StockInfo where StockID=''%s'''; var lStrSql: string; iResult: Integer; begin Result := False; if Trim(edtStockID.Text) = '' then begin edtStockID.SetFocus; ShowMsg('仓库编码不能为空!'); Exit; end; if Trim(edtStockName.Text) = '' then begin edtStockName.SetFocus; ShowMsg('仓库名称不能为空!'); Exit; end; if FAction = 'Append' then lStrSql := Format(cCheckIDExistsSQL, [Trim(edtStockID.Text)]) else begin lStrSql := Format(cCheckIDExistsSQL + ' and Guid <> ''%s''', [Trim(edtStockID.Text), FDataSet.FindField('Guid').AsString]); end; iResult := DBAccess.DataSetIsEmpty(lStrSql); if iResult = -1 then begin ShowMsg('判断仓库编码是否重复失败!'); Exit; end; if iResult = 0 then begin ShowMsg('当前仓库编码已经存在,请重新输入!'); Exit; end; Result := True; end; procedure TFrmStockInfoEdit.btnOkClick(Sender: TObject); begin if not BeforeExecute then Exit; if not DoExecute then Exit; ModalResult := mrOk; end; procedure TFrmStockInfoEdit.ClearControls; begin edtStockID.Text := ''; edtStockName.Text := ''; edtLinkMan.Text := ''; edtPhone.Text := ''; edtAddress.Text := ''; edtRemark.Text := ''; end; function TFrmStockInfoEdit.DoExecute: Boolean; begin Result := False; with FDataSet do begin if FAction = 'Append' then begin Append; FindField('Guid').AsString := CreateGuid; end else Edit; FindField('StockID').AsString := Trim(edtStockID.Text); FindField('StockName').AsString := Trim(edtStockName.Text); FindField('LinkMan').AsString := Trim(edtLinkMan.Text); FindField('Phone').AsString := Trim(edtPhone.Text); FindField('Address').AsString := Trim(edtAddress.Text); FindField('Remark').AsString := Trim(edtRemark.Text); Post; if not DBAccess.ApplyUpdates('StockInfo', FDataSet) then begin FDataSet.CancelUpdates; ShowMsg('仓库信息保存失败!'); Exit; end; MergeChangeLog; end; Result := True; end; procedure TFrmStockInfoEdit.FormShow(Sender: TObject); begin inherited; ClearControls; if FAction = 'Edit' then begin with FDataSet do begin edtStockID.Text := FindField('StockID').AsString; edtStockName.Text := FindField('StockName').AsString; edtLinkMan.Text := FindField('LinkMan').AsString; edtPhone.Text := FindField('Phone').AsString; edtAddress.Text := FindField('Address').AsString; edtRemark.Text := FindField('Remark').AsString; end; end; end; class function TFrmStockInfoEdit.ShowStockInfoEdit(DataSet: TClientDataSet; AAction: string): Boolean; begin with TFrmStockInfoEdit.Create(nil) do begin try FDataSet := DataSet; FAction := AAction; Result := ShowModal = mrOk; finally Free; end; end; end; end.
unit fOtherSchedule; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, Buttons, fAutoSz, rMisc, ORCtrls, rODMeds, VA508AccessibilityManager, VAUtils; const NSS_TXT = 'This order will not become active until a valid schedule is used.'; type TfrmOtherSchedule = class(TfrmAutoSz) Panel1: TPanel; Image1: TImage; Panel3: TPanel; GroupBox1: TGroupBox; cbo7: TCheckBox; cbo1: TCheckBox; cbo2: TCheckBox; cbo3: TCheckBox; cbo4: TCheckBox; cbo5: TCheckBox; cbo6: TCheckBox; GroupBox2: TGroupBox; lstHour: TListBox; lstMinute: TListBox; Panel4: TPanel; btn0k1: TButton; btnCancel: TButton; Label1: TLabel; btnReset: TButton; btnRemove: TButton; memMessage: TMemo; Splitter1: TSplitter; btnAdd: TButton; Button1: TButton; GroupBox3: TGroupBox; NSScboSchedule: TORComboBox; btnSchAdd: TButton; btnSchRemove: TButton; txtSchedule: TEdit; procedure FormCreate(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btn0k1Click(Sender: TObject); procedure cbo7Click(Sender: TObject); procedure cbo1Click(Sender: TObject); procedure cbo2Click(Sender: TObject); procedure cbo3Click(Sender: TObject); procedure cbo4Click(Sender: TObject); procedure cbo5Click(Sender: TObject); procedure cbo6Click(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnResetClick(Sender: TObject); procedure btnRemoveClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure lstHourClick(Sender: TObject); procedure txtScheduleChange(Sender: TObject); procedure lstMinuteMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure lstMinuteKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Button1Click(Sender: TObject); procedure btnSchAddClick(Sender: TObject); procedure btnSchRemoveClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure NSScboScheduleExit(Sender: TObject); procedure NSScboScheduleKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private FDaySchedule: array [1..7] of string; FTimeSchedule: TStringList; FSchedule: String; FOtherSchedule: String; FFromCheckBox: boolean; FFromEditBox: boolean; function GetSiteMessage: string; procedure SetDaySchedule(Sender: TObject); procedure SetTimeSchedule; procedure SetScheduleSelection; procedure UpdateOnFreeTextInput; procedure EnabledTime(TF: boolean); procedure EnabledSch(TF: boolean); function CheckDay(ADayStr: string): string; public end; function ShowOtherSchedule(var ASchedule: string): boolean; var frmOtherSchedule: TfrmOtherSchedule; implementation uses ORFn, ORNet, rOrders; {$R *.dfm} function ShowOtherSchedule(var ASchedule: string): boolean; var AdminTime, SchType: string; begin Result := False; try ASchedule := ''; frmOtherSchedule := TfrmOtherSchedule.Create(Application); ResizeFormToFont(TForm(frmOtherSchedule)); SetFormPosition(frmOtherSchedule); if frmOtherSchedule.ShowModal = mrOK then begin ASchedule := UpperCase(frmOtherSchedule.FOtherSchedule); if frmOtherSchedule.GroupBox3.Enabled = True then begin AdminTime := Piece(frmOtherSchedule.NSScboSchedule.Items.Strings[frmOtherSchedule.NSScboSchedule.itemindex],U,4); schType := Piece(frmOtherSchedule.NSScboSchedule.Items.Strings[frmOtherSchedule.NSScboSchedule.itemindex],U,3); ASchedule := ASchedule + U + AdminTime + U + schType; //if (schType = 'P') or (schType = 'OC') then ASchedule := ASchedule + U + '1' //else ASchedule := ASchedule + U + '0'; end else if frmOtherSchedule.GroupBox2.Enabled = true then begin AdminTime := Piece(ASchedule,'@',2); ASchedule := ASchedule + U + AdminTime + U + 'C'; end; Result := True; end; except ShowMsg('Error happen when building other schedule'); end; end; procedure TfrmOtherSchedule.FormCreate(Sender: TObject); var i: integer; nssMsg: string; begin frmOtherSchedule := nil; FFromCheckBox := False; FFromEditBox := False; image1.Picture.Icon.Handle := LoadIcon(0, IDI_WARNING); for i := 1 to 7 do FDaySchedule[i] := ''; FTimeSchedule := TStringlist.Create; FSchedule := ''; FOtherSchedule := ''; nssMsg := GetSiteMessage; if Length(nssMsg)< 1 then nssMsg := NSS_TXT; memMessage.Lines.Add(nssMsg); LoadDOWSchedules(NSScboSchedule.Items); if ScreenReaderActive = false then txtSchedule.TabStop := false; end; procedure TfrmOtherSchedule.FormDestroy(Sender: TObject); begin inherited; //FDaySchedule FTimeSchedule.Free; frmOtherSchedule := nil; //FSchedule: String; //FOtherSchedule: String; end; procedure TfrmOtherSchedule.btnCancelClick(Sender: TObject); begin frmOtherSchedule.Release; end; procedure TfrmOtherSchedule.btn0k1Click(Sender: TObject); begin if (cbo1.Checked = false) and (cbo2.Checked = false) and (cbo3.Checked = false) and (cbo4.Checked = false) and (cbo5.Checked = false) and (cbo6.Checked = false) and (cbo7.Checked = false) then begin ShowMsg('A day of week must be selected!'); Exit; end; if Pos('@', self.txtSchedule.Text) = 0 then begin ShowMsg('An Administation Time or a schedule needs to be selected'); exit; end; (* if not IsValidSchStr(FOtherSchedule) then begin Show508Message('The schedule you entered is invalid!'); Exit; end; *) modalResult := mrOK; end; procedure TfrmOtherSchedule.SetDaySchedule(Sender: TObject); var i : integer; TimePart, DayPart, Schedule: string; begin with (Sender as TCheckBox) do begin try if TCheckBox(Sender).Checked then FDaySchedule[TCheckBox(Sender).Tag] := Copy(TCheckBox(Sender).Caption,0,2) else FDaySchedule[TCheckBox(Sender).Tag] := ''; except ShowMsg('Error happened when building day schedule.'); Exit; end; end; TimePart := ''; DayPart := ''; schedule := ''; if Self.GroupBox2.Enabled = True then begin for i := 0 to FTimeSchedule.Count - 1 do begin if i = 0 then TimePart := TimePart + FTimeSchedule[i] else TimePart := TimePart + '-' + FTimeSchedule[i]; end; end; if (self.GroupBox3.Enabled = True) and (FSchedule <> '') then schedule := FSchedule; for i := Low(FDaySchedule) to High(FDaySchedule) do begin if Length(FDaySchedule[i])>0 then begin if DayPart = '' then DayPart := FDaySchedule[i] else DayPart := DayPart + '-' + FDaySchedule[i]; end; end; if Length(TimePart) > 0 then begin if Length(DayPart) > 0 then FOtherSchedule := DayPart + '@' + TimePart else if Length(DayPart) = 0 then FOtherSchedule := TimePart; end else if Length(schedule) > 0 then begin if length(DayPart) > 0 then FOtherSchedule := DayPart + '@' + Schedule else if Length(DayPart) = 0 then FOtherSchedule := Schedule; end else FOtherSchedule := DayPart; txtSchedule.Text := FOtherSchedule; end; procedure TfrmOtherSchedule.SetScheduleSelection; var i: integer; DayPart: string; begin DayPart := ''; for i := Low(FDaySchedule) to High(FDaySchedule) do begin if Length(FDaySchedule[i])>0 then begin if DayPart = '' then DayPart := FDaySchedule[i] else DayPart := DayPart + '-' + FDaySchedule[i]; end; end; if Length(DayPart) > 0 then begin if FSchedule <> '' then FOtherSchedule := DayPart + '@' + FSchedule else FOtherSchedule := DayPart; end else FOtherSchedule := FSchedule; //if Length(APRN) > 0 then FOtherSchedule := FOtherSchedule; txtSchedule.Text := FOtherSchedule; end; procedure TfrmOtherSchedule.SetTimeSchedule; var i : integer; TimePart, DayPart,APRN,ASearchTxt: string; begin TimePart := ''; DayPart := ''; APRN := ''; ASearchTxt := UpperCase(txtSchedule.Text); if StrPos(PChar(ASearchTxt),PChar('PRN')) <> nil then APRN := ' PRN'; //hds8326 retain PRN free text if data time entered for i := 0 to FTimeSchedule.Count - 1 do begin if i = 0 then TimePart := TimePart + FTimeSchedule[i] else TimePart := TimePart + '-' + FTimeSchedule[i]; end; for i := Low(FDaySchedule) to High(FDaySchedule) do begin if Length(FDaySchedule[i])>0 then begin if DayPart = '' then DayPart := FDaySchedule[i] else DayPart := DayPart + '-' + FDaySchedule[i]; end; end; if Length(DayPart) > 0 then begin if Length(TimePart) > 0 then FOtherSchedule := DayPart + '@' + TimePart else FOtherSchedule := DayPart; end else FOtherSchedule := TimePart; if Length(APRN) > 0 then FOtherSchedule := FOtherSchedule + APRN; //hds8326 retain PRN free text if data time entered txtSchedule.Text := FOtherSchedule; end; procedure TfrmOtherSchedule.cbo7Click(Sender: TObject); begin FFromCheckBox := True; if not FFromEditBox then SetDaySchedule(Sender); FFromCheckBox := False; end; procedure TfrmOtherSchedule.cbo1Click(Sender: TObject); begin FFromCheckBox := True; if not FFromEditBox then SetDaySchedule(Sender); FFromCheckBox := False; end; procedure TfrmOtherSchedule.cbo2Click(Sender: TObject); begin FFromCheckBox := True; if not FFromEditBox then SetDaySchedule(Sender); FFromCheckBox := False; end; procedure TfrmOtherSchedule.cbo3Click(Sender: TObject); begin FFromCheckBox := True; if not FFromEditBox then SetDaySchedule(Sender); FFromCheckBox := False; end; procedure TfrmOtherSchedule.cbo4Click(Sender: TObject); begin FFromCheckBox := True; if not FFromEditBox then SetDaySchedule(Sender); FFromCheckBox := False; end; procedure TfrmOtherSchedule.cbo5Click(Sender: TObject); begin FFromCheckBox := True; if not FFromEditBox then SetDaySchedule(Sender); FFromCheckBox := False; end; procedure TfrmOtherSchedule.cbo6Click(Sender: TObject); begin FFromCheckBox := True; if not FFromEditBox then SetDaySchedule(Sender); FFromCheckBox := False; end; procedure TfrmOtherSchedule.btnAddClick(Sender: TObject); var hour, min: string; begin if FSchedule <> '' then Exit; if lstHour.ItemIndex < 0 then exit; hour := lstHour.Items[lstHour.ItemIndex]; hour := Trim(Copy(hour,1,3)); if length(Trim(hour)) = 1 then hour := '0' + Trim(hour); if lstMinute.ItemIndex >= 0 then begin min := lstMinute.Items[lstMinute.itemIndex]; min := Copy(min,2,2); end; if min = '' then min := '00'; if (hour='00') and (min='00') then hour := '24'; if FTimeSchedule.IndexOf(hour)>=0 then begin FTimeSchedule[FTimeSchedule.IndexOf(hour)] := hour + min; end; if FTimeSchedule.IndexOf(hour+min) < 0 then FTimeSchedule.Add(hour+min); FTimeSchedule.Sort; SetTimeSchedule; if FTimeSchedule.Count > 0 then EnabledSch(False); end; procedure TfrmOtherSchedule.btnResetClick(Sender: TObject); var i : integer; begin cbo1.Checked := false; cbo2.Checked := false; cbo3.Checked:= false; cbo4.Checked := false; cbo5.Checked := false; cbo6.Checked := false; cbo7.Checked := false; lstHour.ItemIndex := -1; lstMinute.ItemIndex := -1; NSScboSchedule.ItemIndex := -1; for i := low(FDaySchedule) to high(FDaySchedule) do FDaySchedule[i] := ''; FTimeSchedule.Clear; FOtherSchedule := ''; txtSchedule.Text := ''; FSchedule := ''; EnabledTime(True); EnabledSch(True); end; procedure TfrmOtherSchedule.btnSchAddClick(Sender: TObject); begin inherited; if self.NSScboSchedule.ItemIndex < 0 then Exit; if FSchedule <> '' then begin infoBox('A Day-of-week schedule can only contain one schedule','Warning',MB_OK); Exit; end; FSchedule := self.NSScboSchedule.Text; SetScheduleSelection; Self.NSScboSchedule.Enabled := False; EnabledTime(False); end; procedure TfrmOtherSchedule.btnSchRemoveClick(Sender: TObject); begin inherited; if (FSchedule = '') or (self.NSScboSchedule.ItemIndex < 0) then exit; if self.NSScboSchedule.Text <> FSchedule then exit; Fschedule := ''; SetScheduleSelection; self.NSScboSchedule.Enabled := True; EnabledTime(True); end; procedure TfrmOtherSchedule.btnRemoveClick(Sender: TObject); var hour, min: string; idx : integer; begin FFromCheckBox := True; if lstHour.ItemIndex >= 0 then begin hour := lstHour.Items[lstHour.ItemIndex]; hour := Trim(Copy(hour,1,3)); if length(hour) = 1 then hour := '0' + Trim(hour); end; if lstMinute.ItemIndex >= 0 then begin min := lstMinute.Items[lstMinute.itemIndex]; min := Copy(min,2,2); end; if min = '' then min := '00'; if (hour='00') and (min='00') then hour := '24'; idx := FTimeSchedule.IndexOf(hour+min); if idx > -1 then FTimeSchedule.Delete(idx); FTimeSchedule.Sort; SetTimeSchedule; FFromCheckBox := False; if FTimeSchedule.Count = 0 then EnabledSch(True); end; function TfrmOtherSchedule.GetSiteMessage: string; var i: integer; rstStr: string; begin rstStr := ''; CallV('ORWNSS NSSMSG',[nil]); for i := 0 to RPCBrokerV.Results.Count - 1 do rstStr := rstStr + RPCBrokerV.Results[i]; Result := rstStr; end; procedure TfrmOtherSchedule.FormClose(Sender: TObject; var Action: TCloseAction); begin try inherited; SaveUserBounds(Self); Action := caFree; except Action := caFree; end; //frmOtherSchedule := nil; end; procedure TfrmOtherSchedule.UpdateOnFreeTextInput; var dayStr,timeStr: string; dayList: TStringList; i,Code,cnt : integer; OrigSch: string; procedure updateCheckbox(aDList: TStringList); var idx: integer; x: string; begin for idx := aDList.Count - 1 downto 0 do begin // cq hds8326 PRN entered manually split PRN from DOW to retain last DOW x := UpperCase(aDList.Strings[idx]); // added to properly process DOW when followed by a space "PRN". if Piece(x,' ',2) = 'PRN' then aDLIst.Strings[idx] := Piece(x,' ',1); // cq hds8326 if ((CheckDay(aDList[idx]) = 'SUN') or (CheckDay(aDList[idx]) = 'SU')) then begin cbo7.Checked := true; aDList[idx] := 'SU'; FDaySchedule[cbo7.tag] := 'SU'; end else if ((CheckDay(aDList[idx]) = 'MON') or (CheckDay(aDList[idx]) = 'MO')) then begin cbo1.Checked := true; aDList[idx] := 'MO'; FDaySchedule[cbo1.tag] := 'MO'; end else if ((CheckDay(aDList[idx]) = 'TUE') or (CheckDay(aDList[idx]) = 'TU')) then begin cbo2.Checked := true; aDList[idx] := 'TU'; FDaySchedule[cbo2.tag] := 'TU'; end else if ((CheckDay(aDList[idx]) = 'WED') or (CheckDay(aDList[idx]) = 'WE')) then begin cbo3.Checked := true; aDList[idx] := 'WE'; FDaySchedule[cbo3.tag] := 'WE'; end else if ((CheckDay(aDList[idx]) = 'THU') or (CheckDay(aDList[idx]) = 'TH')) then begin cbo4.Checked := true; aDList[idx] := 'TH'; FDaySchedule[cbo4.tag] := 'TH'; end else if ((CheckDay(aDList[idx]) = 'FRI') or (CheckDay(aDList[idx]) = 'FR')) then begin cbo5.Checked := true; aDList[idx] := 'FR'; FDaySchedule[cbo5.tag] := 'FR'; end else if ((CheckDay(aDList[idx]) = 'SAT') or (CheckDay(aDList[idx]) = 'SA')) then begin cbo6.Checked := true; aDList[idx] := 'SA'; FDaySchedule[cbo6.tag] := 'SA'; end else aDList.Delete(idx); end; end; begin inherited; dayStr := ''; timeStr := ''; if Length (txtSchedule.Text) = 0 then begin FOtherSchedule := ''; btnReset.Click; Exit; end; OrigSch := txtSchedule.Text; dayList := TStringList.Create; if Pos('@',txtSchedule.Text)>0 then begin dayStr := Trim(Piece(txtSchedule.Text,'@',1)); timeStr := Trim(Piece(txtSchedule.Text,'@',2)); end else begin Val(Piece(txtSchedule.Text,'-',1), i, Code); if i = 0 then begin end; // just to make compiler not give hint if Code <> 0 then dayStr := Trim(txtSchedule.Text) else timeStr := Trim(txtSchedule.Text); end; FTimeSchedule.Clear; for cnt := Low(FDaySchedule) to High(FDaySchedule) do FDaySchedule[cnt] := ''; PiecesToList(timeStr, '-', FTimeSchedule); if Length(dayStr)>0 then begin PiecesToList(dayStr, '-', dayList); cbo7.Checked := False; cbo1.Checked := False; cbo2.Checked := False; cbo3.Checked := False; cbo4.Checked := False; cbo5.Checked := False; cbo6.Checked := False; updateCheckbox(dayList); end; FOtherSchedule := txtSchedule.Text; end; procedure TfrmOtherSchedule.lstHourClick(Sender: TObject); begin inherited; if lstMinute.ItemIndex = -1 then lstMinute.ItemIndex :=0; end; procedure TfrmOtherSchedule.txtScheduleChange(Sender: TObject); begin inherited; FFromEditBox := True; if not FFromCheckBox then UpdateOnFreeTextInput; FFromEditBox := False; end; function TfrmOtherSchedule.CheckDay(ADayStr: string): string; var lng: integer; begin lng := Length(ADayStr); if lng <2 then begin result := ''; Exit; end; if (lng < 7) and ( UpperCase(aDayStr)= Copy('SUNDAY',1,lng)) then result := 'SU' else if (lng < 7) and (UpperCase(aDayStr)= Copy('MONDAY',1,lng)) then result := 'MO' else if (lng < 8) and (UpperCase(aDayStr)= Copy('TUESDAY',1,lng)) then result := 'TU' else if (lng < 10) and (UpperCase(aDayStr)= Copy('WEDNESDAY',1,lng)) then result := 'WE' else if (lng < 9) and (UpperCase(aDayStr)= Copy('THURSDAY',1,lng)) then result := 'TH' else if (lng < 7) and (UpperCase(aDayStr)= Copy('FRIDAY',1,lng)) then result := 'FR' else if (lng < 9) and (UpperCase(aDayStr)= Copy('SATURDAY',1,lng)) then result := 'SA' else result := ''; end; procedure TfrmOtherSchedule.EnabledSch(TF: boolean); begin self.GroupBox3.Enabled := TF; self.NSScboSchedule.Enabled := TF; self.btnSchAdd.Enabled := TF; self.btnSchRemove.Enabled := TF; // if TF = False then self.NSScboSchedule.Color := cl3DLight // else self.NSScboSchedule.Color := clWindow; if TF = False then self.NSScboSchedule.ItemIndex := -1; end; procedure TfrmOtherSchedule.EnabledTime(TF: boolean); begin self.GroupBox2.Enabled := TF; self.lstHour.Enabled := TF; self.lstMinute.Enabled := TF; self.btnAdd.Enabled := TF; self.btnRemove.Enabled := TF; if TF = False then begin self.lstHour.ItemIndex := -1; self.lstMinute.ItemIndex := -1; end; end; procedure TfrmOtherSchedule.lstMinuteMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; FFromCheckBox := True; if lstHour.ItemIndex < 0 then Exit; //btnAddClick(Self); FFromCheckBox := False; end; procedure TfrmOtherSchedule.NSScboScheduleExit(Sender: TObject); begin inherited; if Pos(CRLF, NSScboSchedule.Text)> 0 then begin NSScboSchedule.Text := ''; NSScboSchedule.ItemIndex := -1; Application.MessageBox('Schedule field cannot contain a control character. Please select a valid unique schedule from the list.' +CRLF + 'Or remove the schedule text from the schedule list and select specific times from the administration times list.', 'Incorrect Schedule.'); NSScboSchedule.SetFocus; end; if (NSScboSchedule.Text <> '') and (NSScboSchedule.ItemIndex = -1) then begin Application.MessageBox('Please select a valid unique schedule from the list.' +CRLF + 'Or remove the schedule text from the schedule list and select specific times from the administration times list.', 'Incorrect Schedule.'); NSSCboSchedule.Text := ''; NSScboSchedule.SetFocus; end; end; procedure TfrmOtherSchedule.NSScboScheduleKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_BACK) and (NSScboSchedule.Text = '') then NSScboSchedule.itemindex:= -1; end; procedure TfrmOtherSchedule.lstMinuteKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key=VK_RETURN) then begin FFromCheckBox := True; if lstHour.ItemIndex < 0 then Exit; //btnAddClick(Self); FFromCheckBox := False; end; end; procedure TfrmOtherSchedule.Button1Click(Sender: TObject); begin inherited; cbo1.Checked := true; cbo2.Checked := true; cbo3.Checked := true; cbo4.Checked := true; cbo5.Checked := true; cbo6.Checked := true; cbo7.Checked := true; end; end.
{ * The contents of this file are subject to the Initial * Developer's Public License Version 1.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.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl. * * Software distributed under the License is distributed AS IS, * WITHOUT WARRANTY OF ANY KIND, either express or implied. * See the License for the specific language governing rights * and limitations under the License. * * The Original Code was created by Adriano dos Santos Fernandes. * * Copyright (c) 2014 Adriano dos Santos Fernandes <adrianosf at gmail.com> * and all contributors signed below. * * All Rights Reserved. * Contributor(s): ______________________________________. } unit PascalClasses; interface uses CalcPascalApi; type MyStatusImpl = class(StatusImpl) constructor create; procedure dispose(); override; function getCode(): Integer; override; procedure setCode(n: Integer); override; private code: Integer; end; MyCalculatorImpl = class(CalculatorImpl) constructor create; procedure dispose(); override; function sum(status: Status; n1: Integer; n2: Integer): Integer; override; function getMemory(): Integer; override; procedure setMemory(n: Integer); override; procedure sumAndStore(status: Status; n1: Integer; n2: Integer); override; private memory: Integer; end; MyCalculator2Impl = class(Calculator2Impl) constructor create; procedure dispose(); override; function sum(status: Status; n1: Integer; n2: Integer): Integer; override; function getMemory(): Integer; override; procedure setMemory(n: Integer); override; procedure sumAndStore(status: Status; n1: Integer; n2: Integer); override; function multiply(status: Status; n1: Integer; n2: Integer): Integer; override; procedure copyMemory(calculator: Calculator); override; procedure copyMemory2(address: IntegerPtr); override; private memory: Integer; end; MyBrokenCalculatorImpl = class(MyCalculatorImpl) function sum(status: Status; n1: Integer; n2: Integer): Integer; override; end; MyFactoryImpl = class(FactoryImpl) procedure dispose(); override; function createStatus(): Status; override; function createCalculator(status: Status): Calculator; override; function createCalculator2(status: Status): Calculator2; override; function createBrokenCalculator(status: Status): Calculator; override; end; implementation //-------------------------------------- // MyStatusImpl constructor MyStatusImpl.create; begin inherited; code := 0; end; procedure MyStatusImpl.dispose(); begin self.destroy(); end; function MyStatusImpl.getCode(): Integer; begin Result := code; end; procedure MyStatusImpl.setCode(n: Integer); begin code := n; end; //-------------------------------------- // MyCalculatorImpl constructor MyCalculatorImpl.create; begin inherited; memory := 0; end; procedure MyCalculatorImpl.dispose(); begin self.destroy(); end; function MyCalculatorImpl.sum(status: Status; n1: Integer; n2: Integer): Integer; begin if (n1 + n2 > 1000) then raise CalcException.create(Status.ERROR_1) else Result := n1 + n2; end; function MyCalculatorImpl.getMemory(): Integer; begin Result := memory; end; procedure MyCalculatorImpl.setMemory(n: Integer); begin memory := n; end; procedure MyCalculatorImpl.sumAndStore(status: Status; n1: Integer; n2: Integer); begin setMemory(sum(status, n1, n2)); end; //-------------------------------------- // MyCalculator2Impl constructor MyCalculator2Impl.create; begin inherited; memory := 0; end; procedure MyCalculator2Impl.dispose(); begin self.destroy(); end; function MyCalculator2Impl.sum(status: Status; n1: Integer; n2: Integer): Integer; begin if (n1 + n2 > 1000) then raise CalcException.create(Status.ERROR_1) else Result := n1 + n2; end; function MyCalculator2Impl.getMemory(): Integer; begin Result := memory; end; procedure MyCalculator2Impl.setMemory(n: Integer); begin memory := n; end; procedure MyCalculator2Impl.sumAndStore(status: Status; n1: Integer; n2: Integer); begin setMemory(sum(status, n1, n2)); end; function MyCalculator2Impl.multiply(status: Status; n1: Integer; n2: Integer): Integer; begin Result := n1 * n2; end; procedure MyCalculator2Impl.copyMemory(calculator: Calculator); begin setMemory(calculator.getMemory()); end; procedure MyCalculator2Impl.copyMemory2(address: IntegerPtr); begin setMemory(address^); end; //-------------------------------------- // MyBrokenCalculatorImpl function MyBrokenCalculatorImpl.sum(status: Status; n1: Integer; n2: Integer): Integer; begin Result := inherited sum(status, n1, n2) + 1; end; //-------------------------------------- // MyFactoryImpl procedure MyFactoryImpl.dispose(); begin self.destroy(); end; function MyFactoryImpl.createStatus(): Status; begin Result := MyStatusImpl.create; end; function MyFactoryImpl.createCalculator(status: Status): Calculator; begin Result := MyCalculatorImpl.create; end; function MyFactoryImpl.createCalculator2(status: Status): Calculator2; begin Result := MyCalculator2Impl.create; end; function MyFactoryImpl.createBrokenCalculator(status: Status): Calculator; begin Result := MyBrokenCalculatorImpl.create; end; end.
unit ConnectionModule; interface uses Aurelius.Drivers.Interfaces, Aurelius.SQL.SQLite, Aurelius.Schema.SQLite, Aurelius.Drivers.SQLite, System.SysUtils, System.Classes, Data.DB, Aurelius.Bind.Dataset; type Tdb = class(TDataModule) private class var FDBFile: string; public class function CreateConnection(DBFile: string = ''): IDBConnection; class function CreateFactory: IDBConnectionFactory; end; var DM: Tdb; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses Aurelius.Drivers.Base; {$R *.dfm} { Tdb } class function Tdb.CreateConnection(DBFile: string = ''): IDBConnection; begin FDBFile := DBFile; Result := TSQLiteNativeConnectionAdapter.Create(FDBFile); (Result as TSQLiteNativeConnectionAdapter).EnableForeignKeys; end; class function Tdb.CreateFactory: IDBConnectionFactory; begin Result := TDBConnectionFactory.Create( function: IDBConnection begin Result := CreateConnection(FDBFile); end ); end; end.
unit SearchDaughterCategoriesQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, SearchCategoriesPathQuery; type TQuerySearchDaughterCategories = class(TQueryBase) private FW: TSearchCategoriesPathW; { Private declarations } public constructor Create(AOwner: TComponent); override; function SearchEx(ACategoryID: Integer): Integer; property W: TSearchCategoriesPathW read FW; { Public declarations } end; implementation {$R *.dfm} constructor TQuerySearchDaughterCategories.Create(AOwner: TComponent); begin inherited; FW := TSearchCategoriesPathW.Create(FDQuery); end; function TQuerySearchDaughterCategories.SearchEx(ACategoryID: Integer): Integer; begin Assert(ACategoryID > 0); Result := Search([W.ID.FieldName], [ACategoryID]) end; end.
unit func_ccreg_set32; interface implementation type TEnum32 = (_a00,_a01,_a02,_a03,_a04,_a05,_a06,_a07,_a08,_a09,_a10,_a11,_a12,_a13,_a14,_a15,_a16,_a17,_a18,_a19,_a20,_a21,_a22,_a23,_a24,_a25,_a26,_a27,_a28,_a29,_a30,_a31); TSet32 = packed set of TEnum32; function F(a: TSet32): TSet32; external 'CAT' name 'func_ccreg_set32'; procedure Test; var a, r: TSet32; begin a := [_a01]; R := F(a); Assert(a = r); end; initialization Test(); finalization end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Data.DBXMSSQLMetaDataReader; interface uses Data.DBXCommon, Data.DBXCommonTable, Data.DBXMetaDataReader, Data.DBXPlatform, Data.DBXSqlScanner; type /// <summary> TDBXMsSqlCustomMetaDataProvider contains custom code for MsSQL. /// </summary> /// <remarks> The synonyms are reported in a strange format in sys.synonyms. /// </remarks> TDBXMsSqlCustomMetaDataReader = class(TDBXBaseMetaDataReader) public type TDBXMsSqlSynonymTableCursor = class(TDBXCustomMetaDataTable) public constructor Create(const Context: TDBXProviderContext; const Scanner: TDBXSqlScanner; const Columns: TDBXValueTypeArray; const Cursor: TDBXTable); destructor Destroy; override; function Next: Boolean; override; protected function FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer; override; function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override; private procedure ParseBaseObject; private FScanner: TDBXSqlScanner; FCatalog: string; FSchema: string; FTable: string; FRow: TDBXSingleValueRow; end; public destructor Destroy; override; function FetchSynonyms(const Catalog: string; const Schema: string; const Synonym: string): TDBXTable; override; protected function IsSPReturnCodeSupported: Boolean; override; private function CreateScanner: TDBXSqlScanner; private FScanner: TDBXSqlScanner; end; TDBXMsSqlMetaDataReader = class(TDBXMsSqlCustomMetaDataReader) public function FetchPackages(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable; override; function FetchPackageProcedures(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ProcedureType: string): TDBXTable; override; function FetchPackageProcedureParameters(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ParameterName: string): TDBXTable; override; function FetchPackageSources(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable; override; protected function AreCatalogsSupported: Boolean; override; function AreSchemasSupported: Boolean; override; function GetProductName: string; override; function GetSqlIdentifierQuotePrefix: string; override; function GetSqlIdentifierQuoteSuffix: string; override; function GetTableType: string; override; function GetViewType: string; override; function GetSystemTableType: string; override; function GetSystemViewType: string; override; function GetSynonymType: string; override; function IsLowerCaseIdentifiersSupported: Boolean; override; function IsParameterMetadataSupported: Boolean; override; function GetSqlForCatalogs: string; override; function GetSqlForSchemas: string; override; function GetSqlForTables: string; override; function GetSqlForViews: string; override; function GetSqlForColumns: string; override; function GetSqlForColumnConstraints: string; override; function GetSqlForIndexes: string; override; function GetSqlForIndexColumns: string; override; function GetSqlForForeignKeys: string; override; function GetSqlForForeignKeyColumns: string; override; function GetSqlForSynonyms: string; override; function GetSqlForProcedures: string; override; function GetSqlForProcedureSources: string; override; function GetSqlForProcedureParameters: string; override; function GetSqlForUsers: string; override; function GetSqlForRoles: string; override; function GetDataTypeDescriptions: TDBXDataTypeDescriptionArray; override; function GetReservedWords: TDBXStringArray; override; end; implementation uses Data.DBXMetaDataNames, System.SysUtils; destructor TDBXMsSqlCustomMetaDataReader.Destroy; begin FreeAndNil(FScanner); inherited Destroy; end; function TDBXMsSqlCustomMetaDataReader.FetchSynonyms(const Catalog: string; const Schema: string; const Synonym: string): TDBXTable; var ParameterNames, ParameterValues: TDBXStringArray; Cursor: TDBXTable; Columns: TDBXValueTypeArray; begin SetLength(ParameterNames,3); ParameterNames[0] := TDBXParameterName.CatalogName; ParameterNames[1] := TDBXParameterName.SchemaName; ParameterNames[2] := TDBXParameterName.SynonymName; SetLength(ParameterValues,3); ParameterValues[0] := Catalog; ParameterValues[1] := Schema; ParameterValues[2] := Synonym; Cursor := Context.ExecuteQuery(SqlForSynonyms, ParameterNames, ParameterValues); Columns := TDBXMetaDataCollectionColumns.CreateSynonymsColumns; Result := TDBXMsSqlCustomMetaDataReader.TDBXMsSqlSynonymTableCursor.Create(Context, CreateScanner, Columns, Cursor); end; function TDBXMsSqlCustomMetaDataReader.CreateScanner: TDBXSqlScanner; begin if FScanner = nil then FScanner := TDBXSqlScanner.Create(SqlIdentifierQuoteChar, SqlIdentifierQuotePrefix, SqlIdentifierQuoteSuffix); Result := FScanner; end; function TDBXMsSqlCustomMetaDataReader.IsSPReturnCodeSupported: Boolean; begin Result := True; end; constructor TDBXMsSqlCustomMetaDataReader.TDBXMsSqlSynonymTableCursor.Create(const Context: TDBXProviderContext; const Scanner: TDBXSqlScanner; const Columns: TDBXValueTypeArray; const Cursor: TDBXTable); begin inherited Create(Context, TDBXMetaDataCollectionName.Synonyms, Columns, Cursor); self.FScanner := Scanner; FRow := TDBXSingleValueRow.Create; FRow.Columns := CopyColumns; end; destructor TDBXMsSqlCustomMetaDataReader.TDBXMsSqlSynonymTableCursor.Destroy; begin FreeAndNil(FRow); inherited Destroy; end; function TDBXMsSqlCustomMetaDataReader.TDBXMsSqlSynonymTableCursor.FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer; var UseOrdinal: Integer; begin UseOrdinal := Ordinal; if Ordinal >= 3 then UseOrdinal := Ordinal - 3; Result := inherited FindStringSize(UseOrdinal, SourceColumns); end; function TDBXMsSqlCustomMetaDataReader.TDBXMsSqlSynonymTableCursor.Next: Boolean; var ReturnValue: Boolean; begin FCatalog := NullString; FSchema := NullString; FTable := NullString; ReturnValue := inherited Next; if ReturnValue then begin ParseBaseObject; if FCatalog.IsEmpty then FRow.Value[3].SetNull else FRow.Value[3].AsString := FCatalog; if FSchema.IsEmpty then FRow.Value[4].SetNull else FRow.Value[4].AsString := FSchema; if FTable.IsEmpty then FRow.Value[5].SetNull else FRow.Value[5].AsString := FTable; end; Result := ReturnValue; end; function TDBXMsSqlCustomMetaDataReader.TDBXMsSqlSynonymTableCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue; begin case Ordinal of 3, 4, 5: Exit(FRow.Value[Ordinal]); end; Result := inherited GetWritableValue(Ordinal); end; procedure TDBXMsSqlCustomMetaDataReader.TDBXMsSqlSynonymTableCursor.ParseBaseObject; var Pattern: string; Token: Integer; begin Pattern := inherited GetWritableValue(3).AsString; FScanner.Init(Pattern); Token := FScanner.NextToken; while Token = TDBXSqlScanner.TokenId do begin FCatalog := FSchema; FSchema := FTable; FTable := FScanner.Id; Token := FScanner.NextToken; if (Token = TDBXSqlScanner.TokenSymbol) and (FScanner.Symbol = '.') then Token := FScanner.NextToken; end; if FSchema.IsEmpty then FSchema := Value[1].AsString; if FCatalog.IsEmpty then FCatalog := Value[0].AsString; end; function TDBXMsSqlMetaDataReader.AreCatalogsSupported: Boolean; begin Result := True; end; function TDBXMsSqlMetaDataReader.AreSchemasSupported: Boolean; begin Result := True; end; function TDBXMsSqlMetaDataReader.GetProductName: string; begin Result := 'Microsoft SQL Server'; end; function TDBXMsSqlMetaDataReader.GetSqlIdentifierQuotePrefix: string; begin Result := '['; end; function TDBXMsSqlMetaDataReader.GetSqlIdentifierQuoteSuffix: string; begin Result := ']'; end; function TDBXMsSqlMetaDataReader.GetTableType: string; begin Result := 'U'; end; function TDBXMsSqlMetaDataReader.GetViewType: string; begin Result := 'V'; end; function TDBXMsSqlMetaDataReader.GetSystemTableType: string; begin Result := 'S'; end; function TDBXMsSqlMetaDataReader.GetSystemViewType: string; begin Result := 'V'; end; function TDBXMsSqlMetaDataReader.GetSynonymType: string; begin Result := 'SN'; end; function TDBXMsSqlMetaDataReader.IsLowerCaseIdentifiersSupported: Boolean; begin Result := True; end; function TDBXMsSqlMetaDataReader.IsParameterMetadataSupported: Boolean; begin Result := True; end; function TDBXMsSqlMetaDataReader.GetSqlForCatalogs: string; begin Result := 'SELECT name FROM master..sysdatabases'; end; function TDBXMsSqlMetaDataReader.GetSqlForSchemas: string; var CurrentVersion: string; begin CurrentVersion := Version; if CurrentVersion >= '09.00.0000' then Result := 'SELECT DISTINCT DB_NAME(), SCHEMA_NAME(schema_id) ' + 'FROM sys.objects ' + 'WHERE type IN (''U'', ''V'', ''S'', ''P'', ''FN'', ''IF'', ''TF'') ' + 'ORDER BY 1, 2' else Result := 'SELECT DISTINCT DB_NAME(), USER_NAME(uid) ' + 'FROM dbo.sysobjects ' + 'WHERE type IN (''U'', ''V'', ''S'', ''P'', ''FN'', ''IF'', ''TF'') ' + 'ORDER BY 1, 2'; end; function TDBXMsSqlMetaDataReader.GetSqlForTables: string; var CurrentVersion: string; begin CurrentVersion := Version; if CurrentVersion >= '09.00.0000' then Result := 'SELECT DB_NAME(), SCHEMA_NAME(a.schema_id), a.name, CASE WHEN a.type=''U'' THEN ''TABLE'' WHEN s.type=''V'' THEN ''SYSTEM VIEW'' WHEN a.type=''V'' THEN ''VIEW'' WHEN a.type=''S'' THEN ''SYSTEM TABLE'' WHEN a.type=''SN'' THEN ''SYNONYM'' END ' + 'FROM sys.all_objects a LEFT OUTER JOIN sys.system_objects s ON a.object_id=s.object_id ' + 'WHERE (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (SCHEMA_NAME(a.schema_id) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (a.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' + ' AND (a.type = :TABLES OR a.type = :VIEWS OR a.type = :SYSTEM_TABLES OR s.type = :SYSTEM_VIEWS OR a.type = :SYNONYMS) ' + 'ORDER BY 1, 2, 3' else Result := 'SELECT DB_NAME(), USER_NAME(uid), name, CASE type WHEN ''U'' THEN ''TABLE'' WHEN ''V'' THEN ''VIEW'' WHEN ''S'' THEN ''SYSTEM TABLE'' WHEN ''SN'' THEN ''SYNONYM'' END ' + 'FROM dbo.sysobjects ' + 'WHERE (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' + ' AND (type = :TABLES OR type = :VIEWS OR type = :SYSTEM_TABLES OR type = :SYNONYMS) ' + 'ORDER BY 1, 2, 3'; end; function TDBXMsSqlMetaDataReader.GetSqlForViews: string; begin Result := 'SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, VIEW_DEFINITION ' + 'FROM INFORMATION_SCHEMA.VIEWS ' + 'WHERE (TABLE_CATALOG = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (TABLE_SCHEMA = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (TABLE_NAME = :VIEW_NAME OR (:VIEW_NAME IS NULL)) ' + 'ORDER BY 1,2,3'; end; function TDBXMsSqlMetaDataReader.GetSqlForColumns: string; var CurrentVersion: string; begin CurrentVersion := Version; if CurrentVersion >= '09.00.0000' then Result := 'SELECT DB_NAME(), SCHEMA_NAME(O.uid), O.name, C.name, T.name, CONVERT(INT,C.prec), CONVERT(INT,C.scale), CONVERT(INT,C.colid), CASE WHEN COM.text LIKE ''((%))'' THEN SUBSTRING(COM.text,3,LEN(COM.text)-4) WHEN COM.text LIKE ''(''''%'''')'' THEN SUBSTRING(COM.text,' + '2,LEN(COM.text)-2) ELSE COM.text END AS DEFAULT_VALUE, CONVERT(BIT, C.isnullable), CONVERT(BIT, COLUMNPROPERTY(O.id, C.name, ''ISIDENTITY'')), NULL ' + 'FROM sysobjects O INNER JOIN syscolumns C ON O.id=C.id INNER JOIN systypes T ON C.xusertype = T.xusertype LEFT OUTER JOIN syscomments COM ON CDEFAULT=COM.id ' + 'WHERE OBJECTPROPERTY(O.id,''IsView'')+OBJECTPROPERTY(O.id,''IsUserTable'') > 0 AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (SCHEMA_NAME(O.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (O.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' + 'ORDER BY 1, 2, 3, C.colid' else Result := 'SELECT DB_NAME(), USER_NAME(O.uid), O.name, C.name, T.name, CONVERT(INT,C.prec), CONVERT(INT,C.scale), CONVERT(INT,C.colid), CASE WHEN COM.text LIKE ''(%)'' THEN SUBSTRING(COM.text,2,LEN(COM.text)-2) WHEN COM.text LIKE ''(''''%'''')'' THEN SUBSTRING(COM.text,2,LE' + 'N(COM.text)-2) ELSE COM.text END AS DEFAULT_VALUE, CONVERT(BIT, C.isnullable), CONVERT(BIT, COLUMNPROPERTY(O.id, C.name, ''ISIDENTITY'')), NULL ' + 'FROM sysobjects O INNER JOIN syscolumns C ON O.id=C.id INNER JOIN systypes T ON C.xusertype = T.xusertype LEFT OUTER JOIN syscomments COM ON CDEFAULT=COM.id ' + 'WHERE OBJECTPROPERTY(O.id,''IsView'')+OBJECTPROPERTY(O.id,''IsUserTable'') > 0 AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(O.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (O.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' + 'ORDER BY 1, 2, 3, C.colid'; end; function TDBXMsSqlMetaDataReader.GetSqlForColumnConstraints: string; var CurrentVersion: string; begin CurrentVersion := Version; if CurrentVersion >= '09.00.0000' then Result := 'SELECT DB_NAME(), SCHEMA_NAME(T.uid), T.name, CON.name AS CONSTRAINT_NAME, COL.name AS COLUMN_NAME ' + 'FROM sysobjects T, syscolumns COL, sysobjects CON ' + 'WHERE T.id=CON.parent_obj AND CON.id=COL.cdefault ' + ' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (SCHEMA_NAME(T.uid)=:SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (T.name=:TABLE_NAME OR (:TABLE_NAME IS NULL))' else Result := 'SELECT DB_NAME(), USER_NAME(T.uid), T.name, CON.name AS CONSTRAINT_NAME, COL.name AS COLUMN_NAME ' + 'FROM sysobjects T, syscolumns COL, sysobjects CON ' + 'WHERE T.id=CON.parent_obj AND CON.id=COL.cdefault ' + ' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(T.uid)=:SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (T.name=:TABLE_NAME OR (:TABLE_NAME IS NULL))'; end; function TDBXMsSqlMetaDataReader.GetSqlForIndexes: string; var CurrentVersion: string; begin CurrentVersion := Version; if CurrentVersion >= '09.00.0000' then Result := 'SELECT DISTINCT DB_NAME(), SCHEMA_NAME(O.uid), O.name, I.name, CASE WHEN INDEXPROPERTY(I.id, I.name, ''IsUnique'') > 0 THEN I.name ELSE NULL END, CONVERT(BIT, COALESCE(OBJECTPROPERTY(object_id(I.name), ''IsPrimaryKey''), 0)), CONVERT(BIT, COALESCE(INDEXPROPE' + 'RTY(I.id, I.name, ''IsUnique''), 0)), CONVERT(BIT, 1) ' + 'FROM sysobjects O, sysindexes I, sysindexkeys IK ' + 'WHERE O.type IN (''U'') and I.id = O.id AND O.id = IK.id AND I.indid = IK.indid AND IK.keyno <= I.keycnt ' + ' AND (DB_NAME() = :CATALOG_NAME or (:CATALOG_NAME IS NULL)) AND (SCHEMA_NAME(O.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (O.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' + 'ORDER BY 1, 2, 3, 4' else Result := 'SELECT DISTINCT DB_NAME(), USER_NAME(O.uid), O.name, I.name, CASE WHEN INDEXPROPERTY(I.id, I.name, ''IsUnique'') > 0 THEN I.name ELSE NULL END, CONVERT(BIT, COALESCE(OBJECTPROPERTY(object_id(I.name), ''IsPrimaryKey''), 0)), CONVERT(BIT, COALESCE(INDEXPROPERT' + 'Y(I.id, I.name, ''IsUnique''), 0)), CONVERT(BIT, 1) ' + 'FROM sysobjects O, sysindexes I, sysindexkeys IK ' + 'WHERE O.type IN (''U'') and I.id = O.id AND O.id = IK.id AND I.indid = IK.indid AND IK.keyno <= I.keycnt AND I.status & 0x800000 = 0 ' + ' AND (DB_NAME() = :CATALOG_NAME or (:CATALOG_NAME IS NULL)) AND (USER_NAME(O.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (O.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' + 'ORDER BY 1, 2, 3, 4'; end; function TDBXMsSqlMetaDataReader.GetSqlForIndexColumns: string; var CurrentVersion: string; begin CurrentVersion := Version; if CurrentVersion >= '09.00.0000' then Result := 'SELECT DISTINCT DB_NAME(), SCHEMA_NAME(O.uid), O.name, I.name, C.name, CONVERT(INT, IK.keyno), CONVERT(BIT, 1 - INDEXKEY_PROPERTY(O.id, I.indid, IK.keyno, ''IsDescending'')) ' + 'FROM sysobjects O, sysindexes I, sysindexkeys IK, syscolumns C ' + 'WHERE O.type IN (''U'') AND I.id = O.id AND O.id = IK.id AND O.id = C.id AND C.colid = IK.colid AND I.indid = IK.indid AND IK.keyno <= I.keycnt AND ' + '(DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (SCHEMA_NAME(O.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (O.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (I.name = :INDEX_NAME OR (:INDEX_NAME IS NULL)) ' + 'ORDER BY 1, 2, 3, 4, 6' else Result := 'SELECT DISTINCT DB_NAME(), USER_NAME(O.uid), O.name, I.name, C.name, CONVERT(INT, IK.keyno), CONVERT(BIT, 1 - INDEXKEY_PROPERTY(O.id, I.indid, IK.keyno, ''IsDescending'')) ' + 'FROM sysobjects O, sysindexes I, sysindexkeys IK, syscolumns C ' + 'WHERE O.type IN (''U'') AND I.id = O.id AND O.id = IK.id AND O.id = C.id AND C.colid = IK.colid AND I.indid = IK.indid AND IK.keyno <= I.keycnt AND ' + '(DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(O.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (O.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (I.name = :INDEX_NAME OR (:INDEX_NAME IS NULL)) ' + 'ORDER BY 1, 2, 3, 4, 6'; end; function TDBXMsSqlMetaDataReader.GetSqlForForeignKeys: string; var CurrentVersion: string; begin CurrentVersion := Version; if CurrentVersion >= '09.00.0000' then Result := 'SELECT DB_NAME(), SCHEMA_NAME(FT.schema_id), FT.name, FK.name ' + 'FROM sys.foreign_keys FK, sys.tables FT ' + 'WHERE FK.parent_object_id = FT.object_id ' + ' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (SCHEMA_NAME(FT.schema_id) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (FT.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' + 'ORDER BY 1, 2, 3, 4' else Result := 'SELECT DB_NAME(), USER_NAME(FT.uid), FT.name, FK.name ' + 'FROM sysreferences R, sysobjects FK, sysobjects FT ' + 'WHERE R.fkeyid=FT.id AND R.constid=FK.id ' + ' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(FT.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (FT.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' + 'ORDER BY 1, 2, 3, 4'; end; function TDBXMsSqlMetaDataReader.GetSqlForForeignKeyColumns: string; var CurrentVersion: string; begin CurrentVersion := Version; if CurrentVersion >= '09.00.0000' then Result := 'SELECT DB_NAME(), SCHEMA_NAME(FT.schema_id), FT.name, FK.name, FC.name, DB_NAME(), SCHEMA_NAME(PT.schema_id), PT.name, I.name, PC.name, FKC.constraint_column_id ' + 'FROM sys.foreign_keys FK, sys.foreign_key_columns FKC, sys.tables PT, sys.tables FT, sys.columns PC, sys.columns FC, sys.indexes I ' + 'WHERE FK.parent_object_id = FT.object_id AND FK.referenced_object_id = PT.object_id AND FKC.constraint_object_id = FK.object_id AND FKC.referenced_column_id = PC.column_id ' + ' AND FKC.parent_object_id = FT.object_id AND FKC.parent_column_id = FC.column_id AND PC.object_id = PT.object_id AND FC.object_id = FT.object_id AND PC.object_id = I.object_id AND FK.key_index_id = I.index_id ' + ' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (SCHEMA_NAME(FT.schema_id) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (FT.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (FK.name = :FOREIGN_KEY_NAME OR (:FOREIGN_KEY_NAME IS NULL)) ' + ' AND (DB_NAME() = :PRIMARY_CATALOG_NAME OR (:PRIMARY_CATALOG_NAME IS NULL)) AND (SCHEMA_NAME(PT.schema_id) = :PRIMARY_SCHEMA_NAME OR (:PRIMARY_SCHEMA_NAME IS NULL)) AND (PT.name = :PRIMARY_TABLE_NAME OR (:PRIMARY_TABLE_NAME IS NULL)) AND (I.name = :PRIMAR' + 'Y_KEY_NAME OR (:PRIMARY_KEY_NAME IS NULL)) ' + 'ORDER BY 1,2,3,4,FKC.constraint_column_id' else Result := 'SELECT DB_NAME(), USER_NAME(FT.uid), FT.name, FK.name, FC.name, DB_NAME(), USER_NAME(PT.uid), PT.name, I.name, PC.name, F.keyno ' + 'FROM sysforeignkeys F, sysobjects FK, sysobjects FT, syscolumns FC, sysobjects PT, syscolumns PC, sysreferences R, sysindexes I ' + 'WHERE F.constid=FK.id AND F.fkeyid=FT.id AND F.rkeyid=PT.id AND F.fkeyid=FC.id AND F.fkey=FC.colid AND F.rkeyid=PC.id AND F.rkey=PC.colid ' + ' AND R.constid=F.constid AND F.rkeyid=I.id AND R.rkeyindid=I.indid ' + ' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(FT.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (FT.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (FK.name = :FOREIGN_KEY_NAME OR (:FOREIGN_KEY_NAME IS NULL)) ' + ' AND (DB_NAME() = :PRIMARY_CATALOG_NAME OR (:PRIMARY_CATALOG_NAME IS NULL)) AND (USER_NAME(PT.uid) = :PRIMARY_SCHEMA_NAME OR (:PRIMARY_SCHEMA_NAME IS NULL)) AND (PT.name = :PRIMARY_TABLE_NAME OR (:PRIMARY_TABLE_NAME IS NULL)) AND (I.name = :PRIMARY_KEY_NA' + 'ME OR (:PRIMARY_KEY_NAME IS NULL)) ' + 'ORDER BY 1,2,3,4,F.keyno'; end; function TDBXMsSqlMetaDataReader.GetSqlForSynonyms: string; var CurrentVersion: string; begin CurrentVersion := Version; if CurrentVersion >= '09.00.0000' then Result := 'SELECT DB_NAME(), SCHEMA_NAME(schema_id), name, base_object_name ' + 'FROM sys.synonyms ' + 'WHERE (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(object_id) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (name = :SYNONYM_NAME OR (:SYNONYM_NAME IS NULL)) ' + 'ORDER BY 1,2,3' else Result := 'SELECT NULL, NULL, NULL, NULL ' + 'FROM sysobjects ' + 'WHERE (:CATALOG_NAME IS NULL) AND (:SCHEMA_NAME IS NULL) AND (:SYNONYM_NAME IS NULL) ' + ' AND 1=2'; end; function TDBXMsSqlMetaDataReader.GetSqlForProcedures: string; begin Result := 'SELECT SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, ROUTINE_TYPE ' + 'FROM INFORMATION_SCHEMA.ROUTINES ' + 'WHERE (SPECIFIC_CATALOG = :CATALOG_NAME or (:CATALOG_NAME IS NULL)) AND (SPECIFIC_SCHEMA = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (SPECIFIC_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (ROUTINE_TYPE = ''PROCEDURE'') ' + 'ORDER BY ROUTINE_CATALOG, ROUTINE_SCHEMA, ROUTINE_NAME'; end; function TDBXMsSqlMetaDataReader.GetSqlForProcedureSources: string; var CurrentVersion: string; begin CurrentVersion := Version; if CurrentVersion >= '09.00.0000' then Result := 'SELECT SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, ROUTINE_TYPE, CASE WHEN LEN(ROUTINE_DEFINITION) > 4000 THEN LEFT(ROUTINE_DEFINITION,4000)+'' ...'' ELSE ROUTINE_DEFINITION END, EXTERNAL_NAME ' + 'FROM INFORMATION_SCHEMA.ROUTINES ' + 'WHERE (SPECIFIC_CATALOG = :CATALOG_NAME or (:CATALOG_NAME IS NULL)) AND (SPECIFIC_SCHEMA = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (SPECIFIC_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) ' + 'ORDER BY ROUTINE_CATALOG, ROUTINE_SCHEMA, ROUTINE_NAME' else Result := 'SELECT SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, ROUTINE_TYPE, CASE WHEN LEN(ROUTINE_DEFINITION) > 2950 THEN LEFT(ROUTINE_DEFINITION,2950)+'' ...'' ELSE ROUTINE_DEFINITION END, EXTERNAL_NAME ' + 'FROM INFORMATION_SCHEMA.ROUTINES ' + 'WHERE (SPECIFIC_CATALOG = :CATALOG_NAME or (:CATALOG_NAME IS NULL)) AND (SPECIFIC_SCHEMA = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (SPECIFIC_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) ' + 'ORDER BY ROUTINE_CATALOG, ROUTINE_SCHEMA, ROUTINE_NAME'; end; function TDBXMsSqlMetaDataReader.GetSqlForProcedureParameters: string; begin Result := 'SELECT SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, PARAMETER_NAME, CASE WHEN IS_RESULT=''YES'' THEN ''RESULT'' ELSE PARAMETER_MODE END, DATA_TYPE, COALESCE(CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION), NUMERIC_SCALE, ORDINAL_POSITION, CONVERT(BIT,1) ' + 'FROM INFORMATION_SCHEMA.PARAMETERS ' + 'WHERE (SPECIFIC_CATALOG = :CATALOG_NAME or (:CATALOG_NAME IS NULL)) AND (SPECIFIC_SCHEMA = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (SPECIFIC_NAME = :PROCEDURE_NAME or (:PROCEDURE_NAME IS NULL)) AND (PARAMETER_NAME = :PARAMETER_NAME or (:PARAMETER_NAME' + ' IS NULL)) ' + 'UNION ALL ' + 'SELECT TOP 1 '''', '''', '''', ''@RETURN_VALUE'', ''RESULT'', ''int'', 10, 0, 0, CONVERT(BIT,1) FROM INFORMATION_SCHEMA.PARAMETERS ' + 'ORDER BY 1, 2, 3, 9'; end; function TDBXMsSqlMetaDataReader.FetchPackages(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable; var Columns: TDBXValueTypeArray; begin Columns := TDBXMetaDataCollectionColumns.CreatePackagesColumns; Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Packages, Columns); end; function TDBXMsSqlMetaDataReader.FetchPackageProcedures(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ProcedureType: string): TDBXTable; var Columns: TDBXValueTypeArray; begin Columns := TDBXMetaDataCollectionColumns.CreatePackageProceduresColumns; Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedures, Columns); end; function TDBXMsSqlMetaDataReader.FetchPackageProcedureParameters(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ParameterName: string): TDBXTable; var Columns: TDBXValueTypeArray; begin Columns := TDBXMetaDataCollectionColumns.CreatePackageProcedureParametersColumns; Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedureParameters, Columns); end; function TDBXMsSqlMetaDataReader.FetchPackageSources(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable; var Columns: TDBXValueTypeArray; begin Columns := TDBXMetaDataCollectionColumns.CreatePackageSourcesColumns; Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageSources, Columns); end; function TDBXMsSqlMetaDataReader.GetSqlForUsers: string; begin Result := 'SELECT name FROM sysusers WHERE islogin=1 AND (sid IS NOT NULL) ORDER BY 1'; end; function TDBXMsSqlMetaDataReader.GetSqlForRoles: string; begin Result := 'SELECT name FROM sysusers WHERE uid != 0 AND (issqlrole=1 OR isapprole=1) ORDER BY 1'; end; function TDBXMsSqlMetaDataReader.GetDataTypeDescriptions: TDBXDataTypeDescriptionArray; var Types: TDBXDataTypeDescriptionArray; begin SetLength(Types,38); Types[0] := TDBXDataTypeDescription.Create('smallint', TDBXDataTypes.Int16Type, 5, 'smallint', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[1] := TDBXDataTypeDescription.Create('int', TDBXDataTypes.Int32Type, 10, 'int', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[2] := TDBXDataTypeDescription.Create('real', TDBXDataTypes.SingleType, 7, 'real', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[3] := TDBXDataTypeDescription.Create('float', TDBXDataTypes.DoubleType, 53, 'float({0})', 'Precision', -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[4] := TDBXDataTypeDescription.Create('money', TDBXDataTypes.BcdType, 19, 'money', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[5] := TDBXDataTypeDescription.Create('smallmoney', TDBXDataTypes.BcdType, 10, 'smallmoney', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[6] := TDBXDataTypeDescription.Create('bit', TDBXDataTypes.BooleanType, 1, 'bit', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[7] := TDBXDataTypeDescription.Create('tinyint', TDBXDataTypes.UInt8Type, 3, 'tinyint', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.Unsigned); Types[8] := TDBXDataTypeDescription.Create('bigint', TDBXDataTypes.Int64Type, 19, 'bigint', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[9] := TDBXDataTypeDescription.Create('timestamp', TDBXDataTypes.VarBytesType, 8, 'timestamp', NullString, -1, -1, '0x', NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Searchable or TDBXTypeFlag.ConcurrencyType); Types[10] := TDBXDataTypeDescription.Create('binary', TDBXDataTypes.BytesType, 8000, 'binary({0})', 'Precision', -1, -1, '0x', NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[11] := TDBXDataTypeDescription.Create('image', TDBXDataTypes.BlobType, 2147483647, 'image', NullString, -1, -1, '0x', NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable); Types[12] := TDBXDataTypeDescription.Create('text', TDBXDataTypes.AnsiStringType, 2147483647, 'text', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.SearchableWithLike); Types[13] := TDBXDataTypeDescription.Create('ntext', TDBXDataTypes.WideStringType, 1073741823, 'ntext', NullString, -1, -1, 'N''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode); Types[14] := TDBXDataTypeDescription.Create('decimal', TDBXDataTypes.BcdType, 38, 'decimal({0}, {1})', 'Precision, Scale', 38, 0, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[15] := TDBXDataTypeDescription.Create('numeric', TDBXDataTypes.BcdType, 38, 'numeric({0}, {1})', 'Precision, Scale', 38, 0, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[16] := TDBXDataTypeDescription.Create('datetime', TDBXDataTypes.TimeStampType, 23, 'datetime', NullString, -1, -1, '{ts ''', '''}', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike); Types[17] := TDBXDataTypeDescription.Create('smalldatetime', TDBXDataTypes.TimeStampType, 16, 'smalldatetime', NullString, -1, -1, '{ts ''', '''}', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike); Types[18] := TDBXDataTypeDescription.Create('sql_variant', TDBXDataTypes.ObjectType, 0, 'sql_variant', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[19] := TDBXDataTypeDescription.Create('xml', TDBXDataTypes.WideStringType, 2147483647, 'xml', NullString, -1, -1, NullString, NullString, NullString, '09.00.0000', TDBXTypeFlag.Long or TDBXTypeFlag.Nullable); Types[20] := TDBXDataTypeDescription.Create('varchar', TDBXDataTypes.AnsiStringType, 8000, 'varchar({0})', 'Precision', -1, -1, '''', '''', '08.99.9999', NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike); Types[21] := TDBXDataTypeDescription.Create('varchar', TDBXDataTypes.AnsiStringType, 2147483647, 'varchar({0})', 'Precision', -1, -1, '''', '''', NullString, '09.00.0000', TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike); Types[22] := TDBXDataTypeDescription.Create('char', TDBXDataTypes.AnsiStringType, 8000, 'char({0})', 'Precision', -1, -1, '''', '''', '08.99.9999', NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike); Types[23] := TDBXDataTypeDescription.Create('char', TDBXDataTypes.AnsiStringType, 2147483647, 'char({0})', 'Precision', -1, -1, '''', '''', NullString, '09.00.0000', TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike); Types[24] := TDBXDataTypeDescription.Create('nchar', TDBXDataTypes.WideStringType, 4000, 'nchar({0})', 'Precision', -1, -1, 'N''', '''', '08.99.9999', NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode); Types[25] := TDBXDataTypeDescription.Create('nchar', TDBXDataTypes.WideStringType, 1073741823, 'nchar({0})', 'Precision', -1, -1, 'N''', '''', NullString, '09.00.0000', TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode); Types[26] := TDBXDataTypeDescription.Create('nvarchar', TDBXDataTypes.WideStringType, 4000, 'nvarchar({0})', 'Precision', -1, -1, 'N''', '''', '08.99.9999', NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode); Types[27] := TDBXDataTypeDescription.Create('nvarchar', TDBXDataTypes.WideStringType, 1073741823, 'nvarchar({0})', 'Precision', -1, -1, 'N''', '''', NullString, '09.00.0000', TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode); Types[28] := TDBXDataTypeDescription.Create('varbinary', TDBXDataTypes.VarBytesType, 8000, 'varbinary({0})', 'Precision', -1, -1, '0x', NullString, '08.99.9999', NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[29] := TDBXDataTypeDescription.Create('varbinary', TDBXDataTypes.VarBytesType, 1073741823, 'varbinary({0})', 'Precision', -1, -1, '0x', NullString, NullString, '09.00.0000', TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[30] := TDBXDataTypeDescription.Create('uniqueidentifier', TDBXDataTypes.AnsiStringType, 16, 'uniqueidentifier', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[31] := TDBXDataTypeDescription.Create('date', TDBXDataTypes.DateType, 10, 'date', NullString, -1, -1, '''', '''', NullString, '10.00.0000', TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike); Types[32] := TDBXDataTypeDescription.Create('datetime2', TDBXDataTypes.TimeStampType, 27, 'datetime2', NullString, -1, -1, '{ts ''', '''}', NullString, '10.00.0000', TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike); Types[33] := TDBXDataTypeDescription.Create('datetimeoffset', TDBXDataTypes.TimeStampOffsetType, 34, 'datetimeoffset', NullString, -1, -1, '{ts ''', '''}', NullString, '10.00.0000', TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike); Types[34] := TDBXDataTypeDescription.Create('time', TDBXDataTypes.TimeType, 16, 'time', NullString, -1, -1, '''', '''', NullString, '10.00.0000', TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike); Types[35] := TDBXDataTypeDescription.Create('hierarchyid', TDBXDataTypes.VarBytesType, 892, 'hierarchyid', NullString, -1, -1, '0x', NullString, NullString, '10.00.0000', TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[36] := TDBXDataTypeDescription.Create('geometry', TDBXDataTypes.VarBytesType, 1073741823, 'geometry', NullString, -1, -1, '0x', NullString, NullString, '10.00.0000', TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Types[37] := TDBXDataTypeDescription.Create('geography', TDBXDataTypes.VarBytesType, 1073741823, 'geography', NullString, -1, -1, '0x', NullString, NullString, '10.00.0000', TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable); Result := Types; end; function TDBXMsSqlMetaDataReader.GetReservedWords: TDBXStringArray; var Words: TDBXStringArray; begin SetLength(Words,393); Words[0] := 'ADD'; Words[1] := 'EXCEPT'; Words[2] := 'PERCENT'; Words[3] := 'ALL'; Words[4] := 'EXEC'; Words[5] := 'PLAN'; Words[6] := 'ALTER'; Words[7] := 'EXECUTE'; Words[8] := 'PRECISION'; Words[9] := 'AND'; Words[10] := 'EXISTS'; Words[11] := 'PRIMARY'; Words[12] := 'ANY'; Words[13] := 'EXIT'; Words[14] := 'PRINT'; Words[15] := 'AS'; Words[16] := 'FETCH'; Words[17] := 'PROC'; Words[18] := 'ASC'; Words[19] := 'FILE'; Words[20] := 'PROCEDURE'; Words[21] := 'AUTHORIZATION'; Words[22] := 'FILLFACTOR'; Words[23] := 'PUBLIC'; Words[24] := 'BACKUP'; Words[25] := 'FOR'; Words[26] := 'RAISERROR'; Words[27] := 'BEGIN'; Words[28] := 'FOREIGN'; Words[29] := 'READ'; Words[30] := 'BETWEEN'; Words[31] := 'FREETEXT'; Words[32] := 'READTEXT'; Words[33] := 'BREAK'; Words[34] := 'FREETEXTTABLE'; Words[35] := 'RECONFIGURE'; Words[36] := 'BROWSE'; Words[37] := 'FROM'; Words[38] := 'REFERENCES'; Words[39] := 'BULK'; Words[40] := 'FULL'; Words[41] := 'REPLICATION'; Words[42] := 'BY'; Words[43] := 'FUNCTION'; Words[44] := 'RESTORE'; Words[45] := 'CASCADE'; Words[46] := 'GOTO'; Words[47] := 'RESTRICT'; Words[48] := 'CASE'; Words[49] := 'GRANT'; Words[50] := 'RETURN'; Words[51] := 'CHECK'; Words[52] := 'GROUP'; Words[53] := 'REVOKE'; Words[54] := 'CHECKPOINT'; Words[55] := 'HAVING'; Words[56] := 'RIGHT'; Words[57] := 'CLOSE'; Words[58] := 'HOLDLOCK'; Words[59] := 'ROLLBACK'; Words[60] := 'CLUSTERED'; Words[61] := 'IDENTITY'; Words[62] := 'ROWCOUNT'; Words[63] := 'COALESCE'; Words[64] := 'IDENTITY_INSERT'; Words[65] := 'ROWGUIDCOL'; Words[66] := 'COLLATE'; Words[67] := 'IDENTITYCOL'; Words[68] := 'RULE'; Words[69] := 'COLUMN'; Words[70] := 'IF'; Words[71] := 'SAVE'; Words[72] := 'COMMIT'; Words[73] := 'IN'; Words[74] := 'SCHEMA'; Words[75] := 'COMPUTE'; Words[76] := 'INDEX'; Words[77] := 'SELECT'; Words[78] := 'CONSTRAINT'; Words[79] := 'INNER'; Words[80] := 'SESSION_USER'; Words[81] := 'CONTAINS'; Words[82] := 'INSERT'; Words[83] := 'SET'; Words[84] := 'CONTAINSTABLE'; Words[85] := 'INTERSECT'; Words[86] := 'SETUSER'; Words[87] := 'CONTINUE'; Words[88] := 'INTO'; Words[89] := 'SHUTDOWN'; Words[90] := 'CONVERT'; Words[91] := 'IS'; Words[92] := 'SOME'; Words[93] := 'CREATE'; Words[94] := 'JOIN'; Words[95] := 'STATISTICS'; Words[96] := 'CROSS'; Words[97] := 'KEY'; Words[98] := 'SYSTEM_USER'; Words[99] := 'CURRENT'; Words[100] := 'KILL'; Words[101] := 'TABLE'; Words[102] := 'CURRENT_DATE'; Words[103] := 'LEFT'; Words[104] := 'TEXTSIZE'; Words[105] := 'CURRENT_TIME'; Words[106] := 'LIKE'; Words[107] := 'THEN'; Words[108] := 'CURRENT_TIMESTAMP'; Words[109] := 'LINENO'; Words[110] := 'TO'; Words[111] := 'CURRENT_USER'; Words[112] := 'LOAD'; Words[113] := 'TOP'; Words[114] := 'CURSOR'; Words[115] := 'NATIONAL'; Words[116] := 'TRAN'; Words[117] := 'DATABASE'; Words[118] := 'NOCHECK'; Words[119] := 'TRANSACTION'; Words[120] := 'DBCC'; Words[121] := 'NONCLUSTERED'; Words[122] := 'TRIGGER'; Words[123] := 'DEALLOCATE'; Words[124] := 'NOT'; Words[125] := 'TRUNCATE'; Words[126] := 'DECLARE'; Words[127] := 'NULL'; Words[128] := 'TSEQUAL'; Words[129] := 'DEFAULT'; Words[130] := 'NULLIF'; Words[131] := 'UNION'; Words[132] := 'DELETE'; Words[133] := 'OF'; Words[134] := 'UNIQUE'; Words[135] := 'DENY'; Words[136] := 'OFF'; Words[137] := 'UPDATE'; Words[138] := 'DESC'; Words[139] := 'OFFSETS'; Words[140] := 'UPDATETEXT'; Words[141] := 'DISK'; Words[142] := 'ON'; Words[143] := 'USE'; Words[144] := 'DISTINCT'; Words[145] := 'OPEN'; Words[146] := 'USER'; Words[147] := 'DISTRIBUTED'; Words[148] := 'OPENDATASOURCE'; Words[149] := 'VALUES'; Words[150] := 'DOUBLE'; Words[151] := 'OPENQUERY'; Words[152] := 'VARYING'; Words[153] := 'DROP'; Words[154] := 'OPENROWSET'; Words[155] := 'VIEW'; Words[156] := 'DUMMY'; Words[157] := 'OPENXML'; Words[158] := 'WAITFOR'; Words[159] := 'DUMP'; Words[160] := 'OPTION'; Words[161] := 'WHEN'; Words[162] := 'ELSE'; Words[163] := 'OR'; Words[164] := 'WHERE'; Words[165] := 'END'; Words[166] := 'ORDER'; Words[167] := 'WHILE'; Words[168] := 'ERRLVL'; Words[169] := 'OUTER'; Words[170] := 'WITH'; Words[171] := 'ESCAPE'; Words[172] := 'OVER'; Words[173] := 'WRITETEXT'; Words[174] := 'ABSOLUTE'; Words[175] := 'FOUND'; Words[176] := 'PRESERVE'; Words[177] := 'ACTION'; Words[178] := 'FREE'; Words[179] := 'PRIOR'; Words[180] := 'ADMIN'; Words[181] := 'GENERAL'; Words[182] := 'PRIVILEGES'; Words[183] := 'AFTER'; Words[184] := 'GET'; Words[185] := 'READS'; Words[186] := 'AGGREGATE'; Words[187] := 'GLOBAL'; Words[188] := 'REAL'; Words[189] := 'ALIAS'; Words[190] := 'GO'; Words[191] := 'RECURSIVE'; Words[192] := 'ALLOCATE'; Words[193] := 'GROUPING'; Words[194] := 'REF'; Words[195] := 'ARE'; Words[196] := 'HOST'; Words[197] := 'REFERENCING'; Words[198] := 'ARRAY'; Words[199] := 'HOUR'; Words[200] := 'RELATIVE'; Words[201] := 'ASSERTION'; Words[202] := 'IGNORE'; Words[203] := 'RESULT'; Words[204] := 'AT'; Words[205] := 'IMMEDIATE'; Words[206] := 'RETURNS'; Words[207] := 'BEFORE'; Words[208] := 'INDICATOR'; Words[209] := 'ROLE'; Words[210] := 'BINARY'; Words[211] := 'INITIALIZE'; Words[212] := 'ROLLUP'; Words[213] := 'BIT'; Words[214] := 'INITIALLY'; Words[215] := 'ROUTINE'; Words[216] := 'BLOB'; Words[217] := 'INOUT'; Words[218] := 'ROW'; Words[219] := 'BOOLEAN'; Words[220] := 'INPUT'; Words[221] := 'ROWS'; Words[222] := 'BOTH'; Words[223] := 'INT'; Words[224] := 'SAVEPOINT'; Words[225] := 'BREADTH'; Words[226] := 'INTEGER'; Words[227] := 'SCROLL'; Words[228] := 'CALL'; Words[229] := 'INTERVAL'; Words[230] := 'SCOPE'; Words[231] := 'CASCADED'; Words[232] := 'ISOLATION'; Words[233] := 'SEARCH'; Words[234] := 'CAST'; Words[235] := 'ITERATE'; Words[236] := 'SECOND'; Words[237] := 'CATALOG'; Words[238] := 'LANGUAGE'; Words[239] := 'SECTION'; Words[240] := 'CHAR'; Words[241] := 'LARGE'; Words[242] := 'SEQUENCE'; Words[243] := 'CHARACTER'; Words[244] := 'LAST'; Words[245] := 'SESSION'; Words[246] := 'CLASS'; Words[247] := 'LATERAL'; Words[248] := 'SETS'; Words[249] := 'CLOB'; Words[250] := 'LEADING'; Words[251] := 'SIZE'; Words[252] := 'COLLATION'; Words[253] := 'LESS'; Words[254] := 'SMALLINT'; Words[255] := 'COMPLETION'; Words[256] := 'LEVEL'; Words[257] := 'SPACE'; Words[258] := 'CONNECT'; Words[259] := 'LIMIT'; Words[260] := 'SPECIFIC'; Words[261] := 'CONNECTION'; Words[262] := 'LOCAL'; Words[263] := 'SPECIFICTYPE'; Words[264] := 'CONSTRAINTS'; Words[265] := 'LOCALTIME'; Words[266] := 'SQL'; Words[267] := 'CONSTRUCTOR'; Words[268] := 'LOCALTIMESTAMP'; Words[269] := 'SQLEXCEPTION'; Words[270] := 'CORRESPONDING'; Words[271] := 'LOCATOR'; Words[272] := 'SQLSTATE'; Words[273] := 'CUBE'; Words[274] := 'MAP'; Words[275] := 'SQLWARNING'; Words[276] := 'CURRENT_PATH'; Words[277] := 'MATCH'; Words[278] := 'START'; Words[279] := 'CURRENT_ROLE'; Words[280] := 'MINUTE'; Words[281] := 'STATE'; Words[282] := 'CYCLE'; Words[283] := 'MODIFIES'; Words[284] := 'STATEMENT'; Words[285] := 'DATA'; Words[286] := 'MODIFY'; Words[287] := 'STATIC'; Words[288] := 'DATE'; Words[289] := 'MODULE'; Words[290] := 'STRUCTURE'; Words[291] := 'DAY'; Words[292] := 'MONTH'; Words[293] := 'TEMPORARY'; Words[294] := 'DEC'; Words[295] := 'NAMES'; Words[296] := 'TERMINATE'; Words[297] := 'DECIMAL'; Words[298] := 'NATURAL'; Words[299] := 'THAN'; Words[300] := 'DEFERRABLE'; Words[301] := 'NCHAR'; Words[302] := 'TIME'; Words[303] := 'DEFERRED'; Words[304] := 'NCLOB'; Words[305] := 'TIMESTAMP'; Words[306] := 'DEPTH'; Words[307] := 'NEW'; Words[308] := 'TIMEZONE_HOUR'; Words[309] := 'DEREF'; Words[310] := 'NEXT'; Words[311] := 'TIMEZONE_MINUTE'; Words[312] := 'DESCRIBE'; Words[313] := 'NO'; Words[314] := 'TRAILING'; Words[315] := 'DESCRIPTOR'; Words[316] := 'NONE'; Words[317] := 'TRANSLATION'; Words[318] := 'DESTROY'; Words[319] := 'NUMERIC'; Words[320] := 'TREAT'; Words[321] := 'DESTRUCTOR'; Words[322] := 'OBJECT'; Words[323] := 'TRUE'; Words[324] := 'DETERMINISTIC'; Words[325] := 'OLD'; Words[326] := 'UNDER'; Words[327] := 'DICTIONARY'; Words[328] := 'ONLY'; Words[329] := 'UNKNOWN'; Words[330] := 'DIAGNOSTICS'; Words[331] := 'OPERATION'; Words[332] := 'UNNEST'; Words[333] := 'DISCONNECT'; Words[334] := 'ORDINALITY'; Words[335] := 'USAGE'; Words[336] := 'DOMAIN'; Words[337] := 'OUT'; Words[338] := 'USING'; Words[339] := 'DYNAMIC'; Words[340] := 'OUTPUT'; Words[341] := 'VALUE'; Words[342] := 'EACH'; Words[343] := 'PAD'; Words[344] := 'VARCHAR'; Words[345] := 'END-EXEC'; Words[346] := 'PARAMETER'; Words[347] := 'VARIABLE'; Words[348] := 'EQUALS'; Words[349] := 'PARAMETERS'; Words[350] := 'WHENEVER'; Words[351] := 'EVERY'; Words[352] := 'PARTIAL'; Words[353] := 'WITHOUT'; Words[354] := 'EXCEPTION'; Words[355] := 'PATH'; Words[356] := 'WORK'; Words[357] := 'EXTERNAL'; Words[358] := 'POSTFIX'; Words[359] := 'WRITE'; Words[360] := 'FALSE'; Words[361] := 'PREFIX'; Words[362] := 'YEAR'; Words[363] := 'FIRST'; Words[364] := 'PREORDER'; Words[365] := 'ZONE'; Words[366] := 'FLOAT'; Words[367] := 'PREPARE'; Words[368] := 'ADA'; Words[369] := 'AVG'; Words[370] := 'BIT_LENGTH'; Words[371] := 'CHAR_LENGTH'; Words[372] := 'CHARACTER_LENGTH'; Words[373] := 'COUNT'; Words[374] := 'EXTRACT'; Words[375] := 'FORTRAN'; Words[376] := 'INCLUDE'; Words[377] := 'INSENSITIVE'; Words[378] := 'LOWER'; Words[379] := 'MAX'; Words[380] := 'MIN'; Words[381] := 'OCTET_LENGTH'; Words[382] := 'OVERLAPS'; Words[383] := 'PASCAL'; Words[384] := 'POSITION'; Words[385] := 'SQLCA'; Words[386] := 'SQLCODE'; Words[387] := 'SQLERROR'; Words[388] := 'SUBSTRING'; Words[389] := 'SUM'; Words[390] := 'TRANSLATE'; Words[391] := 'TRIM'; Words[392] := 'UPPER'; Result := Words; end; end.
(****************************************************************************) (* *) (* REV97.PAS - The Relativity Emag (coded in Borland Pascal 7.0) *) (* *) (* "The Relativity Emag" was originally written by En|{rypt, |MuadDib|. *) (* This source may not be copied, distributed or modified in any shape *) (* or form. Some of the code has been derived from various sources and *) (* units to help us produce a better quality electronic magazine to let *) (* the scene know that we are THE BOSS. *) (* *) (* Program Notes : This program presents "The Relativity Emag" *) (* *) (* ASM/BP70 Coder : xxxxx xxxxxxxxx (MuadDib) - xxxxxx@xxxxxxxxxx.xxx *) (* ------------------------------------------------------------------------ *) (* Older Coder : xxxxx xxxxxxxxx (En|{rypt) - xxxxxx@xxxxxxxxxx.xxx :))) *) (* *) (****************************************************************************) {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Reserved Words - The Heading Specifies The Program Name And Parameters. *) (****************************************************************************) Program The_Relativity_Electronic_Magazine_issue_7; {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Compiler Directives - These Directives Are Not Meant To Be Modified. *) (****************************************************************************) {$M 64000,000,640000} {$S 65535} {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Reserved Words - Statements To Be Executed When The Program Runs. *) (****************************************************************************) {-plans for the future in the coding- -------------------------------------- * compression * f1 search in memory (bin) cd player is bugged ... no disk recognize and no drive recog /cd for cd player options.. /music for music options rad or mod.. - REMEMBER RAD MAX FILESIZE POINTER IS 32K AND SO IS VOC ! - dat file param and names automatically in beta mode !! reminder ! - hide cursor after 03mode doesnt work .. you can still see the _ blinking in the upper left corner :(..delayscreen waitretrace?} {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Reserved Words - Each Identifier Names A Unit Used By The Program. *) (****************************************************************************) uses Crt,Dos,revcom,revcol, revconst,revinit,revmenu,revint,revcfgr,revvoc, revhelp,revpoint,detectso,revwin,revdet, revfnt,revrad,revtech,revgfx,revansi,revdisc,revgif, revdat,revsmth,revhard,revmouse,revgame,revfli{,arkanoid}; var err,i:byte; Begin {Begins The Best Emag In The Scene} {---------------------------------------------------------------} beta:=true; {for assigning auto names to the dat files.. beta mode} if (paramcount = 0) and (not beta) then begin writeln; Writeln('Relativity Emag Viewer v2.0'); writeln('Syntax : RevXX-XX.EXE FxXX-XX.MDB EmagXX-XX.MDB /Commandline.'); halt; end; { beta:=true; {for assigning auto names to the dat files.. beta mode} Assign_names; {assigning names if betamode, or taking them from paramstr} if not beta then checkbreak:=false; vercheck; {secret windows option :) } initconfigpointer; initbright; Err:=ReadGlobalIndex(1); if Err<>0 then kill_emag(err); Err:=ReadGlobalIndex(2); if Err<>0 then kill_emag(err); cc:=1; {menu option} voc_ok:=1; {vocals indicator} {-------------------------------------------------------------------------} Det_sb; Det_adlib; Det_mouse; {-------------------------------------------------------------------------} {TRUE OR FALSE INSIDE CHECKS} g:=true; {change to true b4 release !} cd:=true; {change to true b4 release !} hard:=true; {change to true b4 release !} adlib:=true; {change to true b4 release !} vga_:=true; {change to true b4 release !} bar:=false; {change to FALSE b4 release !} intro:=true; {change to true b4 release !} smooth:=3; {change to 1 b4 release !} start:=true; {change to true b4 release !} if adlib then begin rand:=true; radmuson:=true; dsmmuson:=true; end else begin rand:=false; dsmmuson:=false; end; {-------------------------------------------------------------------------} if not initpointers then kill_emag(5); {taking memory, after that if not enough left for game.. disabling game} for i:= 1 to paramcount+1 do begin if (paramstr(i)<>'/M') and (paramstr(i)<>'/m') then if memavail<game_mem-(k64*1) then {*2 if fury} if not beta then kill_emag(7) {killing ..no /m} else add_not_avail(19,11) {diabling /m appeared} else if memavail<game_mem-(k64*1) then {k64*2 ..deinitptrart..arkanoid} begin add_not_avail(19,11); {diabling /m appeared} writeln('Ignored Memory Restriction, Disabling Game !!'); Writeln('Press Any Key ...'); waitforkey; end; end; randomize; InitTag; if not read_config then kill_emag(6); InitUpper; {makes all filenames to uppercase} DeleteDatFilesInDir(1); DeleteDatFilesInDir(2); initprinter; RevCommand; fontloadpointer(config^.font[config^.curfnt],fontp); {load fonts} initavail; InitradVol; Initcd; if (not mouse) then {diables game if not enough mem or no mouse} add_not_avail(19,11); cursor_off; dospin; DisplayGIF(config^.under_pic,under_file,0,0); {boy and girl} Reset80x25VideoScreen; disclaimercheck; smooth:=1; hidecursor; if hard then HardWareInit; if intro then begin if config^.fli then if fileindat('REVFLI.FLI',FLI_FILE) THEN begin ExtractFileFromDat('REVFLI.FLI',fli_file) ; AAPlay('REVFLI.FLI',true); deletedatfile('REVFLI.FLI'); hidecursor; end; PhazePre; textbackground(black); end; extractpointerfromdat(config^.BMMENUFILE,article_file,boomm,size); extractpointerfromdat(config^.hpmenufile,article_file,helpm,size); extractpointerfromdat(config^.psmenufile,article_file,passM,size); extractpointerfromdat(config^.Secmenufile,article_file,subm,size); Extractpointerfromdat(config^.DEFMENUFILE,article_file,mainm,size); initmouse; StartMainMenuPhase; end.
unit ncSources; // ///////////////////////////////////////////////////////////////////////////// // // NetCom7 Package // // This unit creates a TCP Server Source and a TCP Client Source compoents, // along with their threads dealing with handling commands. // // The idea behind the source components is to be able to extend the sockets // to handle well defined buffers. Sockets on their own are streaming so // you have to implement a mechanism of picking the buffers from the stream // to process. // // The components implemented here introduce an ExecCommand which sends to // the peer (be it a client or a server) the command along with its data to // be executed. The peer then calls the OnHandleCommand with the data supplied, // and packs the result back to the calling peer. If an exception is raised, // it is packed and raised back at the caller, so that client/server applications // can utilise the exception mechanisms. // // The buffer packing and unpacking from the stream can handle garbage thrown // at it. // // These components have built in encryption and compression, set by the // corresponding properties. // // 12/8/2020 // - Complete re-engineering of the base component // // 16/12/2010 // - Initial creation // // Written by Demos Bill // // ///////////////////////////////////////////////////////////////////////////// // To disable as much of RTTI as possible (Delphi 2009/2010), // Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position {$IF CompilerVersion >= 21.0} {$WEAKLINKRTTI ON} {$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])} {$ENDIF} interface uses {$IFDEF MSWINDOWS} Winapi.Windows, Winapi.Winsock2, {$ELSE} Posix.SysSocket, Posix.Unistd, {$ENDIF} System.Classes, System.SysUtils, System.SyncObjs, System.Math, System.ZLib, System.Diagnostics, System.TimeSpan, System.RTLConsts, System.Types, ncCommandPacking, ncLines, ncSocketList, ncThreads, ncSockets, ncPendingCommandsList, ncCompression, ncEncryption; type TncCommandDirection = (cdIncoming, cdOutgoing); ENetComInvalidCommandHandler = class(Exception); ENetComCommandExecutionTimeout = class(Exception); ENetComResultIsException = class(Exception); resourcestring ENetComInvalidCommandHandlerMessage = 'Cannot attach component, it does not support the command handler interface'; ENetComCommandExecutionTimeoutMessage = 'Command execution timeout'; type TMagicHeaderType = UInt32; PMagicHeaderType = ^TMagicHeaderType; const MagicHeader: TMagicHeaderType = $ACF0FF00; // Bin: 10101100111100001111111100000000 DefPort = 17233; DefExecThreadPriority = ntpNormal; DefExecThreads = 0; DefExecThreadsPerCPU = 4; DefExecThreadsGrowUpto = 32; DefExecCommandTimeout = 15000; DefEventsUseMainThread = False; DefNoDelay = True; DefCompression = zcNone; DefEncryption = etNoEncryption; DefEncryptionKey = 'SetEncryptionKey'; DefEncryptOnHashedKey = True; type // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TncSourceLine // Bring in TncLine from ncLines so that components placed on a form will // not have to reference ncLines unit TncLine = ncLines.TncLine; TncSourceLine = class(TncLine) protected MessageData, HeaderBytes: TBytes; BytesToEndOfMessage: UInt64; protected function CreateLineObject: TncLine; override; public constructor Create; overload; override; end; TncOnSourceConnectDisconnect = procedure( Sender: TObject; aLine: TncLine) of object; TncOnSourceReconnected = procedure( Sender: TObject; aLine: TncLine) of object; TncOnSourceHandleCommand = function( Sender: TObject; aLine: TncLine; aCmd: Integer; const aData: TBytes; aRequiresResult: Boolean; const aSenderComponent, aReceiverComponent: string): TBytes of object; TncOnAsyncExecCommandResult = procedure( Sender: TObject; aLine: TncLine; aCmd: Integer; const aResult: TBytes; aResultIsError: Boolean; const aSenderComponent, aReceiverComponent: string) of object; IncCommandHandler = interface ['{22337701-9561-489A-8593-82EAA3B1B431}'] function GetOnConnected: TncOnSourceConnectDisconnect; procedure SetOnConnected(const Value: TncOnSourceConnectDisconnect); function GetOnDisconnected: TncOnSourceConnectDisconnect; procedure SetOnDisconnected(const Value: TncOnSourceConnectDisconnect); function GetOnHandleCommand: TncOnSourceHandleCommand; procedure SetOnHandleCommand(const Value: TncOnSourceHandleCommand); function GetOnAsyncExecCommandResult: TncOnAsyncExecCommandResult; procedure SetOnAsyncExecCommandResult(const Value: TncOnAsyncExecCommandResult); function GetComponentName: string; property OnConnected: TncOnSourceConnectDisconnect read GetOnConnected write SetOnConnected; property OnDisconnected: TncOnSourceConnectDisconnect read GetOnDisconnected write SetOnDisconnected; property OnHandleCommand: TncOnSourceHandleCommand read GetOnHandleCommand write SetOnHandleCommand; property OnAsyncExecCommandResult: TncOnAsyncExecCommandResult read GetOnAsyncExecCommandResult write SetOnAsyncExecCommandResult; end; // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TncSourceBase // Is the base for handling Exec and Handle command for the ServerSource and ClientSource TncSourceBase = class(TComponent, IncCommandHandler) private FCommandExecTimeout: Cardinal; FCommandProcessorThreadPriority: TncThreadPriority; FCommandProcessorThreads: Integer; FCommandProcessorThreadsPerCPU: Integer; FCommandProcessorThreadsGrowUpto: Integer; FEventsUseMainThread: Boolean; FCompression: TncCompressionLevel; FEncryption: TEncryptorType; FEncryptionKey: string; FEncryptOnHashedKey: Boolean; FOnConnected: TncOnSourceConnectDisconnect; FOnDisconnected: TncOnSourceConnectDisconnect; FOnHandleCommand: TncOnSourceHandleCommand; FOnAsyncExecCommandResult: TncOnAsyncExecCommandResult; // From socket function GetActive: Boolean; procedure SetActive(const Value: Boolean); function GetKeepAlive: Boolean; procedure SetKeepAlive(const Value: Boolean); function GetNoDelay: Boolean; procedure SetNoDelay(const Value: Boolean); function GetPort: Integer; procedure SetPort(const Value: Integer); function GetReaderThreadPriority: TncThreadPriority; procedure SetReaderThreadPriority(const Value: TncThreadPriority); // For implementing the IncCommandHandler interface function GetComponentName: string; function GetOnConnected: TncOnSourceConnectDisconnect; procedure SetOnConnected(const Value: TncOnSourceConnectDisconnect); function GetOnDisconnected: TncOnSourceConnectDisconnect; procedure SetOnDisconnected(const Value: TncOnSourceConnectDisconnect); function GetOnHandleCommand: TncOnSourceHandleCommand; procedure SetOnHandleCommand(const Value: TncOnSourceHandleCommand); function GetOnAsyncExecCommandResult: TncOnAsyncExecCommandResult; procedure SetOnAsyncExecCommandResult(const Value: TncOnAsyncExecCommandResult); // Property getters and setters function GetExecCommandTimeout: Cardinal; procedure SetExecCommandTimeout(const Value: Cardinal); function GetCommandProcessorThreadPriority: TncThreadPriority; procedure SetCommandProcessorThreadPriority(const Value: TncThreadPriority); function GetCommandProcessorThreads: Integer; procedure SetCommandProcessorThreads(const Value: Integer); function GetCommandProcessorThreadsPerCPU: Integer; procedure SetCommandProcessorThreadsPerCPU(const Value: Integer); function GetCommandProcessorThreadsGrowUpto: Integer; procedure SetCommandProcessorThreadsGrowUpto(const Value: Integer); function GetEventsUseMainThread: Boolean; procedure SetEventsUseMainThread(const Value: Boolean); function GetCompression: TncCompressionLevel; procedure SetCompression(const Value: TncCompressionLevel); function GetEncryption: TEncryptorType; procedure SetEncryption(const Value: TEncryptorType); function GetEncryptionKey: string; procedure SetEncryptionKey(const Value: string); function GetEncryptOnHashedKey: Boolean; procedure SetEncryptOnHashedKey(const Value: Boolean); private // To set the component active on loaded if was set at design time WasSetActive: Boolean; WithinConnectionHandler: Boolean; protected PropertyLock: TCriticalSection; CommandHandlers: array of IncCommandHandler; UniqueSentID: TncCommandUniqueID; HandleCommandThreadPool: TncThreadPool; Socket: TncTCPBase; ExecuteSerialiser: TCriticalSection; LastConnectedLine, LastDisconnectedLine, LastReconnectedLine: TncLine; PendingCommandsList: TPendingCommandsList; procedure Loaded; override; procedure CallConnectedEvents; procedure SocketConnected(Sender: TObject; aLine: TncLine); procedure CallDisconnectedEvents; procedure SocketDisconnected(Sender: TObject; aLine: TncLine); procedure CallReconnectedEvents; procedure SocketReconnected(Sender: TObject; aLine: TncLine); procedure SocketReadData(Sender: TObject; aLine: TncLine; const aBuf: TBytes; aBufCount: Integer); procedure WriteMessage(aLine: TncSourceLine; const aBuf: TBytes); virtual; procedure WriteCommand(aLine: TncSourceLine; const aCmd: TncCommand); inline; procedure HandleReceivedCommand(aLine: TncSourceLine; const aCommandBytes: TBytes); inline; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function ExecCommand( aLine: TncLine; const aCmd: Integer; const aData: TBytes = nil; const aRequiresResult: Boolean = True; const aAsyncExecute: Boolean = False; const aPeerComponentHandler: string = ''; const aSourceComponentHandler: string = ''): TBytes; overload; virtual; procedure AddCommandHandler(aHandler: TComponent); procedure RemoveCommandHandler(aHandler: TComponent); published // From socket property Active: Boolean read GetActive write SetActive default False; property Port: Integer read GetPort write SetPort default DefPort; property ReaderThreadPriority: TncThreadPriority read GetReaderThreadPriority write SetReaderThreadPriority default DefReaderThreadPriority; property NoDelay: Boolean read GetNoDelay write SetNoDelay default True; property KeepAlive: Boolean read GetKeepAlive write SetKeepAlive default True; // New properties for sources property CommandProcessorThreadPriority: TncThreadPriority read GetCommandProcessorThreadPriority write SetCommandProcessorThreadPriority default DefExecThreadPriority; property CommandProcessorThreads: Integer read GetCommandProcessorThreads write SetCommandProcessorThreads default DefExecThreads; property CommandProcessorThreadsPerCPU: Integer read GetCommandProcessorThreadsPerCPU write SetCommandProcessorThreadsPerCPU default DefExecThreadsPerCPU; property CommandProcessorThreadsGrowUpto: Integer read GetCommandProcessorThreadsGrowUpto write SetCommandProcessorThreadsGrowUpto default DefExecThreadsGrowUpto; property ExecCommandTimeout: Cardinal read GetExecCommandTimeout write SetExecCommandTimeout default DefExecCommandTimeout; property EventsUseMainThread: Boolean read GetEventsUseMainThread write SetEventsUseMainThread default DefEventsUseMainThread; property Compression: TncCompressionLevel read GetCompression write SetCompression default DefCompression; property Encryption: TEncryptorType read GetEncryption write SetEncryption default DefEncryption; property EncryptionKey: string read GetEncryptionKey write SetEncryptionKey; property EncryptOnHashedKey: Boolean read GetEncryptOnHashedKey write SetEncryptOnHashedKey default DefEncryptOnHashedKey; property OnConnected: TncOnSourceConnectDisconnect read GetOnConnected write SetOnConnected; property OnDisconnected: TncOnSourceConnectDisconnect read GetOnDisconnected write SetOnDisconnected; property OnHandleCommand: TncOnSourceHandleCommand read GetOnHandleCommand write SetOnHandleCommand; property OnAsyncExecCommandResult: TncOnAsyncExecCommandResult read GetOnAsyncExecCommandResult write SetOnAsyncExecCommandResult; end; THandleCommandThreadWorkType = (htwtAsyncResponse, htwtOnHandleCommand); THandleCommandThread = class(TncReadyThread) public WorkType: THandleCommandThreadWorkType; OnHandleCommand: TncOnSourceHandleCommand; OnAsyncExecCommandResult: TncOnAsyncExecCommandResult; Source: TncSourceBase; Line: TncSourceLine; Command: TncCommand; CommandHandler: IncCommandHandler; procedure CallOnAsyncEvents; procedure CallOnHandleEvents; procedure ProcessEvent; override; end; // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TncClientSource // Connects to a server source TncClientSource = class(TncSourceBase) private FOnReconnected: TncOnSourceReconnected; function GetHost: string; procedure SetHost(const Value: string); function GetReconnect: Boolean; procedure SetReconnect(const Value: Boolean); function GetReconnectInterval: Cardinal; procedure SetReconnectInterval(const Value: Cardinal); protected procedure WriteMessage(aLine: TncSourceLine; const aBuf: TBytes); override; function GetLine: TncLine; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function ExecCommand( const aCmd: Integer; const aData: TBytes = nil; const aRequiresResult: Boolean = True; const aAsyncExecute: Boolean = False; const aPeerComponentHandler: string = ''; const aSourceComponentHandler: string = ''): TBytes; overload; virtual; property Line: TncLine read GetLine; published property Host: string read GetHost write SetHost; property Reconnect: Boolean read GetReconnect write SetReconnect default True; property ReconnectInterval: Cardinal read GetReconnectInterval write SetReconnectInterval default DefCntReconnectInterval; property OnReconnected: TncOnSourceReconnected read FOnReconnected write FOnReconnected; end; // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TncServerSource TncServerSource = class(TncSourceBase) private protected function GetLines: TThreadLineList; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ShutDownLine(aLine: TncLine); property Lines: TThreadLineList read GetLines; end; implementation // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// { TncSourceLine } // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// constructor TncSourceLine.Create; begin inherited Create; BytesToEndOfMessage := 0; SetLength(HeaderBytes, 0); end; function TncSourceLine.CreateLineObject: TncLine; begin Result := TncSourceLine.Create; // Create its own kind of objects end; // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// { TncSourceBase } // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// constructor TncSourceBase.Create(AOwner: TComponent); begin inherited Create(AOwner); PropertyLock := TCriticalSection.Create; ExecuteSerialiser := TCriticalSection.Create; Socket := nil; WasSetActive := False; WithinConnectionHandler := False; // For encryption purposes this is not set to zero Randomize; UniqueSentID := Random(4096); FCommandProcessorThreadPriority := DefExecThreadPriority; FCommandProcessorThreads := DefExecThreads; FCommandProcessorThreadsPerCPU := DefExecThreadsPerCPU; FCommandProcessorThreadsGrowUpto := DefExecThreadsGrowUpto; FCommandExecTimeout := DefExecCommandTimeout; FEventsUseMainThread := DefEventsUseMainThread; FCompression := DefCompression; FEncryption := DefEncryption; FEncryptionKey := DefEncryptionKey; FEncryptOnHashedKey := DefEncryptOnHashedKey; FOnConnected := nil; FOnDisconnected := nil; FOnHandleCommand := nil; FOnAsyncExecCommandResult := nil; PendingCommandsList := TPendingCommandsList.Create; HandleCommandThreadPool := TncThreadPool.Create(THandleCommandThread); end; destructor TncSourceBase.Destroy; begin HandleCommandThreadPool.Free; PendingCommandsList.Free; ExecuteSerialiser.Free; PropertyLock.Free; inherited Destroy; end; procedure TncSourceBase.Loaded; begin inherited Loaded; HandleCommandThreadPool.SetThreadPriority(FCommandProcessorThreadPriority); HandleCommandThreadPool.SetExecThreads(Max(1, Max(FCommandProcessorThreads, GetNumberOfProcessors * FCommandProcessorThreadsPerCPU)), FCommandProcessorThreadPriority); if WasSetActive then Socket.Active := True; end; procedure TncSourceBase.AddCommandHandler(aHandler: TComponent); var Handler: IncCommandHandler; Len: Integer; begin if aHandler.GetInterface(IncCommandHandler, Handler) then try Len := Length(CommandHandlers); SetLength(CommandHandlers, Len + 1); CommandHandlers[Len] := Handler; finally Handler := nil; end else raise ENetComInvalidCommandHandler.Create(ENetComInvalidCommandHandlerMessage); end; procedure TncSourceBase.RemoveCommandHandler(aHandler: TComponent); var Handler: IncCommandHandler; i: Integer; begin if aHandler.GetInterface(IncCommandHandler, Handler) then try for i := 0 to High(CommandHandlers) do if CommandHandlers[i] = Handler then begin CommandHandlers[i] := CommandHandlers[High(CommandHandlers)]; CommandHandlers[High(CommandHandlers)] := nil; SetLength(CommandHandlers, Length(CommandHandlers) - 1); Break; end; finally Handler := nil; end end; procedure TncSourceBase.CallConnectedEvents; var i: Integer; begin WithinConnectionHandler := True; try if Assigned(OnConnected) then try OnConnected(Self, LastConnectedLine); except end; for i := 0 to High(CommandHandlers) do try if Assigned(CommandHandlers[i].OnConnected) then CommandHandlers[i].OnConnected(Self, LastConnectedLine); except end; finally WithinConnectionHandler := False; end; end; procedure TncSourceBase.SocketConnected(Sender: TObject; aLine: TncLine); begin LastConnectedLine := aLine; if EventsUseMainThread then Socket.LineProcessor.Synchronize(Socket.LineProcessor, CallConnectedEvents) else CallConnectedEvents; end; procedure TncSourceBase.CallDisconnectedEvents; var i: Integer; begin WithinConnectionHandler := True; try if Assigned(FOnDisconnected) then try OnDisconnected(Self, LastDisconnectedLine); except end; for i := 0 to High(CommandHandlers) do try if Assigned(CommandHandlers[i].OnDisconnected) then CommandHandlers[i].OnDisconnected(Self, LastDisconnectedLine); except end; finally WithinConnectionHandler := False; end; end; procedure TncSourceBase.SocketDisconnected(Sender: TObject; aLine: TncLine); begin LastDisconnectedLine := aLine; if EventsUseMainThread then Socket.LineProcessor.Synchronize(Socket.LineProcessor, CallDisconnectedEvents) else CallDisconnectedEvents; end; procedure TncSourceBase.CallReconnectedEvents; begin WithinConnectionHandler := True; try if Assigned(TncClientSource(Self).OnReconnected) then try TncClientSource(Self).OnReconnected(Self, LastReconnectedLine); except end; finally WithinConnectionHandler := False; end; end; procedure TncSourceBase.SocketReconnected(Sender: TObject; aLine: TncLine); begin LastReconnectedLine := aLine; if EventsUseMainThread then Socket.LineProcessor.Synchronize(Socket.LineProcessor, CallReconnectedEvents) else CallReconnectedEvents; end; procedure TncSourceBase.WriteMessage(aLine: TncSourceLine; const aBuf: TBytes); var MessageBytes, FinalBuf: TBytes; MsgByteCount, HeaderBytes: UInt64; begin MessageBytes := aBuf; // Get message data compressed and encrypted if Encryption <> etNoEncryption then MessageBytes := EncryptBytes(MessageBytes, EncryptionKey, Encryption, EncryptOnHashedKey, False); if Compression <> zcNone then MessageBytes := CompressBytes(MessageBytes, Compression); MsgByteCount := Length(MessageBytes); // Send 4 bytes of header, and 4 bytes how long the message will be HeaderBytes := SizeOf(TMagicHeaderType) + SizeOf(MsgByteCount); SetLength(FinalBuf, HeaderBytes + MsgByteCount); PMagicHeaderType(@FinalBuf[0])^ := MagicHeader; // Write MagicHeader PUint64(@FinalBuf[SizeOf(MagicHeader)])^ := MsgByteCount; // Write ByteCount move(MessageBytes[0], FinalBuf[HeaderBytes], MsgByteCount); // Write actual message aLine.SendBuffer(FinalBuf[0], Length(FinalBuf)); end; procedure TncSourceBase.WriteCommand(aLine: TncSourceLine; const aCmd: TncCommand); begin WriteMessage(aLine, aCmd.ToBytes); end; function TncSourceBase.ExecCommand( aLine: TncLine; const aCmd: Integer; const aData: TBytes = nil; const aRequiresResult: Boolean = True; const aAsyncExecute: Boolean = False; const aPeerComponentHandler: string = ''; const aSourceComponentHandler: string = ''): TBytes; var Command: TncCommand; IDSent: TncCommandUniqueID; ReceivedResultEvent: TLightweightEvent; PendingNdx: Integer; WaitForEventTimeout: Integer; begin PropertyLock.Acquire; try IDSent := UniqueSentID; // Random is here for encryption purposes UniqueSentID := UniqueSentID + TncCommandUniqueID(Random(4096)) mod High(TncCommandUniqueID); Command.CommandType := ctInitiator; Command.UniqueID := IDSent; Command.Cmd := aCmd; Command.Data := aData; Command.RequiresResult := aRequiresResult; Command.AsyncExecute := aAsyncExecute; Command.ResultIsErrorString := False; if aSourceComponentHandler = '' then Command.SourceComponentHandler := Name else Command.SourceComponentHandler := aSourceComponentHandler; Command.PeerComponentHandler := aPeerComponentHandler; if aRequiresResult and (not aAsyncExecute) then begin ReceivedResultEvent := TLightweightEvent.Create; PendingNdx := PendingCommandsList.Add(IDSent, ReceivedResultEvent); try // Send command over to peer WriteCommand(TncSourceLine(aLine), Command); except PendingCommandsList.Delete(PendingNdx); ReceivedResultEvent.Free; raise; end; end else begin // Send command over to peer WriteCommand(TncSourceLine(aLine), Command); Exit; // Nothing more to do end; finally PropertyLock.Release; end; // We are here because we require a result and this is not an AsyncExecute SetLength(Result, 0); try try aLine.LastReceived := TStopWatch.GetTimeStamp; if WithinConnectionHandler then WaitForEventTimeout := 0 else WaitForEventTimeout := ExecCommandTimeout; while ReceivedResultEvent.WaitFor(WaitForEventTimeout) <> wrSignaled do begin if not aLine.Active then Abort; // If we are withing an OnConnect/OnDisconnect/OnReconnect handler, // the socket reading is paused, so we need to process it here if WithinConnectionHandler then begin ExecuteSerialiser.Acquire; try if (Socket is TncTCPClient) then begin if ReadableAnySocket(TncTCPClient(Socket).ReadSocketHandles, ExecCommandTimeout) then begin TncClientProcessor(TncTCPClient(Socket).LineProcessor).SocketProcess; TncClientProcessor(TncTCPClient(Socket).LineProcessor).ReadySocketsChanged := True; end; end else begin TncServerProcessor(TncTCPServer(Socket).LineProcessor).ReadySockets := Readable(TncTCPServer(Socket).ReadSocketHandles, ExecCommandTimeout); if Length(TncServerProcessor(TncTCPServer(Socket).LineProcessor).ReadySockets) > 0 then TncServerProcessor(TncTCPServer(Socket).LineProcessor).SocketProcess; TncServerProcessor(TncTCPServer(Socket).LineProcessor).ReadySocketsChanged := True; end; finally ExecuteSerialiser.Release; end; end; if TStopWatch.GetTimeStamp - aLine.LastReceived >= ExecCommandTimeout * TTimeSpan.TicksPerMillisecond then raise ENetComCommandExecutionTimeout.Create(ENetComCommandExecutionTimeoutMessage); end; except PropertyLock.Acquire; try PendingCommandsList.Delete(PendingCommandsList.IndexOf(IDSent)); finally PropertyLock.Release; end; raise; end; // We are here because we got the result // Get the result of the command into the result of this function PropertyLock.Acquire; try PendingNdx := PendingCommandsList.IndexOf(IDSent); try Command := PendingCommandsList.Results[PendingNdx]; if Command.ResultIsErrorString then raise ENetComResultIsException.Create(StringOf(Command.Data)) else Result := Command.Data; finally PendingCommandsList.Delete(PendingNdx); end; finally PropertyLock.Release; end; finally ReceivedResultEvent.Free; // Event not needed any more end; end; // This is run in the reader's thread context procedure TncSourceBase.HandleReceivedCommand(aLine: TncSourceLine; const aCommandBytes: TBytes); var Command: TncCommand; HandleCommandThread: THandleCommandThread; PendingNdx: Integer; begin Command.FromBytes(aCommandBytes); case Command.CommandType of ctInitiator: begin // Handle the command from the thread pool HandleCommandThreadPool.Serialiser.Acquire; try HandleCommandThread := THandleCommandThread(HandleCommandThreadPool.RequestReadyThread); HandleCommandThread.WorkType := htwtOnHandleCommand; HandleCommandThread.OnHandleCommand := OnHandleCommand; HandleCommandThread.Source := Self; HandleCommandThread.Line := aLine; HandleCommandThread.Command := Command; HandleCommandThreadPool.RunRequestedThread(HandleCommandThread); finally HandleCommandThreadPool.Serialiser.Release; end; end; ctResponse: if Command.AsyncExecute then begin // Handle the command from the thread pool HandleCommandThreadPool.Serialiser.Acquire; try HandleCommandThread := THandleCommandThread(HandleCommandThreadPool.RequestReadyThread); HandleCommandThread.WorkType := htwtAsyncResponse; HandleCommandThread.OnAsyncExecCommandResult := OnAsyncExecCommandResult; HandleCommandThread.Source := Self; HandleCommandThread.Line := aLine; HandleCommandThread.Command := Command; HandleCommandThreadPool.RunRequestedThread(HandleCommandThread); finally HandleCommandThreadPool.Serialiser.Release; end; end else begin PropertyLock.Acquire; try // Find the event to set from the PendingCommandsList PendingNdx := PendingCommandsList.IndexOf(Command.UniqueID); // We may not find a pending command as the ExecCommand may have // timed out, so do nothing in that case if PendingNdx <> -1 then begin PendingCommandsList.Results[PendingNdx] := Command; PendingCommandsList.ReceivedResultEvents[PendingNdx].SetEvent; end; finally PropertyLock.Release; end; end; end; end; // Only from one thread called here, the reader thread, or the main vcl procedure TncSourceBase.SocketReadData(Sender: TObject; aLine: TncLine; const aBuf: TBytes; aBufCount: Integer); var Line: TncSourceLine; MagicInt: TMagicHeaderType; Ofs, BytesToRead, MesLen: UInt64; begin // From SocketProcess from Line := TncSourceLine(aLine); Ofs := 0; while Ofs < aBufCount do begin if Line.BytesToEndOfMessage > 0 then begin BytesToRead := Min(Line.BytesToEndOfMessage, UInt64(aBufCount) - Ofs); // Add to MessageData, BytesToRead from aBuf [Ofs] MesLen := Length(Line.MessageData); SetLength(Line.MessageData, MesLen + BytesToRead); move(aBuf[Ofs], Line.MessageData[MesLen], BytesToRead); Ofs := Ofs + BytesToRead; Line.BytesToEndOfMessage := Line.BytesToEndOfMessage - BytesToRead; end; if Line.BytesToEndOfMessage = 0 then begin if Length(Line.MessageData) > 0 then try try // Get message data uncompressed and unencrypted if Compression <> zcNone then Line.MessageData := DecompressBytes(Line.MessageData); if Encryption <> etNoEncryption then Line.MessageData := DecryptBytes(Line.MessageData, EncryptionKey, Encryption, EncryptOnHashedKey, False); HandleReceivedCommand(Line, Line.MessageData); finally // Dispose MessageData, we are complete SetLength(Line.MessageData, 0); end; except end; // Read a character if Ofs < aBufCount then begin if Length(Line.HeaderBytes) < SizeOf(TMagicHeaderType) + SizeOf(UInt64) then begin SetLength(Line.HeaderBytes, Length(Line.HeaderBytes) + 1); Line.HeaderBytes[High(Line.HeaderBytes)] := aBuf[Ofs]; Inc(Ofs); end else begin MagicInt := PMagicHeaderType(@Line.HeaderBytes[0])^; if MagicInt <> MagicHeader then begin SetLength(Line.HeaderBytes, 0); Dec(Ofs, SizeOf(TMagicHeaderType) + SizeOf(UInt64) - 1); end else begin // If a whole integer is read, prepare to read message Line.BytesToEndOfMessage := PUint64(@Line.HeaderBytes[SizeOf(TMagicHeaderType)])^; SetLength(Line.HeaderBytes, 0); end; end; end; end; // if Line.BytesToEndOfMessage = 0 end; // while Ofs < aBufCount end; function TncSourceBase.GetActive: Boolean; begin Result := Socket.Active; end; procedure TncSourceBase.SetActive(const Value: Boolean); begin if csLoading in ComponentState then WasSetActive := Value else Socket.Active := Value; end; function TncSourceBase.GetKeepAlive: Boolean; begin Result := Socket.KeepAlive; end; procedure TncSourceBase.SetKeepAlive(const Value: Boolean); begin Socket.KeepAlive := Value; end; function TncSourceBase.GetNoDelay: Boolean; begin Result := Socket.NoDelay; end; procedure TncSourceBase.SetNoDelay(const Value: Boolean); begin Socket.NoDelay := Value; end; function TncSourceBase.GetPort: Integer; begin Result := Socket.Port; end; procedure TncSourceBase.SetPort(const Value: Integer); begin Socket.Port := Value; end; function TncSourceBase.GetReaderThreadPriority: TncThreadPriority; begin Result := Socket.ReaderThreadPriority; end; procedure TncSourceBase.SetReaderThreadPriority(const Value: TncThreadPriority); begin Socket.ReaderThreadPriority := Value; end; function TncSourceBase.GetExecCommandTimeout: Cardinal; begin PropertyLock.Acquire; try Result := FCommandExecTimeout; finally PropertyLock.Release; end; end; procedure TncSourceBase.SetExecCommandTimeout(const Value: Cardinal); begin PropertyLock.Acquire; try FCommandExecTimeout := Value; finally PropertyLock.Release; end; end; function TncSourceBase.GetCommandProcessorThreadPriority: TncThreadPriority; begin PropertyLock.Acquire; try Result := FCommandProcessorThreadPriority; finally PropertyLock.Release; end; end; procedure TncSourceBase.SetCommandProcessorThreadPriority(const Value: TncThreadPriority); begin PropertyLock.Acquire; try FCommandProcessorThreadPriority := Value; if not(csLoading in ComponentState) then HandleCommandThreadPool.SetThreadPriority(Value); finally PropertyLock.Release; end; end; function TncSourceBase.GetCommandProcessorThreads: Integer; begin PropertyLock.Acquire; try Result := FCommandProcessorThreads; finally PropertyLock.Release; end; end; procedure TncSourceBase.SetCommandProcessorThreads(const Value: Integer); begin PropertyLock.Acquire; try FCommandProcessorThreads := Value; if Value <> 0 then FCommandProcessorThreadsPerCPU := 0; if not(csLoading in ComponentState) then HandleCommandThreadPool.SetExecThreads(Max(1, Max(FCommandProcessorThreads, GetNumberOfProcessors * FCommandProcessorThreadsPerCPU)), FCommandProcessorThreadPriority); finally PropertyLock.Release; end; end; function TncSourceBase.GetCommandProcessorThreadsPerCPU: Integer; begin PropertyLock.Acquire; try Result := FCommandProcessorThreadsPerCPU; finally PropertyLock.Release; end; end; procedure TncSourceBase.SetCommandProcessorThreadsPerCPU(const Value: Integer); begin PropertyLock.Acquire; try FCommandProcessorThreadsPerCPU := Value; if Value <> 0 then FCommandProcessorThreads := 0; if not(csLoading in ComponentState) then HandleCommandThreadPool.SetExecThreads(Max(1, Max(FCommandProcessorThreads, GetNumberOfProcessors * FCommandProcessorThreadsPerCPU)), FCommandProcessorThreadPriority); finally PropertyLock.Release; end; end; function TncSourceBase.GetCommandProcessorThreadsGrowUpto: Integer; begin PropertyLock.Acquire; try Result := FCommandProcessorThreadsGrowUpto; finally PropertyLock.Release; end; end; procedure TncSourceBase.SetCommandProcessorThreadsGrowUpto(const Value: Integer); begin PropertyLock.Acquire; try FCommandProcessorThreadsGrowUpto := Value; HandleCommandThreadPool.GrowUpto := Value; finally PropertyLock.Release; end; end; function TncSourceBase.GetEventsUseMainThread: Boolean; begin PropertyLock.Acquire; try Result := FEventsUseMainThread; finally PropertyLock.Release; end; end; procedure TncSourceBase.SetEventsUseMainThread(const Value: Boolean); begin PropertyLock.Acquire; try FEventsUseMainThread := Value; finally PropertyLock.Release; end; end; function TncSourceBase.GetCompression: TZCompressionLevel; begin PropertyLock.Acquire; try Result := FCompression; finally PropertyLock.Release; end; end; procedure TncSourceBase.SetCompression(const Value: TZCompressionLevel); begin PropertyLock.Acquire; try FCompression := Value; finally PropertyLock.Release; end; end; function TncSourceBase.GetEncryption: TEncryptorType; begin PropertyLock.Acquire; try Result := FEncryption; finally PropertyLock.Release; end; end; procedure TncSourceBase.SetEncryption(const Value: TEncryptorType); begin PropertyLock.Acquire; try FEncryption := Value; finally PropertyLock.Release; end; end; function TncSourceBase.GetEncryptionKey: string; begin PropertyLock.Acquire; try Result := FEncryptionKey; finally PropertyLock.Release; end; end; procedure TncSourceBase.SetEncryptionKey(const Value: string); begin PropertyLock.Acquire; try FEncryptionKey := Value; finally PropertyLock.Release; end; end; function TncSourceBase.GetEncryptOnHashedKey: Boolean; begin PropertyLock.Acquire; try Result := FEncryptOnHashedKey; finally PropertyLock.Release; end; end; procedure TncSourceBase.SetEncryptOnHashedKey(const Value: Boolean); begin PropertyLock.Acquire; try FEncryptOnHashedKey := Value; finally PropertyLock.Release; end; end; function TncSourceBase.GetComponentName: string; begin Result := Name; end; function TncSourceBase.GetOnConnected: TncOnSourceConnectDisconnect; begin Result := FOnConnected; end; procedure TncSourceBase.SetOnConnected(const Value: TncOnSourceConnectDisconnect); begin FOnConnected := Value; end; function TncSourceBase.GetOnDisconnected: TncOnSourceConnectDisconnect; begin Result := FOnDisconnected; end; procedure TncSourceBase.SetOnDisconnected(const Value: TncOnSourceConnectDisconnect); begin FOnDisconnected := Value; end; function TncSourceBase.GetOnHandleCommand: TncOnSourceHandleCommand; begin Result := FOnHandleCommand; end; procedure TncSourceBase.SetOnHandleCommand(const Value: TncOnSourceHandleCommand); begin FOnHandleCommand := Value; end; function TncSourceBase.GetOnAsyncExecCommandResult: TncOnAsyncExecCommandResult; begin Result := FOnAsyncExecCommandResult; end; procedure TncSourceBase.SetOnAsyncExecCommandResult(const Value: TncOnAsyncExecCommandResult); begin FOnAsyncExecCommandResult := Value; end; { THandleCommandThread } procedure THandleCommandThread.CallOnAsyncEvents; begin if Assigned(CommandHandler.OnAsyncExecCommandResult) then CommandHandler.OnAsyncExecCommandResult( Source, Line, Command.Cmd, Command.Data, Command.ResultIsErrorString, Command.SourceComponentHandler, Command.PeerComponentHandler); end; procedure THandleCommandThread.CallOnHandleEvents; begin if Assigned(CommandHandler.OnHandleCommand) then try Command.Data := CommandHandler.OnHandleCommand( Source, Line, Command.Cmd, Command.Data, Command.RequiresResult, Command.SourceComponentHandler, Command.PeerComponentHandler); Command.ResultIsErrorString := False; except on E: Exception do begin Command.ResultIsErrorString := True; Command.Data := BytesOf(E.ClassName + ' error: ' + E.Message); end; end else SetLength(Command.Data, 0); end; procedure THandleCommandThread.ProcessEvent; var i: Integer; begin // Find which command handler handles the events CommandHandler := nil; for i := 0 to High(Source.CommandHandlers) do if Source.CommandHandlers[i].GetComponentName = Command.PeerComponentHandler then begin CommandHandler := Source.CommandHandlers[i]; Break; end; if not Assigned(CommandHandler) then Source.GetInterface(IncCommandHandler, CommandHandler); case WorkType of htwtAsyncResponse: if Source.EventsUseMainThread then Synchronize(CallOnAsyncEvents) else CallOnAsyncEvents; htwtOnHandleCommand: begin Command.ResultIsErrorString := False; if Source.EventsUseMainThread then Synchronize(CallOnHandleEvents) else CallOnHandleEvents; // Send the response if Command.RequiresResult then begin Command.CommandType := ctResponse; Source.WriteCommand(Line, Command); end; end; end; end; // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// { TncClientSource } // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// type TncTCPClientSourceSocket = class(TncTCPClient) protected function CreateLineObject: TncLine; override; end; function TncTCPClientSourceSocket.CreateLineObject: TncLine; begin Result := TncSourceLine.Create; end; constructor TncClientSource.Create(AOwner: TComponent); begin inherited Create(AOwner); FOnReconnected := nil; Socket := TncTCPClientSourceSocket.Create(nil); Socket.Port := DefPort; Socket.NoDelay := DefNoDelay; Socket.EventsUseMainThread := False; Socket.OnConnected := SocketConnected; Socket.OnDisconnected := SocketDisconnected; Socket.OnReadData := SocketReadData; TncTCPClient(Socket).OnReconnected := SocketReconnected; end; destructor TncClientSource.Destroy; begin Socket.Free; inherited Destroy; end; function TncClientSource.GetLine: TncLine; begin Result := TncTCPClient(Socket).Line; end; procedure TncClientSource.WriteMessage(aLine: TncSourceLine; const aBuf: TBytes); begin Active := True; inherited WriteMessage(aLine, aBuf); end; function TncClientSource.ExecCommand( const aCmd: Integer; const aData: TBytes = nil; const aRequiresResult: Boolean = True; const aAsyncExecute: Boolean = False; const aPeerComponentHandler: string = ''; const aSourceComponentHandler: string = ''): TBytes; begin if not Active then Active := True; Result := ExecCommand(TncSourceLine(GetLine), aCmd, aData, aRequiresResult, aAsyncExecute, aPeerComponentHandler, aSourceComponentHandler); end; function TncClientSource.GetHost: string; begin Result := TncTCPClient(Socket).Host; end; procedure TncClientSource.SetHost(const Value: string); begin TncTCPClient(Socket).Host := Value; end; function TncClientSource.GetReconnect: Boolean; begin Result := TncTCPClient(Socket).Reconnect; end; procedure TncClientSource.SetReconnect(const Value: Boolean); begin TncTCPClient(Socket).Reconnect := Value; end; function TncClientSource.GetReconnectInterval: Cardinal; begin Result := TncTCPClient(Socket).ReconnectInterval; end; procedure TncClientSource.SetReconnectInterval(const Value: Cardinal); begin TncTCPClient(Socket).ReconnectInterval := Value; end; // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// { TncServerSource } // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// type TncTCPServerSourceSocket = class(TncTCPServer) protected function CreateLineObject: TncLine; override; end; function TncTCPServerSourceSocket.CreateLineObject: TncLine; begin Result := TncSourceLine.Create; end; constructor TncServerSource.Create(AOwner: TComponent); begin inherited Create(AOwner); Socket := TncTCPServerSourceSocket.Create(nil); Socket.NoDelay := DefNoDelay; Socket.Port := DefPort; Socket.EventsUseMainThread := False; Socket.OnConnected := SocketConnected; Socket.OnDisconnected := SocketDisconnected; Socket.OnReadData := SocketReadData; end; destructor TncServerSource.Destroy; begin Socket.Free; inherited Destroy; end; function TncServerSource.GetLines: TThreadLineList; begin Result := TncTCPServer(Socket).Lines; end; procedure TncServerSource.ShutDownLine(aLine: TncLine); begin TncTCPServer(Socket).ShutDownLine(aLine); end; end.
unit AAlteraEstagioChamado; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, StdCtrls, Buttons, PainelGradiente, ExtCtrls, Componentes1, DBKeyViolation, Localizacao, UnChamado; type TFAlteraEstagioChamado = class(TFormularioPermissao) PanelColor1: TPanelColor; PanelColor2: TPanelColor; PainelGradiente1: TPainelGradiente; BGravar: TBitBtn; BCancelar: TBitBtn; ConsultaPadrao1: TConsultaPadrao; EUsuario: TEditLocaliza; Label5: TLabel; SpeedButton2: TSpeedButton; Label6: TLabel; SpeedButton1: TSpeedButton; Label2: TLabel; Label3: TLabel; BChamado: TSpeedButton; Label1: TLabel; Label4: TLabel; Label7: TLabel; SpeedButton4: TSpeedButton; Label8: TLabel; ECodEstagio: TEditLocaliza; EChamado: TEditLocaliza; EEstagioAtual: TEditLocaliza; ValidaGravacao1: TValidaGravacao; EMotivo: TMemoColor; Label9: TLabel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BCancelarClick(Sender: TObject); procedure BGravarClick(Sender: TObject); procedure EUsuarioChange(Sender: TObject); procedure EChamadoRetorno(Retorno1, Retorno2: String); procedure EChamadoSelect(Sender: TObject); procedure EChamadoChange(Sender: TObject); procedure ECodEstagioRetorno(Retorno1, Retorno2: String); procedure ECodEstagioSelect(Sender: TObject); private { Private declarations } VprAcao : Boolean; VprChamados : String; FunChamado : TRBFuncoesChamado; function DadosValidos : String; public { Public declarations } function AlteraEstagioChamado:Boolean; function AlteraEstagioChamados(VpaChamados : String):Boolean; function AlteraEstagio(VpaNumChamado : Integer):Boolean; end; var FAlteraEstagioChamado: TFAlteraEstagioChamado; implementation uses APrincipal,Constantes, ConstMsg, FunObjeto; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFAlteraEstagioChamado.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } VprAcao := false; FunChamado := TRBFuncoesChamado.cria(FPrincipal.BaseDados); VprChamados := ''; end; { ******************* Quando o formulario e fechado ************************** } procedure TFAlteraEstagioChamado.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } FunChamado.free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFAlteraEstagioChamado.BCancelarClick(Sender: TObject); begin VprAcao := false; close; end; {******************************************************************************} procedure TFAlteraEstagioChamado.BGravarClick(Sender: TObject); var VpfResultado : String; begin VpfResultado := DadosValidos; if VpfResultado = '' then begin if VprChamados = '' then VpfResultado := FunChamado.AlteraEstagioChamado(varia.CodigoEmpfil,EChamado.AInteiro,EUsuario.AInteiro,ECodEstagio.AInteiro,EMotivo.Lines.text) else VpfResultado := FunChamado.AlteraEstagioChamados(varia.CodigoEmpfil,EUsuario.AInteiro,ECodEstagio.AInteiro,VprChamados,EMotivo.Lines.Text); if VpfResultado = '' then begin VprAcao := true; close; end end; if VpfResultado <> '' then aviso(VpfREsultado); end; {******************************************************************************} procedure TFAlteraEstagioChamado.EUsuarioChange(Sender: TObject); begin ValidaGravacao1.Execute; end; {******************************************************************************} procedure TFAlteraEstagioChamado.EChamadoRetorno(Retorno1, Retorno2: String); begin if retorno1 <> '' then EEstagioAtual.Text := Retorno1 else EEstagioAtual.clear; EEstagioAtual.Atualiza; end; {******************************************************************************} procedure TFAlteraEstagioChamado.EChamadoSelect(Sender: TObject); begin EChamado.ASelectValida.Text := 'Select CHA.NUMCHAMADO, CHA.CODESTAGIO, CLI.C_NOM_CLI '+ ' from CHAMADOCORPO CHA, CADCLIENTES CLI '+ ' Where CHA.CODCLIENTE = CLI.I_COD_CLI '+ ' AND CHA.NUMCHAMADO = @ '+ ' AND CHA.CODFILIAL = ' +IntToStr(varia.CodigoEmpFil); EChamado.ASelectLocaliza.Text := 'Select CHA.NUMCHAMADO, CHA.CODESTAGIO, CLI.C_NOM_CLI '+ ' from CHAMADOCORPO CHA, CADCLIENTES CLI '+ ' Where CHA.CODCLIENTE = CLI.I_COD_CLI '+ ' AND CLI.C_NOM_CLI LIKE ''@%'''+ ' AND CHA.CODFILIAL = ' +IntToStr(varia.CodigoEmpFil); end; {******************************************************************************} function TFAlteraEstagioChamado.AlteraEstagioChamado:Boolean; begin EUsuario.AInteiro := varia.CodigoUsuario; EUsuario.Atualiza; showmodal; result := VprAcao; end; {******************************************************************************} function TFAlteraEstagioChamado.AlteraEstagioChamados(VpaChamados : String):Boolean; begin EUsuario.AInteiro := varia.CodigoUsuario; EUsuario.Atualiza; VprChamados := VpaChamados; AlterarEnabledDet([EChamado,BChamado],false); EChamado.ACampoObrigatorio := false; showmodal; result := VprAcao; end; {******************************************************************************} function TFAlteraEstagioChamado.AlteraEstagio(VpaNumChamado : Integer):Boolean; begin EUsuario.AInteiro := varia.CodigoUsuario; EUsuario.Atualiza; EChamado.AInteiro := VpaNumChamado; EChamado.Atualiza; ActiveControl := ECodEstagio; showmodal; result := VprAcao; end; {******************************************************************************} function TFAlteraEstagioChamado.DadosValidos : String; begin result := ''; if EMotivo.ACampoObrigatorio then if EMotivo.Lines.Text = '' then result := 'MOTIVO NÃO PREENCHIDO!!!'#13'É necessário preencher o motivo pelo qual se está mudando de estágio'; end; {******************************************************************************} procedure TFAlteraEstagioChamado.EChamadoChange(Sender: TObject); begin ValidaGravacao1.execute; end; {******************************************************************************} procedure TFAlteraEstagioChamado.ECodEstagioRetorno(Retorno1,Retorno2: String); begin EMotivo.ACampoObrigatorio := false; if retorno1 <> '' then begin if Retorno1 = 'S' then EMotivo.ACampoObrigatorio := true; end; end; {******************************************************************************} procedure TFAlteraEstagioChamado.ECodEstagioSelect(Sender: TObject); begin ECodEstagio.ASelectLocaliza.Text := ' Select * from ESTAGIOPRODUCAO ' + ' Where TIPEST = ''A'' '+ ' AND NOMEST LIKE ''@%'''; ECodEstagio.ASelectValida.Text := ' Select * from ESTAGIOPRODUCAO '+ ' Where CODEST = @ ' + ' AND TIPEST = ''A'' '; if not (puAdministrador in varia.PermissoesUsuario) then if (puCREstagiosAutorizados in varia.PermissoesUsuario) then begin // somente os estágios autorizados deste grupo de usuario ECodEstagio.ASelectLocaliza.Text := ECodEstagio.ASelectLocaliza.Text + ' AND CODEST IN ' + varia.CodigosEstagiosAutorizados; ECodEstagio.ASelectValida.Text := ECodEstagio.ASelectValida.Text + ' AND CODEST IN ' + varia.CodigosEstagiosAutorizados; end; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFAlteraEstagioChamado]); end.
(* Этот модуль позволяет производить дифференцирование This unit have to perform derivatives Created by Scherbakov Maksim Sherbakov.maks@gmail.com *) unit Derivatives; interface uses System.SysUtils, RegularExpressions, Math; type TStack = class private private StackArray: array of string; Top: Integer; public constructor Create; destructor Destroy; procedure Push(Input: String); function Pop: String; function Peek: String; function isEmpty: Boolean; function Item(Index: Integer): String; end; TFormula = record Pattern: String; // Character // Deriv: integer; // ID of derivatives Deriv: String; // Derivatives end; function TableDeriv(s: String): String; procedure Fragm(Derivatives: String); function getDerivs(Input: String): String; procedure AppointSubexprID(var Input: String); // procedure DisappointSubexprID (var Input: String; Option: TOptions); implementation CONST NUM_FORMUL = 15; // number of differentiation formulas // TAB_VALUE: array [0 .. n] of TFormula = ( // (Pattern: '^'; Deriv: 0), // n*x^(n-1) // (Pattern: 'sqrt'; Deriv: 1), // 1/2*sqrt(x) // (Pattern: '/'; Deriv: 2), // -1/x^2 // (Pattern: 'e'; Deriv: 3), // e^x // (Pattern: '^x'; Deriv: 4), // a^x*ln(a) // (Pattern: 'ln'; Deriv: 5), // 1/x // (Pattern: 'log'; Deriv: 6), // 1/x*ln(a) // (Pattern: 'sin'; Deriv: 7), // cos(x) // (Pattern: 'cos'; Deriv: 8), // -sin(x) // (Pattern: 'tg'; Deriv: 9), // 1/cos(x)^2 // (Pattern: 'ctg'; Deriv: 10), // -1/sin(x)^2 // (Pattern: 'arcsin'; Deriv: 11), // 1/sqrt(1-x^2) // (Pattern: 'arccos'; Deriv: 12), // -1/sqrt(1-x^2) // (Pattern: 'arctg'; Deriv: 13), // 1/(1+x^2) // (Pattern: 'arcctg'; Deriv: 14) // -1/(1+x^2) // { ... } // ); { TODO -oMax -cRefactoring : сделать рабочую таблицу, сейчас стоит заглушка } TAB_VALUE: array [0 .. NUM_FORMUL] of TFormula = ( // /// / (Pattern: '\d*\^?\d*'; Deriv: '0'), // a (Pattern: '\d*\*?x'; Deriv: 'a'), // a*x (Pattern: 'x\^?\d*'; Deriv: 'n*x^(n-1)'), // a*x^n (Pattern: 'sqrt\(.*?x.*?\)'; Deriv: '1/(2*sqrt(x))'), // b*sqrt(x) (Pattern: '1/\(?.*x.*\)?'; Deriv: '-1/(x)'), // b/(x) (Pattern: 'e\^?\d*\*?x'; Deriv: 'a*b*e^(a*x)'), // b*e^(a*x) // it is problem formula (Pattern: '\d+\^\d*\*?x'; Deriv: 'a^x*ln(a)'), // a^x // it is problem formula (Pattern: '\d*\*?ln\(.*x.*\)'; Deriv: '1/x'), // b*ln(x) (Pattern: '\d*\*?log\(\d+,.*x.*\)'; Deriv: '1/x*ln(a)'), // b*log(p, x) (Pattern: '\d*\*?sin\(\d*\*?x\^?\d*\)'; Deriv: 'a*b*n*x^(n-1)*cos(a*x^n)'), // b*sin(a*x^n) // maybe it is not tabular formula (Pattern: '\d*\*?cos\(\d*\*?x\^?\d*\)'; Deriv: '-a*b*n*x^(n-1)*sin(a*x^n)'), // b*cos(a*x^n) // maybe it is not tabular formula (Pattern: 'tan'; Deriv: '1/cos(x)^2'), (Pattern: 'cot'; Deriv: '-1/sin(x)^2'), (Pattern: 'arcsin'; Deriv: '1/sqrt(1-x^2)'), (Pattern: 'arccos'; Deriv: '-1/sqrt(1-x^2)'), (Pattern: 'arctg'; Deriv: '1/(1+x^2)'), (Pattern: 'arcctg'; Deriv: '-1/(1+x^2)') { ... } ); var BrokenDeriv: array of String; // Хранит частные производные, полученные с помощью Fragm(); RegEx: TRegEx; // Экземпляр класса TRegEx, для использования регулярных выражений Subexpr: TStack; // Хранит выражения в скобках // TStack+ constructor TStack.Create; begin SetLength(StackArray, 1); Top := -1; end; destructor TStack.Destroy; begin SetLength(StackArray, 0); end; procedure TStack.Push(Input: String); begin Inc(Top); SetLength(StackArray, Top + 1); StackArray[Top] := Input; end; function TStack.Pop: String; begin Result := StackArray[Top]; Dec(Top); SetLength(StackArray, Top + 1); end; function TStack.Peek: String; begin Result := StackArray[Top]; end; function TStack.isEmpty: Boolean; begin Result := (Top = -1); end; function TStack.Item(Index: Integer): String; begin Result := StackArray[Index]; end; // TStack- function TableDeriv(s: String): String; // Checks what type belongs to the derivative function CheckType(s: String): Integer; var i: Integer; begin for i := Low(TAB_VALUE) to High(TAB_VALUE) do begin if Not(AnsiPos(TAB_VALUE[i].Pattern, s) = 0) then begin Result := i; Exit; end else begin Result := -1; Exit; end; end; end; begin { TODO -oMax -cNext : Преобразовать табличную производную } Result := IntToStr(CheckType(s)); end; // Replaces subexpressions on the ID {completed} procedure AppointSubexprID(var Input: String); var Pattern: String; begin // D+ // Subexpr := TStack.Create; // D- Pattern := '\([^x\(\)]*?(x|#)[^x\(\)]*?\)'; // Выражения в скобках while RegEx.IsMatch(Input, Pattern) do begin Subexpr.Push(RegEx.Match(Input, Pattern).Value); Input := StringReplace(Input, Subexpr.Peek, '#', []); // D+ writeln('Stack = ' + Subexpr.Peek); // D- end; // Subexpr.Push(Input); // D+ // while Not(Subexpr.isEmpty) do // writeln('Subexpr = ' + Subexpr.Pop); // Writeln('Input after = ' + Input); // Subexpr.Destroy; // D- end; // Replaces IDs on the subexpression {completed} procedure DisappointSubexprID(var Input: String; Single: Boolean); var i: Integer; begin // S+ if Single then begin for i := High(Input) downto Low(Input) do begin if Input[i] = '#' then begin Delete(Input, i, 1); Insert(Subexpr.Pop, Input, i); end; end; end else begin while (pos('#', Input) <> 0) do for i := High(Input) downto Low(Input) do begin if Input[i] = '#' then begin Delete(Input, i, 1); Insert(Subexpr.Pop, Input, i); end; end; end; // S- end; // Fragmentation of derivatives {Completed} procedure Fragm(Derivatives: String); var n: Integer; TempPos: Integer; Pattern: String; begin // D+ writeln('Before = ' + Derivatives); // D- Subexpr := TStack.Create; AppointSubexprID(Derivatives); // ОПАСНО, КОСТЫЛЬ! // Приравнивание к нулю всех чисел без "х" Pattern := '(^-?\d+|[\+-]\d+$)'; Derivatives := RegEx.Replace(Derivatives, Pattern, ''); Pattern := '[\+-]\d+\+'; Derivatives := RegEx.Replace(Derivatives, Pattern, '+'); Pattern := '[\+-]\d+-'; Derivatives := RegEx.Replace(Derivatives, Pattern, '-'); // Разделения оставшихся производных знаками "+" и "-" // И сохранения их в массив BrokenDeriv n := 0; Pattern := '(^|[\+-])[^\+-]+'; while Length(Derivatives) > 0 do begin Inc(n); SetLength(BrokenDeriv, n); BrokenDeriv[n - 1] := RegEx.Match(Derivatives, Pattern).Value; TempPos := RegEx.Match(Derivatives, Pattern).Index + (RegEx.Match(Derivatives, Pattern).Length - 1); Delete(Derivatives, 1, TempPos); end; for n := High(BrokenDeriv) downto Low(BrokenDeriv) do DisappointSubexprID(BrokenDeriv[n], False); Subexpr.Destroy; // D+ writeln('After = '); for n := Low(BrokenDeriv) to High(BrokenDeriv) do writeln(BrokenDeriv[n]); // D- end; // Возвращает табличную производную function getDerivs(Input: String): String; // Возвращает количество вхождений Subtext в Text function CountPos(Text: String; Subtext: String): Integer; begin if (Length(Subtext) = 0) or (Length(Text) = 0) or (pos(Subtext, Text) = 0) then Result := 0 else Result := (Length(Text) - Length(StringReplace(Text, Subtext, '', [rfReplaceAll]))) div Length(Subtext); end; function QuotientRule(Input: String): String; begin { TODO -oMax -cCoding : writting code here } end; Function ProductRule(Input: String): String; begin { TODO -oMax -cCoding : writting code here } end; var i, depth: Integer; Derivatives: String; Pattern: String; begin // Inc(depth); Subexpr := TStack.Create; {TODO -oMax -cCoding : Проработать алгоритм} AppointSubexprID(Input); if CountPos(Input, '#') > 1 then begin if Not(pos('/', Input) = 0) then Input := QuotientRule(Input) else Input := ProductRule(Input); end else Input := '$' + Input; Input := TableDeriv(Input); DisappointSubexprID(Input, True); Result := Result + Input; if Subexpr.isEmpty then Exit else begin { TODO -oMax -cCoding : Начало рекурсии/цикла } Subexpr.Destroy; end; end; end.
{----------------------------------------------------------------------------- Author: Roman Fadeyev Purpose: Реализация IStockDataSourceConnection для загрузки данных из файла History: -----------------------------------------------------------------------------} unit FC.StockData.StockDataConnectionFile; {$I Compiler.inc} interface uses SysUtils,Classes,DB, Serialization, FC.Definitions,FC.StockData.StockDataSource; type //Basic connection TStockDataSourceConnectionFile = class (TNameValuePersistentObjectRefCounted,IStockDataSourceConnection) private FConnectionString: string; FSymbol: string; FInterval : TStockTimeInterval; public constructor Create(const aSymbol: string; aInterval: TStockTimeInterval; const aConnectionString: string); property Symbol: string read FSymbol; property Interval : TStockTimeInterval read FInterval; //TPersistentObject procedure OnDefineValues; override; procedure OnReadValue(const aReader: INameValueDataReader; const aName: string; var aHandled: boolean); override; procedure OnWriteValues(const aWriter: INameValueDataWriter); override; //IStockDataSourceConnection function CreateDataSource(aUseCacheIfPossible: boolean=true): IStockDataSource; virtual; abstract; function ConnectionString: string; end; TFileStreamEx = class(TFileStream) public constructor CreateForRead(const aFileName:string); end; implementation uses RTLConsts; { TFileStreamEx } constructor TFileStreamEx.CreateForRead(const aFileName:string); var x: integer; begin x:=SysUtils.FileOpen(aFileName, fmOpenRead or fmShareDenyNone); if x < 0 then raise EFOpenError.CreateResFmt(@SFOpenErrorEx, [ExpandFileName(aFileName), SysErrorMessage(GetLastError)]); inherited Create(x); end; { TStockDataSourceConnectionFile } function TStockDataSourceConnectionFile.ConnectionString: string; begin result:=FConnectionString; end; constructor TStockDataSourceConnectionFile.Create(const aSymbol: string; aInterval: TStockTimeInterval; const aConnectionString: string); begin inherited Create; FSymbol:=aSymbol; FInterval:=aInterval; FConnectionString:=aConnectionString; end; procedure TStockDataSourceConnectionFile.OnDefineValues; begin inherited; DefValString('ConnectionString',FConnectionString); DefValString('Symbol',FSymbol); end; procedure TStockDataSourceConnectionFile.OnReadValue(const aReader: INameValueDataReader; const aName: string; var aHandled: boolean); begin inherited; if aName='Interval' then begin aReader.ReadEnum(FInterval); aHandled:=true; end; end; procedure TStockDataSourceConnectionFile.OnWriteValues(const aWriter: INameValueDataWriter); begin inherited; aWriter.WriteEnum('Interval',FInterval); end; end.
unit myunion_impl; {This file was generated on 16 Jun 2000 16:37:51 GMT by version 03.03.03.C1.04} {of the Inprise VisiBroker idl2pas CORBA IDL compiler. } {Please do not edit the contents of this file. You should instead edit and } {recompile the original IDL which was located in the file myunion.idl. } {Delphi Pascal unit : myunion_impl } {derived from IDL module : default } interface uses SysUtils, CORBA, myunion_i, myunion_c; type TAccount = class; TAccount = class(TInterfacedObject, myunion_i.Account) protected _balance : Single; public constructor Create; function balance ( const myUnion : myunion_i.UnionType): Single; end; implementation uses ServerMain; constructor TAccount.Create; begin inherited; _balance := Random * 1000; end; function TAccount.balance ( const myUnion : myunion_i.UnionType): Single; var st : String; disc : Integer; begin Result := _balance; with Form1 do begin Memo1.Lines.Add('Got a balance call from the client...'); disc := myUnion._discriminator; case disc of -1 : st := 'discriminator = -1 -- union value = ' + IntToStr(myUnion.s); 0 : st := 'discriminator = 0 -- union value = ' + IntToStr(myUnion.l); 1 : st := 'discriminator = 1 -- union value = ' + myUnion.i; end; Memo1.Lines.Add(st); end; end; initialization Randomize; end.
{*************************************************************************** * * Orion-project.org Lazarus Helper Library * Copyright (C) 2016-2017 by Nikolay Chunosov * * This file is part of the Orion-project.org Lazarus Helper Library * https://github.com/Chunosov/orion-lazarus * * This Library is free software: you can redistribute it and/or modify it * under the terms of the MIT License. See enclosed LICENSE.txt for details. * ***************************************************************************} unit OriUtils_Gui; {$mode objfpc}{$H+} interface uses Classes, Graphics, Controls, ExtCtrls, Forms; procedure SetDefaultColor(AControl: TWinControl; AColor: TColor = clNone); procedure ScaleDPI(AControl: TControl; FromDPI: Integer); {%region Message Dialogs} procedure MessageDlg(const S: String); overload; procedure ErrorDlg(const S: String); procedure ErrorDlg(const S: String; Args: array of const); function ConfirmDlg(const S: String): Boolean; function ConfirmDlg(const S: String; Args: array of const): Boolean; {%endregion} {%region Form Helpers} procedure SaveFormPos(AForm: TForm; var ASavedPos: Longword); procedure SaveFormSize(AForm: TForm; var ASavedSize: Longword); procedure SaveFormSizePos(AForm: TForm; var ASavedSize, ASavedPos: Longword); procedure RestoreFormPos(AForm: TForm; ASavedPos: Longword); procedure RestoreFormSize(AForm: TForm; ASavedSize: Longword); procedure RestoreFormSizePos(AForm: TForm; ASavedSize, ASavedPos: Longword); procedure SetPosNoOverlap(AForm: TForm; X, Y: Integer; Position: TPosition = poDesigned); overload; procedure SetPosNoOverlap(AForm: TForm; X, Y, W, H: Integer; Position: TPosition = poDesigned); overload; {%endregion} {%region File Dialogs} type TFileDialogParams = record Title: String; Filters: String; FilterIndex: Integer; FileName: String; FileNames: TStrings; InitialDir: String; MultiSelect: Boolean; DefaultExt: String; end; function OpenFileDialog(var Params: TFileDialogParams): Boolean; overload; function SaveFileDialog(var Params: TFileDialogParams): Boolean; overload; function OpenFileDialog(const Title, Filters, Ext: String; var FileName: String): Boolean; overload; function SaveFileDialog(const Title, Filters, Ext: String; var FileName: String): Boolean; overload; function FileDlgParams(const Title, Filters, Ext: String): TFileDialogParams; {%endregion} function GetMaxTopChild(AParent: TWinControl): Integer; implementation uses {$ifdef WINDOWS} Windows, CommDlg, {$endif} SysUtils, Dialogs, LCLIntf, LazUTF8; {%region Controls} // Sets a default theme-aware color for TPanels. On some environments // (for example on Ubuntu Unity) the default window color is not clBtnFace. // But TPanel has clBtnFace color when we set clDefault for it. procedure SetDefaultColor(AControl: TWinControl; AColor: TColor = clNone); var I: Integer; Control: TControl; begin if AColor = clNone then AColor := AControl.GetDefaultColor(dctBrush); if AControl is TCustomPanel then AControl.Color := AColor; for I := 0 to AControl.ControlCount-1 do begin Control := AControl.Controls[I]; if Control is TWinControl then SetDefaultColor(TWinControl(Control), AColor); end; end; // Scales a control and its children according to current screen dpi. // From here: http://wiki.lazarus.freepascal.org/High_DPI procedure ScaleDPI(AControl: TControl; FromDPI: Integer); var I: Integer; Control: TWinControl; begin if Screen.PixelsPerInch = FromDPI then Exit; with AControl do begin Left := ScaleX(Left, FromDPI); Top := ScaleY(Top, FromDPI); Width := ScaleX(Width, FromDPI); Height := ScaleY(Height, FromDPI); end; if AControl is TWinControl then begin Control := TWinControl(AControl); if Control.ControlCount = 0 then Exit; with Control.ChildSizing do begin HorizontalSpacing := ScaleX(HorizontalSpacing, FromDPI); LeftRightSpacing := ScaleX(LeftRightSpacing, FromDPI); TopBottomSpacing := ScaleY(TopBottomSpacing, FromDPI); VerticalSpacing := ScaleY(VerticalSpacing, FromDPI); end; for I := 0 to Control.ControlCount - 1 do ScaleDPI(Control.Controls[I], FromDPI); end; end; {%endregion} {%region Message Dialogs} procedure MessageDlg(const S: String); begin Dialogs.MessageDlg(Application.Title, S, mtInformation, [mbOK], ''); end; procedure ErrorDlg(const S: String); begin Dialogs.MessageDlg(Application.Title, S, mtError, [mbOK], ''); end; procedure ErrorDlg(const S: String; Args: array of const); begin ErrorDlg(Format(S, Args)); end; function ConfirmDlg(const S: String): Boolean; begin Result := Dialogs.MessageDlg(Application.Title, S, mtConfirmation, mbYesNo, '') = mrYes; end; function ConfirmDlg(const S: String; Args: array of const): Boolean; begin Result := ConfirmDlg(Format(S, Args)); end; {%endregion} {%region Form Helpers} procedure SaveFormPos(AForm: TForm; var ASavedPos: Longword); begin with AForm do ASavedPos := MakeLong(Left, Top); end; procedure SaveFormSize(AForm: TForm; var ASavedSize: Longword); begin with AForm do ASavedSize := MakeLong(Width, Height); end; procedure SaveFormSizePos(AForm: TForm; var ASavedSize, ASavedPos: Longword); begin SaveFormPos(AForm, ASavedPos); SaveFormSize(AForm, ASavedSize); end; procedure RestoreFormPos(AForm: TForm; ASavedPos: Longword); begin with AForm do if ASavedPos <> 0 then begin Position := poDesigned; Left := Lo(ASavedPos); Top := Hi(ASavedPos); end else Position := poScreenCenter end; procedure RestoreFormSize(AForm: TForm; ASavedSize: Longword); begin with AForm do if ASavedSize <> 0 then begin Width := Lo(ASavedSize); Height := Hi(ASavedSize); end; end; procedure RestoreFormSizePos(AForm: TForm; ASavedSize, ASavedPos: Longword); begin RestoreFormSize(AForm, ASavedSize); RestoreFormPos(AForm, ASavedPos); end; procedure SetPosNoOverlap(AForm: TForm; X, Y: Integer; Position: TPosition = poDesigned); begin SetPosNoOverlap(AForm, X, Y, AForm.Width, AForm.Height, Position) end; procedure SetPosNoOverlap(AForm: TForm; X, Y, W, H: Integer; Position: TPosition = poDesigned); const SafeCounter = 100; var FormClass: TClass; I, J, DW, DH: Integer; begin DW := Screen.DesktopWidth; DH := Screen.DesktopHeight; if Position = poDesktopCenter then begin X := (DW - W) div 2; Y := (DH - H) div 2; end else if Position = poScreenCenter then with Screen.WorkAreaRect do begin X := (Right - Left - W) div 2; Y := (Bottom - Top - H) div 2; end; I := 0; J := 0; FormClass := AForm.ClassType; while (I < Screen.FormCount-1) and (J < SafeCounter) do begin if (Screen.Forms[I] is FormClass) and (Screen.Forms[I] <> AForm) then if (X = Screen.Forms[I].Left) and (Y = Screen.Forms[I].Top) then begin Inc(X, 40); if X >= DW then X := 0; Inc(Y, 40); if Y >= DH then Y := 0; I := -1; end; Inc(I); Inc(J); end; AForm.SetBounds(X, Y, W, H); end; {%endregion} {%region File Dialogs} function FileDlgParams(const Title, Filters, Ext: String): TFileDialogParams; begin Result.Title := Title; Result.Filters := Filters; Result.FilterIndex := 1; Result.DefaultExt := Ext; Result.MultiSelect := False; Result.FileNames := nil; end; function OpenFileDialog(const Title, Filters, Ext: String; var FileName: String): Boolean; var Params: TFileDialogParams; begin Params := FileDlgParams(Title, Filters, Ext); Params.FileName := FileName; Result := OpenFileDialog(Params); if Result then FileName := Params.FileName; end; function SaveFileDialog(const Title, Filters, Ext: String; var FileName: String): Boolean; var Params: TFileDialogParams; begin Params := FileDlgParams(Title, Filters, Ext); Params.FileName := FileName; Result := SaveFileDialog(Params); if Result then FileName := Params.FileName; end; {$ifdef WINDOWS} type TWinApiFileDlgType = (wadtOpen, wadtSave); function WinApiFileDialog(var Params: TFileDialogParams; DlgType: TWinApiFileDlgType): Boolean; var fnStruct: TOpenFileName; szFile: array[0..MAX_PATH] of Char; procedure ParseMultipleFileNames; var I: Integer; Index: Integer = 0; CurDir: String = ''; FileName: String; begin for I := 0 to MAX_PATH do if szFile[I] = #0 then begin if (I > 0) and (szFile[I-1] = #0) then // #0#0 ends the string begin if (Params.FileNames.Count = 0) and (CurDir <> '') then // single file is selected if FileExists(CurDir) then Params.FileNames.Add(SysToUTF8(CurDir)); exit; end; if CurDir <> '' then begin FileName := PChar(@(szFile[Index])); FileName := IncludeTrailingPathDelimiter(CurDir) + FileName; if FileExists(FileName) then Params.FileNames.Add(SysToUTF8(FileName)); end else CurDir := szFile; Index := I+1; end; end; begin Result := False; FillChar(fnStruct{%H-}, SizeOf(TOpenFileName), 0); with fnStruct do begin hwndOwner := Application.MainFormHandle; lStructSize := SizeOf(TOpenFileName); lpstrFile := {%H-}szFile; StrPCopy(lpstrFile, UTF8ToSys(Params.FileName)); nMaxFile := Length(szFile); lpstrFilter := PChar(StringReplace(Params.Filters, '|', #0, [rfReplaceAll]) + #0#0); nFilterIndex := Params.FilterIndex; if Params.Title <> '' then lpstrTitle := PChar(Params.Title); if Params.InitialDir <> '' then lpstrInitialDir := PChar(Params.InitialDir); if Params.DefaultExt <> '' then lpstrDefExt := PChar(Params.DefaultExt); if Params.MultiSelect then Flags := Flags or OFN_ALLOWMULTISELECT; Flags := Flags or OFN_ENABLESIZING or OFN_EXPLORER; end; case DlgType of wadtOpen: begin with fnStruct do Flags := Flags or OFN_FILEMUSTEXIST or OFN_PATHMUSTEXIST; Result := GetOpenFileName(@fnStruct); if Result then begin if Params.MultiSelect and Assigned(Params.FileNames) then begin ParseMultipleFileNames; if Params.FileNames.Count > 0 then Params.FileName := Params.FileNames[0]; end else Params.FileName := SysToUTF8(StrPas(szFile)); Params.FilterIndex := fnStruct.nFilterIndex; end; end; wadtSave: begin with fnStruct do Flags := Flags or OFN_PATHMUSTEXIST or OFN_OVERWRITEPROMPT; Result := GetSaveFileName(@fnStruct); if Result then begin Params.FileName := SysToUTF8(StrPas(szFile)); Params.FilterIndex := fnStruct.nFilterIndex; end; end; end; end; {$endif} function OpenFileDialog(var Params: TFileDialogParams): Boolean; begin if Assigned(Params.FileNames) then Params.FileNames.Clear; {$ifdef WINDOWS} Result := WinApiFileDialog(Params, wadtOpen); {$else} with TOpenDialog.Create(nil) do try if Params.Title <> '' then Title := Params.Title; Filter := Params.Filters; FileName := Params.FileName; if Params.MultiSelect then Options := Options + [ofAllowMultiSelect]; Options := Options + [ofFileMustExist, ofPathMustExist]; FilterIndex := Params.FilterIndex; if Params.InitialDir <> '' then InitialDir := Params.InitialDir; if Params.DefaultExt <> '' then DefaultExt := PChar(Params.DefaultExt); Result := Execute; if Result then begin Params.FilterIndex := FilterIndex; Params.FileName := FileName; if Assigned(Params.FileNames) then begin if Params.MultiSelect then Params.FileNames.Assign(Files) else Params.FileNames.Add(FileName); end; end; finally Free; end; {$endif} end; function SaveFileDialog(var Params: TFileDialogParams): Boolean; begin {$ifdef WINDOWS} Result := WinApiFileDialog(Params, wadtSave); {$else} Result := False; // TODO {$endif} end; {%endregion} // Можно использовать при размещении контролов друг под другом. Если добавить // новый контрол и просто выставить Align = alTop, то он помещается над старыми. // Нужно выставить ему нужный Top, чтобы он встал в самый низ (обычно еще +1). function GetMaxTopChild(AParent: TWinControl): Integer; var i: Integer; begin Result := -1; for I := 0 to AParent.ControlCount-1 do with AParent.Controls[I] do if Top > Result then Result := Top + Height; end; end.
unit uRangeElement; interface uses Generics.Collections; type TRangeElement = class(TObject) private FRange_ID: Integer; FElement_ID: Integer; FDescription: string; FSizeDesc: string; FColourDesc: string; FQuantity: Integer; FRangeElementList: TDictionary<Integer, TRangeElement>; public constructor Create(aRange_ID: Integer; aElement_ID: Integer; aDescription: string; aSizeDesc: string; aColourDesc: string; aQuantity: Integer); procedure AddRangeElement(const aRangeElement: TRangeElement); procedure RemoveElementById(aElement_ID: Integer); function GetPlannedQuantity: Integer; published property Range_ID: Integer read FRange_ID; property Element_ID: Integer read FElement_ID; property Description: string read FDescription write FDescription; property SizeDesc: string read FSizeDesc write FSizeDesc; property ColourDesc: string read FColourDesc write FColourDesc; property Quantity: Integer read FQuantity write FQuantity; property PlannedQuantity: Integer read GetPlannedQuantity; property Elements:TDictionary<Integer, TRangeElement> read FRangeElementList; end; implementation constructor TRangeElement.Create(aRange_ID: Integer; aElement_ID: Integer; aDescription: string; aSizeDesc: string; aColourDesc: string; aQuantity: Integer); begin FRange_ID := aRange_ID; FElement_ID:= aElement_ID; FDescription := aDescription; FSizeDesc := aSizeDesc; FColourDesc := aColourDesc; FQuantity := aQuantity; FRangeElementList := TDictionary<Integer, TRangeElement>.Create; end; procedure TRangeElement.AddRangeElement(const aRangeElement: TRangeElement); begin FRangeElementList.Add(aRangeElement.FElement_ID, aRangeElement); end; function TRangeElement.GetPlannedQuantity:Integer; var key: Integer; begin result:= 0; for key in FRangeElementList.keys do begin result := result + FRangeElementList.Items[key].GetPlannedQuantity; end; end; procedure TRangeElement.RemoveElementById(aElement_ID: Integer); begin if FRangeElementList.ContainsKey(aElement_ID) then FRangeElementList.Remove(aElement_ID); end; end.
{ **********************************************************************} { } { DeskMetrics - Application Example (Delphi) } { Copyright (c) 2010-2011 DeskMetrics Limited } { } { http://deskmetrics.com } { support@deskmetrics.com } { } { This code is provided under the DeskMetrics Modified BSD License } { A copy of this license has been distributed in a file called } { LICENSE with this source code. } { } { **********************************************************************} unit frmCustomerExperience; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type Tfrm_CustomerExperience = class(TForm) lblTitle: TLabel; lblText: TLabel; rbYes: TRadioButton; rbNo: TRadioButton; btnOK: TButton; btnCancel: TButton; lblPrivacy: TLabel; procedure btnOKClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frm_CustomerExperience: Tfrm_CustomerExperience; implementation uses DeskMetrics; {$R *.dfm} procedure Tfrm_CustomerExperience.btnCancelClick(Sender: TObject); begin Close; end; procedure Tfrm_CustomerExperience.btnOKClick(Sender: TObject); begin if rbYes.Checked then DeskMetricsSetEnabled(True) else if rbNo.Checked then DeskMetricsSetEnabled(False); Close; end; end.
unit FormOpstellingPlayer; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, uHTPredictor, cxControls, cxContainer, cxEdit, cxTextEdit, formHTPredictor, cxMaskEdit, cxDropDownEdit, cxImageComboBox, uOpstelling, StdCtrls; type TfrmOpstellingPlayer = class(TFrame) pnlPlayer: TPanel; cbPlayer: TcxImageComboBox; cbOrder: TcxImageComboBox; lblCaption: TLabel; vTempCB: TcxImageComboBox; tiHint: TTimer; procedure cbPlayerPropertiesPopup(Sender: TObject); procedure cbPlayerPropertiesChange(Sender: TObject); procedure cbPlayerPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure cbOrderPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure CMMouseEnter(var Msg: TMessage); message CM_MouseEnter; procedure CMMouseLeave(var Msg: TMessage); message CM_MouseLeave; procedure tiHintTimer(Sender: TObject); private FPosition: TPlayerPosition; FOpstelling: TOpstelling; FAanvoerder: Boolean; FHintWindow: THintWindow; FMyHint: String; procedure SetPosition(const Value: TPlayerPosition); procedure VulCBOrder; procedure SetAanvoerder(const Value: Boolean); { Private declarations } public { Public declarations } property Opstelling: TOpstelling read FOpstelling write FOpstelling; property Position: TPlayerPosition read FPosition write SetPosition; property Aanvoerder: Boolean read FAanvoerder write SetAanvoerder; constructor Create(AOwner: TComponent); override; procedure ChangeOpstelling(aSender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); end; function ToonOpstellingPlayer(aParent: TWinControl; aOpstelling: TOpstelling; aPosition: TPlayerPosition): TfrmOpstellingPlayer; overload; function ToonOpstellingPlayer(aParent: TWinControl; aOpstelling: TOpstelling; aAanvoerder: Boolean): TfrmOpstellingPlayer; overload; implementation uses uPlayer; {$R *.DFM} {----------------------------------------------------------------------------- Author: Pieter Bas Datum: 18-04-2012 Doel: <eventuele fixes> -----------------------------------------------------------------------------} function ToonOpstellingPlayer(aParent: TWinControl; aOpstelling: TOpstelling; aPosition: TPlayerPosition): TfrmOpstellingPlayer; begin Result := TfrmOpstellingPlayer.Create(nil); Result.Parent := aParent; Result.Opstelling := aOpstelling; Result.Position := aPosition; Result.Align := alNone; end; {----------------------------------------------------------------------------- Author: Pieter Bas Datum: 18-04-2012 Doel: <eventuele fixes> -----------------------------------------------------------------------------} function ToonOpstellingPlayer(aParent: TWinControl; aOpstelling: TOpstelling; aAanvoerder: Boolean): TfrmOpstellingPlayer; begin Result := TfrmOpstellingPlayer.Create(nil); Result.Parent := aParent; Result.Opstelling := aOpstelling; Result.Position := pOnbekend; Result.Align := alNone; Result.Aanvoerder := aAanvoerder; Result.cbOrder.Visible := FALSE; Result.cbPlayer.Top := Result.cbOrder.Top; end; {----------------------------------------------------------------------------- Author: Pieter Bas Datum: 17-04-2012 Doel: <eventuele fixes> -----------------------------------------------------------------------------} procedure TfrmOpstellingPlayer.cbPlayerPropertiesPopup(Sender: TObject); var vItem: TcxImageComboBoxItem; vCount: integer; vPlayerPosition: TPlayerPosition; vPlayer: TPlayer; vToevoegen: Boolean; vRating: double; vSortSL: TStringList; vString: String; begin if (FOpstelling <> nil) and (FOpstelling.Selectie <> nil) then begin cbPlayer.Properties.Items.Clear; vTempCB.Properties.Items.Clear; vSortSL := TStringList.Create; try //leeg item toevoegen vItem := cbPlayer.Properties.Items.Add; vItem.Value := -1; vItem.Description := ''; vItem.ImageIndex := -1; for vCount := 0 to FOpstelling.Selectie.Players.Count - 1 do begin vPlayer := TPlayer(FOpstelling.Selectie.Players[vCount]); vPlayerPosition := FOpstelling.GetPositionOfPlayer(vPlayer); if (Position = pOnbekend) then begin if Aanvoerder then begin vToevoegen := (Ord(vPlayerPosition) >= Ord(pKP)); end else begin //let op: groter dan KP omdat keeper geen SH-er mag zijn vToevoegen := (Ord(vPlayerPosition) > Ord(pKP)); end; end else begin vToevoegen := TRUE; end; if (vToevoegen) then begin vItem := vTempCB.Properties.Items.Add; vItem.Value := vPlayer.ID; if (Position = pOnbekend) then begin if Aanvoerder then begin vRating := vPlayer.XP; end else begin vRating := vPlayer.SP; end; end else begin vRating := vPlayer.GetPositionRating(Position, TPlayerOrder(cbOrder.EditValue)); end; vItem.Description := Format('%s %.2f', [vPlayer.Naam, vRating]); if (Position = pOnbekend) or (vPlayerPosition = pOnbekend) or (vPlayerPosition = Position) then begin vItem.ImageIndex := -1; end else begin vItem.ImageIndex := 202; end; if (vRating < 10) then begin vString := '0'; end else begin vString := ''; end; vString := vString + Format('%.2f', [vRating]); vSortSL.AddObject(vString, vItem); end; end; vSortSL.Sort; for vCount := vSortSL.Count - 1 downto 0 do begin vItem := cbPlayer.Properties.Items.Add; vItem.Value := TcxImageComboBoxItem(vSortSL.Objects[vCount]).Value; vItem.Description := TcxImageComboBoxItem(vSortSL.Objects[vCount]).Description; vItem.ImageIndex := TcxImageComboBoxItem(vSortSL.Objects[vCount]).ImageIndex; end; vTempCB.Properties.Items.Clear; finally vSortSL.Free; end; end; end; {----------------------------------------------------------------------------- Author: Pieter Bas Datum: 17-04-2012 Doel: <eventuele fixes> -----------------------------------------------------------------------------} procedure TfrmOpstellingPlayer.SetPosition(const Value: TPlayerPosition); begin FPosition := Value; case FPosition of pKP: begin Left := 320; Top := 10; end; pRB: begin Left := 20; Top := 60; end; pRCV: begin Left := 170; Top := 60; end; pCV: begin Left := 320; Top := 60; end; pLCV: begin Left := 470; Top := 60; end; pLB: begin Left := 620; Top := 60; end; pRW: begin Left := 20; Top := 110; end; pRCM: begin Left := 170; Top := 110; end; pCM: begin Left := 320; Top := 110; end; pLCM: begin Left := 470; Top := 110; end; pLW: begin Left := 620; Top := 110; end; pRCA: begin Left := 170; Top := 160; end; pCA: begin Left := 320; Top := 160; end; pLCA: begin Left := 470; Top := 160; end; end; VulCBOrder; end; {----------------------------------------------------------------------------- Author: Pieter Bas Datum: 17-04-2012 Doel: <eventuele fixes> -----------------------------------------------------------------------------} procedure TfrmOpstellingPlayer.VulCBOrder; var vItem: TcxImageComboBoxItem; begin cbOrder.Properties.BeginUpdate; try cbOrder.Properties.Items.Clear; vItem := cbOrder.Properties.Items.Add; vItem.Value := Ord(oNormaal); vItem.Description := uHTPredictor.OrderToString(oNormaal); if (Position in [pRB, pLB, pRW, pRCM, pCM, pLCM, pLW, pRCA, pCA, pLCA]) then begin vItem := cbOrder.Properties.Items.Add; vItem.Value := Ord(oVerdedigend); vItem.Description := uHTPredictor.OrderToString(oVerdedigend); end; if (Position in [pRB, pRCV, pCV, pLCV, pLB, pRW, pRCM, pCM, pLCM, pLW]) then begin vItem := cbOrder.Properties.Items.Add; vItem.Value := Ord(oAanvallend); vItem.Description := uHTPredictor.OrderToString(oAanvallend); end; if (Position in [pRCV, pLCV, pRCM, pLCM, pRCA, pLCA]) then begin vItem := cbOrder.Properties.Items.Add; vItem.Value := Ord(oNaarVleugel); vItem.Description := uHTPredictor.OrderToString(oNaarVleugel); end; if (Position in [pRB, pLB, pRW, pLW]) then begin vItem := cbOrder.Properties.Items.Add; vItem.Value := Ord(oNaarMidden); vItem.Description := uHTPredictor.OrderToString(oNaarMidden); end; cbOrder.ItemIndex := Ord(oNormaal); finally cbOrder.Properties.EndUpdate; end; end; {----------------------------------------------------------------------------- Author: Pieter Bas Datum: 17-04-2012 Doel: <eventuele fixes> -----------------------------------------------------------------------------} procedure TfrmOpstellingPlayer.cbPlayerPropertiesChange(Sender: TObject); begin //niets doen. de speler wordt in de cbPlayerPropertiesValidate gecontroleerd en gekoppeld end; {----------------------------------------------------------------------------- Author: Pieter Bas Datum: 17-04-2012 Doel: <eventuele fixes> -----------------------------------------------------------------------------} procedure TfrmOpstellingPlayer.cbPlayerPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin ChangeOpstelling(Sender, DisplayValue, ErrorText, Error); end; {----------------------------------------------------------------------------- Author: Pieter Bas Datum: 17-04-2012 Doel: <eventuele fixes> -----------------------------------------------------------------------------} procedure TfrmOpstellingPlayer.cbOrderPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin if (cbPlayer.EditValue <> Null) then begin ChangeOpstelling(Sender, DisplayValue, ErrorText, Error); end; end; {----------------------------------------------------------------------------- Author: Pieter Bas Datum: 17-04-2012 Doel: <eventuele fixes> -----------------------------------------------------------------------------} procedure TfrmOpstellingPlayer.ChangeOpstelling(aSender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); var vPlayer: TPlayer; vPlayerID: integer; vPlayerOrder: TPlayerOrder; vText: String; begin if (FOpstelling <> nil) then begin if (cbPlayer.EditValue <> Null) then begin vPlayer := FOpstelling.Selectie.GetPlayer(cbPlayer.EditValue); end else begin vPlayer := nil; end; if (Position = pOnbekend) then begin if (Aanvoerder) then begin FOpstelling.Aanvoerder := vPlayer; end else begin FOpstelling.Spelhervatter := vPlayer; end; end else begin if (vPlayer = nil) or (FOpstelling.GetPositionOfPlayer(vPlayer) in [pOnbekend, Position]) then begin vPlayerOrder := TPlayerOrder(cbOrder.EditValue); Error := FALSE; if (cbPlayer.EditValue <> Null) then begin vPlayerID := cbPlayer.EditValue; end else begin vPlayerID := 0; end; FOpstelling.ZetPlayerIDOpPositie(vPlayerID, Position, vPlayerOrder); if (vPlayer = nil) then begin vText := ''; FMyHint := ''; end else begin vText := Format('%s %.2f', [vPlayer.Naam, vPlayer.GetPositionRating(Position, vPlayerOrder)]); FMyHint := Format('MID: %.2f'+#13#10+ 'RV: %.2f CV: %.2f LV: %.2f'+#13#10+ 'RA: %.2f CA: %.2f LA: %.2f', [vPlayer.MID_Bijdrage(Opstelling), vPlayer.DEF_R_Bijdrage(Opstelling), vPlayer.DEF_C_Bijdrage(Opstelling), vPlayer.DEF_L_Bijdrage(Opstelling), vPlayer.AANV_R_Bijdrage(Opstelling), vPlayer.AANV_C_Bijdrage(Opstelling), vPlayer.AANV_L_Bijdrage(Opstelling)]); end; if aSender = cbPlayer then begin DisplayValue := vText; end else begin cbPlayer.Properties.Items[cbPlayer.SelectedItem].Description := vText; end; end else begin Error := TRUE; ErrorText := 'Deze speler is reeds op een andere positie geselecteerd. Kies een andere speler.'; end; end; end; end; {----------------------------------------------------------------------------- Author: Pieter Bas Datum: 18-04-2012 Doel: <eventuele fixes> -----------------------------------------------------------------------------} procedure TfrmOpstellingPlayer.SetAanvoerder(const Value: Boolean); begin FAanvoerder := Value; if (FAanvoerder) then begin Left := 20; Top := 210; lblCaption.Caption := 'Aanvoerder'; end else begin Left := 170; Top := 210; lblCaption.Caption := 'Spelhervatter'; end; end; procedure TfrmOpstellingPlayer.CMMouseEnter(var Msg: TMessage); begin if TControl(Msg.LParam) = pnlPlayer then begin if (FMyHint <> '') then begin tiHint.Enabled := TRUE; end; end; end; procedure TfrmOpstellingPlayer.CMMouseLeave(var Msg: TMessage); begin if TControl(Msg.LParam) = pnlPlayer then begin if Assigned(FHintWindow) then begin FHintWindow.ReleaseHandle; FHintWindow := nil; end else begin tiHint.Enabled := FALSE; end; end; end; procedure TfrmOpstellingPlayer.tiHintTimer(Sender: TObject); var aRect: TRect; begin tiHint.Enabled := FALSE; if (FMyHint <> '') then begin FHintWindow := THintWindow.Create(Self); with FHintWindow do begin try //Font.Name := 'Consolas'; //Canvas.Font.Name := 'Courier'; Canvas.Font.Name := 'Monaco'; //mooi aligned! Canvas.Font.Size := 8; Color := clInfoBk; aRect.TopLeft := Self.ClientToScreen(Point(cbPlayer.Left,cbPlayer.Top + 40)); aRect.BottomRight := Self.ClientToScreen(Point(cbPlayer.Left + 170,cbPlayer.Top + 90)); finally ActivateHint(aRect, FMyHint); end; end; end; end; constructor TfrmOpstellingPlayer.Create(AOwner: TComponent); begin inherited; cbPlayer.Properties.Images := frmHTPredictor.imgListHTPredictor; end; end.
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info) unit SMARTSupport.Intel; interface uses BufferInterpreter, Device.SMART.List, SMARTSupport, Support; type TIntelSMARTSupport = class(TSMARTSupport) private function ModelHasIntelString(const Model: String): Boolean; function SMARTHasIntelCharacteristics( const SMARTList: TSMARTValueList): Boolean; function CheckCommonCharacteristics( const SMARTList: TSMARTValueList): Boolean; function CheckSpecificCharacteristics( const SMARTList: TSMARTValueList): Boolean; function CheckSpecificCharacteristics1( const SMARTList: TSMARTValueList): Boolean; function CheckSpecificCharacteristics2( const SMARTList: TSMARTValueList): Boolean; function CheckSpecificCharacteristics3( const SMARTList: TSMARTValueList): Boolean; function GetTotalWrite(const SMARTList: TSMARTValueList): TTotalWrite; const EntryID = $E8; public function IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; override; function GetTypeName: String; override; function IsSSD: Boolean; override; function IsInsufficientSMART: Boolean; override; function GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; override; function IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; override; protected function ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer; override; function InnerIsErrorAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsCautionAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsError(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; function InnerIsCaution(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; end; implementation { TIntelSMARTSupport } function TIntelSMARTSupport.GetTypeName: String; begin result := 'SmartIntel'; end; function TIntelSMARTSupport.IsInsufficientSMART: Boolean; begin result := false; end; function TIntelSMARTSupport.IsSSD: Boolean; begin result := true; end; function TIntelSMARTSupport.IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; begin result := ModelHasIntelString(IdentifyDevice.Model) or SMARTHasIntelCharacteristics(SMARTList); end; function TIntelSMARTSupport.ModelHasIntelString(const Model: String): Boolean; begin result := Find('INTEL', Model); end; function TIntelSMARTSupport.SMARTHasIntelCharacteristics( const SMARTList: TSMARTValueList): Boolean; begin result := CheckCommonCharacteristics(SMARTList) and CheckSpecificCharacteristics(SMARTList); end; function TIntelSMARTSupport.CheckSpecificCharacteristics( const SMARTList: TSMARTValueList): Boolean; begin result := CheckSpecificCharacteristics1(SMARTList) or CheckSpecificCharacteristics2(SMARTList) or CheckSpecificCharacteristics3(SMARTList); end; function TIntelSMARTSupport.CheckCommonCharacteristics( const SMARTList: TSMARTValueList): Boolean; begin result := (SMARTList.Count >= 5) and (SMARTList[0].Id = $03) and (SMARTList[1].Id = $04) and (SMARTList[2].Id = $05) and (SMARTList[3].Id = $09) and (SMARTList[4].Id = $0C); end; function TIntelSMARTSupport.CheckSpecificCharacteristics1( const SMARTList: TSMARTValueList): Boolean; begin result := (SMARTList.Count >= 8) and (SMARTList[5].Id = $C0) and (SMARTList[6].Id = $E8) and (SMARTList[7].Id = $E9); end; function TIntelSMARTSupport.CheckSpecificCharacteristics2( const SMARTList: TSMARTValueList): Boolean; begin result := (SMARTList.Count >= 7) and (SMARTList[5].Id = $C0) and (SMARTList[6].Id = $E1); end; function TIntelSMARTSupport.CheckSpecificCharacteristics3( const SMARTList: TSMARTValueList): Boolean; begin result := (SMARTList.Count >= 8) and (SMARTList[5].Id = $AA) and (SMARTList[6].Id = $AB) and (SMARTList[7].Id = $AC); end; function TIntelSMARTSupport.ErrorCheckedGetLife( const SMARTList: TSMARTValueList): Integer; begin result := SMARTList[SMARTList.GetIndexByID($E8)].Current; end; function TIntelSMARTSupport.InnerIsErrorAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := true; end; function TIntelSMARTSupport.InnerIsCautionAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := IsEntryAvailable(EntryID, SMARTList); end; function TIntelSMARTSupport.InnerIsError( const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result.Override := false; result.Status := InnerCommonIsError(EntryID, SMARTList).Status; end; function TIntelSMARTSupport.InnerIsCaution( const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result := InnerCommonIsCaution(EntryID, SMARTList, CommonLifeThreshold); end; function TIntelSMARTSupport.IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; const WriteID1 = $E1; WriteID2 = $F1; begin try SMARTList.GetIndexByID(WriteID1); result := true; except result := false; end; if not result then begin try SMARTList.GetIndexByID(WriteID2); result := true; except result := false; end; end; end; function TIntelSMARTSupport.GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; const ReadError = true; EraseError = false; UsedHourID = $09; ThisErrorType = ReadError; ErrorID = $01; ReplacedSectorsID = $05; begin FillChar(result, SizeOf(result), 0); result.UsedHour := SMARTList.ExceptionFreeGetRAWByID(UsedHourID); result.ReadEraseError.TrueReadErrorFalseEraseError := ReadError; result.ReadEraseError.Value := SMARTList.ExceptionFreeGetRAWByID(ErrorID); result.ReplacedSectors := SMARTList.ExceptionFreeGetRAWByID(ReplacedSectorsID); result.TotalWrite := GetTotalWrite(SMARTList); end; function TIntelSMARTSupport.GetTotalWrite( const SMARTList: TSMARTValueList): TTotalWrite; function LBAToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shr 1; end; function GBToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shl 10; end; const HostWrite = true; NANDWrite = false; WriteID1 = $E1; WriteID2 = $F1; begin result.InValue.TrueHostWriteFalseNANDWrite := HostWrite; try result.InValue.ValueInMiB := SMARTList.GetRAWByID(WriteID1) * 32; except try result.InValue.ValueInMiB := SMARTList.ExceptionFreeGetRAWByID(WriteID2) * 32; except result.InValue.ValueInMiB := 0; end; end; end; end.
unit FrameConnectDB; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, CommonConnection.Intf; type TDBConnectFrame = class(TFrame) lblHostName: TLabel; lblDBName: TLabel; lblConnectUsing: TLabel; lblLoginName: TLabel; lblPassword: TLabel; btnSQLLoadConnection: TSpeedButton; btnSQLSaveConnection: TSpeedButton; HostName: TComboBox; radWindowsAuthentication: TRadioButton; radSQLServerAuthentication: TRadioButton; AdminUserName: TEdit; AdminPassword: TEdit; DBName: TComboBox; btnSQLServerConnect: TBitBtn; procedure btnSQLServerConnectClick(Sender: TObject); private FDBConnectType: TDBConnectType; function GetDBConnectType: TDBConnectType; procedure SetDBConnectType(Value: TDBConnectType); public property DBConnectType: TDBConnectType read GetDBConnectType write SetDBConnectType; constructor Create(AOwner : TComponent); override; end; implementation {$R *.dfm} { TFrame1 } procedure TDBConnectFrame.btnSQLServerConnectClick(Sender: TObject); begin if FDBConnectType = dctFD then begin cdpFDGlobal.SetConnectionString(dtoSQLServer, HostName.Text, DBName.Text, '', AdminUserName.Text, AdminPassword.Text, radWindowsAuthentication.Checked); cdpFDGlobal.Connected := True; end else begin cdpADOGlobal.SetConnectionString(dtoSQLServer, HostName.Text, DBName.Text, '', AdminUserName.Text, AdminPassword.Text, radWindowsAuthentication.Checked); cdpADOGlobal.Connected := True; end; end; constructor TDBConnectFrame.Create(AOwner: TComponent); begin inherited; //HostName.Text := 'hong-java\SQLEXPRESS,1433'; FDBConnectType := dctFD; end; function TDBConnectFrame.GetDBConnectType: TDBConnectType; begin Result := FDBConnectType; end; procedure TDBConnectFrame.SetDBConnectType(Value: TDBConnectType); begin FDBConnectType := Value; end; end.