text
stringlengths
14
6.51M
unit NoteParametersUnit; interface uses HttpQueryMemberAttributeUnit, JSONNullableAttributeUnit, NullableBasicTypesUnit, GenericParametersUnit, EnumsUnit; type TNoteParameters = class(TGenericParameters) private [HttpQueryMember('route_id')] [Nullable] FRouteId: NullableString; [HttpQueryMember('address_id')] [Nullable] FAddressId: NullableInteger; [HttpQueryMember('dev_lat')] [Nullable] FLatitude: NullableDouble; [HttpQueryMember('dev_lng')] [Nullable] FLongitude: NullableDouble; [HttpQueryMember('device_type')] [Nullable] FDeviceType: NullableString; [HttpQueryMember('strUpdateType')] [Nullable] FActivityType: NullableString; function GetDeviceType: TDeviceType; procedure SetDeviceType(const Value: TDeviceType); function GetActivityType: TStatusUpdateType; procedure SetActivityType(const Value: TStatusUpdateType); public constructor Create; override; property RouteId: NullableString read FRouteId write FRouteId; property AddressId: NullableInteger read FAddressId write FAddressId; property Latitude: NullableDouble read FLatitude write FLatitude; property Longitude: NullableDouble read FLongitude write FLongitude; property DeviceType: TDeviceType read GetDeviceType write SetDeviceType; property ActivityType: TStatusUpdateType read GetActivityType write SetActivityType; end; implementation { TNoteParameters } constructor TNoteParameters.Create; begin Inherited Create; FRouteId := NullableString.Null; FAddressId := NullableInteger.Null; FLatitude := NullableDouble.Null; FLongitude := NullableDouble.Null; FDeviceType := NullableString.Null; FActivityType := NullableString.Null; end; function TNoteParameters.GetActivityType: TStatusUpdateType; var ActivityType: TStatusUpdateType; begin Result := TStatusUpdateType.Unclassified; if FActivityType.IsNotNull then for ActivityType := Low(TStatusUpdateType) to High(TStatusUpdateType) do if (FActivityType = TStatusUpdateTypeDescription[ActivityType]) then Exit(ActivityType); end; function TNoteParameters.GetDeviceType: TDeviceType; var DeviceType: TDeviceType; begin Result := TDeviceType.UnknownDevice; if FDeviceType.IsNotNull then for DeviceType := Low(TDeviceType) to High(TDeviceType) do if (FDeviceType = TDeviceTypeDescription[DeviceType]) then Exit(DeviceType); end; procedure TNoteParameters.SetActivityType(const Value: TStatusUpdateType); begin FActivityType := TStatusUpdateTypeDescription[Value]; end; procedure TNoteParameters.SetDeviceType(const Value: TDeviceType); begin FDeviceType := TDeviceTypeDescription[Value]; end; end.
unit dcRadioButton; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, dbctrls, datacontroller,db; type TdcRadioButton = class(TRadioButton) private Fclearing: boolean; procedure Setclearing(const Value: boolean); function GetDataBufIndex: integer; procedure SetDataBufIndex(const Value: integer); private { Private declarations } fdcLink : TdcLink; property clearing : boolean read Fclearing write Setclearing; protected { Protected declarations } // std data awareness function GetDataSource:TDataSource; procedure SetDataSource(value:Tdatasource); function GetDataField:string; procedure SetDataField(value:string); // data controller function GetDataController:TDataController; procedure SetDataController(value:TDataController); procedure ReadData(sender:TObject); procedure WriteData(sender:TObject); procedure ClearData(sender:TObject); procedure Click;override; public { Public declarations } constructor Create(AOwner:Tcomponent);override; destructor Destroy;override; published { Published declarations } property DataController : TDataController read GetDataController write setDataController; property DataField : String read GetDataField write SetDataField; property DataSource : TDataSource read getDataSource write SetDatasource; property DataBufIndex:integer read GetDataBufIndex write SetDataBufIndex; end; procedure Register; implementation function strtobool(s:string):boolean; begin if trim(s) = '' then result := false else begin if uppercase(copy(trim(s),1,1)) = 'T' then result := true else result := false; end; end; constructor TdcRadioButton.Create(AOwner:Tcomponent); begin inherited; fdclink := tdclink.create(self); fdclink.OnReadData := ReadData; fdclink.OnWriteData := WriteData; fdclink.OnClearData := ClearData; end; destructor TdcRadioButton.Destroy; begin fdclink.Free; inherited; end; procedure TdcRadioButton.SetDataController(value:TDataController); begin fdcLink.datacontroller := value; end; function TdcRadioButton.GetDataController:TDataController; begin result := fdcLink.DataController; end; procedure TdcRadioButton.SetDataSource(value:TDataSource); begin end; function TdcRadioButton.GetDataField:string; begin result := fdclink.FieldName; end; function TdcRadioButton.GetDataSource:TDataSource; begin result := fdclink.DataSource; end; procedure TdcRadioButton.SetDataField(value:string); begin fdclink.FieldName := value; end; procedure TdcRadioButton.ReadData; begin if not assigned(fdclink.DataController) then exit; if (DataBufIndex = 0) and (DataField <> '') then checked := fdcLink.DataController.dcStrings.BoolVal[DataField] else if assigned(fdclink.datacontroller.databuf) then checked := fdclink.datacontroller.databuf.AsBoolean[DataBufIndex] else checked := false; end; procedure TdcRadioButton.WriteData; begin if not assigned(fdclink.DataController) then exit; if (DataBufIndex = 0) and (DataField <> '') then fdcLink.DataController.dcStrings.BoolVal[DataField] := Checked else if assigned(fdclink.datacontroller.databuf) then fdclink.datacontroller.databuf.asBoolean[DataBufIndex] := Checked; end; procedure TdcRadioButton.ClearData; begin clearing := true; if fdclink.Field <> nil then checked := strtobool(fdclink.Field.DefaultExpression) else checked := false; clearing := false; end; procedure TdcRadioButton.Click; begin if not clearing then fdclink.BeginEdit; inherited; end; procedure Register; begin RegisterComponents('FFS Data Entry', [TdcRadioButton]); end; procedure TdcRadioButton.Setclearing(const Value: boolean); begin Fclearing := Value; end; function TdcRadioButton.GetDataBufIndex: integer; begin result := 0; if assigned(fdclink.Datacontroller) then if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName); end; procedure TdcRadioButton.SetDataBufIndex(const Value: integer); begin end; end.
unit UOperationResume; interface uses UAccountKey, URawBytes, UMultiOpSender, UMultiOpReceiver, UMultiOpChangeInfo; type TOperationResume = Record valid : Boolean; Block : Cardinal; NOpInsideBlock : Integer; OpType : Word; OpSubtype : Word; time : Cardinal; AffectedAccount : Cardinal; SignerAccount : Int64; // Is the account that executes this operation n_operation : Cardinal; DestAccount : Int64; // SellerAccount : Int64; // Protocol 2 - only used when is a pay to transaction newKey : TAccountKey; OperationTxt : AnsiString; Amount : Int64; Fee : Int64; Balance : Int64; OriginalPayload : TRawBytes; PrintablePayload : AnsiString; OperationHash : TRawBytes; OperationHash_OLD : TRawBytes; // Will include old oeration hash value errors : AnsiString; // New on V3 for PIP-0017 isMultiOperation : Boolean; Senders : TMultiOpSenders; Receivers : TMultiOpReceivers; Changers : TMultiOpChangesInfo; end; var CT_TOperationResume_NUL : TOperationResume; // initialized in initialization section implementation initialization Initialize(CT_TOperationResume_NUL); with CT_TOperationResume_NUL do begin NOpInsideBlock:=-1; SignerAccount:=-1; DestAccount:=-1; SellerAccount:=-1; end; end.
unit MSFL; interface type TMBFFloat = packed record strict private b0: Byte; b1: Byte; b2: Byte; b3: Byte; public class operator Implicit(MBF: TMBFFloat): Single; class operator Explicit(MBF: TMBFFloat): Single; end; TMBFDate = packed record private Data: TMBFFloat; public class operator Implicit(MBFDate: TMBFDate): TDateTime; class operator Explicit(MBFDate: TMBFDate): TDateTime; end; TMBFDate2 = packed record strict private Data: Single; public class operator Implicit(MBFDate: TMBFDate2): TDateTime; class operator Explicit(MBFDate: TMBFDate2): TDateTime; end; TMBFDate3 = packed record strict private Data: Cardinal; public class operator Implicit(MBFDate: TMBFDate3): TDateTime; class operator Explicit(MBFDate: TMBFDate3): TDateTime; end; TMasterRecordHeader = packed record public NumFiles: Word; NextFile: Word; strict private Padding: array[0..48] of Byte; end; TMasterRecordInfo = packed record public FileNumber: Byte; FileType: Word; RecordLength: Byte; RecordCound: Byte; strict private a1: Word; public IssueName: array[0..15] of AnsiChar; strict private a2: Byte; public CT_V2_8_Flag: Byte; FirstDate: TMBFDate; LastDate: TMBFDate; TimeFrame: AnsiChar; IntradayTimeBase: Word; StockSymbol: array[0..13] of AnsiChar; strict private a3: Byte; public Flag: Byte; strict private a4: Byte; end; TExtendedMasterRecordFieldFlag = (ff0 = 0, ff1 = 1, ff2 = 2, ffLow = 3, ffHigh = 4, ffOpenPrice = 5, ffOpenInterest = 6); TExtendedMasterRecordFieldFlags = set of TExtendedMasterRecordFieldFlag; TExtendedMasterRecordHeader = packed record public NumFiles: Word; NextFile: Word; strict private a1: array[0..$2C] of Byte; a2: array[0..3] of Byte; public Info: array[0..138] of AnsiChar; end; TExtendedMasterRecordInfo = packed record public IDCode: Byte; IDCode2: Byte; FileNumber: Word; strict private a1: Word; public RecordCount: Byte; Fields: TExtendedMasterRecordFieldFlags; AutoRun: Word; strict private a2: Byte; public Symbol: array[0..12] of AnsiChar; strict private a3: array[0..7] of Byte; public IssueName: array[0..15] of AnsiChar; strict private a4: array[0..11] of Byte; public TimeFrame: array[0..3] of AnsiChar; public FirstDate: TMBFDate2; strict private Padding1: array[0..3] of Byte; public LastDate: TMBFDate2; strict private Padding2: array[0..3] of Byte; public StartTime: Single; StopTime: Single; strict private a5: array[0..37] of Byte; public FirstDateLong: TMBFDate3; strict private a6: Byte; public DividenDate: TMBFDate2; DividenRate: Single; Desription: array[0..52] of AnsiChar; end; TQuoteRecordHeader = packed record strict private a1: Word; public Count: Word; strict private a2: array[0..23] of Byte; end; TQuoteRecordInfo = packed record public Date: TMBFDate; Open: TMBFFloat; High: TMBFFloat; Low: TMBFFloat; Close: TMBFFloat; Volume: TMBFFloat; OpenInterest: TMBFFloat; end; function NumberToMetaDate(Number: Single): TDateTime; overload; function NumberToMetaDate(Number: Int64): TDateTime; overload; implementation uses SysUtils; function NumberToMetaDate(Number: Single): TDateTime; overload; inline; begin Result := NumberToMetaDate(Trunc(Number)); end; function NumberToMetaDate(Number: Int64): TDateTime; overload; var i,j: Int64; d, m, y: Integer; begin i := Number; if i >= 0 then begin d := i mod 100; i := i div 100; m := i mod 100; i := i div 100; y := i; if (y < 1000) then Inc(y, 1900); end else begin j := 1000000 + i; d := j mod 100; j := j div 100; m := j mod 100; // i := i div 100; i := i div 100; y := 1900 + i end; Result := EncodeDate(y, m, d); end; { TMBFFloat } class operator TMBFFloat.Implicit(MBF: TMBFFloat): Single; var mantissa, ieeeFloatBits: Cardinal; exp: SmallInt; sign: SmallInt; begin with MBF do begin mantissa := ((b2 shl 16) or (b1 shl 8) or b0) and $7fffff; sign := b2 and $80; exp := b3 - 2; ieeeFloatBits := (sign shl 24) or (exp shl 23) or mantissa; Result := PSingle(@ieeeFloatBits)^; end; end; class operator TMBFFloat.Explicit(MBF: TMBFFloat): Single; begin Result := MBF; end; { TMBFDate } class operator TMBFDate.Explicit(MBFDate: TMBFDate): TDateTime; begin Result := MBFDate; end; class operator TMBFDate.Implicit(MBFDate: TMBFDate): TDateTime; begin Result := NumberToMetaDate(MBFDate.Data); end; { TMBFDate2 } class operator TMBFDate2.Explicit(MBFDate: TMBFDate2): TDateTime; begin Result := MBFDate; end; class operator TMBFDate2.Implicit(MBFDate: TMBFDate2): TDateTime; begin Result := NumberToMetaDate(MBFDate.Data); end; { TMBFDate3 } class operator TMBFDate3.Explicit(MBFDate: TMBFDate3): TDateTime; begin Result := MBFDate; end; class operator TMBFDate3.Implicit(MBFDate: TMBFDate3): TDateTime; begin Result := NumberToMetaDate(MBFDate.Data); end; end.
unit DaemonSchedulerReport; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, Menus, DaemonScheduler; type TDaemonSchedulerWindow = class(TForm) PageControl: TPageControl; General: TTabSheet; Daemons: TTabSheet; DirectoryServerAddr: TEdit; Label1: TLabel; DirectoryServerPort: TEdit; Label2: TLabel; StartScheduler: TButton; StopScheduler: TButton; DaemonsList: TListBox; Label3: TLabel; DaemonsListPopupMenu: TPopupMenu; Run1: TMenuItem; Properties1: TMenuItem; procedure StartSchedulerClick(Sender: TObject); procedure Run1Click(Sender: TObject); procedure StopSchedulerClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Properties1Click(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } fScheduler : TDaemonScheduler; public { Public declarations } end; var DaemonSchedulerWindow: TDaemonSchedulerWindow; implementation {$R *.DFM} uses Registry, Daemons, Logs; procedure TDaemonSchedulerWindow.StartSchedulerClick(Sender: TObject); var i : integer; Reg : TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey('Software\Oceanus\Five\Daemons', true) then begin Reg.WriteString('DSAddr', DirectoryServerAddr.Text); Reg.WriteString('DSPort', DirectoryServerPort.Text) end; finally Reg.Free; end; if fScheduler.Start(DirectoryServerAddr.Text, StrToInt(DirectoryServerPort.Text)) then begin for i := 0 to pred(fScheduler.DaemonCount) do DaemonsList.Items.Add(fScheduler.Daemons[i].GetName); StartScheduler.Enabled := false; StopScheduler.Enabled := true; Log(cLogId, 'Scheduler successfully started'); end else Log(cLogId, 'Could not start scheduler'); end; procedure TDaemonSchedulerWindow.Run1Click(Sender: TObject); var Daemon : IDaemon; begin Daemon := fScheduler.Daemons[DaemonsList.ItemIndex]; fScheduler.Schedule(Daemon); end; procedure TDaemonSchedulerWindow.StopSchedulerClick(Sender: TObject); begin fScheduler.Stop; DaemonsList.Items.Clear; StartScheduler.Enabled := true; StopScheduler.Enabled := false; end; procedure TDaemonSchedulerWindow.FormCreate(Sender: TObject); begin fScheduler := TDaemonScheduler.Create(2); end; procedure TDaemonSchedulerWindow.FormDestroy(Sender: TObject); begin fScheduler.Free; end; procedure TDaemonSchedulerWindow.Properties1Click(Sender: TObject); var Daemon : IDaemon; begin Daemon := fScheduler.Daemons[DaemonsList.ItemIndex]; if not Daemon.ShowPropertiesUI then begin end; end; procedure TDaemonSchedulerWindow.FormShow(Sender: TObject); var Reg : TRegistry; CmdLine : TStringList; i : integer; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey('Software\Oceanus\Five\Daemons', false) then begin if Reg.ValueExists('DSAddr') then DirectoryServerAddr.Text := Reg.ReadString('DSAddr'); if Reg.ValueExists('DSPort') then DirectoryServerPort.Text := Reg.ReadString('DSPort'); end; finally Reg.Free; end; CmdLine := TStringList.Create; try for i := 1 to ParamCount do CmdLine.Add(ParamStr(i)); if CmdLine.Values['DSAddr'] <> '' then DirectoryServerAddr.Text := CmdLine.Values['DSAddr']; if CmdLine.Values['DSPort'] <> '' then DirectoryServerPort.Text := CmdLine.Values['DSPort']; if CmdLine.IndexOf('AUTORUN') <> -1 then StartSchedulerClick(Self); finally CmdLine.Free; end; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpBerSequenceGenerator; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpAsn1Tags, ClpBerGenerator, ClpIBerSequenceGenerator; type TBerSequenceGenerator = class(TBerGenerator, IBerSequenceGenerator) public constructor Create(outStream: TStream); overload; constructor Create(outStream: TStream; tagNo: Int32; isExplicit: Boolean); overload; end; implementation { TBerSequenceGenerator } constructor TBerSequenceGenerator.Create(outStream: TStream); begin Inherited Create(outStream); WriteBerHeader(TAsn1Tags.Constructed or TAsn1Tags.Sequence); end; constructor TBerSequenceGenerator.Create(outStream: TStream; tagNo: Int32; isExplicit: Boolean); begin Inherited Create(outStream, tagNo, isExplicit); WriteBerHeader(TAsn1Tags.Constructed or TAsn1Tags.Sequence); end; end.
(********************************************) (*************** HEADER ******************) (********************************************) Program Mining; (*************** Units ******************) Uses Sysutils, Constants, BankUtils; (*************** Structures******************) (*************** Constants ******************) const mine_X = 2580; mine_Y = 450; bank_X = 2505; bank_Y = 542; storageContainerType = $09AA; (*************** Variables ******************) var pickaxe: Cardinal; (*************** Methods ******************) procedure Setup(); begin AddToDebugJournal('Setting Up ...'); Disarm(); Wait(1000); pickaxe := FindType(pickaxeType, Backpack); AddToDebugJournal('Done.'); end; function CheckWeight(): Boolean; begin Result := Weight < (MaxWeight - 30); end; procedure MineTile(x: Integer; y: Integer); var startTime: TDateTime; option: Cardinal; begin AddToDebugJournal(' Mining (' + IntToStr(x) + ', ' + IntToStr(y) + ') ...'); repeat if TargetPresent then CancelTarget; Disarm(); UseObject(FindType(pickaxeType,Backpack)); WaitTargetXYZ(x, y, GetZ(Self)) startTime := Now(); WaitJournalLineSystem(startTime, 'line|elsewhere|nothing|close|decide|away|rocks|put', 10000); option := FoundedParamId; AddToDebugJournal(' ' + Journal(LineIndex())); until option <= 5; end; procedure MineAround(); var x, y, x_idx, y_idx : Integer; begin x := GetX(Self); y := GetY(Self); x_idx := -2; y_idx := -2; AddToDebugJournal(' Starting to Mine around (' + IntToStr(x) + ', ' + IntToStr(y) + ') ...'); while (x_idx < 3) do begin while (y_idx < 3) and (CheckWeight()) do begin MineTile(x + x_idx, y + y_idx); y_idx := y_idx + 1; end; x_idx := x_idx + 1; y_idx := -2; end; AddToDebugJournal(' Done Mining around (' + IntToStr(x) + ', ' + IntToStr(y) + ').'); end; procedure Move(); var new_x, new_y: Integer; begin AddToDebugJournal(' Relocating randomly ...'); repeat new_x := GetX(Self) + (2 * RandomRange(-2, 2)); new_y := GetY(Self) + (2 * RandomRange(-2, 2)); until (new_x <> GetX(Self)) or (new_y <> GetY(Self)) MoveXY(new_x, new_y, True, 1, True); AddToDebugJournal(' Done relocating to (' + IntToStr(GetX(Self)) + ', ' + IntToStr(GetY(Self)) + ').'); end; procedure Mine(); begin AddToDebugJournal('Starting to Mine ...'); while CheckWeight() do begin Move(); MineAround(); end; AddToDebugJournal('Done Mining ...'); end; procedure GoToMine(); begin AddToDebugJournal('Going to the mine ...'); MoveXY(mine_X, mine_Y, True, 3, True); AddToDebugJournal('Arrived at the mine (' + IntToStr(GetX(Self)) + ', ' + IntToStr(GetY(Self)) + ')'); end; procedure GoToBank(); begin AddToDebugJournal('Going to the bank ...'); MoveXY(bank_X, bank_Y, True, 1, True); AddToDebugJournal('Arrived at the bank (' + IntToStr(GetX(Self)) + ', ' + IntToStr(GetY(Self)) + ')'); end; procedure StoreOres(); begin StoreItemsAtBankContainer(orePileTypes, storageContainerType); StoreItemsAtBankContainer(gemStoneTypes, storageContainerType); end; begin Setup(); repeat GoToBank(); StoreOres(); GoToMine(); Mine(); until Dead; end.
unit sdsCommonDiction; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "CommonDiction" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/CommonDiction/sdsCommonDiction.pas" // Начат: 11.12.2008 22:09 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UseCaseControllerImp::Class>> F1 Core::Common::CommonDiction::CommonDiction::TsdsCommonDiction // // Обобщённый словарь // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses CommonDictionInterfaces {$If not defined(NoVCM)} , vcmControllers {$IfEnd} //not NoVCM , DocumentInterfaces, BaseDocumentWithAttributesInterfaces, DocumentUnit, DocumentAndListInterfaces, bsTypesNew {$If not defined(NoVCM)} , vcmInterfaces {$IfEnd} //not NoVCM , l3ProtoObjectWithCOMQI, l3Interfaces, l3NotifyPtrList {$If not defined(NoVCM)} , vcmExternalInterfaces {$IfEnd} //not NoVCM , l3IID, nevTools, bsTypes, afwInterfaces, FoldersDomainInterfaces, l3InternalInterfaces, l3TreeInterfaces, DynamicTreeUnit, QueryCardInterfaces ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type _SetDataType_ = IdCommonDiction; _SetType_ = IsdsCommonDiction; {$Include ..\CommonDiction\sdsCommonDiction.imp.pas} TsdsCommonDiction = {ucc} class(_sdsCommonDiction_) {* Обобщённый словарь } protected // realized methods {$If not defined(NoVCM)} function MakeData: _SetDataType_; override; {* Данные сборки. } {$IfEnd} //not NoVCM end;//TsdsCommonDiction {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses dsSaveLoad, SysUtils {$If not defined(NoVCM)} , vcmFormSetRefreshParams {$IfEnd} //not NoVCM , afwFacade, l3Base, dCommonDiction, dsChild, dsAttributes, l3Types, bsUtils, l3Utils, deDocInfo, Windows {$If not defined(NoVCM)} , vcmLocalInterfaces {$IfEnd} //not NoVCM , vcmFormDataSourceRef {a} ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type _Instance_R_ = TsdsCommonDiction; {$Include ..\CommonDiction\sdsCommonDiction.imp.pas} // start class TsdsCommonDiction {$If not defined(NoVCM)} function TsdsCommonDiction.MakeData: _SetDataType_; //#UC START# *47F3778403D9_4941654603E7_var* //#UC END# *47F3778403D9_4941654603E7_var* begin //#UC START# *47F3778403D9_4941654603E7_impl* Result := TdCommonDiction.Make; //#UC END# *47F3778403D9_4941654603E7_impl* end;//TsdsCommonDiction.MakeData {$IfEnd} //not NoVCM {$IfEnd} //not Admin AND not Monitorings end.
unit TTSAGENTTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSAGENTRecord = record PLenderNum: String[4]; PAgentID: String[8]; PLine1: String[40]; PLine2: String[40]; PLine3: String[40]; PLine4: String[40]; PPhone: String[40]; PEMail: String[80]; End; TTTSAGENTBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSAGENTRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSAGENT = (TTSAGENTPrimaryKey); TTTSAGENTTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFAgentID: TStringField; FDFLine1: TStringField; FDFLine2: TStringField; FDFLine3: TStringField; FDFLine4: TStringField; FDFPhone: TStringField; FDFEMail: TStringField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPAgentID(const Value: String); function GetPAgentID:String; procedure SetPLine1(const Value: String); function GetPLine1:String; procedure SetPLine2(const Value: String); function GetPLine2:String; procedure SetPLine3(const Value: String); function GetPLine3:String; procedure SetPLine4(const Value: String); function GetPLine4:String; procedure SetPPhone(const Value: String); function GetPPhone:String; procedure SetPEMail(const Value: String); function GetPEMail:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSAGENT); function GetEnumIndex: TEITTSAGENT; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSAGENTRecord; procedure StoreDataBuffer(ABuffer:TTTSAGENTRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFAgentID: TStringField read FDFAgentID; property DFLine1: TStringField read FDFLine1; property DFLine2: TStringField read FDFLine2; property DFLine3: TStringField read FDFLine3; property DFLine4: TStringField read FDFLine4; property DFPhone: TStringField read FDFPhone; property DFEMail: TStringField read FDFEMail; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PAgentID: String read GetPAgentID write SetPAgentID; property PLine1: String read GetPLine1 write SetPLine1; property PLine2: String read GetPLine2 write SetPLine2; property PLine3: String read GetPLine3 write SetPLine3; property PLine4: String read GetPLine4 write SetPLine4; property PPhone: String read GetPPhone write SetPPhone; property PEMail: String read GetPEMail write SetPEMail; published property Active write SetActive; property EnumIndex: TEITTSAGENT read GetEnumIndex write SetEnumIndex; end; { TTTSAGENTTable } procedure Register; implementation function TTTSAGENTTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSAGENTTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSAGENTTable.GenerateNewFieldName } function TTTSAGENTTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSAGENTTable.CreateField } procedure TTTSAGENTTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFAgentID := CreateField( 'AgentID' ) as TStringField; FDFLine1 := CreateField( 'Line1' ) as TStringField; FDFLine2 := CreateField( 'Line2' ) as TStringField; FDFLine3 := CreateField( 'Line3' ) as TStringField; FDFLine4 := CreateField( 'Line4' ) as TStringField; FDFPhone := CreateField( 'Phone' ) as TStringField; FDFEMail := CreateField( 'EMail' ) as TStringField; end; { TTTSAGENTTable.CreateFields } procedure TTTSAGENTTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSAGENTTable.SetActive } procedure TTTSAGENTTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSAGENTTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSAGENTTable.SetPAgentID(const Value: String); begin DFAgentID.Value := Value; end; function TTTSAGENTTable.GetPAgentID:String; begin result := DFAgentID.Value; end; procedure TTTSAGENTTable.SetPLine1(const Value: String); begin DFLine1.Value := Value; end; function TTTSAGENTTable.GetPLine1:String; begin result := DFLine1.Value; end; procedure TTTSAGENTTable.SetPLine2(const Value: String); begin DFLine2.Value := Value; end; function TTTSAGENTTable.GetPLine2:String; begin result := DFLine2.Value; end; procedure TTTSAGENTTable.SetPLine3(const Value: String); begin DFLine3.Value := Value; end; function TTTSAGENTTable.GetPLine3:String; begin result := DFLine3.Value; end; procedure TTTSAGENTTable.SetPLine4(const Value: String); begin DFLine4.Value := Value; end; function TTTSAGENTTable.GetPLine4:String; begin result := DFLine4.Value; end; procedure TTTSAGENTTable.SetPPhone(const Value: String); begin DFPhone.Value := Value; end; function TTTSAGENTTable.GetPPhone:String; begin result := DFPhone.Value; end; procedure TTTSAGENTTable.SetPEMail(const Value: String); begin DFEMail.Value := Value; end; function TTTSAGENTTable.GetPEMail:String; begin result := DFEMail.Value; end; procedure TTTSAGENTTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('AgentID, String, 8, N'); Add('Line1, String, 40, N'); Add('Line2, String, 40, N'); Add('Line3, String, 40, N'); Add('Line4, String, 40, N'); Add('Phone, String, 40, N'); Add('EMail, String, 80, N'); end; end; procedure TTTSAGENTTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;AgentID, Y, Y, N, N'); end; end; procedure TTTSAGENTTable.SetEnumIndex(Value: TEITTSAGENT); begin case Value of TTSAGENTPrimaryKey : IndexName := ''; end; end; function TTTSAGENTTable.GetDataBuffer:TTTSAGENTRecord; var buf: TTTSAGENTRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PAgentID := DFAgentID.Value; buf.PLine1 := DFLine1.Value; buf.PLine2 := DFLine2.Value; buf.PLine3 := DFLine3.Value; buf.PLine4 := DFLine4.Value; buf.PPhone := DFPhone.Value; buf.PEMail := DFEMail.Value; result := buf; end; procedure TTTSAGENTTable.StoreDataBuffer(ABuffer:TTTSAGENTRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFAgentID.Value := ABuffer.PAgentID; DFLine1.Value := ABuffer.PLine1; DFLine2.Value := ABuffer.PLine2; DFLine3.Value := ABuffer.PLine3; DFLine4.Value := ABuffer.PLine4; DFPhone.Value := ABuffer.PPhone; DFEMail.Value := ABuffer.PEMail; end; function TTTSAGENTTable.GetEnumIndex: TEITTSAGENT; var iname : string; begin result := TTSAGENTPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSAGENTPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSAGENTTable, TTTSAGENTBuffer ] ); end; { Register } function TTTSAGENTBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..8] of string = ('LENDERNUM','AGENTID','LINE1','LINE2','LINE3','LINE4' ,'PHONE','EMAIL' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 8) and (flist[x] <> s) do inc(x); if x <= 8 then result := x else result := 0; end; function TTTSAGENTBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; end; end; function TTTSAGENTBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PAgentID; 3 : result := @Data.PLine1; 4 : result := @Data.PLine2; 5 : result := @Data.PLine3; 6 : result := @Data.PLine4; 7 : result := @Data.PPhone; 8 : result := @Data.PEMail; end; end; end.
unit osDBDateTimePicker; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, wwdbdatetimepicker, wwDataInspector; type TosDBDateTimePicker = class(TwwDBDateTimePicker) private FRefObject: TObject; procedure SetRefObject(const Value: TObject); { Private declarations } protected { Protected declarations } public { Public declarations } published property RefObject: TObject read FRefObject write SetRefObject; end; procedure Register; implementation procedure Register; begin RegisterComponents('OS Controls', [TosDBDateTimePicker]); end; { TosDBDateTimePicker } procedure TosDBDateTimePicker.SetRefObject( const Value: TObject); begin FRefObject := Value; end; end.
unit IntegerList; interface uses Classes, SysUtils; type TIntegerList = class private list:TStringList; public constructor create; destructor destroy; override; procedure addInt(ii:integer); procedure deleteInt(ind:integer); function getInt(ind:integer):integer; procedure setInt(ind:integer; ii:integer); function findInt(ii:integer):integer; function countInt:integer; procedure clearIntList; procedure copy(list1:TIntegerList; list2:TIntegerList); function printIntList : string; end; implementation constructor TIntegerList.Create; begin list := TStringList.Create; end; destructor TIntegerList.destroy; var ii:integer; begin for ii := 0 to list.count - 1 do list.Objects[ii].free; list.clear; list.free; end; procedure TIntegerList.addInt(ii:integer); begin list.Add(IntToStr(ii)); end; procedure TIntegerList.deleteInt(ind:integer); begin list.Delete(ind); end; function TIntegerList.getInt(ind:integer):integer; begin Result := StrToInt(list[ind]); end; procedure TIntegerList.setInt(ind:integer; ii:integer); begin list[ind] := IntToStr(ii); end; function TIntegerList.findInt(ii:integer):integer; var loop_var:integer; begin Result := -1; for loop_var := 0 to list.Count do begin if StrToInt(list[loop_var]) = ii then Result := loop_var; end; end; function TIntegerList.countInt:integer; begin Result := list.Count; end; procedure TIntegerList.clearIntList; var ii:integer; begin list.Clear; end; procedure TIntegerList.copy(list1:TIntegerList; list2:TIntegerList); var ii:integer; begin list1.clearIntList; for ii := 0 to list2.countInt - 1 do list1.addInt(list2.getInt(ii)); end; function TIntegerList.printIntList : string; var ii:integer; temp:string; begin temp := ''; for ii := 0 to list.Count - 1 do temp := temp + list[ii] + sLineBreak; result := temp; end; end.
unit DeXTree; interface uses Windows, Messages, SysUtils, Classes, Controls, VirtualTrees, Forms, Graphics; type TDeXTree = class(TVirtualStringTree) private { Private declarations } protected procedure DoBeforeCellPaint(Canvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellRect: TRect); override; public constructor Create(AOwner: TComponent); override; published { Published declarations } end; procedure Register; implementation procedure Register; begin RegisterComponents('NLDelphi', [TDeXTree]); end; { TDeXTree } constructor TDeXTree.Create(AOwner: TComponent); begin inherited; Header.Options := Header.Options + [hoVisible]; TreeOptions.PaintOptions := TreeOptions.PaintOptions - [toShowRoot]; TreeOptions.SelectionOptions := TreeOptions.SelectionOptions + [toFullRowSelect, toMultiSelect, toRightClickSelect]; end; procedure TDeXTree.DoBeforeCellPaint(Canvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellRect: TRect); begin inherited; if Node.Index mod 2 = 0 then begin Canvas.Brush.Color := StringToColor('$00F0F0F0'); Canvas.FillRect(CellRect); end; end; end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit Importar; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons, QComCtrls, IniFiles, SciZipFile; type TfrmImportar = class(TForm) grpDatos: TGroupBox; chkArticulos: TCheckBox; chkClientes: TCheckBox; chkProveedores: TCheckBox; chkDepartamentos: TCheckBox; chkCategorias: TCheckBox; chkAreasVenta: TCheckBox; chkTiposPago: TCheckBox; btnImportar: TBitBtn; btnCancelar: TBitBtn; grpRuta: TGroupBox; txtRuta: TEdit; Label1: TLabel; btnDir: TBitBtn; grpAvance: TGroupBox; barAvance: TProgressBar; lblTabla: TLabel; chkVentas: TCheckBox; chkUsuarios: TCheckBox; chkTicket: TCheckBox; chkEmpresa: TCheckBox; chkDescuentos: TCheckBox; grpTipo: TGroupBox; rdbSincronizar: TRadioButton; rdbReemplazar: TRadioButton; chkCajas: TCheckBox; txtDiaVentaIni: TEdit; txtMesVentaIni: TEdit; txtAnioVentaIni: TEdit; lbl2: TLabel; lbl1: TLabel; txtDiaVentaFin: TEdit; txtMesVentaFin: TEdit; txtAnioVentaFin: TEdit; lbl4: TLabel; lbl3: TLabel; lblAl: TLabel; dlgAbrir: TOpenDialog; chkVendedores: TCheckBox; chkInventario: TCheckBox; chkCompras: TCheckBox; txtDiaCompraIni: TEdit; txtMesCompraIni: TEdit; Label2: TLabel; Label3: TLabel; txtAnioCompraIni: TEdit; Label4: TLabel; txtDiaCompraFin: TEdit; Label5: TLabel; txtMesCompraFin: TEdit; Label6: TLabel; txtAnioCompraFin: TEdit; chkUnidades: TCheckBox; procedure btnImportarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure chkArticulosClick(Sender: TObject); procedure btnDirClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure chkVentasClick(Sender: TObject); procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure txtRutaExit(Sender: TObject); procedure txtAnioVentaIniExit(Sender: TObject); procedure txtDiaVentaIniExit(Sender: TObject); procedure chkComprasClick(Sender: TObject); private dteFecha, dteFechaIni, dteFechaFin : TDateTime; zipArchivo : TZipFile; StrStream : TStringStream; function VerificaDatos:boolean; procedure ImportaAreasVenta; procedure RecuperaConfig; procedure ImportaArticulos; procedure ImportaProveedores; procedure ImportaCategorias; procedure ImportaDepartamentos; procedure ImportaInventario; procedure ImportaJuegos; procedure ImportaClientes; procedure ImportaTiposPago; procedure ImportaUsuarios; procedure ImportaTicket; procedure ImportaEmpresa; procedure ImportaDescuentos; procedure ImportaVentas; procedure ImportaDetalleVenta; procedure ImportaPagoVenta; procedure ImportaComprobantes; procedure ImportaCajas; procedure ImportaVendedores; procedure ImportaCtsXCobrar; function VerificaFechas(sFecha : string):boolean; procedure ImportaCodigos; procedure Rellena(Sender: TObject); procedure ImportaNotasCredito; procedure ImportaInventario2; procedure ImportaCompras; procedure ImportaUnidades; public end; var frmImportar: TfrmImportar; implementation uses dm; {$R *.xfm} procedure TfrmImportar.btnImportarClick(Sender: TObject); begin if(VerificaDatos) then begin if(chkAreasVenta.Checked) then ImportaAreasVenta; if(chkArticulos.Checked) then ImportaArticulos; if(chkCategorias.Checked) and (not chkArticulos.Checked) then ImportaCategorias; if(chkDepartamentos.Checked) and (not chkArticulos.Checked) then ImportaDepartamentos; if(chkProveedores.Checked) and (not chkArticulos.Checked) then ImportaProveedores; if(chkUnidades.Checked) and (not chkArticulos.Checked) then ImportaUnidades; if(chkVendedores.Checked) then ImportaVendedores; if(chkCajas.Checked) then ImportaCajas; if(chkClientes.Checked) then ImportaClientes; if(chkTiposPago.Checked) then ImportaTiposPago; if(chkUsuarios.Checked) then ImportaUsuarios; if(chkTicket.Checked) then ImportaTicket; if(chkEmpresa.Checked) then ImportaEmpresa; if(chkDescuentos.Checked) then ImportaDescuentos; if(chkInventario.Checked) then ImportaInventario2; if(chkCompras.Checked) then begin ImportaCompras; end; if(chkVentas.Checked) then begin // ImportaVendedores; ImportaVentas; ImportaComprobantes; ImportaNotasCredito; ImportaDetalleVenta; ImportaPagoVenta; ImportaCtsXCobrar; end; Application.MessageBox('Proceso terminado','Importar',[smbOk]); end end; function TfrmImportar.VerificaDatos:boolean; begin btnImportar.SetFocus; Result := true; if(not FileExists(txtRuta.Text)) then begin Application.MessageBox('El archivo no existe','Error',[smbOk]); txtRuta.SetFocus; Result := false; end else if(chkVentas.Checked) then begin if (not VerificaFechas(txtDiaVentaIni.Text + '/' + txtMesVentaIni.Text + '/' + txtAnioVentaIni.Text)) then begin Application.MessageBox('Introduce un fecha inicial válida para las ventas','Error',[smbOK],smsCritical); txtDiaVentaIni.SetFocus; Result := false; end else if (not VerificaFechas(txtDiaVentaFin.Text + '/' + txtMesVentaFin.Text + '/' + txtAnioVentaFin.Text)) then begin Application.MessageBox('Introduce un fecha final válida para las ventas','Error',[smbOK],smsCritical); txtDiaVentaFin.SetFocus; Result := false; end else begin dteFechaIni := StrToDate(txtDiaVentaIni.Text + '/' + txtMesVentaIni.Text + '/' + txtAnioVentaIni.Text); dteFechaFin := StrToDate(txtDiaVentaFin.Text + '/' + txtMesVentaFin.Text + '/' + txtAnioVentaFin.Text); if(dteFechaIni > dteFechaFin) then begin Application.MessageBox('La fecha final debe ser mayor o igual que la fecha inicial','Error',[smbOK],smsCritical); txtDiaVentaIni.SetFocus; Result := false; end; end; end else if(chkCompras.Checked) then begin if (not VerificaFechas(txtDiaCompraIni.Text + '/' + txtMesCompraIni.Text + '/' + txtAnioCompraIni.Text)) then begin Application.MessageBox('Introduce un fecha inicial válida para las compras','Error',[smbOK],smsCritical); txtDiaCompraIni.SetFocus; Result := false; end else if (not VerificaFechas(txtDiaCompraFin.Text + '/' + txtMesCompraFin.Text + '/' + txtAnioCompraFin.Text)) then begin Application.MessageBox('Introduce un fecha final válida para las compras','Error',[smbOK],smsCritical); txtDiaCompraFin.SetFocus; Result := false; end else begin dteFechaIni := StrToDate(txtDiaCompraIni.Text + '/' + txtMesCompraIni.Text + '/' + txtAnioCompraIni.Text); dteFechaFin := StrToDate(txtDiaCompraFin.Text + '/' + txtMesCompraFin.Text + '/' + txtAnioCompraFin.Text); if(dteFechaIni > dteFechaFin) then begin Application.MessageBox('La fecha final debe ser mayor o igual que la fecha inicial','Error',[smbOK],smsCritical); txtDiaCompraIni.SetFocus; Result := false; end; end; end; end; procedure TfrmImportar.ImportaAreasVenta; var sClave, sNombre, sCaja, sFechaUMov : String; dteFechaMov : TDateTime; i : integer; begin lblTabla.Caption := 'Áreas de venta'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'areasventa.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; sFechaUMov := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now); while(not (dmDatos.cdsImExportar.Eof)) do begin sNombre := Trim(dmDatos.cdsImExportar.FieldByName('nombre').AsString); sCaja := dmDatos.cdsImExportar.FieldByName('caja').AsString; dteFechaMov := dmDatos.cdsImExportar.FieldByName('fecha_umov').AsDateTime; if(Length(sCaja) = 0) then sCaja := 'null'; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave, fecha_umov FROM areasventa WHERE nombre = ''' + sNombre + ''''); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO areasventa (nombre, caja, fecha_umov) VALUES('); SQL.Add('''' + sNombre + ''',' + sCaja + ',''' + sFechaUMov + ''')'); ExecSQL; Close; end else begin // Modifica el registro sClave := FieldByName('clave').AsString; if(dteFechaMov > FieldByName('fecha_umov').AsDateTime) or (rdbReemplazar.Checked) then begin Close; SQL.Clear; SQL.Add('UPDATE areasventa SET nombre = ''' + sNombre + ''','); SQL.Add('caja = ' + sCaja + ','); SQL.Add('fecha_umov = ''' + sFechaUMov + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end else begin Close; SQL.Clear; SQL.Add('UPDATE areasventa SET fecha_umov = ''' + sFechaUMov + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; if(rdbReemplazar.Checked) then //Elimina todo lo que no estaba en la importación with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM areasventa WHERE fecha_umov <> ''' + sFechaUMov + ''''); ExecSQL; Close; end; end; procedure TfrmImportar.ImportaArticulos; begin ImportaCategorias; ImportaProveedores; ImportaDepartamentos; ImportaInventario; ImportaCodigos; ImportaJuegos; ImportaUnidades; end; procedure TfrmImportar.ImportaCategorias; var sClave, sNombre, sTipo, sCuenta, sFechaUMov : String; i : integer; begin lblTabla.Caption := 'Categorías'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'categorias.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; sFechaUMov := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now); while(not (dmDatos.cdsImExportar.Eof)) do begin sNombre := Trim(dmDatos.cdsImExportar.FieldByName('nombre').AsString); sTipo := Trim(dmDatos.cdsImExportar.FieldByName('tipo').AsString); sCuenta := Trim(dmDatos.cdsImExportar.FieldByName('cuenta').AsString); with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave, fecha_umov FROM categorias WHERE nombre = '); SQL.Add('''' + sNombre + ''' AND tipo = ''' + sTipo + ''''); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO categorias (nombre, tipo, cuenta, fecha_umov) VALUES('); SQL.Add('''' + sNombre + ''',''' + sTipo + ''',''' + sCuenta + ''',''' + sFechaUMov + ''')'); ExecSQL; Close; end else begin // Modifica el registro sClave := FieldByName('clave').AsString; Close; SQL.Clear; SQL.Add('UPDATE categorias SET fecha_umov = ''' + sFechaUMov + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; if(rdbReemplazar.Checked) then //Elimina todo lo que no estaba en la importación with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM categorias WHERE fecha_umov <> ''' + sFechaUMov + ''''); ExecSQL; Close; end; end; procedure TfrmImportar.ImportaUnidades; var sClave, sNombre, sFechaUMov : String; i, iTipo : integer; begin lblTabla.Caption := 'Unidades'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'unidades.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; sFechaUMov := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now); while(not (dmDatos.cdsImExportar.Eof)) do begin sNombre := Trim(dmDatos.cdsImExportar.FieldByName('nombre').AsString); iTipo := dmDatos.cdsImExportar.FieldByName('tipo').AsInteger; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave, fecha_umov FROM unidades WHERE nombre = '); SQL.Add('''' + sNombre + ''' AND tipo = ' + IntToStr(iTipo)); Open; if(Eof) then begin // obtener la nueva clave para el unidade (mas correcto el uso del generators de esa manera) Close; SQL.Clear; SQL.Add('SELECT CAST(GEN_ID(unidades,1) AS integer) AS Clave'); SQL.Add('from RDB$DATABASE'); Open; sClave := FieldByName('clave').AsString; Close; SQL.Clear; SQL.Add('INSERT INTO unidades (nombre, clave, tipo, fecha_umov) VALUES('); SQL.Add('''' + sNombre + ''',' + sClave + ',' + IntToStr(iTipo) + ',''' + sFechaUMov + ''')'); ExecSQL; Close; end else begin // Modifica el registro sClave := FieldByName('clave').AsString; Close; SQL.Clear; SQL.Add('UPDATE unidades SET fecha_umov = ''' + sFechaUMov + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; if(rdbReemplazar.Checked) then //Elimina todo lo que no estaba en la importación with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM unidades WHERE fecha_umov <> ''' + sFechaUMov + ''''); ExecSQL; Close; end; end; procedure TfrmImportar.ImportaProveedores; var sClave, sRfc, sNombre, sCalle, sColonia, sCp, sLocalidad, sCateg, sNombreFiscal : String; sEstado, sEncargado, sFax, sCorreo, sFechaCap, sTelefono, sFechaUMov : String; dteFechaMov : TDateTime; i : integer; begin lblTabla.Caption := 'Proveedores'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'proveedores.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; sFechaUMov := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now); while(not (dmDatos.cdsImExportar.Eof)) do begin sClave := dmDatos.cdsImExportar.FieldByName('clave').AsString; sRfc := Trim(dmDatos.cdsImExportar.FieldByName('rfc').AsString); sNombre := Trim(dmDatos.cdsImExportar.FieldByName('nombre').AsString); sNombreFiscal := Trim(dmDatos.cdsImExportar.FieldByName('nombrefiscal').AsString); sCalle := Trim(dmDatos.cdsImExportar.FieldByName('calle').AsString); sColonia := Trim(dmDatos.cdsImExportar.FieldByName('colonia').AsString); sCp := Trim(dmDatos.cdsImExportar.FieldByName('cp').AsString); sLocalidad := Trim(dmDatos.cdsImExportar.FieldByName('localidad').AsString); sEstado := Trim(dmDatos.cdsImExportar.FieldByName('estado').AsString); sEncargado := Trim(dmDatos.cdsImExportar.FieldByName('encargado').AsString); sFax := Trim(dmDatos.cdsImExportar.FieldByName('fax').AsString); sCorreo := Trim(dmDatos.cdsImExportar.FieldByName('ecorreo').AsString); sFechaCap := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha_cap').AsDateTime); sTelefono := Trim(dmDatos.cdsImExportar.FieldByName('telefono').AsString); sCateg := Trim(dmDatos.cdsImExportar.FieldByName('categoria').AsString); dteFechaMov := dmDatos.cdsImExportar.FieldByName('fecha_umov').AsDateTime; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM categorias WHERE nombre = ''' + sCateg + ''' AND tipo = ''P'''); Open; sCateg := FieldByName('clave').AsString; if(Length(sCateg) = 0) then sCateg := 'null'; Close; SQL.Clear; SQL.Add('SELECT clave, fecha_umov FROM proveedores WHERE clave = ' + sClave); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO proveedores (clave, rfc, nombre, nombrefiscal, calle, colonia, cp,'); SQL.Add('localidad, estado, encargado, fax, ecorreo, fecha_cap,'); SQL.Add('telefono, fecha_umov, categoria) VALUES('); SQL.Add(sClave + ',''' + sRfc + ''',''' + sNombre + ''',''' + sNombreFiscal + ''',''' + sCalle + ''','); SQL.Add('''' + sColonia + ''',''' + sCp + ''',''' + sLocalidad + ''',''' + sEstado + ''','); SQL.Add('''' + sEncargado + ''',''' + sFax + ''',''' + sCorreo + ''','); SQL.Add('''' + sFechaCap + ''',''' + sTelefono + ''',''' + sFechaUMov + ''',' + sCateg + ')'); ExecSQL; Close; end else begin // Modifica el registro sClave := FieldByName('clave').AsString; if(dteFechaMov > FieldByName('fecha_umov').AsDateTime) or (rdbReemplazar.Checked) then begin Close; SQL.Clear; SQL.Add('UPDATE proveedores SET rfc = ''' + sRfc + ''','); SQL.Add('nombre = ''' + sNombre + ''','); SQL.Add('nombrefiscal = ''' + sNombreFiscal + ''','); SQL.Add('calle = ''' + sCalle + ''','); SQL.Add('colonia = ''' + sColonia + ''','); SQL.Add('cp = ''' + sCp + ''','); SQL.Add('localidad = ''' + sLocalidad + ''','); SQL.Add('estado = ''' + sEstado + ''','); SQL.Add('encargado = ''' + sEncargado + ''','); SQL.Add('fax = ''' + sFax + ''','); SQL.Add('ecorreo = ''' + sCorreo + ''','); SQL.Add('fecha_cap = ''' + sFechaCap + ''','); SQL.Add('telefono = ''' + sTelefono + ''','); SQL.Add('fecha_umov = ''' + sFechaUmov + ''','); SQL.Add('categoria = ' + sCateg); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end else begin Close; SQL.Clear; SQL.Add('UPDATE proveedores SET fecha_umov = ''' + sFechaUMov + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; if(rdbReemplazar.Checked) then //Elimina todo lo que no estaba en la importación with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM proveedores WHERE fecha_umov <> ''' + sFechaUMov + ''''); ExecSQL; Close; end; end; procedure TfrmImportar.ImportaDepartamentos; var sClave, sNombre, sFechaUMov : String; i : integer; begin lblTabla.Caption := 'Departamentos'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'departamentos.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; sFechaUMov := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now); while(not (dmDatos.cdsImExportar.Eof)) do begin sNombre := Trim(dmDatos.cdsImExportar.FieldByName('nombre').AsString); with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM departamentos WHERE nombre = ''' + sNombre + ''''); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO departamentos (nombre, fecha_umov) VALUES(''' + sNombre + ''',''' + sFechaUMov + ''')'); ExecSQL; Close; end else begin // Modifica el registro sClave := FieldByName('clave').AsString; Close; SQL.Clear; SQL.Add('UPDATE departamentos SET fecha_umov = ''' + sFechaUMov + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; if(rdbReemplazar.Checked) then //Elimina todo lo que no estaba en la importación with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM departamentos WHERE fecha_umov <> ''' + sFechaUMov + ''''); ExecSQL; Close; end; end; procedure TfrmImportar.ImportaInventario; var sClave, sCodigo, sDesCorta, sDesLarga, sPrecio1, sPrecio2, sPrecio3, sPrecio4 : String; sUltCosto, sDescAuto, sExistencia, sMinimo, sMaximo, sFechaUMov, sCostoProm : String; sTipo, sCateg, sDepto, sProv1, sProv2, sIva, sFechaCap, sEstatus, sfiscal : String; dteFechaMov : TDateTime; i : integer; begin lblTabla.Caption := 'Artículos'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'articulos.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; sFechaUMov := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now); while(not (dmDatos.cdsImExportar.Eof)) do begin sCodigo := Trim(dmDatos.cdsImExportar.FieldByName('codigo').AsString); sDesCorta := Trim(dmDatos.cdsImExportar.FieldByName('desc_corta').AsString); sDesLarga := Trim(dmDatos.cdsImExportar.FieldByName('desc_larga').AsString); sPrecio1 := dmDatos.cdsImExportar.FieldByName('precio1').AsString; sPrecio2 := dmDatos.cdsImExportar.FieldByName('precio2').AsString; sPrecio3 := dmDatos.cdsImExportar.FieldByName('precio3').AsString; sPrecio4 := dmDatos.cdsImExportar.FieldByName('precio4').AsString; sUltCosto := dmDatos.cdsImExportar.FieldByName('ult_costo').AsString; sCostoProm := dmDatos.cdsImExportar.FieldByName('costoprom').AsString; sDescAuto := Trim(dmDatos.cdsImExportar.FieldByName('desc_auto').AsString); sExistencia := dmDatos.cdsImExportar.FieldByName('existencia').AsString; sMinimo := dmDatos.cdsImExportar.FieldByName('minimo').AsString; sMaximo := dmDatos.cdsImExportar.FieldByName('maximo').AsString; sTipo := dmDatos.cdsImExportar.FieldByName('tipo').AsString; sIva := dmDatos.cdsImExportar.FieldByName('iva').AsString; sFechaCap := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha_cap').AsDateTime); sEstatus := dmDatos.cdsImExportar.FieldByName('estatus').AsString; sCateg := dmDatos.cdsImExportar.FieldByName('categoria').AsString; sDepto := dmDatos.cdsImExportar.FieldByName('departamento').AsString; sProv1 := dmDatos.cdsImExportar.FieldByName('proveedor1').AsString; sProv2 := dmDatos.cdsImExportar.FieldByName('proveedor2').AsString; dteFechaMov := dmDatos.cdsImExportar.FieldByName('fecha_umov').AsDateTime; sfiscal:= dmDatos.cdsImExportar.FieldByName('fiscal').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM categorias WHERE nombre = ''' + sCateg + ''''); Open; sCateg := FieldByName('clave').AsString; if(Length(sCateg) = 0) then sCateg := 'null'; if(Length(sExistencia) = 0) then sExistencia := '0'; if(Length(sMinimo) = 0) then sMinimo := '0'; if(Length(sMaximo) = 0) then sMaximo := '0'; if(Length(sfiscal) = 0) then sfiscal := '0'; Close; SQL.Clear; SQL.Add('SELECT clave FROM departamentos WHERE nombre = ''' + sDepto + ''''); Open; sDepto := FieldByName('clave').AsString; if(Length(sDepto) = 0) then sDepto := 'null'; if(Length(sProv1) = 0) then sProv1 := 'null'; if(Length(sProv2) = 0) then sProv2 := 'null'; Close; SQL.Clear; SQL.Add('SELECT a.clave, a.fecha_umov FROM articulos a WHERE a.desc_larga = ''' + sDesLarga + ''''); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('SELECT a.clave, a.fecha_umov FROM codigos o JOIN articulos a ON o.articulo = a.clave AND o.tipo = ''P'' WHERE o.codigo = ''' + sCodigo + ''''); Open; end; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO articulos (desc_corta, desc_larga,'); SQL.Add('precio1, precio2, precio3, precio4, ult_costo, costoprom,'); SQL.Add('desc_auto, existencia, minimo, maximo, categoria, departamento,'); SQL.Add('tipo, proveedor1, proveedor2, iva, fecha_cap, fecha_umov,'); SQL.Add('estatus, fiscal) VALUES('); SQL.Add('''' + sDesCorta + ''',''' + sDesLarga + ''','); SQL.Add(sPrecio1 + ',' + sPrecio2 + ',' + sPrecio3 + ',' + sPrecio4 + ','); SQL.Add(sUltCosto + ',' + sCostoProm + ',''' + sDescAuto + ''','); SQL.Add(sExistencia + ',' + sMinimo + ',' + sMaximo + ',' + sCateg + ','); SQL.Add(sDepto + ',''' + sTipo + ''',' + sProv1 + ',' + sProv2 + ','); SQL.Add(sIva + ',''' + sFechaCap + ''',''' + sFechaUMov + ''','); SQL.Add('''' + sEstatus + ''','+sfiscal+' )'); ExecSQL; Close; SQL.Clear; SQL.Add('SELECT clave FROM articulos WHERE desc_larga = ''' + sDesLarga + ''''); Open; sClave := FieldByName('clave').AsString; Close; end else begin // Modifica el registro sClave := FieldByName('clave').AsString; if(dteFechaMov > FieldByName('fecha_umov').AsDateTime) or (rdbReemplazar.Checked) then begin Close; SQL.Clear; SQL.Add('UPDATE articulos SET'); SQL.Add('desc_corta = ''' + sDesCorta + ''','); SQL.Add('desc_larga = ''' + sDesLarga + ''','); SQL.Add('precio1 = ' + sPrecio1 + ','); SQL.Add('precio2 = ' + sPrecio2 + ','); SQL.Add('precio3 = ' + sPrecio3 + ','); SQL.Add('precio4 = ' + sPrecio4 + ','); SQL.Add('ult_costo = ' + sUltCosto + ','); SQL.Add('costoprom = ' + sCostoProm + ','); SQL.Add('desc_auto = ''' + sDescAuto + ''','); SQL.Add('minimo = ' + sMinimo + ','); SQL.Add('maximo = ' + sMaximo + ','); SQL.Add('categoria = ' + sCateg + ','); SQL.Add('departamento = ' + sDepto + ','); SQL.Add('tipo = ''' + sTipo + ''','); SQL.Add('proveedor1 = ' + sProv1 + ','); SQL.Add('proveedor2 = ' + sProv2 + ','); SQL.Add('iva = ' + sIva + ','); SQL.Add('fecha_UMov = ''' + sFechaUMov + ''','); SQL.Add('fecha_cap = ''' + sFechaCap + ''','); SQL.Add('estatus = ''' + sEstatus + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end else begin Close; SQL.Clear; SQL.Add('UPDATE articulos SET fecha_umov = ''' + sFechaUMov + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end; end; Close; SQL.Clear; SQL.Add('DELETE FROM codigos WHERE articulo = ' + sClave + ' OR codigo = ''' + sCodigo + ''''); ExecSQL; Close; SQL.Clear; SQL.Add('INSERT INTO codigos (articulo, codigo, tipo) VALUES('); SQL.Add(sClave + ',''' + sCodigo + ''',''P'')'); ExecSQL; Close; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; if(rdbReemplazar.Checked) then //Elimina todo lo que no estaba en la importación with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM articulos WHERE fecha_umov <> ''' + sFechaUMov + ''''); ExecSQL; Close; end; end; procedure TfrmImportar.ImportaJuegos; var sJuego, sArticulo, sCantidad, sPrecio, sFechaUMov : String; i : integer; begin lblTabla.Caption := 'Juegos'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'juegos.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; sFechaUMov := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now); with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM juegos'); ExecSQL; Close; end; while(not (dmDatos.cdsImExportar.Eof)) do begin sJuego := Trim(dmDatos.cdsImExportar.FieldByName('juego').AsString); sArticulo := Trim(dmDatos.cdsImExportar.FieldByName('codigo').AsString); sCantidad := dmDatos.cdsImExportar.FieldByName('cantidad').AsString; sPrecio := dmDatos.cdsImExportar.FieldByName('precio').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT articulo FROM codigos WHERE codigo = ''' + sJuego + ''''); Open; sJuego := FieldByName('articulo').AsString; Close; SQL.Clear; SQL.Add('SELECT articulo FROM codigos WHERE codigo = ''' + sArticulo + ''''); Open; sArticulo := FieldByName('articulo').AsString; Close; SQL.Clear; SQL.Add('SELECT clave FROM juegos WHERE clave = ''' + sJuego + ''''); SQL.Add('AND articulo = ''' + sArticulo + ''''); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO juegos (clave, articulo, cantidad, precio) VALUES('); SQL.Add(sJuego + ',' + sArticulo + ',' + sCantidad + ',' + sPrecio + ')'); ExecSQL; end; Close; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; end; procedure TfrmImportar.ImportaCodigos; var sClave, sPrimario, sAlterno : String; i : integer; begin lblTabla.Caption := 'Códigos'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'codigos.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; while(not (dmDatos.cdsImExportar.Eof)) do begin sPrimario := Trim(dmDatos.cdsImExportar.FieldByName('primario').AsString); sAlterno := Trim(dmDatos.cdsImExportar.FieldByName('alterno').AsString); with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT articulo FROM codigos WHERE codigo = ''' + sPrimario + ''''); Open; sClave := FieldByName('articulo').AsString; Close; SQL.Clear; SQL.Add('INSERT INTO codigos (articulo, codigo, tipo) VALUES('); SQL.Add(sClave + ',''' + sAlterno + ''',''S'')'); ExecSQL; Close; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; end; procedure TfrmImportar.ImportaClientes; var sClave, sRfc, sNombre, sCalle, sColonia, sCp, sLocalidad, sCateg : String; sEstado, sContacto, sCelular, sCorreo, sFechaCap, sTelefono, sFechaUMov : String; sCredencial, sVenceCreden, sLimite, sPrecio, sDescuento : String; sRfcEmp, sNombreEmp, sCalleEmp, sColoniaEmp, sCpEmp, sLocalidadEmp : String; sEstadoEmp, sFaxEmp, sCorreoEmp, sTelEmp : String; dteFechaUMov : TDateTime; i : integer; begin lblTabla.Caption := 'Clientes'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'clientes.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; sFechaUMov := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now); while(not (dmDatos.cdsImExportar.Eof)) do begin sRfc := Trim(dmDatos.cdsImExportar.FieldByName('rfc').AsString); sNombre := Trim(dmDatos.cdsImExportar.FieldByName('nombre').AsString); sCalle := Trim(dmDatos.cdsImExportar.FieldByName('calle').AsString); sColonia := Trim(dmDatos.cdsImExportar.FieldByName('colonia').AsString); sCp := Trim(dmDatos.cdsImExportar.FieldByName('cp').AsString); sLocalidad := Trim(dmDatos.cdsImExportar.FieldByName('localidad').AsString); sEstado := Trim(dmDatos.cdsImExportar.FieldByName('estado').AsString); sCelular := Trim(dmDatos.cdsImExportar.FieldByName('celular').AsString); sCorreo := Trim(dmDatos.cdsImExportar.FieldByName('ecorreo').AsString); sContacto := Trim(dmDatos.cdsImExportar.FieldByName('contacto').AsString); sFechaCap := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fechacap').AsDateTime); sTelefono := Trim(dmDatos.cdsImExportar.FieldByName('telefono').AsString); sCateg := Trim(dmDatos.cdsImExportar.FieldByName('categoria').AsString); sCredencial := Trim(dmDatos.cdsImExportar.FieldByName('credencial').AsString); sDescuento := Trim(dmDatos.cdsImExportar.FieldByName('descuento').AsString); if(Length(sDescuento) = 0) then sDescuento := '0'; sVenceCreden := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('vencimcreden').AsDateTime); sLimite := Trim(dmDatos.cdsImExportar.FieldByName('limitecredito').AsString); if(Length(sLimite) = 0) then sLimite := '0'; sPrecio := dmDatos.cdsImExportar.FieldByName('precio').AsString; sRfcEmp := Trim(dmDatos.cdsImExportar.FieldByName('rfcemp').AsString); sNombreEmp := Trim(dmDatos.cdsImExportar.FieldByName('empresa').AsString); sCalleEmp := Trim(dmDatos.cdsImExportar.FieldByName('calleemp').AsString); sColoniaEmp := Trim(dmDatos.cdsImExportar.FieldByName('coloniaemp').AsString); sCpEmp := Trim(dmDatos.cdsImExportar.FieldByName('cpemp').AsString); sLocalidadEmp := Trim(dmDatos.cdsImExportar.FieldByName('localidademp').AsString); sEstadoEmp := Trim(dmDatos.cdsImExportar.FieldByName('estadoemp').AsString); sTelEmp := Trim(dmDatos.cdsImExportar.FieldByName('telemp').AsString); sFaxEmp := Trim(dmDatos.cdsImExportar.FieldByName('faxemp').AsString); sCorreoEmp := Trim(dmDatos.cdsImExportar.FieldByName('correoemp').AsString); dteFechaUMov := dmDatos.cdsImExportar.FieldByName('fechaumov').AsDateTime; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM categorias WHERE nombre = ''' + sCateg + ''' AND tipo = ''C'''); Open; sCateg := FieldByName('clave').AsString; if(Length(sCateg) = 0) then sCateg := 'null'; Close; SQL.Clear; SQL.Add('SELECT clave, fechaumov FROM clientes WHERE nombre = ''' + sNombre + ''''); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO clientes (rfc, nombre, calle, colonia, cp,'); SQL.Add('localidad, estado, contacto, celular, ecorreo, fechacap,'); SQL.Add('telefono, fechaumov, categoria, precio, credencial,'); SQL.Add('vencimcreden, limitecredito, descuento, rfcemp, empresa,'); SQL.Add('calleemp, coloniaemp, cpemp, localidademp, estadoemp,'); SQL.Add('faxemp, correoemp, telemp, acumulado) VALUES('); SQL.Add('''' + sRfc + ''',''' + sNombre + ''',''' + sCalle + ''','); SQL.Add('''' + sColonia + ''',''' + sCp + ''',''' + sLocalidad + ''',''' + sEstado + ''','); SQL.Add('''' + sContacto + ''',''' + sCelular + ''',''' + sCorreo + ''','); SQL.Add('''' + sFechaCap + ''',''' + sTelefono + ''',''' + sFechaUMov + ''','); SQL.Add(sCateg + ',' + sPrecio + ',''' + sCredencial + ''','); SQL.Add('''' + sVenceCreden + ''',' + sLimite + ',' + sDescuento + ','); SQL.Add('''' + sRfcEmp + ''',''' + sNombreEmp + ''','); SQL.Add('''' + sCalleEmp + ''',''' + sColoniaEmp + ''',''' + sCpEmp + ''','); SQL.Add('''' + sLocalidadEmp + ''',''' + sEstadoEmp + ''',''' + sFaxEmp + ''','); SQL.Add('''' + sCorreoEmp + ''',''' + sTelEmp + ''',0)'); ExecSQL; Close; end else begin // Modifica el registro sClave := FieldByName('clave').AsString; if(dteFechaUMov > FieldByName('fechaumov').AsDateTime) or (rdbReemplazar.Checked) then begin Close; SQL.Clear; SQL.Add('UPDATE clientes SET rfc = ''' + sRfc + ''','); SQL.Add('nombre = ''' + sNombre + ''','); SQL.Add('calle = ''' + sCalle + ''','); SQL.Add('colonia = ''' + sColonia + ''','); SQL.Add('cp = ''' + sCp + ''','); SQL.Add('localidad = ''' + sLocalidad + ''','); SQL.Add('estado = ''' + sEstado + ''','); SQL.Add('contacto = ''' + sContacto + ''','); SQL.Add('celular = ''' + sCelular + ''','); SQL.Add('ecorreo = ''' + sCorreo + ''','); SQL.Add('fechacap = ''' + sFechaCap + ''','); SQL.Add('telefono = ''' + sTelefono + ''','); SQL.Add('fechaumov = ''' + sFechaUmov + ''','); SQL.Add('categoria = ' + sCateg + ','); SQL.Add('precio = ' + sPrecio + ','); SQL.Add('credencial = ''' + sCredencial + ''','); SQL.Add('vencimcreden = ''' + sVenceCreden + ''','); SQL.Add('limitecredito = ' + sLimite + ','); SQL.Add('descuento = ' + sDescuento + ','); SQL.Add('rfcemp = ''' + sRfcEmp + ''','); SQL.Add('empresa = ''' + sNombreEmp + ''','); SQL.Add('calleemp = ''' + sCalleEmp + ''','); SQL.Add('coloniaemp = ''' + sColoniaEmp + ''','); SQL.Add('cpemp = ''' + sCpEmp + ''','); SQL.Add('localidademp = ''' + sLocalidadEmp + ''','); SQL.Add('estadoemp = ''' + sEstadoEmp + ''','); SQL.Add('faxemp = ''' + sFaxEmp + ''','); SQL.Add('telemp = ''' + sTelEmp + ''','); SQL.Add('correoemp = ''' + sCorreoEmp + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end else begin Close; SQL.Clear; SQL.Add('UPDATE clientes SET fechaumov = ''' + sFechaUMov + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; if(rdbReemplazar.Checked) then //Elimina todo lo que no estaba en la importación with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM clientes WHERE fechaumov <> ''' + sFechaUMov + ''''); ExecSQL; Close; end; end; procedure TfrmImportar.ImportaTiposPago; var sClave, sNombre, sCajon, sReferencia, sFechaUMov : String; sModo, sPagos, sPlazo, sInteres, sEnganche, sMontoMinimo : String; sAplica, sIntMorat, sTipoInteres, sTipoPlazo : String; dteFechaUMov : TDateTime; i : integer; begin lblTabla.Caption := 'Tipos de pago'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'tipospago.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; sFechaUMov := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now); while(not (dmDatos.cdsImExportar.Eof)) do begin sNombre := Trim(dmDatos.cdsImExportar.FieldByName('nombre').AsString); sCajon := dmDatos.cdsImExportar.FieldByName('abrircajon').AsString; sReferencia := dmDatos.cdsImExportar.FieldByName('referencia').AsString; dteFechaUMov := dmDatos.cdsImExportar.FieldByName('fecha_umov').AsDateTime; sModo := Trim(dmDatos.cdsImExportar.FieldByName('modo').AsString); sAplica := '''' + Trim(dmDatos.cdsImExportar.FieldByName('aplica').AsString) + ''''; if(sModo = 'CREDITO') then begin sPagos := dmDatos.cdsImExportar.FieldByName('pagos').AsString; sPlazo := dmDatos.cdsImExportar.FieldByName('plazo').AsString; sInteres := dmDatos.cdsImExportar.FieldByName('interes').AsString; sEnganche := dmDatos.cdsImExportar.FieldByName('enganche').AsString; sMontoMinimo := dmDatos.cdsImExportar.FieldByName('montominimo').AsString; sIntMorat := dmDatos.cdsImExportar.FieldByName('intmoratorio').AsString; sTipoInteres := '''' + Trim(dmDatos.cdsImExportar.FieldByName('tipointeres').AsString) + ''''; sTipoPlazo := dmDatos.cdsImExportar.FieldByName('tipoplazo').AsString; end else begin sPagos := 'null'; sPlazo := 'null'; sInteres := 'null'; sEnganche := 'null'; sMontoMinimo := 'null'; sIntMorat := 'null'; sTipoInteres := 'null'; sTipoPlazo := 'null'; end; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave, fecha_umov FROM tipopago WHERE nombre = ''' + sNombre + ''''); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO tipopago (nombre, abrircajon, referencia,'); SQL.Add('fecha_umov, modo, pagos, plazo, interes, enganche,'); SQL.Add('montominimo, aplica, intmoratorio, tipointeres, tipoplazo) VALUES('); SQL.Add('''' + sNombre + ''',''' + sCajon + ''',''' + sReferencia + ''',''' +sFechaUMov + ''','); SQL.Add('''' + sModo + ''',' + sPagos + ',' + sPlazo + ',' + sInteres + ',' + sEnganche + ','); SQL.Add(sMontoMinimo + ',' + sAplica + ',' + sIntMorat + ','); SQL.Add(sTipoInteres + ',' + sTipoPlazo + ')'); ExecSQL; Close; end else begin // Modifica el registro sClave := FieldByName('clave').AsString; if(dteFechaUMov > FieldByName('fecha_umov').AsDateTime) or (rdbReemplazar.Checked) then begin Close; SQL.Clear; SQL.Add('UPDATE tipopago SET nombre = ''' + sNombre + ''','); SQL.Add('abrircajon = ''' + sCajon + ''','); SQL.Add('referencia = ''' + sReferencia + ''','); SQL.Add('fecha_umov = ''' + sFechaUMov + ''','); SQL.Add('modo = ''' + sModo + ''','); SQL.Add('pagos = ' + sPagos + ','); SQL.Add('plazo = ' + sPlazo + ','); SQL.Add('interes = ' + sInteres + ','); SQL.Add('enganche = ' + sEnganche + ','); SQL.Add('montominimo = ' + sMontoMinimo + ','); SQL.Add('aplica = ' + sAplica + ','); SQL.Add('intmoratorio = ' + sIntMorat + ','); SQL.Add('tipointeres = ' + sTipoInteres + ','); SQL.Add('tipoplazo = ' + sTipoPlazo); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end else begin Close; SQL.Clear; SQL.Add('UPDATE tipopago SET fecha_umov = ''' + sFechaUMov + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; if(rdbReemplazar.Checked) then //Elimina todo lo que no estaba en la importación with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM tipopago WHERE fecha_umov <> ''' + sFechaUMov + ''''); ExecSQL; Close; end; end; procedure TfrmImportar.RecuperaConfig; var iniArchivo : TIniFile; sIzq, sArriba, sValor: String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin //Recupera la posición Y de la ventana sArriba := ReadString('Importar', 'Posy', ''); //Recupera la posición X de la ventana sIzq := ReadString('Importar', 'Posx', ''); if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin Left := StrToInt(sIzq); Top := StrToInt(sArriba); end; //Recupera la ruta de exportación sValor := ReadString('Importar', 'Ruta', ''); if (Length(sValor) > 0) then txtRuta.Text := sValor; //Recupera el tipo de importación sValor := ReadString('Importar', 'Tipo', ''); if (sValor = 'S') then rdbSincronizar.Checked := true else rdbReemplazar.Checked := true end; end; procedure TfrmImportar.FormClose(Sender: TObject; var Action: TCloseAction); var iniArchivo : TIniFile; begin zipArchivo.Free; iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin // Registra la posición y de la ventana WriteString('Importar', 'Posy', IntToStr(Top)); // Registra la posición X de la ventana WriteString('Importar', 'Posx', IntToStr(Left)); // Registra la ruta de exportación WriteString('Importar', 'Ruta', txtRuta.Text); // Registra el tipo de importación if(rdbSincronizar.Checked) then WriteString('Importar', 'Tipo', 'S') else WriteString('Importar', 'Tipo', 'R'); Free; end; end; procedure TfrmImportar.chkArticulosClick(Sender: TObject); begin if(chkArticulos.Checked) then begin chkProveedores.Checked := true; chkDepartamentos.Checked := true; chkCategorias.Checked := true; chkUnidades.Checked := true; chkProveedores.Enabled := false; chkDepartamentos.Enabled := false; chkCategorias.Enabled := false; chkUnidades.Enabled := false; end else begin chkProveedores.Checked := false; chkDepartamentos.Checked := false; chkCategorias.Checked := false; chkUnidades.Checked := false; chkProveedores.Enabled := true; chkDepartamentos.Enabled := true; chkCategorias.Enabled := true; chkUnidades.Enabled := true; end; end; procedure TfrmImportar.ImportaUsuarios; var sLogin, sContra, sNombre, sCalle, sColonia, sCp, sLocalidad, sPermisos : String; sClave, sEstado, sTelefono, sFechaUMov, sFechaCap, sMenu, sOpciones: String; sPrivilegio, sAdicional, sDescuento : String; dteFechaUMov : TDateTime; i : integer; begin lblTabla.Caption := 'Usuarios'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'usuarios.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; sFechaUMov := FormatDateTime('mm/dd/yyyy',Now); while(not (dmDatos.cdsImExportar.Eof)) do begin sLogin := Trim(dmDatos.cdsImExportar.FieldByName('login').AsString); sContra := Trim(dmDatos.cdsImExportar.FieldByName('contra').AsString); sNombre := Trim(dmDatos.cdsImExportar.FieldByName('nombre').AsString); sCalle := Trim(dmDatos.cdsImExportar.FieldByName('calle').AsString); sColonia := Trim(dmDatos.cdsImExportar.FieldByName('colonia').AsString); sCp := Trim(dmDatos.cdsImExportar.FieldByName('cp').AsString); sLocalidad := Trim(dmDatos.cdsImExportar.FieldByName('localidad').AsString); sEstado := Trim(dmDatos.cdsImExportar.FieldByName('estado').AsString); sTelefono := Trim(dmDatos.cdsImExportar.FieldByName('telefono').AsString); sFechaCap := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha_cap').AsDateTime); dteFechaUMov := dmDatos.cdsImExportar.FieldByName('fecha_umov').AsDateTime; sDescuento := dmDatos.cdsImExportar.FieldByName('descuento').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave, fecha_umov FROM usuarios WHERE login = ''' + sLogin + ''''); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO usuarios (login, contra, nombre, calle, colonia, cp,'); SQL.Add('localidad, estado, telefono, fecha_cap, fecha_umov, descuento) VALUES('); SQL.Add('''' + sLogin + ''',''' + sContra + ''',''' + sNombre + ''','); SQL.Add('''' + sCalle + ''',''' + sColonia + ''',''' + sCp + ''','); SQL.Add('''' + sLocalidad + ''',''' + sEstado + ''','); SQL.Add('''' + sTelefono + ''',''' + sFechaCap + ''','); SQL.Add('''' + sFechaUMov + ''',' + sDescuento + ')'); ExecSQL; Close; end else begin sClave := FieldByName('clave').AsString; // Modifica el registro if(dteFechaUMov > FieldByName('fecha_umov').AsDateTime) or (rdbReemplazar.Checked) then begin Close; SQL.Clear; SQL.Add('UPDATE usuarios SET'); SQL.Add('nombre = ''' + sNombre + ''','); SQL.Add('calle = ''' + sCalle + ''','); SQL.Add('colonia = ''' + sColonia + ''','); SQL.Add('cp = ''' + sCp + ''','); SQL.Add('localidad = ''' + sLocalidad + ''','); SQL.Add('estado = ''' + sEstado + ''','); SQL.Add('fecha_cap = ''' + sFechaCap + ''','); SQL.Add('fecha_umov = ''' + sFechaUMov + ''','); SQL.Add('telefono = ''' + sTelefono + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end else begin Close; SQL.Clear; SQL.Add('UPDATE usuarios SET fecha_umov = ''' + sFechaUmov + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; with dmDatos.qryModifica do begin // Elimina todos los permisos de lo usuarios Close; SQL.Clear; SQL.Add('DELETE FROM permisos'); ExecSQL; Close; end; lblTabla.Caption := 'Permisos'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'permisos.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; while(not (dmDatos.cdsImExportar.Eof)) do begin sLogin := Trim(dmDatos.cdsImExportar.FieldByName('login').AsString); sMenu := dmDatos.cdsImExportar.FieldByName('menu').AsString; sOpciones := dmDatos.cdsImExportar.FieldByName('opciones').AsString; sPermisos := dmDatos.cdsImExportar.FieldByName('permiso').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM usuarios WHERE login = ''' + sLogin + ''''); Open; sClave := FieldByName('clave').AsString; if(not Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO permisos (usuario,menu,opciones,permiso) VALUES('); SQL.Add(sClave + ',' + sMenu + ',' + sOpciones + ',' + sPermisos + ')'); ExecSQL; end; Close; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; with dmDatos.qryModifica do begin // Elimina todos los privilegios de lo usuarios Close; SQL.Clear; SQL.Add('DELETE FROM privilegios'); ExecSQL; Close; end; lblTabla.Caption := 'Privilegios'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'privilegios.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; while(not (dmDatos.cdsImExportar.Eof)) do begin sLogin := Trim(dmDatos.cdsImExportar.FieldByName('login').AsString); sPrivilegio := dmDatos.cdsImExportar.FieldByName('clave').AsString; sAdicional := dmDatos.cdsImExportar.FieldByName('adicional').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM usuarios WHERE login = ''' + sLogin + ''''); Open; sClave := FieldByName('clave').AsString; if(not Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO privilegios (usuario,clave,adicional) VALUES('); SQL.Add(sClave + ',''' + sPrivilegio + ''',''' + sAdicional + ''')'); ExecSQL; end; Close; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; end; procedure TfrmImportar.ImportaTicket; var sNivel, sRenglon, sTexto : String; i : integer; begin lblTabla.Caption := 'Ticket'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'ticket.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM ticket'); ExecSQL; Close; end; while(not (dmDatos.cdsImExportar.Eof)) do begin sNivel := Trim(dmDatos.cdsImExportar.FieldByName('nivel').AsString); sRenglon := Trim(dmDatos.cdsImExportar.FieldByName('renglon').AsString); sTexto := dmDatos.cdsImExportar.FieldByName('texto').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('INSERT INTO ticket (nivel, renglon, texto) VALUES( '); SQL.Add(sNivel + ',' + sRenglon + ',''' + sTexto + ''')'); ExecSQL; Close; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; end; procedure TfrmImportar.ImportaEmpresa; var sRfc, sNombre, sCalle, sColonia, sCp, sLocalidad : String; sEstado, sFax, sCorreo, sTelefono, sPagina, sFecha : String; i : integer; begin lblTabla.Caption := 'Empresa'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'empresa.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Position := 0; with dmDatos.cdsImExportar do begin barAvance.Max := RecordCount; sRfc := Trim(FieldByName('rfc').AsString); sNombre := Trim(FieldByName('nombre').AsString); sCalle := Trim(FieldByName('calle').AsString); sColonia := Trim(FieldByName('colonia').AsString); sCp := Trim(FieldByName('cp').AsString); sLocalidad := Trim(FieldByName('localidad').AsString); sEstado := Trim(FieldByName('estado').AsString); sTelefono := Trim(FieldByName('telefono').AsString); sFax := Trim(FieldByName('fax').AsString); sCorreo := Trim(FieldByName('correoe').AsString); sFecha := FormatDateTime('mm/dd/yyyy',FieldByName('fecha').AsDateTime); sPagina := Trim(FieldByName('paginaweb').AsString); end; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM empresa'); ExecSQL; Close; Close; SQL.Clear; SQL.Add('INSERT INTO empresa (rfc, nombre, calle, colonia, cp,'); SQL.Add('localidad, estado, fax, correoe,'); SQL.Add('fecha, telefono) VALUES('); SQL.Add('''' + sRfc + ''',''' + sNombre + ''',''' + sCalle + ''','); SQL.Add('''' + sColonia + ''',''' + sCp + ''',''' + sLocalidad + ''',''' + sEstado + ''','); SQL.Add('''' + sFax + ''',''' + sCorreo + ''','); SQL.Add('''' + sFecha + ''',''' + sTelefono + '''' + ')'); ExecSQL; Close; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; end; procedure TfrmImportar.ImportaDescuentos; var sFechaIni, sFechaFin, sArticulo, sDepto, sCateg, sTotal, sCantidad, sPorcent, sVolumen : String; i : integer; begin lblTabla.Caption := 'Descuentos'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'descuentos.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM descuentos'); ExecSQL; Close; end; while(not (dmDatos.cdsImExportar.Eof)) do begin sFechaIni := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fechaini').AsDateTime); sFechaFin := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fechafin').AsDateTime); sArticulo := Trim(dmDatos.cdsImExportar.FieldByName('codigo').AsString); sDepto := Trim(dmDatos.cdsImExportar.FieldByName('departamento').AsString); sCateg := Trim(dmDatos.cdsImExportar.FieldByName('categoria').AsString); sTotal := dmDatos.cdsImExportar.FieldByName('total').AsString; sCantidad := dmDatos.cdsImExportar.FieldByName('cantidad').AsString; sPorcent := dmDatos.cdsImExportar.FieldByName('porcentaje').AsString; sVolumen := dmDatos.cdsImExportar.FieldByName('volumen').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT articulo FROM codigos WHERE codigo = ''' + sArticulo + ''''); Open; if(not Eof) then sArticulo := FieldByName('articulo').AsString else sArticulo := 'null'; Close; SQL.Clear; SQL.Add('SELECT clave FROM departamentos WHERE nombre = ''' + sDepto + ''''); Open; if(not Eof) then sDepto := FieldByName('clave').AsString else sDepto := 'null'; Close; SQL.Clear; SQL.Add('SELECT clave FROM categorias WHERE nombre = ''' + sCateg + ''''); Open; if(not Eof) then sCateg := FieldByName('clave').AsString else sCateg := 'null'; Close; SQL.Clear; SQL.Add('INSERT INTO descuentos (fechaini, fechafin, articulo, departamento,'); SQL.Add('categoria, total, cantidad, porcentaje, volumen) VALUES('); SQL.Add('''' + sFechaIni + ''',''' + sFechaFin + ''',' + sArticulo + ','); SQL.Add(sDepto + ',' + sCateg + ',' + sTotal + ',' + sCantidad + ','); SQL.Add(sPorcent + ',' + sVolumen + ')'); ExecSQL; Close; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; end; procedure TfrmImportar.ImportaVentas; var sCaja, sNumero, sIva, sTotal, sCambio, sRedondeo, sEstatus, sCliente, sventaRef : String; sUsuario, sFecha, sHora, sAreaVenta, sVenta, sCajaRef, sFechaRef, sHoraRef : String; i : integer; begin lblTabla.Caption := 'Ventas'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'ventas.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; while(not (dmDatos.cdsImExportar.Eof)) do begin dteFecha := dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime; if(dteFechaIni <= dteFecha) and (dteFechaFin >= dteFecha) then begin sFecha := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime); sCaja := dmDatos.cdsImExportar.FieldByName('caja').AsString; sNumero := dmDatos.cdsImExportar.FieldByName('numero').AsString; sIva := dmDatos.cdsImExportar.FieldByName('iva').AsString; sTotal := dmDatos.cdsImExportar.FieldByName('total').AsString; sCambio := dmDatos.cdsImExportar.FieldByName('cambio').AsString; sRedondeo := dmDatos.cdsImExportar.FieldByName('redondeo').AsString; sEstatus := dmDatos.cdsImExportar.FieldByName('estatus').AsString; sCliente := dmDatos.cdsImExportar.FieldByName('cliente').AsString; sUsuario := dmDatos.cdsImExportar.FieldByName('login').AsString; sHora := FormatDateTime('hh:nn:ss',dmDatos.cdsImExportar.FieldByName('hora').AsDateTime); sAreaVenta := dmDatos.cdsImExportar.FieldByName('area').AsString; sCajaRef := dmDatos.cdsImExportar.FieldByName('cajaref').AsString; sFechaRef := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecharef').AsDateTime); sHoraRef := FormatDateTime('hh:nn:ss',dmDatos.cdsImExportar.FieldByName('horaref').AsDateTime); with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM clientes WHERE nombre = ''' + sCliente + ''''); Open; if(not Eof) then sCliente := FieldByName('clave').AsString else sCliente := 'null'; Close; SQL.Clear; SQL.Add('SELECT clave FROM usuarios WHERE login = ''' + sUsuario + ''''); Open; if(not Eof) then sUsuario := FieldByName('clave').AsString else sUsuario := 'null'; Close; SQL.Clear; SQL.Add('SELECT clave FROM areasventa WHERE nombre = ''' + sAreaVenta + ''''); Open; if(not Eof) then sAreaVenta := FieldByName('clave').AsString else sAreaVenta := 'null'; //Busca la venta Close; SQL.Clear; SQL.Add('SELECT clave FROM ventas WHERE caja = ' + sCaja + ' AND '); SQL.Add('fecha = ''' + sFecha + ''' AND hora = ''' + sHora + ''''); Open; if(Eof) then begin sVentaRef := 'null'; if(Length(sCajaRef) > 0) then begin //Busca la venta de referencia Close; SQL.Clear; SQL.Add('SELECT clave FROM ventas WHERE caja = ''' + sCajaRef + ''' AND '); SQL.Add('fecha = ''' + sFechaRef + ''' AND hora = ''' + sHoraRef + ''''); Open; if(not Eof) then sVentaRef := FieldByName('clave').AsString; end; Close; SQL.Clear; SQL.Add('INSERT INTO ventas (caja, numero, iva, total, cambio, redondeo,'); SQL.Add('estatus, cliente, usuario, fecha, hora, areaventa, ventaref) VALUES('); SQL.Add(sCaja + ',' + sNumero + ',' + sIva + ',' + sTotal + ',' + sCambio + ','); SQL.Add(sRedondeo + ',''' + sEstatus + ''',' + sCliente + ','); SQL.Add(sUsuario + ',''' + sFecha + ''',''' + sHora + ''',' + sAreaVenta + ',' + sVentaRef + ')'); ExecSQL; Close; //Recupera la clave que genera el Trigger Close; SQL.Clear; SQL.Add('SELECT clave FROM ventas WHERE caja = ' + sCaja); SQL.Add('AND fecha = ''' + sFecha + ''' AND hora = ''' + sHora + ''''); Open; sVenta := FieldByName('clave').AsString; Close; if(sCliente <> 'null') then begin // Guarda la última venta al cliente Close; SQL.Clear; SQL.Add('UPDATE clientes SET ultimacompra = ' + sVenta + ','); SQL.Add('acumulado = acumulado + ' + sTotal); SQL.Add('WHERE clave = ' + sCliente); ExecSQL; Close; end; end; Close; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; end; procedure TfrmImportar.ImportaDetalleVenta; var sCaja, sFecha, sHora, sOrden, sArticulo, sCantidad, sIva, sPrecio : String; sDescuento, sVenta, sTipoComp, sTipoArt, sJuego, sDevolucion, sOrdenRef : String; i : integer; begin lblTabla.Caption := 'Detalle de ventas'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'ventasdet.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; while(not (dmDatos.cdsImExportar.Eof)) do begin dteFecha := dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime; if(dteFechaIni <= dteFecha) and (dteFechaFin >= dteFecha) then begin sFecha := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime); sCaja := dmDatos.cdsImExportar.FieldByName('caja').AsString; sHora := FormatDateTime('hh:nn:ss',dmDatos.cdsImExportar.FieldByName('hora').AsDateTime); sOrden := dmDatos.cdsImExportar.FieldByName('orden').AsString; sArticulo := Trim(dmDatos.cdsImExportar.FieldByName('codigo').AsString); sCantidad := dmDatos.cdsImExportar.FieldByName('cantidad').AsString; sIva := dmDatos.cdsImExportar.FieldByName('iva').AsString; sPrecio := dmDatos.cdsImExportar.FieldByName('precio').AsString; sDescuento := dmDatos.cdsImExportar.FieldByName('descuento').AsString; sJuego := dmDatos.cdsImExportar.FieldByName('juego').AsString; sDevolucion := dmDatos.cdsImExportar.FieldByName('devolucion').AsString; if(Length(sDevolucion) = 0) then sDevolucion := '0'; sOrdenRef := dmDatos.cdsImExportar.FieldByName('ventareforden').AsString; if(Length(sOrdenRef) = 0) then sOrdenRef := 'null'; with dmDatos.qryModifica do begin //Recupera la clave y el tipo de articulo Close; SQL.Clear; SQL.Add('SELECT a.clave, a.tipo FROM articulos a LEFT JOIN '); SQL.Add('codigos o ON a.clave = o.articulo WHERE o.codigo = ''' + sArticulo + ''''); Open; if(not Eof) then begin sArticulo := FieldByName('clave').AsString; sTipoArt := FieldByName('tipo').AsString; end else sArticulo := 'null'; // Recupera la clave de la venta Close; SQL.Clear; SQL.Add('SELECT clave FROM ventas WHERE caja = ' + sCaja + ' AND '); SQL.Add('fecha = ''' + sFecha + ''' AND hora = ''' + sHora + ''''); Open; if(not Eof) then begin sVenta := FieldByName('clave').AsString; // Recupera el tipo de comprobante Close; SQL.Clear; SQL.Add('SELECT tipo FROM comprobantes WHERE venta = ' + sVenta + ' AND '); SQL.Add('estatus = ''A'''); Open; sTipoComp := FieldByName('tipo').AsString; // Verifica que no exista el registro Close; SQL.Clear; SQL.Add('SELECT orden FROM ventasdet WHERE venta = ' + sVenta + ' AND '); SQL.Add('orden = ' + sOrden + ' AND juego = ' + sJuego); Open; if(Eof) then begin // Si el comprobante es diferente de cotización if(sTipoComp <> 'C') then begin if(sArticulo <> 'null') then //Cuando sea no inventariable o juego if(sTipoArt <> '1') and (sTipoArt <> '2') then begin Close; SQL.Clear; SQL.Add('UPDATE articulos SET'); SQL.Add('existencia = existencia - ' + sCantidad + ','); SQL.Add('ultventa = ' + sVenta); SQL.Add('WHERE clave = ' + sArticulo); ExecSQL; Close; end else begin Close; SQL.Clear; SQL.Add('UPDATE articulos SET ultventa = ' + sVenta); SQL.Add('WHERE clave = ' + sArticulo); ExecSQL; Close; end; end; Close; SQL.Clear; SQL.Add('INSERT INTO ventasdet (venta, articulo, cantidad, iva, precio,'); SQL.Add('descuento, orden, juego, devolucion, ventareforden, fiscal) VALUES('); SQL.Add(sVenta + ',' + sArticulo + ','); SQL.Add(sCantidad + ',' + sIva + ',' + sPrecio + ',' + sDescuento + ','); SQL.Add(sOrden + ',' + sJuego + ',' + sDevolucion + ',' + sOrdenRef + ')'); ExecSQL; Close; end; end; Close; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; end; procedure TfrmImportar.ImportaPagoVenta; var sCaja, sFecha, sHora, sTipoPago, sImporte, sReferencia, sVenta, sOrden: String; sNotaCredito, sCajaNotaCred : String; i : integer; begin lblTabla.Caption := 'Pago de ventas'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'ventaspago.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; while(not (dmDatos.cdsImExportar.Eof)) do begin dteFecha := dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime; if(dteFechaIni <= dteFecha) and (dteFechaFin >= dteFecha) then begin sFecha := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime); sCaja := dmDatos.cdsImExportar.FieldByName('caja').AsString; sHora := FormatDateTime('hh:nn:ss',dmDatos.cdsImExportar.FieldByName('hora').AsDateTime); sTipoPago := dmDatos.cdsImExportar.FieldByName('nombre').AsString; sImporte := Trim(dmDatos.cdsImExportar.FieldByName('importe').AsString); sReferencia := dmDatos.cdsImExportar.FieldByName('referencia').AsString; sOrden := dmDatos.cdsImExportar.FieldByName('orden').AsString; sNotaCredito := dmDatos.cdsImExportar.FieldByName('notacredito').AsString; sCajaNotaCred := dmDatos.cdsImExportar.FieldByName('cajanotacred').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM ventas WHERE caja = ' + sCaja + ' AND '); SQL.Add('fecha = ''' + sFecha + ''' AND hora = ''' + sHora + ''''); Open; if(not Eof) then begin sVenta := FieldByName('clave').AsString; Close; SQL.Clear; SQL.Add('SELECT venta FROM ventaspago WHERE venta = ' + sVenta); SQL.Add('AND orden = ' + sOrden); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('SELECT clave FROM tipopago WHERE nombre = ''' + sTipoPago + ''''); Open; if(not Eof) then sTipoPago := FieldByName('clave').AsString else sTipoPago := 'null'; if(Length(sNotaCredito) > 0) then begin Close; SQL.Clear; SQL.Add('SELECT clave FROM notascredito WHERE numero = ' + sNotaCredito); SQL.Add('AND estatus = ''A'' AND caja = ' + sCajaNotaCred); Open; if(not Eof) then sNotaCredito := FieldByName('clave').AsString else sNotaCredito := 'null'; end else sNotaCredito := 'null'; Close; SQL.Clear; SQL.Add('INSERT INTO ventaspago (venta, tipopago, importe, referencia, orden, notacredito) VALUES('); SQL.Add(sVenta + ',' + sTipoPago + ',' + sImporte + ',''' + sReferencia + ''',' + sOrden + ',' + sNotaCredito + ')'); ExecSQL; Close; end; end; Close; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; end; procedure TfrmImportar.ImportaComprobantes; var sCaja, sTipo, sNumero, sCliente, sFecha, sHora, sEstatus, sVenta: String; i : integer; begin lblTabla.Caption := 'Comprobantes'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'comprobantes.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; while(not (dmDatos.cdsImExportar.Eof)) do begin dteFecha := dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime; if(dteFechaIni <= dteFecha) and (dteFechaFin >= dteFecha) then begin sFecha := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime); sCaja := dmDatos.cdsImExportar.FieldByName('caja').AsString; sHora := FormatDateTime('hh:nn:ss',dmDatos.cdsImExportar.FieldByName('hora').AsDateTime); sTipo := dmDatos.cdsImExportar.FieldByName('tipo').AsString; sNumero := dmDatos.cdsImExportar.FieldByName('numero').AsString; sCliente := dmDatos.cdsImExportar.FieldByName('cliente').AsString; sFecha := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime); sEstatus := dmDatos.cdsImExportar.FieldByName('estatus').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM clientes WHERE nombre = ''' + sCliente + ''''); Open; if(not Eof) then sCliente := FieldByName('clave').AsString else sCliente := 'null'; Close; SQL.Clear; SQL.Add('SELECT clave FROM ventas WHERE caja = ' + sCaja + ' AND '); SQL.Add('fecha = ''' + sFecha + ''' AND hora = ''' + sHora + ''''); Open; if(not Eof) then begin sVenta := FieldByName('clave').AsString; Close; SQL.Clear; SQL.Add('SELECT venta FROM comprobantes WHERE venta = ' + sVenta); SQL.Add('AND tipo = ''' + sTipo + ''' AND fecha = ''' + sFecha + ''''); SQL.Add('AND estatus = ''' + sEstatus + ''''); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO comprobantes (venta, tipo, numero, cliente,'); SQL.Add('fecha, estatus, caja) VALUES(' + sVenta + ','); SQL.Add('''' + sTipo + ''',' + sNumero + ',' + sCliente + ','); SQL.Add('''' + sFecha + ''',''' + sEstatus + ''',' + sCaja + ')'); ExecSQL; Close; end; end; Close; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; end; procedure TfrmImportar.ImportaNotasCredito; var sCaja, sImporte, sNumero, sCliente, sFecha, sNumComprob, sCajaComprob : String; sEstatus, sComprobante: String; i : integer; begin lblTabla.Caption := 'Notas de crédito'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'notascredito.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; while(not (dmDatos.cdsImExportar.Eof)) do begin dteFecha := dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime; if(dteFechaIni <= dteFecha) and (dteFechaFin >= dteFecha) then begin sFecha := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime); sNumero := dmDatos.cdsImExportar.FieldByName('numero').AsString; sImporte := dmDatos.cdsImExportar.FieldByName('importe').AsString; sEstatus := dmDatos.cdsImExportar.FieldByName('estatus').AsString; sCaja := dmDatos.cdsImExportar.FieldByName('caja').AsString; sCliente := dmDatos.cdsImExportar.FieldByName('cliente').AsString; sNumComprob := dmDatos.cdsImExportar.FieldByName('numcomprob').AsString; sCajaComprob := dmDatos.cdsImExportar.FieldByName('cajacomprob').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM clientes WHERE nombre = ''' + sCliente + ''''); Open; if(not Eof) then sCliente := FieldByName('clave').AsString else sCliente := 'null'; Close; SQL.Clear; SQL.Add('SELECT clave FROM comprobantes WHERE numero = ' + sNumComprob); SQL.Add('AND estatus = ''A'' AND tipo = ''D'' AND caja = ' + sCajaComprob); Open; if(not Eof) then begin sComprobante := FieldByName('clave').AsString; Close; SQL.Clear; SQL.Add('SELECT clave FROM notascredito WHERE numero = ' + sNumero); SQL.Add('AND estatus = ''A'' AND fecha = ''' + sFecha + ''''); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO notascredito (numero, fecha, cliente,'); SQL.Add('importe, estatus, caja, comprobante) VALUES(' + sNumero + ','); SQL.Add('''' + sFecha + ''',' + sCliente + ',' + sImporte + ','); SQL.Add('''' + sEstatus + ''',' + sCaja + ',' + sComprobante + ')'); ExecSQL; Close; end; end; Close; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; end; procedure TfrmImportar.btnDirClick(Sender: TObject); begin dlgAbrir.InitialDir := ExtractFilePath(txtRuta.Text); if(dlgAbrir.Execute) then txtRuta.Text := dlgAbrir.FileName; txtRutaExit(Sender); end; procedure TfrmImportar.FormCreate(Sender: TObject); begin RecuperaConfig; end; procedure TfrmImportar.ImportaCajas; var sNombre, sCaja, sSerieTicket, sSerieNota, sSerieFactura, sFechaUMov : String; dteFechaMov : TDateTime; i : integer; begin lblTabla.Caption := 'Cajas'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'cajas.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; sFechaUMov := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now); while(not (dmDatos.cdsImExportar.Eof)) do begin sCaja := dmDatos.cdsImExportar.FieldByName('numero').AsString; sNombre := Trim(dmDatos.cdsImExportar.FieldByName('nombre').AsString); sSerieTicket := Trim(dmDatos.cdsImExportar.FieldByName('serieticket').AsString); sSerieNota := Trim(dmDatos.cdsImExportar.FieldByName('serienota').AsString); sSerieFactura := Trim(dmDatos.cdsImExportar.FieldByName('seriefactura').AsString); dteFechaMov := dmDatos.cdsImExportar.FieldByName('fecha_umov').AsDateTime; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT numero, fecha_umov FROM cajas WHERE numero = ' + sCaja); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO cajas (numero, nombre, serieticket, serienota, seriefactura, fecha_umov) VALUES('); SQL.Add(sCaja + ',''' + sNombre + ''',''' + sSerieTicket + ''',''' + sSerieNota + ''',''' + sSerieFactura + ''',''' + sFechaUMov + ''')'); ExecSQL; Close; end else begin // Modifica el registro if(dteFechaMov > FieldByName('fecha_umov').AsDateTime) or (rdbReemplazar.Checked) then begin Close; SQL.Clear; SQL.Add('UPDATE cajas SET nombre = ''' + sNombre + ''','); SQL.Add('numero = ' + sCaja + ','); SQL.Add('serieticket = ''' + sSerieTicket + ''','); SQL.Add('serienota = ''' + sSerieNota + ''','); SQL.Add('seriefactura = ''' + sSerieFactura + ''','); SQL.Add('fecha_umov = ''' + sFechaUMov + ''''); SQL.Add('WHERE numero = ' + sCaja); ExecSQL; Close; end else begin Close; SQL.Clear; SQL.Add('UPDATE cajas SET fecha_umov = ''' + sFechaUMov + ''''); SQL.Add('WHERE numero = ' + sCaja); ExecSQL; Close; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; if(rdbReemplazar.Checked) then //Elimina todo lo que no estaba en la importación with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM cajas WHERE fecha_umov <> ''' + sFechaUMov + ''''); ExecSQL; Close; end; end; function TfrmImportar.VerificaFechas(sFecha : string):boolean; var dteFecha : TDateTime; begin Result:=true; if(not TryStrToDate(sFecha,dteFecha)) then Result:=false; end; procedure TfrmImportar.chkVentasClick(Sender: TObject); begin if(chkVentas.Checked) then begin txtDiaVentaIni.Visible := true; txtMesVentaIni.Visible := true; txtAnioVentaIni.Visible := true; txtDiaVentaFin.Visible := true; txtMesVentaFin.Visible := true; txtAnioVentaFin.Visible := true; txtDiaVentaIni.SetFocus; end else begin txtDiaVentaIni.Visible := false; txtMesVentaIni.Visible := false; txtAnioVentaIni.Visible := false; txtDiaVentaFin.Visible := false; txtMesVentaFin.Visible := false; txtAnioVentaFin.Visible := false; end; end; procedure TfrmImportar.Salta(Sender: TObject; var Key: Word; Shift: TShiftState); begin {Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)} if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then SelectNext(Sender as TWidgetControl, true, true); end; procedure TfrmImportar.FormShow(Sender: TObject); begin zipArchivo := TZipFile.Create ; txtRutaExit(Sender); end; procedure TfrmImportar.txtRutaExit(Sender: TObject); var chkComponente : TCheckBox; sComponente : String; i : integer; begin if(FileExists(txtRuta.Text)) then begin //Desahabilita todos las casillas de verificación for i := 0 to grpDatos.ControlCount - 1 do if (grpDatos.Controls[i] is TCheckBox) then begin (grpDatos.Controls[i] as TCheckBox).Enabled := false; (grpDatos.Controls[i] as TCheckBox).Checked := false; end; zipArchivo.LoadFromFile(txtRuta.Text); for i := 0 to zipArchivo.Count -1 do begin sComponente := 'chk' + Copy(zipArchivo.Name[i],1,Length(zipArchivo.Name[i]) - 4); chkComponente := (FindComponent(sComponente) as TCheckBox); if(chkComponente <> nil) then begin chkComponente.Enabled := true; chkComponente.Checked := true; end; end; end; end; procedure TfrmImportar.txtAnioVentaIniExit(Sender: TObject); begin (Sender as TEdit).Text := Trim((Sender as TEdit).Text); if(Length((Sender as TEdit).Text) < 4) and (Length((Sender as TEdit).Text) > 0) then (Sender as TEdit).Text := IntToStr(StrToInt((Sender as TEdit).Text) + 2000); end; procedure TfrmImportar.txtDiaVentaIniExit(Sender: TObject); begin Rellena(Sender); end; procedure TfrmImportar.Rellena(Sender: TObject); var i : integer; begin for i := Length((Sender as TEdit).Text) to (Sender as TEdit).MaxLength - 1 do (Sender as TEdit).Text := '0' + (Sender as TEdit).Text; end; procedure TfrmImportar.ImportaVendedores; var sClave, sRfc, sNombre, sCalle, sColonia, sCp, sLocalidad, sCateg : String; sEstado, sFax, sCorreo, sFechaCap, sTelefono, sFechaUMov : String; dteFechaMov : TDateTime; i : integer; begin lblTabla.Caption := 'Vendedores'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'Vendedores.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; sFechaUMov := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now); while(not (dmDatos.cdsImExportar.Eof)) do begin sClave := dmDatos.cdsImExportar.FieldByName('clave').AsString; sRfc := Trim(dmDatos.cdsImExportar.FieldByName('rfc').AsString); sNombre := Trim(dmDatos.cdsImExportar.FieldByName('nombre').AsString); sCalle := Trim(dmDatos.cdsImExportar.FieldByName('calle').AsString); sColonia := Trim(dmDatos.cdsImExportar.FieldByName('colonia').AsString); sCp := Trim(dmDatos.cdsImExportar.FieldByName('cp').AsString); sLocalidad := Trim(dmDatos.cdsImExportar.FieldByName('localidad').AsString); sEstado := Trim(dmDatos.cdsImExportar.FieldByName('estado').AsString); sFax := Trim(dmDatos.cdsImExportar.FieldByName('fax').AsString); sCorreo := Trim(dmDatos.cdsImExportar.FieldByName('ecorreo').AsString); sFechaCap := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha_cap').AsDateTime); sTelefono := Trim(dmDatos.cdsImExportar.FieldByName('telefono').AsString); sCateg := Trim(dmDatos.cdsImExportar.FieldByName('categoria').AsString); dteFechaMov := dmDatos.cdsImExportar.FieldByName('fecha_umov').AsDateTime; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM categorias WHERE nombre = ''' + sCateg + ''' AND tipo = ''V'''); Open; sCateg := FieldByName('clave').AsString; if(Length(sCateg) = 0) then sCateg := 'null'; Close; SQL.Clear; SQL.Add('SELECT clave, fecha_umov FROM vendedores WHERE clave = ' + sClave); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO vendedores (clave, rfc, nombre, calle, colonia, cp,'); SQL.Add('localidad, estado, fax, ecorreo, fecha_cap,'); SQL.Add('telefono, fecha_umov, categoria) VALUES('); SQL.Add(sClave + ',''' + sRfc + ''',''' + sNombre + ''',''' + sCalle + ''','); SQL.Add('''' + sColonia + ''',''' + sCp + ''',''' + sLocalidad + ''',''' + sEstado + ''','); SQL.Add('''' + sFax + ''',''' + sCorreo + ''','); SQL.Add('''' + sFechaCap + ''',''' + sTelefono + ''',''' + sFechaUMov + ''',' + sCateg + ')'); ExecSQL; Close; end else begin // Modifica el registro sClave := FieldByName('clave').AsString; if(dteFechaMov > FieldByName('fecha_umov').AsDateTime) or (rdbReemplazar.Checked) then begin Close; SQL.Clear; SQL.Add('UPDATE vendedores SET rfc = ''' + sRfc + ''','); SQL.Add('nombre = ''' + sNombre + ''','); SQL.Add('calle = ''' + sCalle + ''','); SQL.Add('colonia = ''' + sColonia + ''','); SQL.Add('cp = ''' + sCp + ''','); SQL.Add('localidad = ''' + sLocalidad + ''','); SQL.Add('estado = ''' + sEstado + ''','); SQL.Add('fax = ''' + sFax + ''','); SQL.Add('ecorreo = ''' + sCorreo + ''','); SQL.Add('fecha_cap = ''' + sFechaCap + ''','); SQL.Add('telefono = ''' + sTelefono + ''','); SQL.Add('fecha_umov = ''' + sFechaUmov + ''','); SQL.Add('categoria = ' + sCateg); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end else begin Close; SQL.Clear; SQL.Add('UPDATE vendedores SET fecha_umov = ''' + sFechaUMov + ''''); SQL.Add('WHERE clave = ' + sClave); ExecSQL; Close; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; dmDatos.cdsImExportar.Active := false; StrStream.Free; if(rdbReemplazar.Checked) then //Elimina todo lo que no estaba en la importación with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM proveedores WHERE fecha_umov <> ''' + sFechaUMov + ''''); ExecSQL; Close; end; end; procedure TfrmImportar.ImportaCtsXCobrar; var sImporte, sPlazo, sInteres, sIntMoratorio, sProxPago, sVenta, sOrden : String; sTipoInteres, sTipoPlazo, sEstatus, sHora, sFechaUMov, sCaja : String; sCliente, sNumPago, sCantIntMorat, sPagado, sFecha, sCantInteres : String; sFechaV, sNumero, sTipoPago, sComentario, sClaveXCobrar : String; i : integer; begin lblTabla.Caption := 'XCobrar'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'XCobrar.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; sFechaUMov := FormatDateTime('mm/dd/yyyy hh:nn:ss',Now); while(not (dmDatos.cdsImExportar.Eof)) do begin sImporte := dmDatos.cdsImExportar.FieldByName('importe').AsString; sPlazo := dmDatos.cdsImExportar.FieldByName('plazo').AsString; sInteres := dmDatos.cdsImExportar.FieldByName('interes').AsString; sIntMoratorio := dmDatos.cdsImExportar.FieldByName('intmoratorio').AsString; sProxPago := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('proximopago').AsDateTime); sTipoInteres := dmDatos.cdsImExportar.FieldByName('tipointeres').AsString; sTipoPlazo := dmDatos.cdsImExportar.FieldByName('tipoplazo').AsString; sEstatus := dmDatos.cdsImExportar.FieldByName('estatus').AsString; sCliente:= dmDatos.cdsImExportar.FieldByName('cliente').AsString; sFecha := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime); sNumPago := dmDatos.cdsImExportar.FieldByName('numpago').AsString; sCantIntMorat := dmDatos.cdsImExportar.FieldByName('cantintmorat').AsString; sCantInteres := dmDatos.cdsImExportar.FieldByName('cantinteres').AsString; sPagado := dmDatos.cdsImExportar.FieldByName('pagado').AsString; sHora := FormatDateTime('hh:nn:ss',dmDatos.cdsImExportar.FieldByName('hora').AsDateTime); sCaja:= dmDatos.cdsImExportar.FieldByName('caja').AsString; sOrden := dmDatos.cdsImExportar.FieldByName('Orden').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM clientes WHERE nombre = ''' + sCliente + ''''); Open; if(not Eof) then sCliente := FieldByName('clave').AsString else sCliente := 'null'; Close; SQL.Clear; SQL.Add('SELECT clave FROM ventas WHERE caja = ' + sCaja + ' AND '); SQL.Add('fecha = ''' + sFecha + ''' AND hora = ''' + sHora + ''''); Open; if(not Eof) then begin sVenta := FieldByName('clave').AsString; Close; SQL.Clear; SQL.Add('SELECT orden FROM xcobrar WHERE venta = ' + sVenta + ' AND '); SQL.Add('orden = ' + sOrden); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO xcobrar (venta, importe, plazo, interes, intmoratorio,'); SQL.Add('proximopago, tipointeres, tipoplazo, estatus, cliente, fecha, numpago,'); SQL.Add('cantintmorat,cantinteres, pagado, orden )values ('); SQL.Add( sVenta +','+ sImporte +','+ sPlazo + ','+sInteres + ','+ sIntMoratorio +','); SQL.Add('''' + sProxPago + ''','''+sTipoInteres+''','+ sTipoPlazo + ','''+ sEstatus+''','); SQL.Add(sCliente+','''+sFecha+''','''+sNumPago+''','+ sCantIntMorat+','+sCantInteres+','+sPagado+','+sOrden+')'); ExecSQL; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; lblTabla.Caption := 'XCobrar'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'XCobrarPagos.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; while(not (dmDatos.cdsImExportar.Eof)) do begin sOrden := dmDatos.cdsImExportar.FieldByName('orden').AsString; sFechaV :=FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fechav').AsDateTime); sHora := FormatDateTime('hh:nn:ss',dmDatos.cdsImExportar.FieldByName('hora').AsDateTime); sCaja := dmDatos.cdsImExportar.FieldByName('caja').AsString; sNumero :=dmDatos.cdsImExportar.FieldByName('numero').AsString; sFecha := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime); sImporte := dmDatos.cdsImExportar.FieldByName('importe').AsString; sInteres := dmDatos.cdsImExportar.FieldByName('interes').AsString; sIntMoratorio := dmDatos.cdsImExportar.FieldByName('interesmorat').AsString; sTipoPago := dmDatos.cdsImExportar.FieldByName('tipopago').AsString; sComentario := dmDatos.cdsImExportar.FieldByName('comentario').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM tipopago WHERE nombre = ''' + sTipoPago + ''''); Open; if(not Eof) then sTipoPago := FieldByName('clave').AsString else sTipoPago := 'null'; Close; SQL.Clear; SQL.Add('SELECT clave FROM ventas WHERE caja = ' + sCaja + ' AND '); SQL.Add('fecha = ''' + sFechaV + ''' AND hora = ''' + sHora + ''''); Open; if(not Eof) then begin sVenta := FieldByName('clave').AsString; Close; SQL.Clear; SQL.Add('SELECT clave FROM xcobrar WHERE venta = ' + sVenta + ' AND '); SQL.Add('orden = ' + sOrden + 'AND fecha=''' + sFechaV + ''''); Open; if(not Eof) then begin sClaveXCobrar := FieldByName('clave').AsString; SQL.Add('SELECT xcobrar FROM xcobrarpagos WHERE xcobrar = ' + sClaveXCobrar + ' AND '); SQL.Add('numero = ' + sNumero); if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO xcobrarpagos (xCobrar, numero, fecha, importe, interes, interesmorat,'); SQL.Add('tipopago, comentario) values('); SQL.Add( sClaveXCobrar + ',' + sNumero + ','''+sFecha+''','+sImporte + ','+ sInteres+','); SQL.Add( sIntMoratorio + ',' + sTipoPago +',''' +sComentario+''''+')'); ExecSQL; end; end; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; procedure TfrmImportar.ImportaInventario2; var sFecha, sAplicado, sDescrip, sClave :String; sArticulo, sCantidad, sExistencia, sJuego, sCantJuego :String; i : integer; begin lblTabla.Caption := 'Inventario'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'Inventario.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; while(not (dmDatos.cdsImExportar.Eof)) do begin sDescrip := dmDatos.cdsImExportar.FieldByName('descrip').AsString; sAplicado:= dmDatos.cdsImExportar.FieldByName('aplicado').AsString; sFecha := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime); with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT clave FROM inventario WHERE fecha = ''' + sFecha + '''AND'); SQL.Add('descrip = ''' + sdescrip +''''); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO inventario (fecha, descrip, aplicado) values ('); SQL.Add('''' + sFecha + ''','''+sDescrip+''','''+ sAplicado + ''')'); ExecSQL; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; lblTabla.Caption := 'InventDet'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'InventDet.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; while(not (dmDatos.cdsImExportar.Eof)) do begin sDescrip := dmDatos.cdsImExportar.FieldByName('descrip').AsString; sFecha := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime); sArticulo:= dmDatos.cdsImExportar.FieldByName('codigo').AsString; sCantidad := dmDatos.cdsImExportar.FieldByName('cantidad').AsString; sExistencia := dmDatos.cdsImExportar.FieldByName('existencia').AsString; sJuego := dmDatos.cdsImExportar.FieldByName('juego').AsString; sCantJuego := dmDatos.cdsImExportar.FieldByName('cantjuego').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT articulo FROM codigos WHERE codigo = ''' + sArticulo + ''''); Open; if(not Eof) then sArticulo := FieldByName('articulo').AsString else sArticulo := 'null'; Close; SQL.Clear; SQL.Add('SELECT clave FROM inventario WHERE '); SQL.Add('fecha = ''' + sFecha + ''' AND Descrip = ''' + sDescrip + ''''); Open; if(not Eof) then begin sClave := FieldByName('clave').AsString; Close; SQL.Clear; SQL.Add('SELECT inventario FROM inventdet WHERE inventario = ' + sClave); SQL.add(' AND articulo = ' + sArticulo); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO inventdet (inventario, articulo, cantidad, existencia, juego, cantjuego) VALUES('); SQL.Add( sClave + ',' + sArticulo + ',' + sCantidad + ',' + sExistencia + ',''' + sJuego + ''',' + sCantJuego + ')'); ExecSQL; end; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; end; procedure TfrmImportar.ImportaCompras; var sCaja, sProveedor, sDocumento, sFecha, sIva, sTotal, sUsuario, sEstatus, sTipoPago, sImporte : String; sDescuento, sFechaCap, sTipo, sOrden, sCodigo, sCantidad, sCosto, sCompra, sReferencia : String; i: integer ; begin lblTabla.Caption := 'Compras'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'compras.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; dteFechaIni := StrToDate(txtDiaCompraIni.Text + '/' + txtMesCompraIni.Text + '/' + txtAnioCompraIni.Text); dteFechaFin := StrToDate(txtDiaCompraFin.Text + '/' + txtMesCompraFin.Text + '/' + txtAnioCompraFin.Text); while(not (dmDatos.cdsImExportar.Eof)) do begin dteFecha := dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime; if(dteFechaIni <= dteFecha) and (dteFechaFin >= dteFecha) then begin sDocumento := dmDatos.cdsImExportar.FieldByName('documento').AsString; sFecha := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime); sEstatus := dmDatos.cdsImExportar.FieldByName('estatus').AsString; sFechaCap := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha_cap').AsDateTime); sCaja := dmDatos.cdsImExportar.FieldByName('caja').AsString; sProveedor := dmDatos.cdsImExportar.FieldByName('clave').AsString; sIva := dmDatos.cdsImExportar.FieldByName('iva').AsString; sTotal := dmDatos.cdsImExportar.FieldByName('total').AsString; sUsuario := dmDatos.cdsImExportar.FieldByName('login').AsString; sDescuento := dmDatos.cdsImExportar.FieldByName('descuento').AsString; sTipo := dmDatos.cdsImExportar.FieldByName('tipo').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT * FROM compras WHERE documento = ''' + sDocumento + ''' AND'); SQL.Add('estatus = ''' + sEstatus + ''' AND fecha = ''' + sFecha + ''' AND'); SQL.Add('fecha_cap = ''' + sFechaCap + ''' AND caja = ' + sCaja); // SQL.Add('fecha_cap = ''' + sFechaCap + ''' AND caja = ' + sCaja); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('SELECT clave FROM usuarios WHERE login = ''' + sUsuario + ''''); Open; if(not Eof) then sUsuario := FieldByName('clave').AsString else sUsuario := 'null'; Close; SQL.Clear; SQL.Add('SELECT clave FROM proveedores WHERE clave = ''' + sProveedor + ''''); Open; if(Eof) then sProveedor := 'null'; Close; SQL.Clear; SQL.Add('INSERT INTO compras (caja, proveedor, documento, fecha, iva, total,'); SQL.Add('usuario, estatus, descuento, fecha_cap, tipo) VALUES('); SQL.Add(sCaja + ',' + sProveedor + ',''' + sDocumento + ''',''' + sFecha + ''','+ sIva + ',' + sTotal + ','); SQL.Add(sUsuario + ',''' + sEstatus + ''',' + sDescuento + ',''' + sFechaCap + ''',''' + sTipo + ''')'); ExecSQL; end; end; end; dmDatos.cdsImExportar.Next; barAvance.StepIt; end; lblTabla.Caption := 'Comprasdet'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'comprasdet.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; while(not (dmDatos.cdsImExportar.Eof)) do begin sCaja := dmDatos.cdsImExportar.FieldByName('caja').AsString; sDocumento := dmDatos.cdsImExportar.FieldByName('documento').AsString; sFecha := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime); sFechaCap := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha_cap').AsDateTime); sEstatus := dmDatos.cdsImExportar.FieldByName('estatus').AsString; sOrden := dmDatos.cdsImExportar.FieldByName('orden').AsString; sCodigo := dmDatos.cdsImExportar.FieldByName('codigo').AsString; sCantidad := dmDatos.cdsImExportar.FieldByName('cantidad').AsString; sIva := dmDatos.cdsImExportar.FieldByName('iva').AsString; sCosto := dmDatos.cdsImExportar.FieldByName('costo').AsString; sDescuento := dmDatos.cdsImExportar.FieldByName('descuento').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT * FROM compras WHERE documento = ''' + sDocumento + ''' AND'); SQL.Add('estatus = ''' + sEstatus + ''' AND fecha = ''' + sFecha + ''' AND'); SQL.Add('caja = ' + sCaja + ' AND fecha_cap = ''' + sFechaCap + ''''); Open; if(not Eof) then begin sCompra := FieldByName('clave').AsString; Close; SQL.Clear; SQL.Add('SELECT a.clave FROM articulos a LEFT JOIN '); SQL.Add('codigos o ON a.clave = o.articulo WHERE o.codigo = ''' + sCodigo + ''''); Open; if(not Eof) then sCodigo := FieldByName('clave').AsString else sCodigo := 'null'; Close; SQL.Clear; SQL.Add('SELECT orden FROM comprasdet WHERE compra = ' + sCompra + ' AND '); SQL.Add('orden = ' + sOrden); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO comprasdet (compra, orden, articulo, cantidad, costo, iva,'); SQL.Add('descuento, fiscal) VALUES('); SQL.Add( sCompra + ',' + sOrden + ',' + sCodigo + ',' + sCantidad + ','+ sCosto + ','); SQL.Add( sIva + ',' + sDescuento + ')'); ExecSQL; end; end; end; barAvance.StepIt; dmDatos.cdsImExportar.Next; end; lblTabla.Caption := 'ComprasPago'; lblTabla.Refresh; for i := 0 to zipArchivo.Count do if (zipArchivo.Name[i] = 'compraspago.xml') then break; dmDatos.cdsImExportar.Active := false; StrStream := TStringStream.Create(zipArchivo.Data[i]); dmDatos.cdsImExportar.LoadFromStream(strStream); dmDatos.cdsImExportar.Active := true; barAvance.Max := dmDatos.cdsImExportar.RecordCount; barAvance.Position := 0; while(not (dmDatos.cdsImExportar.Eof)) do begin sCaja := dmDatos.cdsImExportar.FieldByName('caja').AsString; sDocumento := dmDatos.cdsImExportar.FieldByName('documento').AsString; sFecha := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha').AsDateTime); sFechaCap := FormatDateTime('mm/dd/yyyy',dmDatos.cdsImExportar.FieldByName('fecha_cap').AsDateTime); sEstatus := dmDatos.cdsImExportar.FieldByName('estatus').AsString; sTipoPago := dmDatos.cdsImExportar.FieldByName('nombre').AsString; sImporte := dmDatos.cdsImExportar.FieldByName('Importe').AsString; sReferencia := dmDatos.cdsImExportar.FieldByName('referencia').AsString; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT * FROM compras WHERE documento = ''' + sDocumento + ''' AND'); SQL.Add('estatus = ''' + sEstatus + ''' AND fecha = ''' + sFecha + ''' AND'); SQL.Add('caja = ' + sCaja + ' AND fecha_cap = ''' + sFechaCap + ''''); Open; if(not Eof) then begin sCompra := FieldByName('clave').AsString; Close; SQL.Clear; SQL.Add('SELECT clave FROM tipopago WHERE nombre = ''' + sTipoPago + ''''); Open; if(not Eof) then sTipoPago := FieldByName('clave').AsString else sTipoPago := 'null'; Close; SQL.Clear; SQL.Add('SELECT * FROM compraspago WHERE compra = ' + sCompra ); SQL.Add('AND tipopago = ' + sTipoPago + ' AND importe = ' + sImporte); Open; if(Eof) then begin Close; SQL.Clear; SQL.Add('INSERT INTO compraspago (compra, tipopago, importe, referencia) values('); SQL.Add( sCompra + ',' + sTipopago + ',' + sImporte + ',''' + sReferencia + ''')'); ExecSQL; end; end; end; barAvance.StepIt; dmDatos.cdsImExportar.Next; end; end; procedure TfrmImportar.chkComprasClick(Sender: TObject); begin if(chkCompras.Checked) then begin txtDiaCompraIni.Visible := true; txtMesCompraIni.Visible := true; txtAnioCompraIni.Visible := true; txtDiaCompraFin.Visible := true; txtMesCompraFin.Visible := true; txtAnioCompraFin.Visible := true; label2.Visible:=true; label3.Visible:=true; label4.Visible:=true; label5.Visible:=true; label6.Visible:=true; txtDiaCompraIni.SetFocus; end else begin txtDiaCompraIni.Visible := false; txtMesCompraIni.Visible := false; txtAnioCompraIni.Visible := false; txtDiaCompraFin.Visible := false; txtMesCompraFin.Visible := false; label2.Visible:=false; label3.Visible:=false; label4.Visible:=false; label5.Visible:=false; label6.Visible:=false; txtAnioCompraFin.Visible := false; end; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clChecksum; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, Windows; {$ELSE} System.Classes, Winapi.Windows; {$ENDIF} type TclCheckSum = class private FValue: LongWord; public constructor Create; procedure Reset; virtual; abstract; procedure Update(AValue: Integer); overload; virtual; abstract; procedure Update(const ABuffer; ALen: Integer); overload; virtual; abstract; property Value: LongWord read FValue; end; TclCrc32 = class(TclCheckSum) private function ComputeCrc32(AOldCrc: LongWord; BVal: Byte): LongWord; public procedure Reset; override; procedure Update(AValue: Integer); overload; override; procedure Update(const ABuffer; ALen: Integer); overload; override; end; TclAdler32 = class(TclCheckSum) public procedure Reset; override; procedure Update(AValue: Integer); overload; override; procedure Update(const ABuffer; ALen: Integer); overload; override; end; implementation const CrcSeed = $FFFFFFFF; CrcTable : array[0..256 - 1] of DWORD = ( $00000000, $77073096, $ee0e612c, $990951ba, $076dc419, $706af48f, $e963a535, $9e6495a3, $0edb8832, $79dcb8a4, $e0d5e91e, $97d2d988, $09b64c2b, $7eb17cbd, $e7b82d07, $90bf1d91, $1db71064, $6ab020f2, $f3b97148, $84be41de, $1adad47d, $6ddde4eb, $f4d4b551, $83d385c7, $136c9856, $646ba8c0, $fd62f97a, $8a65c9ec, $14015c4f, $63066cd9, $fa0f3d63, $8d080df5, $3b6e20c8, $4c69105e, $d56041e4, $a2677172, $3c03e4d1, $4b04d447, $d20d85fd, $a50ab56b, $35b5a8fa, $42b2986c, $dbbbc9d6, $acbcf940, $32d86ce3, $45df5c75, $dcd60dcf, $abd13d59, $26d930ac, $51de003a, $c8d75180, $bfd06116, $21b4f4b5, $56b3c423, $cfba9599, $b8bda50f, $2802b89e, $5f058808, $c60cd9b2, $b10be924, $2f6f7c87, $58684c11, $c1611dab, $b6662d3d, $76dc4190, $01db7106, $98d220bc, $efd5102a, $71b18589, $06b6b51f, $9fbfe4a5, $e8b8d433, $7807c9a2, $0f00f934, $9609a88e, $e10e9818, $7f6a0dbb, $086d3d2d, $91646c97, $e6635c01, $6b6b51f4, $1c6c6162, $856530d8, $f262004e, $6c0695ed, $1b01a57b, $8208f4c1, $f50fc457, $65b0d9c6, $12b7e950, $8bbeb8ea, $fcb9887c, $62dd1ddf, $15da2d49, $8cd37cf3, $fbd44c65, $4db26158, $3ab551ce, $a3bc0074, $d4bb30e2, $4adfa541, $3dd895d7, $a4d1c46d, $d3d6f4fb, $4369e96a, $346ed9fc, $ad678846, $da60b8d0, $44042d73, $33031de5, $aa0a4c5f, $dd0d7cc9, $5005713c, $270241aa, $be0b1010, $c90c2086, $5768b525, $206f85b3, $b966d409, $ce61e49f, $5edef90e, $29d9c998, $b0d09822, $c7d7a8b4, $59b33d17, $2eb40d81, $b7bd5c3b, $c0ba6cad, $edb88320, $9abfb3b6, $03b6e20c, $74b1d29a, $ead54739, $9dd277af, $04db2615, $73dc1683, $e3630b12, $94643b84, $0d6d6a3e, $7a6a5aa8, $e40ecf0b, $9309ff9d, $0a00ae27, $7d079eb1, $f00f9344, $8708a3d2, $1e01f268, $6906c2fe, $f762575d, $806567cb, $196c3671, $6e6b06e7, $fed41b76, $89d32be0, $10da7a5a, $67dd4acc, $f9b9df6f, $8ebeeff9, $17b7be43, $60b08ed5, $d6d6a3e8, $a1d1937e, $38d8c2c4, $4fdff252, $d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b, $d80d2bda, $af0a1b4c, $36034af6, $41047a60, $df60efc3, $a867df55, $316e8eef, $4669be79, $cb61b38c, $bc66831a, $256fd2a0, $5268e236, $cc0c7795, $bb0b4703, $220216b9, $5505262f, $c5ba3bbe, $b2bd0b28, $2bb45a92, $5cb36a04, $c2d7ffa7, $b5d0cf31, $2cd99e8b, $5bdeae1d, $9b64c2b0, $ec63f226, $756aa39c, $026d930a, $9c0906a9, $eb0e363f, $72076785, $05005713, $95bf4a82, $e2b87a14, $7bb12bae, $0cb61b38, $92d28e9b, $e5d5be0d, $7cdcefb7, $0bdbdf21, $86d3d2d4, $f1d4e242, $68ddb3f8, $1fda836e, $81be16cd, $f6b9265b, $6fb077e1, $18b74777, $88085ae6, $ff0f6a70, $66063bca, $11010b5c, $8f659eff, $f862ae69, $616bffd3, $166ccf45, $a00ae278, $d70dd2ee, $4e048354, $3903b3c2, $a7672661, $d06016f7, $4969474d, $3e6e77db, $aed16a4a, $d9d65adc, $40df0b66, $37d83bf0, $a9bcae53, $debb9ec5, $47b2cf7f, $30b5ffe9, $bdbdf21c, $cabac28a, $53b39330, $24b4a3a6, $bad03605, $cdd70693, $54de5729, $23d967bf, $b3667a2e, $c4614ab8, $5d681b02, $2a6f2b94, $b40bbe37, $c30c8ea1, $5a05df1b, $2d02ef8d); BASE = 65521; NMAX = 3800; { TclCrc32 } function TclCrc32.ComputeCrc32(AOldCrc: LongWord; BVal: Byte): LongWord; begin Result := CrcTable[(AOldCrc xor BVal) and LongWord($FF)] xor (AOldCrc shr 8); end; procedure TclCrc32.Reset; begin FValue := 0; end; procedure TclCrc32.Update(AValue: Integer); begin FValue := FValue xor CrcSeed; FValue := ComputeCrc32(FValue, AValue); FValue := FValue xor CrcSeed; end; procedure TclCrc32.Update(const ABuffer; ALen: Integer); var buf: PByte; begin FValue := FValue xor CrcSeed; buf := @ABuffer; while (ALen > 0) do begin FValue := ComputeCrc32(FValue, buf^); Inc(buf); Dec(ALen); end; FValue := FValue xor CrcSeed; end; { TclCheckSum } constructor TclCheckSum.Create; begin inherited Create(); Reset(); end; { TclAdler32 } procedure TclAdler32.Reset; begin FValue := 1; end; procedure TclAdler32.Update(AValue: Integer); var s1, s2: LongWord; begin s1 := FValue and LongWord($FFFF); s2 := FValue shr 16; s1 := (s1 + (AValue and LongWord($FF))) mod BASE; s2 := (s1 + s2) mod BASE; FValue := (s2 shl 16) or s1; end; procedure TclAdler32.Update(const ABuffer; ALen: Integer); var s1, s2: LongWord; n: Integer; buf: PByte; begin s1 := FValue and LongWord($FFFF); s2 := FValue shr 16; buf := @ABuffer; while (ALen > 0) do begin n := NMAX; if (n > ALen) then begin n := ALen; end; Dec(ALen, n); while (n > 0) do begin Inc(s1, buf^); Inc(s2, s1); Inc(buf); Dec(n); end; s1 := s1 mod BASE; s2 := s2 mod BASE; end; FValue := (s2 shl 16) or s1; end; end.
unit NetServerIocp; interface uses Windows, WinSock2, win.iocp, Win.Thread, DataChain, NetSrvClientIocp, NetBaseObj; type PNetServerIocp = ^TNetServerIocp; PNetIOCPServerWorkThread = ^TNetIOCPServerWorkThread; TNetIOCPServerAcceptThread = packed record SysThread : TSysWinThread; Server : PNetServerIocp; end; TNetIOCPServerWorkThread = packed record SysThread : TSysWinThread; Server : PNetServerIocp; end; TNetServerIocp = packed record BaseServer : TNetServer; Iocp : TWinIocp; AcceptThread : TNetIOCPServerAcceptThread; IocpWorkThread : array[0..255] of TNetIOCPServerWorkThread; end; procedure OpenIOCPNetServer(AServer: PNetServerIocp); implementation uses //SDLogUtils, Sysutils, BaseDataIO, win.cpu; function ThreadProc_IocpDataBufferWorkThread(AParam: PNetIOCPServerWorkThread): HResult; stdcall; begin Result := 0; ExitThread(Result); end; procedure DealAgentServerDataHandle(const AIocpBuffer: PNetIocpBuffer); type PCommandProtocol = ^TCommandProtocol; TCommandProtocol = packed record Magic: Word; Version: Word; CommandID: Word; CommandParam: array[0..255] of AnsiChar; end; var tmpCommand: PCommandProtocol; tmpHeadChar: AnsiChar; begin // GET POST HEAD PUT DELETE TRACE CONNECT OPTIONS PATCH if nil = AIocpBuffer then exit; if 0 = AIocpBuffer.DataBufferPtr.BufferHead.DataLength then exit; tmpCommand := @AIocpBuffer.DataBufferPtr.Data[0]; if 2121 = tmpCommand.Magic then begin end else begin tmpHeadChar := AIocpBuffer.DataBufferPtr.Data[0]; if ('G' = tmpHeadChar) then begin //SDLog('DealServerAppStart.pas', 'DealAgentServerDataIn begin'); try // 这里为什么多线程出错了 ???? //DealServerHttpProtocol.HttpServerDataInHandle(@AIocpBuffer.ClientConnect.BaseConnect, @AIocpBuffer.DataBuffer); except end; //SDLog('DealServerAppStart.pas', 'DealAgentServerDataIn end'); exit; end; if ('P' = tmpHeadChar) then begin //DealServerHttpProtocol.HttpServerDataHandle(ADataIO, AData); exit; end; if ('D' = tmpHeadChar) then begin //DealServerHttpProtocol.HttpServerDataHandle(ADataIO, AData); exit; end; end; end; function ThreadProc_IOCPServerWorkThread(AParam: PNetIOCPServerWorkThread): HResult; stdcall; var tmpCompleteKey: DWORD; tmpServer: PNetServerIocp; tmpBytes: Cardinal; tmpConnect: PNetClientConnectIOCP; tmpIocpBuffer: PNetIocpBuffer; begin Result := 0; if nil <> AParam then begin tmpServer := AParam.Server; if nil <> tmpServer then begin while (1 = tmpServer.BaseServer.IsActiveStatus) and (1 = AParam.SysThread.Core.IsActiveStatus) do begin Sleep(1); tmpIocpBuffer := nil; //此处有可能多个线程处理同一个SocketHandle对象,因此需要加锁 if not GetQueuedCompletionStatus(tmpServer.Iocp.Handle, tmpBytes, tmpCompleteKey, POverlapped(tmpIocpBuffer), INFINITE) then begin //客户端异常断开 Writeln('client disconnected 1'); if nil <> tmpIocpBuffer then begin end; end else begin if nil <> tmpIocpBuffer then begin tmpConnect := tmpIocpBuffer.ClientConnect; if ioHandle = tmpIocpBuffer.IocpOperate then begin DealAgentServerDataHandle(tmpIocpBuffer); CheckInIocpBuffer(tmpIocpBuffer); Continue; end; if ioSockRead = tmpIocpBuffer.IocpOperate then begin if 0 < tmpBytes then begin // 处理进来的数据 tmpIocpBuffer.IocpOperate := ioHandle; tmpIocpBuffer.DataBufferPtr.BufferHead.DataLength := tmpBytes; Writeln(PAnsiChar(@tmpIocpBuffer.DataBufferPtr.Data[0])); Windows.PostQueuedCompletionStatus(tmpServer.Iocp.Handle, 0, 0, @tmpIocpBuffer.Overlapped); ReadIocpDataIn(tmpConnect, CheckOutIocpBuffer); end else begin Writeln('client disconnected 2'); WinSock2.closesocket(tmpConnect.BaseConnect.ClientSocketHandle); tmpConnect.BaseConnect.ClientSocketHandle := 0; CheckInClientConnectionIocp(tmpConnect); CheckInIocpBuffer(tmpIocpBuffer); end; Continue; end; if ioSockWrite = tmpIocpBuffer.IocpOperate then begin //HttpServerDataOutEndHandle(@tmpIocpBuffer.ClientConnect.BaseConnect, @tmpIocpBuffer.DataBuffer); CheckInIocpBuffer(tmpIocpBuffer); Continue; end; end else begin // tmpBuffer.ClientConnect.ConnectSocketHandle 失效了 可以不用管了 ?? Continue; end; end; end; end; end; ExitThread(Result); end; function ThreadProc_IOCPServerAcceptThread(AParam: PNetIOCPServerWorkThread): HResult; stdcall; var tmpClientConnectionSocket: Winsock2.TSocket; tmpClient: PNetClientConnectIOCP; tmpAddr: TSockAddr; tmpAddrlen: Integer; begin Result := 0; while 1 = AParam.SysThread.Core.IsActiveStatus do begin Sleep(1); FillChar(tmpAddr, SizeOf(tmpAddr), 0); tmpAddrlen := SizeOf(tmpAddr); tmpClientConnectionSocket := WinSock2.WSAAccept(AParam.Server.BaseServer.ListenSocketHandle, @tmpAddr, @tmpAddrlen, nil, 0); // tmpClientConnectionSocket := WinSock2.Accept( // AParam.Server.BaseServer.ListenSocketHandle, @tmpAddr, tmpAddrlen); if INVALID_SOCKET <> tmpClientConnectionSocket then begin if 1 <> AParam.SysThread.Core.IsActiveStatus then begin WinSock2.CloseSocket(tmpClientConnectionSocket); Exit; end; if not BindWinIocp(tmpClientConnectionSocket, @AParam.Server.Iocp) then begin // error end else begin Writeln('client connected'); tmpClient := CheckOutClientConnectionIocp(@AParam.Server.BaseServer); if nil <> tmpClient then begin tmpClient.BaseConnect.ClientSocketHandle := tmpClientConnectionSocket; ReadIocpDataIn(tmpClient, CheckOutIocpBuffer); end; end; end; end; ExitThread(Result); end; procedure OpenIOCPNetServer(AServer: PNetServerIocp); var tmpAddr: Winsock2.TSockAddr; tmpWorkThreadCount: integer; i: integer; begin InitWinIocp(@AServer.Iocp); if (0 = AServer.Iocp.Handle) or (INVALID_HANDLE_VALUE = AServer.Iocp.Handle) then begin exit; end; if 0 = AServer.BaseServer.ListenSocketHandle then begin AServer.BaseServer.ListenSocketHandle := WSASocket(PF_INET, SOCK_STREAM, 0, nil, 0, WSA_FLAG_OVERLAPPED); end; if INVALID_SOCKET <> AServer.BaseServer.ListenSocketHandle then begin if 0 = AServer.BaseServer.ListenPort then AServer.BaseServer.ListenPort := 80; AServer.BaseServer.IsActiveStatus := 1; FillChar(tmpAddr, SizeOf(tmpAddr), 0); tmpAddr.sin_family := AF_INET; tmpAddr.sin_port := htons(AServer.BaseServer.ListenPort); tmpAddr.sin_addr.S_addr := htonl(INADDR_ANY); //在任何地址上监听,如果有多块网卡,会每块都监听 if 0 <> bind(AServer.BaseServer.ListenSocketHandle, @tmpAddr, SizeOf(tmpAddr)) then begin //raise ESocketError.Create(GetLastWsaErrorStr); WinSock2.closesocket(AServer.BaseServer.ListenSocketHandle); AServer.BaseServer.ListenSocketHandle := 0; AServer.BaseServer.IsActiveStatus := 0; end; if 1 = AServer.BaseServer.IsActiveStatus then begin if 0 <> listen(AServer.BaseServer.ListenSocketHandle, MaxInt) then begin //raise ESocketError.Create(GetLastWsaErrorStr); WinSock2.closesocket(AServer.BaseServer.ListenSocketHandle); AServer.BaseServer.ListenSocketHandle := 0; AServer.BaseServer.IsActiveStatus := 0; end; end; //tmpWorkThreadCount := GetCPUCount * 2 + 4; if 1 = AServer.BaseServer.IsActiveStatus then begin tmpWorkThreadCount := GetProcessorCount * 2; for i := 0 to tmpWorkThreadCount - 1 do begin AServer.IocpWorkThread[i].SysThread.Core.IsActiveStatus := 1; AServer.IocpWorkThread[i].Server := AServer; AServer.IocpWorkThread[i].SysThread.Core.ThreadHandle := Windows.CreateThread(nil, 0, @ThreadProc_IOCPServerWorkThread, @AServer.IocpWorkThread[i], CREATE_SUSPENDED, AServer.IocpWorkThread[i].SysThread.Core.ThreadID); Windows.ResumeThread(AServer.IocpWorkThread[i].SysThread.Core.ThreadHandle); end; AServer.BaseServer.CheckOutDataOutBuffer := CheckOutIocpDataOutBuffer; AServer.BaseServer.SendDataOut := SendIocpDataOut; // AServer.BaseServer.CheckOutClientSession := CheckOutHttpClientSession; // AServer.BaseServer.CheckInClientSession := CheckInHttpClientSession; AServer.AcceptThread.Server := AServer; AServer.AcceptThread.SysThread.Core.IsActiveStatus := 1; AServer.AcceptThread.SysThread.Core.ThreadHandle := Windows.CreateThread(nil, 0, @ThreadProc_IOCPServerAcceptThread, @AServer.AcceptThread, CREATE_SUSPENDED, AServer.AcceptThread.SysThread.Core.ThreadID); Windows.ResumeThread(AServer.AcceptThread.SysThread.Core.ThreadHandle); // FMaxWorkThrCount := 160; // FMinWorkThrCount := 120; // FMaxCheckThrCount := 60; // FMinCheckThrCount := 40; end; end; end; procedure CloseIOCPNetServer(AServer: PNetServerIocp); const CompleteKey_CloseIocp = 255; var tmpBytes: DWord; begin if (0 <> AServer.BaseServer.ListenSocketHandle) and (INVALID_SOCKET <> AServer.BaseServer.ListenSocketHandle) then begin WinSock2.CloseSocket(AServer.BaseServer.ListenSocketHandle); AServer.BaseServer.ListenSocketHandle := 0; end; if (0 <> AServer.Iocp.Handle) and (INVALID_HANDLE_VALUE <> AServer.Iocp.Handle) then begin tmpBytes := 0; PostQueuedCompletionStatus(AServer.Iocp.Handle, tmpBytes, CompleteKey_CloseIocp, nil); Windows.CloseHandle(AServer.Iocp.Handle); AServer.Iocp.Handle := 0; end; end; end.
unit l3Bits; {* Функции для работы с битами. } { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3Bits - } { Начат: 05.10.1999 15:31 } { $Id: l3Bits.pas,v 1.19 2012/11/01 09:42:57 lulin Exp $ } // $Log: l3Bits.pas,v $ // Revision 1.19 2012/11/01 09:42:57 lulin // - забыл точку с запятой. // // Revision 1.18 2012/11/01 07:45:08 lulin // - делаем возможность логирования процесса загрузки модулей. // // Revision 1.17 2008/04/01 17:07:09 lulin // - нарисовал контейнер документа на модели. // // Revision 1.16 2007/08/14 14:30:12 lulin // - оптимизируем перемещение блоков памяти. // // Revision 1.15 2005/07/21 14:47:36 lulin // - базовая виртуальная нода вынесена в отдельный модуль. // // Revision 1.14 2004/03/05 15:52:11 demon // - new function: l3TestPartMask // // Revision 1.13 2003/12/11 13:29:13 voba // - add: новая функция l3GetByMask // // Revision 1.12 2003/05/30 17:05:12 voba // - rename l3*Flag to l3*Mask // // Revision 1.11 2002/01/23 10:20:13 voba // -bug fix : borland non correct size of type workarround // // Revision 1.10 2001/11/21 15:17:32 law // - new procs: l3*Bit - для работы с Word'ом. // // Revision 1.9 2001/11/21 14:11:00 law // - new type: Tl3BitNum. // // Revision 1.8 2001/11/21 13:56:32 law // - new behavior: _l3TestBit теперь возвращает Boolean - 0 или 1. // // Revision 1.7 2001/07/26 15:55:03 law // - comments: xHelpGen. // // Revision 1.6 2001/04/05 08:53:51 law // - _move: функции l3TestFlag & Co переехали в модуль l3Bits. // // Revision 1.5 2000/12/15 15:18:59 law // - вставлены директивы Log. // {$Include l3Define.inc } interface uses l3Types ; const l3MinBitNum = Integer(0); {* - минимальный номер бита в целом. } l3MaxBitNum = Integer(31); {* - максимальный номер бита в целом. } type Tl3BitNum = integer;//l3MinBitNum .. l3MaxBitNum; {* - число бит в целом. } {$IfDef WIN32} function l3TestBit(W: Long; N: Tl3BitNum): Boolean; {* - проверить N-й бит. } {$Else WIN32} function l3TestBit(W: Long; N: Tl3BitNum): LongBool; {* - проверить N-й бит. } {$EndIf WIN32} procedure l3SetBit(var W : Long; N: Tl3BitNum); overload; {* - установить N-й бит. } procedure l3SetBit(var W : Word; N: Tl3BitNum); overload; {* - установить N-й бит. } procedure l3ClearBit(var W: Long; N: Tl3BitNum); overload; {* - очистить N-й бит. } procedure l3ClearBit(var W: Word; N: Tl3BitNum); overload; {* - очистить N-й бит. } procedure l3InvertBit(var W: Long; N: Tl3BitNum); overload; {* - инвертировать N-й бит. } procedure l3InvertBit(var W: Word; N: Tl3BitNum); overload; {* - инвертировать N-й бит. } function l3BitCount(X: Long): Long; {* - подсчитать число бит. } function l3BitCountF(X: Long): Long; {* - "быстро" подсчитать число бит. } function l3TestMask(W, N : Integer) : Boolean; {* - проверить маску. } function l3TestPartMask(W, N : Integer) : Boolean; {* - проверить на пересечение с маской. } function l3GetByMask(W, N : Integer) : Integer; {* - сфильтровать маской. } procedure l3SetMask(var W : Integer; N : Integer); {* - установить маску. } procedure l3ClearMask(var W : Integer; N : Integer); {* - очистить маску. } procedure l3InvertMask(var W: Integer; N : Integer); {* - инвертировать маску. } implementation var l3BitTable: array[0..255] of Long; procedure LoadBitTable; var i : Long; begin for i:=0 to 255 do l3BitTable[i] := l3BitCount(i); end; function l3BitCount(X: Long): Long; {-} var Y : Long; begin Y := X; Y := Y - ((Y shr 1) and $55555555); Y := (Y and $33333333) + ((Y shr 2) and $33333333); Y := Y + Y shr 4; Y := Y and $0f0f0f0f; Y := Y + Y shr 8; y := Y + Y shr 16; Result := Y and $000000ff; end; function l3BitCountF(X:Long):Long; register; {-} asm test eax,eax jz @@Done push ebx mov ebx,eax xor ecx,ecx xor edx,edx mov cl,bl mov dl,bh shr ebx,16 mov eax, dword ptr [l3BitTable+ecx*4] add eax, dword ptr [l3BitTable+edx*4] mov cl,bl add eax, dword ptr [l3BitTable+ecx*4] mov dl,bh add eax, dword ptr [l3BitTable+edx*4] pop ebx @@Done: end; {$IFDEF WIN32} function l3TestBit(W: Long; N: Tl3BitNum): Boolean; register; {eax, edx} {-} asm mov ecx, eax xor eax, eax bt ecx, edx adc eax, eax end; {$ELSE WIN32} function l3TestBit(W: Long; N: Tl3BitNum): LongBool; assembler; {-} asm db $66; mov ax, word ptr ss:[W] db $66; mov dx, word ptr ss:[N] dd $D0A30F66 { bt eax, edx } db $66; jc @@ret db $66; xor ax, ax { xor eax, eax } @@ret: db $66; push ax { push eax } pop ax { eax.Lo -> ax } pop dx { eax.Hi -> dx } end; {$ENDIF WIN32} (*begin Result := (W AND (1 shl N)) <> 0; end;*) {$IFDEF WIN32} procedure l3SetBit(var W : Long; N: Tl3BitNum); register; {-} {eax, edx} asm bts [eax], edx end; procedure l3SetBit(var W : Word; N: Tl3BitNum); register; {-} {eax, edx} asm bts word ptr [eax], edx end; {$ELSE WIN32} procedure l3SetBit(var W : Long; N: Tl3BitNum); {-} begin W := (W OR (1 shl N)); end; {$ENDIF WIN32} (*begin W := (W OR (1 shl N)); end;*) {$IFDEF WIN32} procedure l3ClearBit(var W: Long; N: Tl3BitNum); {-} asm btr [eax], edx end; procedure l3ClearBit(var W: Word; N: Tl3BitNum); {-} asm btr word ptr [eax], edx end; {$ELSE WIN32} procedure l3ClearBit(var W: Long; N: Tl3BitNum); {-} begin W := (W AND not(1 shl N)); end; {$ENDIF WIN32} (*begin W := (W AND not(1 shl N)); end;*) procedure l3InvertBit(var W: Long; N: Tl3BitNum); {-} asm btc [eax], edx end; procedure l3InvertBit(var W: Word; N: Tl3BitNum); {-} asm btc word ptr [eax], edx end; function l3TestMask(W, N : Integer) : Boolean; {-} begin Result := W and N = N; end; function l3TestPartMask(W, N : Integer) : Boolean; {-} begin Result := W and N <> 0; end; function l3GetByMask(W, N : Integer) : Integer; {-} begin Result := W and N; end; procedure l3SetMask(var W : Integer; N : Integer); {-} begin W := W or N; end; procedure l3ClearMask(var W : Integer; N : Integer); {-} begin W := W and not N; end; procedure l3InvertMask(var W: Integer; N : Integer); {-} begin W := W xor N; end; initialization {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\L3\l3Bits.pas initialization enter'); {$EndIf} LoadBitTable; {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\L3\l3Bits.pas initialization leave'); {$EndIf} end.
unit alcuAsyncSubmitter; {* Асинхронно посылает с сервера запросы на выполнение утилите. } // Модуль: "w:\archi\source\projects\PipeInAuto\Tasks\alcuAsyncSubmitter.pas" // Стереотип: "UtilityPack" // Элемент модели: "alcuAsyncSubmitter" MUID: (53C900CA012E) {$Include w:\archi\source\projects\PipeInAuto\alcuDefine.inc} interface {$If Defined(ServerTasks) AND Defined(AppServerSide)} uses l3IntfUses , l3Base , l3ProtoObject {$If NOT Defined(Nemesis)} , csProcessTask {$IfEnd} // NOT Defined(Nemesis) , daTypes , alcuServerAsyncExecutionInterfaces , alcuAsyncTaskFinishedNotifierList ; type PalcuSubmitterWorkThread = ^TalcuSubmitterWorkThread; TalcuWorkThreadContainer = class(Tl3ThreadContainer) private f_TaskFileName: AnsiString; f_ServerHostName: AnsiString; f_UserName: AnsiString; f_Password: AnsiString; f_ServerPort: Integer; f_ExitCode: Cardinal; {* Чем процесс завершился } protected procedure SubmitTask(const aTaskFile: AnsiString); procedure DoExecute; override; {* основная процедура нити. Для перекрытия в потомках } public constructor Create(const anHostName: AnsiString; aPort: Integer; const aUserName: AnsiString; const aPassword: AnsiString); reintroduce; class function AssistantFileName: AnsiString; public property ExitCode: Cardinal read f_ExitCode; {* Чем процесс завершился } end;//TalcuWorkThreadContainer TalcuSubmitterWorkThread = class(Tl3ProtoObject{$If NOT Defined(Nemesis)} , IcsExternalTaskAbortProcessor {$IfEnd} // NOT Defined(Nemesis) ) private f_Thread: TalcuWorkThreadContainer; f_FinishNotifierList: TalcuAsyncTaskFinishedNotifierList; f_TaskFileName: AnsiString; f_SubmitGuard: Integer; f_CheckExecutionGuard: Integer; f_UserID: TdaUserID; f_ActiveTask: TddProcessTask; f_Manager: IalcuAsyncSubmitterManager; f_Active: Boolean; {* Можно ли отцеплять утилиту } private procedure NotifySubscribers; protected {$If NOT Defined(Nemesis)} function ProcessAbort(const aTask: TddProcessTask): Boolean; {* Если успешно абортировала задачу вернет True. Тогда штатная обработка обключается } {$IfEnd} // NOT Defined(Nemesis) procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public constructor Create(aUserID: TdaUserID; const aManager: IalcuAsyncSubmitterManager); reintroduce; function SubmitTask(const aTask: TddProcessTask): Boolean; procedure CheckExecution(const aServices: IcsRunTaskServices); {* Проверить что процесс завершился и освободиться по необходимости } procedure RegisterNotifier(const aNotifier: IalcuAsyncTaskFinishedNotifier); procedure UnRegisterNotifier(const aNotifier: IalcuAsyncTaskFinishedNotifier); class function AssistantExists: Boolean; function StillRunning(CountAbortingTask: Boolean): Boolean; protected property UserID: TdaUserID read f_UserID; property ActiveTask: TddProcessTask read f_ActiveTask; property Manager: IalcuAsyncSubmitterManager read f_Manager; public property Active: Boolean read f_Active write f_Active; {* Можно ли отцеплять утилиту } end;//TalcuSubmitterWorkThread {$IfEnd} // Defined(ServerTasks) AND Defined(AppServerSide) implementation {$If Defined(ServerTasks) AND Defined(AppServerSide)} uses l3ImplUses , Windows , SysUtils , l3Base64 {$If NOT Defined(Nemesis)} , csTaskTypes {$IfEnd} // NOT Defined(Nemesis) , Classes , l3Stream , l3Types , l3FileUtils , l3Interlocked //#UC START# *53C900CA012Eimpl_uses* //#UC END# *53C900CA012Eimpl_uses* ; constructor TalcuWorkThreadContainer.Create(const anHostName: AnsiString; aPort: Integer; const aUserName: AnsiString; const aPassword: AnsiString); //#UC START# *53CCF6F70264_53C9011903D6_var* //#UC END# *53CCF6F70264_53C9011903D6_var* begin //#UC START# *53CCF6F70264_53C9011903D6_impl* inherited Create; f_ServerHostName := anHostName; f_UserName := aUserName; f_Password := aPassword; f_ServerPort := aPort; f_ExitCode := cs_arsSuccess; //#UC END# *53CCF6F70264_53C9011903D6_impl* end;//TalcuWorkThreadContainer.Create procedure TalcuWorkThreadContainer.SubmitTask(const aTaskFile: AnsiString); //#UC START# *53C917C30155_53C9011903D6_var* //#UC END# *53C917C30155_53C9011903D6_var* begin //#UC START# *53C917C30155_53C9011903D6_impl* Assert(Suspended); f_TaskFileName := aTaskFile; Suspended := False; //#UC END# *53C917C30155_53C9011903D6_impl* end;//TalcuWorkThreadContainer.SubmitTask class function TalcuWorkThreadContainer.AssistantFileName: AnsiString; //#UC START# *540475CA0270_53C9011903D6_var* //#UC END# *540475CA0270_53C9011903D6_var* begin //#UC START# *540475CA0270_53C9011903D6_impl* Result := Format('%salcuTaskExecutor.exe', [ExtractFilePath(ParamStr(0))]); //#UC END# *540475CA0270_53C9011903D6_impl* end;//TalcuWorkThreadContainer.AssistantFileName procedure TalcuWorkThreadContainer.DoExecute; {* основная процедура нити. Для перекрытия в потомках } //#UC START# *4911B69E037D_53C9011903D6_var* var l_StartupInfo: TStartupInfo; l_ProcessInfo: TProcessInformation; l_ExeFile: String; //#UC END# *4911B69E037D_53C9011903D6_var* begin //#UC START# *4911B69E037D_53C9011903D6_impl* f_ExitCode := cs_arsSuccess; l3FillChar(l_StartupInfo, SizeOf(l_StartupInfo)); l_StartupInfo.cb := SizeOf(l_StartupInfo); l_StartupInfo.wShowWindow := SW_SHOW; l_ExeFile := Format('"%s" "%s" "%s" %d %s %s', [AssistantFileName, f_TaskFileName, f_ServerHostName, f_ServerPort, l3EncodeBase64(f_UserName), l3EncodeBase64(f_Password)]); if CreateProcess(nil, PAnsiChar(l_ExeFile), nil, nil, TRUE, NORMAL_PRIORITY_CLASS, nil, nil, l_StartupInfo, l_ProcessInfo) then begin CloseHandle(l_ProcessInfo.hThread); WaitForSingleObject(l_ProcessInfo.hProcess, INFINITE); GetExitCodeProcess(l_ProcessInfo.hProcess, f_ExitCode); CloseHandle(l_ProcessInfo.hProcess); end else begin f_ExitCode := cs_arsUtilityNotFound; end; //#UC END# *4911B69E037D_53C9011903D6_impl* end;//TalcuWorkThreadContainer.DoExecute constructor TalcuSubmitterWorkThread.Create(aUserID: TdaUserID; const aManager: IalcuAsyncSubmitterManager); //#UC START# *53CCF726039A_53C92B390005_var* var l_UserName: AnsiString; l_Password: AnsiString; //#UC END# *53CCF726039A_53C92B390005_var* begin //#UC START# *53CCF726039A_53C92B390005_impl* inherited Create; f_UserID := aUserID; Assert(Assigned(aManager)); f_Manager := aManager; f_Manager.GetUserAccountByID(f_UserID, l_UserName, l_Password); f_Thread := TalcuWorkThreadContainer.Create(Manager.ServerHostName, Manager.ServerPort, l_UserName, l_Password); f_FinishNotifierList := TalcuAsyncTaskFinishedNotifierList.Make; f_Active := True; //#UC END# *53CCF726039A_53C92B390005_impl* end;//TalcuSubmitterWorkThread.Create function TalcuSubmitterWorkThread.SubmitTask(const aTask: TddProcessTask): Boolean; //#UC START# *53CCF77201EF_53C92B390005_var* var l_Stream: TStream; l_ExportDir: String; //#UC END# *53CCF77201EF_53C92B390005_var* begin //#UC START# *53CCF77201EF_53C92B390005_impl* l3InterlockedIncrement(f_SubmitGuard); try Result := (f_SubmitGuard = 1) and Active and Assigned(aTask) and (f_ActiveTask = nil) and not f_Manager.IsUserLogined(f_UserID); if Result then begin if (aTask.Status = cs_tsAsyncRun) then Exit; if Manager.EnterTaskExecution(aTask) then begin aTask.SetRefTo(f_ActiveTask); {$If not defined(Nemesis)} f_ActiveTask.RegisterAbortProcessor(Self); {$IfEnd not defined(Nemesis)} f_ActiveTask.RequestAsyncRun; f_TaskFileName := ChangeFileExt(l3GetTempFileName('alcuAssistant'), '.tsk'); l_Stream := Tl3FileStream.Create(f_TaskFileName, l3_fmCreateReadWrite); try ActiveTask.SaveToEvd(l_Stream, nil{True}); finally FreeAndNil(l_Stream); end; ActiveTask.RequestAsyncRun; f_Thread.SubmitTask(f_TaskFileName); end else Result := False; end;//Result finally l3InterlockedDecrement(f_SubmitGuard); end; //#UC END# *53CCF77201EF_53C92B390005_impl* end;//TalcuSubmitterWorkThread.SubmitTask procedure TalcuSubmitterWorkThread.CheckExecution(const aServices: IcsRunTaskServices); {* Проверить что процесс завершился и освободиться по необходимости } //#UC START# *53CDF9B0012E_53C92B390005_var* function lp_ErrorMessage: String; begin Result := Format('Ошибка. Exit code = %d. %s. См. лог alcuTaskExecutor.', [f_Thread.ExitCode, f_ActiveTask.TaskID]); end; //#UC END# *53CDF9B0012E_53C92B390005_var* begin //#UC START# *53CDF9B0012E_53C92B390005_impl* if (f_CheckExecutionGuard = 0) and (f_SubmitGuard = 0) and Assigned(f_ActiveTask) and (f_ActiveTask.Status in [cs_tsAsyncRun, cs_tsFrozen, cs_tsFrozenRun, cs_tsDeleted, cs_tsAborting]) then begin l3InterlockedIncrement(f_CheckExecutionGuard); try if f_Thread.Suspended and (f_CheckExecutionGuard = 1) then begin case f_Thread.ExitCode of cs_arsSuccess: f_ActiveTask.RunSuccessfullyFinished(aServices); cs_arsAborted: f_ActiveTask.AsyncErrorIfRunning('Операция прервана'); cs_arsUtilityNotFound: f_ActiveTask.AsyncErrorIfRunning('Не удалось запустить утилиту'); cs_arsTaskUnregistered: f_ActiveTask.AsyncErrorIfRunning('Задача не заргестрирована для асинхронного выполнения'); else begin if f_ActiveTask.IgnoreStrangeExitCode and ((f_Thread.ExitCode < 0) or (f_Thread.ExitCode > 100)) then begin f_ActiveTask.RunSuccessfullyFinished(aServices); l3System.Msg2Log(lp_ErrorMessage); end else f_ActiveTask.AsyncErrorIfRunning(lp_ErrorMessage); end; end; {$If not defined(Nemesis)} f_ActiveTask.UnRegisterAbortProcessor(Self); {$IfEnd not defined(Nemesis)} Manager.LeaveTaskExecution(ActiveTask); NotifySubscribers; f_ActiveTask.RunEnded(aServices); FreeAndNil(f_ActiveTask); DeleteFile(f_TaskFileName); end; finally l3InterlockedDecrement(f_CheckExecutionGuard); end; end; //#UC END# *53CDF9B0012E_53C92B390005_impl* end;//TalcuSubmitterWorkThread.CheckExecution procedure TalcuSubmitterWorkThread.RegisterNotifier(const aNotifier: IalcuAsyncTaskFinishedNotifier); //#UC START# *53D0E880001E_53C92B390005_var* //#UC END# *53D0E880001E_53C92B390005_var* begin //#UC START# *53D0E880001E_53C92B390005_impl* f_FinishNotifierList.Add(aNotifier); //#UC END# *53D0E880001E_53C92B390005_impl* end;//TalcuSubmitterWorkThread.RegisterNotifier procedure TalcuSubmitterWorkThread.UnRegisterNotifier(const aNotifier: IalcuAsyncTaskFinishedNotifier); //#UC START# *53D0E88D0368_53C92B390005_var* //#UC END# *53D0E88D0368_53C92B390005_var* begin //#UC START# *53D0E88D0368_53C92B390005_impl* f_FinishNotifierList.Remove(aNotifier); //#UC END# *53D0E88D0368_53C92B390005_impl* end;//TalcuSubmitterWorkThread.UnRegisterNotifier procedure TalcuSubmitterWorkThread.NotifySubscribers; //#UC START# *53D0E89C0113_53C92B390005_var* function DoIt(aNotifier: PalcuAsyncTaskFinishedNotifier; Index: Long): Bool; begin aNotifier.TaskFinished(f_ActiveTask); Result := True; end; //#UC END# *53D0E89C0113_53C92B390005_var* begin //#UC START# *53D0E89C0113_53C92B390005_impl* if Assigned(f_ActiveTask) then f_FinishNotifierList.IterateAllF(l3L2IA(@DoIt)) //#UC END# *53D0E89C0113_53C92B390005_impl* end;//TalcuSubmitterWorkThread.NotifySubscribers class function TalcuSubmitterWorkThread.AssistantExists: Boolean; //#UC START# *5404732A00CC_53C92B390005_var* //#UC END# *5404732A00CC_53C92B390005_var* begin //#UC START# *5404732A00CC_53C92B390005_impl* Result := FileExists(TalcuWorkThreadContainer.AssistantFileName); //#UC END# *5404732A00CC_53C92B390005_impl* end;//TalcuSubmitterWorkThread.AssistantExists function TalcuSubmitterWorkThread.StillRunning(CountAbortingTask: Boolean): Boolean; //#UC START# *573EC2C80226_53C92B390005_var* const cSet = [cs_tsAsyncRun, cs_tsFrozenRun, cs_tsDeleted]; //#UC END# *573EC2C80226_53C92B390005_var* begin //#UC START# *573EC2C80226_53C92B390005_impl* if CountAbortingTask then Result := Assigned(f_ActiveTask) and (ActiveTask.Status in (cSet + [cs_tsAborting])) else Result := Assigned(f_ActiveTask) and (ActiveTask.Status in cSet) //#UC END# *573EC2C80226_53C92B390005_impl* end;//TalcuSubmitterWorkThread.StillRunning {$If NOT Defined(Nemesis)} function TalcuSubmitterWorkThread.ProcessAbort(const aTask: TddProcessTask): Boolean; {* Если успешно абортировала задачу вернет True. Тогда штатная обработка обключается } //#UC START# *53CF5E600196_53C92B390005_var* //#UC END# *53CF5E600196_53C92B390005_var* begin //#UC START# *53CF5E600196_53C92B390005_impl* Manager.SendAbortNotification(f_UserID); //#UC END# *53CF5E600196_53C92B390005_impl* end;//TalcuSubmitterWorkThread.ProcessAbort {$IfEnd} // NOT Defined(Nemesis) procedure TalcuSubmitterWorkThread.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_53C92B390005_var* //#UC END# *479731C50290_53C92B390005_var* begin //#UC START# *479731C50290_53C92B390005_impl* FreeAndNil(f_Thread); FreeAndNil(f_ActiveTask); f_Manager := nil; FreeAndNil(f_FinishNotifierList); inherited Cleanup; //#UC END# *479731C50290_53C92B390005_impl* end;//TalcuSubmitterWorkThread.Cleanup procedure TalcuSubmitterWorkThread.ClearFields; begin f_Manager := nil; inherited; end;//TalcuSubmitterWorkThread.ClearFields {$IfEnd} // Defined(ServerTasks) AND Defined(AppServerSide) end.
unit Benjamim.Utils; {$IF DEFINED(FPC)} {$MODE DELPHI}{$H+} {$ENDIF} interface uses {$IF DEFINED(FPC)} SysUtils, StrUtils, variants, fpjson, base64, TypInfo; {$ELSE} System.Variants, System.JSON, System.Hash; {$ENDIF} type TJwtAlgorithm = (HS256, HS384, HS512); TSHA2Version = (SHA224, SHA256, SHA384, SHA512, SHA512_224, SHA512_256); const DEFAULT_EXPIRE_IN_HOURS = 2; DEFAULT_PASSWORD = 'your-256-bit-secret'; DEFAULT_ALGORITHM = TJwtAlgorithm.HS256; type TJwtAlgorithmHelper = record Helper for TJwtAlgorithm function AsAlgorithm: TSHA2Version; function AsString: String; end; TSHA2VersionHelper = record Helper for TSHA2Version function AsJwtAlgorithm: TJwtAlgorithm; function AsString: String; end; TStringHelper = record Helper for String const Empty = ''; function AsJwtAlgorithm: TJwtAlgorithm; function ClearLineBreak: String; function AsJSONObject: TJSONObject; function AsBase64: String; function FixBase64: string; function AsBase64url: String; function AsString: String; end; TVariantHelper = record Helper for Variant function AsString: String; end; implementation {$IF NOT DEFINED(FPC)} uses System.TypInfo, System.SysUtils, System.StrUtils, System.NetEncoding; {$ENDIF} { TJwtAlgorithmHelper } function TJwtAlgorithmHelper.AsAlgorithm: TSHA2Version; var LValue: string; begin LValue := Self.AsString; LValue := 'SHA' + LValue[3] + LValue[4] + LValue[5]; Result := TSHA2Version(GetEnumValue(TypeInfo(TSHA2Version), LValue)); end; function TJwtAlgorithmHelper.AsString: String; begin Result := GetEnumName(TypeInfo(TJwtAlgorithm), integer(Self)); end; { TSHA2VersionHelper } function TSHA2VersionHelper.AsJwtAlgorithm: TJwtAlgorithm; var LValue: string; begin LValue := Self.AsString; LValue := 'HS' + LValue[4] + LValue[5] + LValue[6]; Result := TJwtAlgorithm(GetEnumValue(TypeInfo(TJwtAlgorithm), LValue)); end; function TSHA2VersionHelper.AsString: String; begin Result := GetEnumName(TypeInfo(TSHA2Version), integer(Self)); end; { TStringHelper } function TStringHelper.AsJwtAlgorithm: TJwtAlgorithm; begin Result := TJwtAlgorithm(GetEnumValue(TypeInfo(TJwtAlgorithm), String(Self))); end; function TStringHelper.ClearLineBreak: String; begin Self := StringReplace(Self, sLineBreak, '', [rfReplaceAll]); Result := Self; end; function TStringHelper.AsJSONObject: TJSONObject; begin Result := {$IF DEFINED(FPC)}GetJSON(Self) as TJSONObject{$ELSE}TJSONObject(TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(Self), 0)){$ENDIF}; end; function Fix(aValue: string): string; const STR_TO_CLEAR = '= '; var I: integer; begin Result := aValue; for I := 1 to Length(STR_TO_CLEAR) do Result := StringReplace(Result, STR_TO_CLEAR[I], '', [rfReplaceAll]); end; function TStringHelper.FixBase64: string; begin Result := Self; Result := StringReplace(Result, '+', '-', [rfReplaceAll]); Result := StringReplace(Result, '/', '_', [rfReplaceAll]); Result := StringReplace(Result, '=', '', [rfReplaceAll]); end; function TStringHelper.AsBase64url: String; begin {$IF DEFINED(FPC)} Result := EncodeStringBase64(Self).FixBase64; {$ELSE} Result := TBase64Encoding.Base64.Encode(Self).FixBase64; {$ENDIF} end; function TStringHelper.AsBase64: String; begin {$IF DEFINED(FPC)} Result := EncodeStringBase64(Self); {$ELSE} Result := Fix(TBase64Encoding.Base64.Encode(Self)); {$ENDIF} end; function TStringHelper.AsString: String; begin {$IF DEFINED(FPC)} Result := DecodeStringBase64(Self); {$ELSE} Result := TBase64Encoding.Base64.Decode(Self); {$ENDIF} end; { TVariantHelper } function TVariantHelper.AsString: String; begin Result := VarToStrDef(Self, EmptyStr); end; end.
unit ExtAISharedNetworkTypes; interface uses Math; // Here are all shared network types with creators of the new ExtAI // Structure of the data stream // ____________Head of the Message_____________ _Message_ // | Recipient | Sender | Length of the Message | ... | // ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ ¯¯¯¯¯¯¯¯¯ // Message may contain multiple data sets, size of Type may differ based on Kind // ____________________Message____________________ // | Kind | Type | Length of the Data | Data | ... | // ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ type // General types TExtAINetHandleIndex = SmallInt; // Index of client // Data types of main parts TExtAIMsgRecipient = ShortInt; TExtAIMsgSender = ShortInt; TExtAIMsgLengthMsg = Cardinal; TExtAIMsgLengthData = Cardinal; {$Z1} // Use 1 Byte to store enumeration TExtAIMsgKind = ( mkServerCfg = 0, mkGameCfg = 1, mkExtAICfg = 2, mkPerformance = 3, mkAction = 4, mkEvent = 5, mkState = 6 ); const ExtAI_MSG_MAX_SIZE = 255*255*255; // Maximum length of message ExtAI_MSG_ADDRESS_SERVER = -1; ExtAI_MSG_HEAD_SIZE = SizeOf(TExtAIMsgRecipient) + SizeOf(TExtAIMsgSender) + SizeOf(TExtAIMsgLengthMsg); type // Configurations {$Z1} // Use 1 Byte to store enumeration TExtAIMsgTypeCfgServer = ( csName = 0, csVersion = 1, csClientHandle = 2, csExtAIID = 3 ); {$Z1} // Use 1 Byte to store enumeration TExtAIMsgTypeCfgGame = ( cgLoc = 0, cgMap = 1, cgGameSpeed = 2, cgFoWActive = 3 ); {$Z1} // Use 1 Byte to store enumeration TExtAIMsgTypeCfgAI = ( caID = 0, caAuthor = 1, caName = 2, caDescription = 3, caVersion = 4 ); {$Z1} // Use 1 Byte to store enumeration TExtAIMsgTypePerformance = ( prPing = 0, // Ping request from server prPong = 1, // Pong response of client to Ping request prTick = 2 // Duration of Tick ); // Actions, Events, States {$Z2} // Use 2 Bytes to store enumeration TExtAIMsgTypeAction = ( taGroupOrderAttackUnit = 0, taGroupOrderWalk = 1, taLog = 2 ); {$Z2} // Use 2 Bytes to store enumeration TExtAIMsgTypeEvent = ( teOnMissionStart = 0, teOnMissionEnd = 1, teOnTick = 2, teOnPlayerDefeated = 3, teOnPlayerVictory = 4 ); {$Z2} // Use 2 Bytes to store enumeration TExtAIMsgTypeState = ( tsTerrainSize = 0, tsTerrainPassability = 1, tsTerrainFertility = 2, tsPlayerGroups = 3, tsPlayerUnits = 4 ); const MSG_KIND2TYPE_SIZE: array[TExtAIMsgKind] of Byte = ( SizeOf(TExtAIMsgTypeCfgServer), SizeOf(TExtAIMsgTypeCfgGame), SizeOf(TExtAIMsgTypeCfgAI), SizeOf(TExtAIMsgTypePerformance), SizeOf(TExtAIMsgTypeAction), SizeOf(TExtAIMsgTypeEvent), SizeOf(TExtAIMsgTypeState) ); type TExtAIEventNewMsg = procedure (aData: Pointer; aLength: Cardinal) of object; pExtAINewData = ^TExtAINewData; TExtAINewData = record Ptr: Pointer; Length: Cardinal; Next: pExtAINewData; end; implementation end.
unit GX_GrepSearch; {$I GX_CondDefine.inc} interface uses Classes, Controls, Forms, StdCtrls, ExtCtrls, GX_Experts, GX_GrepExpert, GX_GrepBackend, GX_BaseForm, GX_KbdShortCutBroker; type TfmGrepSearch = class(TfmBaseForm) lblFind: TLabel; cbText: TComboBox; gbxOptions: TGroupBox; cbCaseSensitive: TCheckBox; cbForms: TCheckBox; gbxWhere: TGroupBox; rbAllProjFiles: TRadioButton; rbOpenFiles: TRadioButton; rbDirectories: TRadioButton; gbxDirectories: TGroupBox; lblMasks: TLabel; cbMasks: TComboBox; cbInclude: TCheckBox; pnlBottom: TPanel; btnOK: TButton; btnCancel: TButton; cbWholeWord: TCheckBox; rbCurrentOnly: TRadioButton; btnHelp: TButton; cbRegEx: TCheckBox; cbDirectory: TComboBox; btnBrowse: TButton; lblDirectory: TLabel; rbAllProjGroupFiles: TRadioButton; rbResults: TRadioButton; cbExcludedDirs: TComboBox; lblExcludeDirs: TLabel; cbSQLFiles: TCheckBox; gbxContentTypes: TGroupBox; cbGrepCode: TCheckBox; cbGrepStrings: TCheckBox; cbGrepComments: TCheckBox; gbxUnitSections: TGroupBox; cbSectionInterface: TCheckBox; cbSectionImplementation: TCheckBox; cbSectionInitialization: TCheckBox; cbSectionFinalization: TCheckBox; btnOptions: TButton; rgSaveOption: TRadioGroup; btnSearch: TButton; timHintTimer: TTimer; procedure btnBrowseClick(Sender: TObject); procedure rbDirectoriesClick(Sender: TObject); procedure btnHelpClick(Sender: TObject); procedure cbDirectoryDropDown(Sender: TObject); procedure cbExcludedDirsDropDown(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure ComboKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure btnOptionsClick(Sender: TObject); procedure cbGrepCodeClick(Sender: TObject); procedure cbGrepStringsClick(Sender: TObject); procedure cbGrepCommentsClick(Sender: TObject); procedure cbSectionInterfaceClick(Sender: TObject); procedure cbSectionImplementationClick(Sender: TObject); procedure cbSectionInitializationClick(Sender: TObject); procedure cbSectionFinalizationClick(Sender: TObject); procedure timHintTimerTimer(Sender: TObject); private FGrepExpert: TGrepExpert; FEmbedded: Boolean; FCheckedWhere: Boolean; FEmbeddedHolder: TWinControl; FSaveWidth: Integer; FSaveOptionsGroupWidth: Integer; FSaveWhereGroupWidth: Integer; FSaveWhereGroupLeft: Integer; FLoadingSettings: Boolean; FTheHintWindow: THintWindow; procedure EnableDirectoryControls(New: Boolean); procedure LoadFormSettings; procedure SaveFormSettings; procedure UpdateMRUs; procedure cbDirectoryOnDropFiles(_Sender: TObject; _Files: TStrings); procedure CheckEnabledWhereControls; procedure CheckContentTypeSelection(ClickedOption: TCheckBox); procedure CheckSectionSelection(ClickedOption: TCheckBox); procedure ShowControlHint(ctrl: TWinControl; const HintText: string); public constructor Create(AOwner: TComponent); override; procedure EmbeddedInit(AHolderControl: TWinControl; ASearchEvent: TNotifyEvent); procedure EmbeddedUpdatePos; procedure EmbeddedShow; procedure EmbeddedSetHeights; procedure RetrieveSettings(var Value: TGrepSettings); procedure AdjustSettings(Value: TGrepSettings); property GrepExpert: TGrepExpert read FGrepExpert; end; TGrepDlgExpert = class(TGX_Expert) public constructor Create; override; function GetActionCaption: string; override; function GetDefaultShortCut: TShortCut; override; class function GetName: string; override; function GetHelpString: string; override; procedure Execute(Sender: TObject); override; procedure Configure; override; end; implementation {$R *.dfm} uses SysUtils, Windows, Messages, Graphics, Menus, RegExpr, Math, GX_GenericUtils, GX_GxUtils, GX_OtaUtils, GX_GrepResults, GX_GrepOptions, GX_GrepRegExSearch, GX_dzVclUtils; resourcestring SGrepResultsNotActive = 'The Grep Results window is not active'; const cEmbeddedLeft = 2; cEmbeddedTop = 55; { TfmGrepSearch } procedure TfmGrepSearch.btnBrowseClick(Sender: TObject); var Temp: string; begin Temp := cbDirectory.Text; if GetDirectory(Temp) then cbDirectory.Text := Temp; end; procedure TfmGrepSearch.btnOptionsClick(Sender: TObject); var UseCurrentIdent: Boolean; begin UseCurrentIdent := GrepExpert.GrepUseCurrentIdent; if TfmGrepOptions.Execute(UseCurrentIdent) then GrepExpert.GrepUseCurrentIdent := UseCurrentIdent; end; procedure TfmGrepSearch.EnableDirectoryControls(New: Boolean); begin cbDirectory.Enabled := New; cbMasks.Enabled := New; cbExcludedDirs.Enabled := New; cbInclude.Enabled := New; btnBrowse.Enabled := New; if not New then begin cbDirectory.Color := clBtnface; cbExcludedDirs.Color := clBtnface; cbMasks.Color := clBtnface; end else begin cbDirectory.Color := clWindow; cbExcludedDirs.Color := clWindow; cbMasks.Color := clWindow; end end; procedure TfmGrepSearch.rbDirectoriesClick(Sender: TObject); begin EnableDirectoryControls(rbDirectories.Checked); end; procedure TfmGrepSearch.btnHelpClick(Sender: TObject); begin GxContextHelp(Self, 1); end; procedure TfmGrepSearch.cbDirectoryDropDown(Sender: TObject); begin SizeComboDropdownToItems(cbDirectory); end; procedure TfmGrepSearch.cbExcludedDirsDropDown(Sender: TObject); begin SizeComboDropdownToItems(cbExcludedDirs); end; procedure TfmGrepSearch.ShowControlHint(ctrl: TWinControl; const HintText: string); var r: TRect; Size: TSize; begin timHintTimer.Enabled := False; if Assigned(FTheHintWindow) then begin FTheHintWindow.ReleaseHandle; FTheHintWindow.Free; end; FTheHintWindow := THintWindow.Create(Self); FTheHintWindow.Color := clInfoBk; r.TopLeft := ctrl.ClientToScreen(Point(0, ctrl.Height)); Size := FTheHintWindow.Canvas.TextExtent(HintText); r.Right := r.Left + Size.cx + 8; r.Bottom := r.Top + Size.cy; FTheHintWindow.ActivateHint(r, HintText); timHintTimer.Enabled := True; end; procedure TfmGrepSearch.CheckContentTypeSelection(ClickedOption: TCheckBox); resourcestring SCannotDisableAllContentTypes = 'You cannot disable all content types.'; begin if FLoadingSettings then Exit; if cbGrepCode.Checked or cbGrepStrings.Checked or cbGrepComments.Checked then begin // at least one option is selected -> OK end else begin if Assigned(ClickedOption) then begin // unchecked interactively -> check the last unchecked option again ClickedOption.Checked := True; ShowControlHint(ClickedOption, SCannotDisableAllContentTypes); end else begin // not interactively -> check them all cbGrepCode.Checked := True; cbGrepStrings.Checked := True; cbGrepComments.Checked := True; end; end; end; procedure TfmGrepSearch.cbGrepCodeClick(Sender: TObject); begin CheckContentTypeSelection(cbGrepCode); end; procedure TfmGrepSearch.cbGrepCommentsClick(Sender: TObject); begin CheckContentTypeSelection(cbGrepComments); end; procedure TfmGrepSearch.cbGrepStringsClick(Sender: TObject); begin CheckContentTypeSelection(cbGrepStrings); end; procedure TfmGrepSearch.CheckSectionSelection(ClickedOption: TCheckBox); resourcestring SCannotDisableAllContentTypes = 'You cannot disable all unit sections.'; begin if FLoadingSettings then Exit; if cbSectionInterface.Checked or cbSectionImplementation.Checked or cbSectionInitialization.Checked or cbSectionFinalization.Checked then begin // at least one option is selected -> OK end else begin if Assigned(ClickedOption) then begin // unchecked interactively -> check the last unchecked option again ClickedOption.Checked := True; ShowControlHint(ClickedOption, SCannotDisableAllContentTypes); end else begin // not interactively -> check them all cbSectionInterface.Checked := True; cbSectionImplementation.Checked := True; cbSectionInitialization.Checked := True; cbSectionFinalization.Checked := True; end; end; end; procedure TfmGrepSearch.cbSectionFinalizationClick(Sender: TObject); begin CheckSectionSelection(cbSectionFinalization); end; procedure TfmGrepSearch.cbSectionImplementationClick(Sender: TObject); begin CheckSectionSelection(cbSectionImplementation); end; procedure TfmGrepSearch.cbSectionInitializationClick(Sender: TObject); begin CheckSectionSelection(cbSectionInitialization); end; procedure TfmGrepSearch.cbSectionInterfaceClick(Sender: TObject); begin CheckSectionSelection(cbSectionInterface); end; { TGrepDlgExpert } constructor TGrepDlgExpert.Create; begin inherited Create; end; function TGrepDlgExpert.GetActionCaption: string; resourcestring SActionCaption = '&Grep Search...'; begin Result := SActionCaption; end; function TGrepDlgExpert.GetDefaultShortCut: TShortCut; begin Result := Menus.ShortCut(Word('S'), [ssAlt, ssShift]); end; function TGrepDlgExpert.GetHelpString: string; resourcestring SHelpString = ' Grep regular expressions allow you to formulate complex searches'#13#10 + ' that are not possible using a basic text search.'#13#10 + ' GExperts implements a subset of the Perl regular expression syntax.'; begin Result := SHelpString; end; class function TGrepDlgExpert.GetName: string; begin Result := 'GrepSearch'; // Do not localize. end; procedure TGrepDlgExpert.Execute(Sender: TObject); begin if Assigned(fmGrepResults) then fmGrepResults.Execute(gssNormal) else raise Exception.Create(SGrepResultsNotActive); end; procedure TGrepDlgExpert.Configure; var GrepExpert: TGrepExpert; UseCurrentIdent: Boolean; begin if not Assigned(fmGrepResults) then raise Exception.Create(SGrepResultsNotActive); GrepExpert := fmGrepResults.GrepExpert; Assert(Assigned(GrepExpert)); UseCurrentIdent := GrepExpert.GrepUseCurrentIdent; if TfmGrepOptions.Execute(UseCurrentIdent) then GrepExpert.GrepUseCurrentIdent := UseCurrentIdent; end; procedure TfmGrepSearch.btnOKClick(Sender: TObject); resourcestring SSpecifiedDirectoryDoesNotExist = 'The search directory %s does not exist.'; SSearchTextEmpty = 'The search text is empty.'; var i: Integer; Dirs: TStringList; begin if IsEmpty(cbText.Text) then raise Exception.Create(SSearchTextEmpty); if rbDirectories.Checked then begin if Trim(cbDirectory.Text) = '' then cbDirectory.Text := GetCurrentDir; Dirs := TStringList.Create; try AnsiStrTok(cbDirectory.Text, ';', Dirs); for i := 0 to Dirs.Count - 1 do begin Dirs[i] := ExpandFileName(AddSlash(Dirs[i])); if not DirectoryExists(Dirs[i]) then raise Exception.CreateFmt(SSpecifiedDirectoryDoesNotExist, [Dirs[i]]); if i < Dirs.Count - 1 then Dirs[i] := Dirs[i] + ';' end; cbDirectory.Text := StringReplace(Dirs.Text, #13#10, '', [rfReplaceAll]); finally FreeAndNil(Dirs); end; end; while StrBeginsWith(';', cbExcludedDirs.Text) do cbExcludedDirs.Text := Copy(cbExcludedDirs.Text, 2, MaxInt); cbExcludedDirs.Text := StringReplace(cbExcludedDirs.Text, ';;', ';', [rfReplaceAll]); SaveFormSettings; if cbRegEx.Checked then try ExecRegExpr(cbText.Text, ''); except on E: ERegExpr do begin ShowError(E.Message); TryFocusControl(cbText); cbText.SelStart := E.CompilerErrorPos; cbText.SelLength := 0; Abort; end; end; ModalResult := mrOk; end; constructor TfmGrepSearch.Create(AOwner: TComponent); begin inherited; FEmbedded := False; FEmbeddedHolder := nil; TWinControl_ActivateDropFiles(cbDirectory, cbDirectoryOnDropFiles); pnlBottom.BevelOuter := bvNone; LoadFormSettings; FCheckedWhere := True; end; procedure TfmGrepSearch.FormCreate(Sender: TObject); begin FSaveWidth := Width; FSaveOptionsGroupWidth := gbxOptions.Width; FSaveWhereGroupWidth := gbxWhere.Width; FSaveWhereGroupLeft := gbxWhere.Left; end; procedure TfmGrepSearch.cbDirectoryOnDropFiles(_Sender: TObject; _Files: TStrings); var s: string; begin if IsShiftDown then s := cbDirectory.Text + ';' else s := ''; cbDirectory.Text := s + _Files.DelimitedText; end; procedure TfmGrepSearch.SaveFormSettings; begin AddMRUString(cbText.Text, FGrepExpert.SearchList, False, 90, -1); AddMRUString(cbDirectory.Text, FGrepExpert.DirList, True); AddMRUString(cbMasks.Text, FGrepExpert.MaskList, False); AddMRUString(cbExcludedDirs.Text, FGrepExpert.ExcludedDirsList, False, True); FGrepExpert.GrepCaseSensitive := cbCaseSensitive.Checked; FGrepExpert.GrepCode := cbGrepCode.Checked; FGrepExpert.GrepComments := cbGrepComments.Checked; FGrepExpert.GrepStrings := cbGrepStrings.Checked; FGrepExpert.GrepFinalization := cbSectionFinalization.Checked; FGrepExpert.GrepImplementation := cbSectionImplementation.Checked; FGrepExpert.GrepInitialization := cbSectionInitialization.Checked; FGrepExpert.GrepInterface := cbSectionInterface.Checked; FGrepExpert.GrepForms := cbForms.Checked; FGrepExpert.GrepSQLFiles := cbSQLFiles.Checked; FGrepExpert.GrepSub := cbInclude.Checked; FGrepExpert.GrepWholeWord := cbWholeWord.Checked; FGrepExpert.GrepRegEx := cbRegEx.Checked; FGrepExpert.GrepSaveOption := TGrepSaveOption(rgSaveOption.ItemIndex); if rbCurrentOnly.Checked then FGrepExpert.GrepSearch := 0 else if rbAllProjFiles.Checked then FGrepExpert.GrepSearch := 1 else if rbOpenFiles.Checked then FGrepExpert.GrepSearch := 2 else if rbDirectories.Checked then FGrepExpert.GrepSearch := 3 else if rbAllProjGroupFiles.Checked then FGrepExpert.GrepSearch := 4 else if rbResults.Checked then FGrepExpert.GrepSearch := 5; end; procedure TfmGrepSearch.timHintTimerTimer(Sender: TObject); begin timHintTimer.Enabled := False; if Assigned(FTheHintWindow) then begin FTheHintWindow.ReleaseHandle; FreeAndNil(FTheHintWindow); end; end; procedure TfmGrepSearch.LoadFormSettings; function RetrieveEditorBlockSelection: string; var Temp: string; i: Integer; begin Temp := GxOtaGetCurrentSelection; // Only use the currently selected text if the length is between 1 and 80 if (Length(Trim(Temp)) >= 1) and (Length(Trim(Temp)) <= 80) then begin i := Min(Pos(#13, Temp), Pos(#10, Temp)); if i > 0 then Temp := Copy(Temp, 1, i - 1); end else Temp := ''; Result := Temp; end; procedure SetSearchPattern(Str: string); begin cbText.Text := Str; cbText.SelectAll; end; procedure SetDefaultSearchPattern; var Selection: string; begin Selection := fmGrepResults.ContextSearchText; if Trim(Selection) = '' then Selection := RetrieveEditorBlockSelection; if (Trim(Selection) = '') and FGrepExpert.GrepUseCurrentIdent then try Selection := GxOtaGetCurrentIdent; //if access violation created except on E: Exception do Selection := ''; end; if (Selection = '') and (cbText.Items.Count > 0) then Selection := cbText.Items[0]; SetSearchPattern(Selection); end; begin if not Assigned(fmGrepResults) then raise Exception.Create(SGrepResultsNotActive); FGrepExpert := fmGrepResults.GrepExpert; FLoadingSettings := True; try cbText.Items.Assign(FGrepExpert.SearchList); cbDirectory.Items.Assign(FGrepExpert.DirList); cbMasks.Items.Assign(FGrepExpert.MaskList); cbExcludedDirs.Items.Assign(FGrepExpert.ExcludedDirsList); rbResults.Enabled := fmGrepResults.lbResults.Count > 0; cbCaseSensitive.Checked := FGrepExpert.GrepCaseSensitive; cbGrepCode.Checked := FGrepExpert.GrepCode; cbGrepComments.Checked := FGrepExpert.GrepComments; cbGrepStrings.Checked := FGrepExpert.GrepStrings; cbSectionFinalization.Checked := FGrepExpert.GrepFinalization; cbSectionImplementation.Checked := FGrepExpert.GrepImplementation; cbSectionInitialization.Checked := FGrepExpert.GrepInitialization; cbSectionInterface.Checked := FGrepExpert.GrepInterface; cbForms.Checked := FGrepExpert.GrepForms; cbSQLFiles.Checked := FGrepExpert.GrepSQLFiles; cbInclude.Checked := FGrepExpert.GrepSub; cbWholeWord.Checked := FGrepExpert.GrepWholeWord; cbRegEx.Checked := FGrepExpert.GrepRegEx; rgSaveOption.ItemIndex := Integer(FGrepExpert.SaveOption); case FGrepExpert.GrepSearch of 0: rbCurrentOnly.Checked := True; 1: rbAllProjFiles.Checked := True; 2: rbOpenFiles.Checked := True; 3: rbDirectories.Checked := True; 4: rbAllProjGroupFiles.Checked := True; 5: begin if rbResults.Enabled then rbResults.Checked := True else rbAllProjFiles.Checked := True; end; else rbAllProjFiles.Checked := True; end; if cbText.Items.Count > 0 then cbText.Text := cbText.Items[0]; if cbDirectory.Items.Count > 0 then cbDirectory.Text := cbDirectory.Items[0]; if cbMasks.Items.Count > 0 then cbMasks.Text := cbMasks.Items[0]; if cbExcludedDirs.Items.Count > 0 then cbExcludedDirs.Text := cbExcludedDirs.Items[0]; if not FGrepExpert.GrepSaveHistoryListItems then begin rgSaveOption.Visible := False; Height := Height - rgSaveOption.Height; end; if not IsStandAlone then SetDefaultSearchPattern; finally FLoadingSettings := False; end; CheckContentTypeSelection(nil); CheckSectionSelection(nil); CheckEnabledWhereControls; EnableDirectoryControls(rbDirectories.Checked); end; procedure TfmGrepSearch.CheckEnabledWhereControls; begin if not IsStandAlone then begin if Trim(GxOtaGetCurrentProjectName) = '' then begin rbAllProjFiles.Enabled := False; rbOpenFiles.Enabled := False; end else begin rbAllProjFiles.Enabled := True; rbOpenFiles.Enabled := True; end; if Trim(GxOtaGetProjectGroupFileName) = '' then rbAllProjGroupFiles.Enabled := False else rbAllProjGroupFiles.Enabled := True; rbCurrentOnly.Enabled := Trim(GxOtaGetFileNameOfCurrentModule) <> ''; end else // IsStandAlone begin rbDirectories.Checked := True; rbAllProjFiles.Enabled := False; rbOpenFiles.Enabled := False; rbAllProjGroupFiles.Enabled := False; rbAllProjFiles.Enabled := False; rbCurrentOnly.Enabled := False; end; end; procedure TfmGrepSearch.RetrieveSettings(var Value: TGrepSettings); begin Value.IncludeComments := cbGrepComments.Checked; Value.IncludeCode := cbGrepCode.Checked; Value.IncludeStrings := cbGrepStrings.Checked; Value.SectionInterface := cbSectionInterface.Checked; Value.SectionImplementation := cbSectionImplementation.Checked; Value.SectionInitialization := cbSectionInitialization.Checked; Value.SectionFinalization := cbSectionFinalization.Checked; Value.CaseSensitive := cbCaseSensitive.Checked; Value.WholeWord := cbWholeWord.Checked; Value.RegEx := cbRegEx.Checked; Value.Pattern := cbText.Text; Value.IncludeForms := cbForms.Checked; Value.IncludeSQLs := cbSQLFiles.Checked; Value.SaveOption := TGrepSaveOption(rgSaveOption.ItemIndex); Value.Mask := ''; Value.Directories := ''; Value.ExcludedDirs := ''; Value.IncludeSubdirs := True; if rbAllProjFiles.Checked then Value.GrepAction := gaProjGrep else if rbCurrentOnly.Checked then Value.GrepAction := gaCurrentOnlyGrep else if rbOpenFiles.Checked then Value.GrepAction := gaOpenFilesGrep else if rbAllProjGroupFiles.Checked then Value.GrepAction := gaProjGroupGrep else if rbResults.Checked then Value.GrepAction := gaResults else begin Value.GrepAction := gaDirGrep; Value.Mask := cbMasks.Text; Value.Directories := cbDirectory.Text; Value.IncludeSubdirs := cbInclude.Checked; Value.ExcludedDirs := cbExcludedDirs.Text; end; end; procedure TfmGrepSearch.AdjustSettings(Value: TGrepSettings); begin cbGrepComments.Checked := Value.IncludeComments; cbGrepCode.Checked := Value.IncludeCode; cbGrepStrings.Checked := Value.IncludeStrings; cbSectionInterface.Checked := Value.SectionInterface; cbSectionImplementation.Checked := Value.SectionImplementation; cbSectionInitialization.Checked := Value.SectionInitialization; cbSectionFinalization.Checked := Value.SectionFinalization; cbCaseSensitive.Checked := Value.CaseSensitive; cbWholeWord.Checked := Value.WholeWord; cbRegEx.Checked := Value.RegEx; cbText.Text := Value.Pattern; cbText.SelectAll; cbForms.Checked := Value.IncludeForms; cbSQLFiles.Checked := Value.IncludeSQLs; rgSaveOption.ItemIndex := Integer(Value.SaveOption); cbMasks.Text := ''; cbDirectory.Text := ''; cbExcludedDirs.Text := ''; cbInclude.Checked := True; case Value.GrepAction of gaProjGrep: rbAllProjFiles.Checked := True; gaCurrentOnlyGrep: rbCurrentOnly.Checked := True; gaOpenFilesGrep: rbOpenFiles.Checked := True; gaProjGroupGrep: rbAllProjGroupFiles.Checked := True; gaResults: rbResults.Checked := True; gaDirGrep: begin rbDirectories.Checked := True; cbMasks.Text := Value.Mask; cbDirectory.Text := Value.Directories; cbInclude.Checked := Value.IncludeSubdirs; cbExcludedDirs.Text := Value.ExcludedDirs; end ; end; EnableDirectoryControls(rbDirectories.Checked); end; procedure TfmGrepSearch.FormShow(Sender: TObject); begin Constraints.MaxHeight := Height; Constraints.MinHeight := Height; Constraints.MinWidth := Width; end; procedure TfmGrepSearch.ComboKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var SelectedIndex: Integer; Combo: TCustomComboBox; begin if (Key = VK_DELETE) and (ssCtrl in Shift) then begin Combo := (Sender as TCustomComboBox); if Combo.DroppedDown then begin SelectedIndex := Combo.ItemIndex; if SelectedIndex > -1 then begin Combo.Items.Delete(SelectedIndex); UpdateMRUs; end; end; end; end; procedure TfmGrepSearch.UpdateMRUs; begin FGrepExpert.SearchList.Assign(cbText.Items); FGrepExpert.DirList.Assign(cbDirectory.Items); FGrepExpert.MaskList.Assign(cbMasks.Items); FGrepExpert.ExcludedDirsList.Assign(cbExcludedDirs.Items); end; procedure TfmGrepSearch.EmbeddedInit(AHolderControl: TWinControl; ASearchEvent: TNotifyEvent); begin FEmbedded := True; FEmbeddedHolder := AHolderControl; //.Left + 2, lbResults.Top + 55, lbResults.Width - 4 Parent := TWinControl(Owner); Height := ClientHeight; BorderIcons := []; BorderStyle := bsNone; //ToolWindow; Position := poDesigned; FormStyle := fsStayOnTop; btnSearch.Left := btnOptions.Left; EmbeddedSetHeights; EmbeddedUpdatePos; btnOK.Visible := False; btnCancel.Visible := False; btnOptions.Visible := False; btnSearch.Visible := True; btnSearch.OnClick := ASearchEvent; FCheckedWhere := False; end; procedure TfmGrepSearch.EmbeddedSetHeights; function MoveTo(ATopDelta: Integer; AMainCtrl: TControl; AItemsDelta: Integer; AItems: array of TControl): Integer; var I, ADelta: Integer; begin AMainCtrl.Top := AMainCtrl.Top - ATopDelta; Result := 0; for I := 0 to High(AItems) do begin if AItemsDelta > 0 then begin ADelta := (I+1) * AItemsDelta; Inc(Result, ADelta div 2); end else ADelta := ATopDelta; AItems[I].Top := AItems[I].Top - ADelta; end; if High(AItems) = -1 then Inc(Result, AItemsDelta); if AItemsDelta > 0 then AMainCtrl.Height := AMainCtrl.Height - Result; Inc(Result, ATopDelta); end; var LHS: Integer; // LastHeightsSum begin MoveTo(5, cbText, 0, [lblFind]); MoveTo(10, gbxOptions, 3, [cbCaseSensitive, cbWholeWord, cbForms, cbSQLFiles, cbRegEx]); LHS := MoveTo(10, gbxWhere, 5, [rbCurrentOnly, rbAllProjGroupFiles, rbAllProjFiles, rbOpenFiles, rbDirectories, rbResults]); gbxWhere.Height := gbxWhere.Height + 13; gbxOptions.Height := gbxWhere.Height; MoveTo(-5 + LHS, gbxContentTypes, 3, [cbGrepCode, cbGrepStrings, cbGrepComments]); LHS := MoveTo(-5 + LHS, gbxUnitSections, 3, [cbSectionInterface, cbSectionImplementation, cbSectionInitialization, cbSectionFinalization]); gbxContentTypes.Height := gbxUnitSections.Height; LHS := MoveTo(4 + LHS, gbxDirectories, 5, [cbDirectory, cbExcludedDirs, cbMasks, cbInclude]); lblDirectory.Top := cbDirectory.Top; btnBrowse.Top := cbDirectory.Top; lblExcludeDirs.Top := cbExcludedDirs.Top; lblMasks.Top := cbMasks.Top; LHS := MoveTo(5 + LHS, rgSaveOption, 15, []); Height := Height - LHS - 3; end; procedure TfmGrepSearch.EmbeddedUpdatePos; const cMinWidth = 382; cWhereWidthCorrection = 5; //??? var ADelta, ADeltaLeft, ADeltaRight, AWidth: Integer; begin Left := FEmbeddedHolder.Left + cEmbeddedLeft; Top := FEmbeddedHolder.Top + cEmbeddedTop; AWidth := FEmbeddedHolder.Width - 4; if AWidth >= FSaveWidth then Exit; AWidth := Max(AWidth, cMinWidth); gbxWhere.Anchors := [akTop, akLeft]; gbxUnitSections.Anchors := [akTop, akLeft]; ADelta := FSaveWidth - AWidth; ADeltaLeft := ADelta div 2; ADeltaRight := ADelta - ADeltaLeft; Width := AWidth; gbxOptions.Width := FSaveOptionsGroupWidth - ADeltaLeft; gbxContentTypes.Width := FSaveOptionsGroupWidth - ADeltaLeft; gbxWhere.Left := FSaveWhereGroupLeft - ADeltaLeft; gbxWhere.Width := FSaveWhereGroupWidth - ADeltaRight + cWhereWidthCorrection; gbxUnitSections.Left := FSaveWhereGroupLeft - ADeltaLeft; gbxUnitSections.Width := FSaveWhereGroupWidth - ADeltaRight + cWhereWidthCorrection; end; procedure TfmGrepSearch.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; if FEmbedded then Action := caHide; end; procedure TfmGrepSearch.EmbeddedShow; begin if not FEmbedded then Exit; if not FCheckedWhere then begin FCheckedWhere := True; CheckEnabledWhereControls; end; if not Visible then EmbeddedUpdatePos; Show; BringToFront; end; initialization RegisterGX_Expert(TGrepDlgExpert); end.
unit DeviceLicenseRequestUnit; interface uses REST.Json.Types, GenericParametersUnit, CommonTypesUnit, EnumsUnit; type TDeviceLicenseRequest = class(TGenericParameters) private [JSONName('device_id')] FDeviceId: String; [JSONName('device_type')] FDeviceType: String; [JSONName('format')] FFormat: String; public constructor Create(DeviceId: String; DeviceType: TDeviceType; Format: String); reintroduce; end; implementation { TDeviceLicenseRequest } constructor TDeviceLicenseRequest.Create(DeviceId: String; DeviceType: TDeviceType; Format: String); begin Inherited Create; FDeviceId := DeviceId; FDeviceType := TDeviceTypeDescription[DeviceType]; FFormat := Format; end; end.
unit WPPrTab1; { ----------------------------------------------------------------------------- Copyright (C) 2002-2015 by wpcubed GmbH - Author: Julian Ziersch info: http://www.wptools.de mailto:support@wptools.de __ __ ___ _____ _ _____ / / /\ \ \/ _ \/__ \___ ___ | |___ |___ | \ \/ \/ / /_)/ / /\/ _ \ / _ \| / __| / / \ /\ / ___/ / / | (_) | (_) | \__ \ / / \/ \/\/ \/ \___/ \___/|_|___/ /_/ ***************************************************************************** WPCTRRich - high level editor interface TWPRichText ----------------------------------------------------------------------------- THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. ----------------------------------------------------------------------------- } interface {$I WPINC.INC} uses {$IFDEF DELPHIXE}WinAPI.Windows, {$ELSE} Windows, {$ENDIF} Classes, SysUtils, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, WPRTEDefs, WPRTEDefsConsts, WPCTRRich, WPUtil, WPCTRMemo, WPRTEPlatform ; type TWPTableSelect = class(TForm) Panel2: TPanel; PaintBox1: TPaintBox; Status: TPanel; ShowBord: TSpeedButton; Button1: TBitBtn; PaintBox2: TPaintBox; Shape1: TShape; procedure FormPaint(Sender: TObject); procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure PaintBox1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure PaintBox1DblClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure PaintBox1Click(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure PaintBox2Paint(Sender: TObject); procedure FormShow(Sender: TObject); {$IFNDEF LAC} protected procedure CreateParams(var Params: TCreateParams); override; {$ENDIF} private FButton, FDontClose: Boolean; public row, col: Integer; { Public-Deklarationen } end; procedure WPCreateTableForm(Form: TWinControl; Sender: TControl; editor: TWPCustomRichText; AllowNestedTables: Boolean = FALSE); implementation const ElementWidth = 20; {$R *.DFM} procedure WPCreateTableForm(Form: TWinControl; Sender: TControl; editor: TWPCustomRichText; AllowNestedTables: Boolean = FALSE); var dia: TWPTableSelect; p: TPoint; count, ccount: Integer; opt: TWPTableAddOptions; newtable: TParagraph; HasUndo: Boolean; begin dia := nil; HasUndo := FALSE; if editor <> nil then try dia := TWPTableSelect.Create(Form); if Sender <> nil then begin p.X := 0; p.Y := 0; p := Sender.ClientToScreen(p); inc(p.Y, Sender.Height); end else GetCursorPos(p); if p.X + dia.Width > Screen.DesktopWidth then p.X := Screen.DesktopWidth - dia.Width; if p.Y + dia.Height > Screen.DesktopWidth then p.Y := Screen.DesktopWidth - dia.Height; dia.Left := p.X; dia.Top := p.Y; dia.Position := poDesigned; // dia.FButton := TRUE; if (dia.ShowModal = IDOK) then begin { Style := Editor.Memo.active_paragraph.Style; if editor.Memo.active_line^.plen>0 then Editor.InputText(#13); Editor.BeginUpdate; Editor.InputText(#13); Editor.CPMoveBack; Editor.Memo.active_paragraph.Style := Style; } count := dia.row; ccount := dia.col; {$IFDEF ALLOWUNDO} if (wpActivateUndo in editor.EditOptions) then begin editor.RTFData.UndoBufferSaveTo(nil, wpuStoreCursorPos, wputChangeTable); if editor.Table <> nil then begin editor.RTFData.UndoBufferSaveTo(editor.Table, wpuReplaceParTotal, wputChangeTable); editor.RTFData.UndoDisable; HasUndo := TRUE; end; end; {$ENDIF} if AllowNestedTables then begin opt := [wptblAllowNestedTables, wptblPlaceCursorInLastCell]; if dia.ShowBord.Down then include(opt, wptblActivateBorders); newtable := editor.TableAdd(ccount, count, opt); end else newtable := editor.AddTable(ccount, count, dia.ShowBord.Down); if (newtable <> nil) and (newtable.ParentTable <> nil) then // V5.22.2 begin newtable := newtable.ParentTable; if newtable.NextPar = nil then begin newtable.NextPar := TParagraph.Create(newtable.RTFData); {$IFDEF ALLOWUNDO} if (wpActivateUndo in editor.EditOptions) then editor.RTFData.UndoBufferSaveTo(newtable.NextPar, wpuDeletePar, wputChangeTable); {$ENDIF} end; end; end; finally dia.Free; {$IFDEF ALLOWUNDO} if HasUndo then editor.RTFData.UndoEnable; {$ENDIF} end; end; { Table select form } procedure TWPTableSelect.PaintBox2Paint(Sender: TObject); begin if WPAllDialogsBitmap <> nil then WPDrawShade(PaintBox2.Canvas, PaintBox2.ClientRect, 192 - 128, WPShadedFormHorizontal, WPShadedFormBothWays, WPAllDialogsBitmap, TRUE, Color); end; procedure TWPTableSelect.FormPaint(Sender: TObject); var w: Integer; X, Y, r, c: Integer; begin with PaintBox1 do begin w := ElementWidth; if row <= 0 then row := 1; if col <= 0 then col := 1; Status.Caption := IntToStr(col) + #32 + 'X' + IntToStr(row); Y := 2; r := 1; Canvas.Brush.Style := bsSolid; Canvas.Pen.Color := clBtnShadow; while Y < Height-2 do begin c := 1; x := 2; while X < Width-2 do begin if (c <= col) and (r <= row) then Canvas.Brush.Color := clHighlight else Canvas.Brush.Color := clWhite; Canvas.Rectangle(X, Y, X + w, Y + w); inc(X, w + 2); inc(c); end; inc(y, w + 2); inc(r); end; end; end; procedure TWPTableSelect.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var r, c, w: Integer; begin w := ElementWidth; r := (Y + w div 2) div (w+2); c := (X + w div 2) div (w+2); if (r <> row) or (c <> col) then begin row := r; col := c; if col * (w+2) >= PaintBox1.Width-10 then Width := col * (w+2)+8; if row * (w+2) >= PaintBox1.Height then Height := PaintBox2.Height + row * (w+2)+8; PaintBox1.Update; end; FButton := TRUE; end; procedure TWPTableSelect.PaintBox1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FButton := FALSE; end; procedure TWPTableSelect.PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var r, c, w: Integer; begin w := ElementWidth; r := (Y + w div 2) div (w+2); c := (X + w div 2) div (w+2); if (r <> row) or (c <> col) then begin row := r; col := c; if FButton then begin if col * (w+2) >= PaintBox1.Width-10 then Width := col * (w+2)+8; if row * (w+2) >= PaintBox1.Height then Height := PaintBox2.Height + row * (w+2)+8; FDontClose := TRUE; end; PaintBox1.invalidate; end; end; procedure TWPTableSelect.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if FButton then PaintBox1MouseMove(Sender, Shift, X, Y); end; {$IFNDEF LAC} procedure TWPTableSelect.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do Style := Style or WS_BORDER; end; {$ENDIF} procedure TWPTableSelect.PaintBox1DblClick(Sender: TObject); begin if col >= 1 then ModalResult := IDOK else ModalResult := IDCANCEL; end; procedure TWPTableSelect.FormCreate(Sender: TObject); begin ShowBord.Flat := TRUE; Panel2.DoubleBuffered := TRUE; DoubleBuffered := true; end; procedure TWPTableSelect.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then ModalResult := IDOK else if Key = #27 then ModalResult := IDCANCEL; end; procedure TWPTableSelect.PaintBox1Click(Sender: TObject); begin if not FDontClose then begin if col >= 1 then ModalResult := IDOK else ModalResult := IDCANCEL; end; FDontClose := FALSE; end; procedure TWPTableSelect.FormResize(Sender: TObject); begin Panel2.BoundsRect := Rect(2, 2, Width - 4, Height - 4 - Status.Height); end; procedure TWPTableSelect.FormShow(Sender: TObject); begin Width := 5 * (ElementWidth+2)+8; Height := PaintBox2.Height + 5 * (ElementWidth+2)+8; end; end.
unit udmSldoArmazenagem; interface uses System.SysUtils, System.Classes, udmPadrao, DBAccess, IBC, Data.DB, MemDS; type TdmSldoArmazenagem = class(TdmPadrao) qryManutencaoCGC: TStringField; qryManutencaoSERIE: TStringField; qryManutencaoLOTE: TStringField; qryManutencaoNOTA: TFloatField; qryManutencaoPRODUTO: TStringField; qryManutencaoRUA: TStringField; qryManutencaoNUMERO: TIntegerField; qryManutencaoANDAR: TIntegerField; qryManutencaoAPARTAMENTO: TIntegerField; qryManutencaoDT_SALDO: TDateTimeField; qryManutencaoQTD_SALDO: TFloatField; qryManutencaoVLR_SALDO: TFloatField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryLocalizacaoCGC: TStringField; qryLocalizacaoSERIE: TStringField; qryLocalizacaoLOTE: TStringField; qryLocalizacaoNOTA: TFloatField; qryLocalizacaoPRODUTO: TStringField; qryLocalizacaoRUA: TStringField; qryLocalizacaoNUMERO: TIntegerField; qryLocalizacaoANDAR: TIntegerField; qryLocalizacaoAPARTAMENTO: TIntegerField; qryLocalizacaoDT_SALDO: TDateTimeField; qryLocalizacaoQTD_SALDO: TFloatField; qryLocalizacaoVLR_SALDO: TFloatField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; protected procedure MontaSQLBusca(DataSet :TDataSet = Nil); override; procedure MontaSQLRefresh; override; private FProduto: String; FDtaMovimentacao: TDateTime; FApartamento: Real; FDtaMovimentacaoI: TDateTime; FCliente: String; FSerie: String; FDtaMovimentacaoF: TDateTime; FNumero: Real; FSomenteAtivos: Boolean; FLote: String; FAndar: Real; FNota: Real; FRua: String; public property Cliente :String read FCliente write FCliente; property Lote :String read FLote write FLote; property Serie :String read FSerie write FSerie; property Nota_Fiscal :Real read FNota write FNota; property Produto :String read FProduto write FProduto; property Rua :String read FRua write FRua; property Numero :Real read FNumero write FNumero; property Andar :Real read FAndar write FAndar; property Apartamento :Real read FApartamento write FApartamento; property Dta_Movimentacao :TDateTime read FDtaMovimentacao write FDtaMovimentacao; property Dta_MovimentacaoI :TDateTime read FDtaMovimentacaoI write FDtaMovimentacaoI; property Dta_MovimentacaoF :TDateTime read FDtaMovimentacaoF write FDtaMovimentacaoF; property Somente_Ativos :Boolean read FSomenteAtivos write FSomenteAtivos; function LocalizaLotesDisponiveis(DataSet :TDataSet = Nil) :Boolean; function LocalizaNotasDisponiveis(DataSet :TDataSet = Nil) :Boolean; function LocalizarPorNotaFiscal(DataSet :TDataSet = Nil) :Boolean; function LocalizarPorPeriodo(DataSet :TDataSet = Nil) :Boolean; end; var dmSldoArmazenagem: TdmSldoArmazenagem; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TdmSldoArmazenagem } function TdmSldoArmazenagem.LocalizaLotesDisponiveis(DataSet: TDataSet): Boolean; begin if DataSet = Nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add('SELECT * FROM STWARMTSAL'); SQL.Add('WHERE ( CGC = :CGC ) AND ( PRODUTO = :PRODUTO ) AND ( DT_SALDO = :DT_SALDO )'); if FSomenteAtivos then SQL.Add(' AND ( QTD_SALDO > 0 )'); SQL.Add('ORDER BY CGC, PRODUTO, LOTE, SERIE, NOTA'); Params[0].AsString := FCliente; Params[1].AsString := FProduto; Params[2].AsDate := FDtaMovimentacao; Open; Result := Not IsEmpty; end; end; function TdmSldoArmazenagem.LocalizaNotasDisponiveis(DataSet: TDataSet): Boolean; begin if DataSet = Nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add('SELECT * FROM STWARMTSAL'); SQL.Add('WHERE ( CGC = :CGC ) AND ( PRODUTO = :PRODUTO ) AND ( DT_SALDO = :DT_SALDO ) AND ( LOTE = :LOTE )'); if FSomenteAtivos then SQL.Add(' AND ( QTD_SALDO > 0 )'); SQL.Add('ORDER BY CGC, PRODUTO, SERIE, NOTA'); Params[0].AsString := FCliente; Params[1].AsString := FProduto; Params[2].AsDate := FDtaMovimentacao; Params[3].AsString := FLote; Open; Result := Not IsEmpty; end; end; function TdmSldoArmazenagem.LocalizarPorNotaFiscal(DataSet: TDataSet): Boolean; begin if DataSet = Nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add('SELECT * FROM STWARMTSAL'); SQL.Add('WHERE ( CGC = :CGC ) AND ( PRODUTO = :PRODUTO ) AND ( DT_SALDO = :DT_SALDO ) AND ( LOTE = :LOTE ) AND ( SERIE = :SERIE ) AND ( NOTA = :NOTA )'); if FSomenteAtivos then SQL.Add(' AND ( QTD_SALDO > 0 )'); SQL.Add('ORDER BY CGC, PRODUTO, SERIE, NOTA'); Params[0].AsString := FCliente; Params[1].AsString := FProduto; Params[2].AsDate := FDtaMovimentacao; Params[3].AsString := FLote; Params[4].AsString := FSerie; Params[5].AsFloat := FNota; Open; Result := Not IsEmpty; end; end; function TdmSldoArmazenagem.LocalizarPorPeriodo(DataSet: TDataSet): Boolean; begin if DataSet = Nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add('SELECT * FROM STWARMTSAL'); SQL.Add('WHERE ( DT_SALDO >= :DT_INICIO ) AND ( DT_SALDO <= :DT_TERMINO )'); if Length(FCliente) > 0 then SQL.Add(' AND ( CGC = ' + QuotedStr(FCliente) + ' )'); if Length(FLote) > 0 then SQL.Add(' AND ( LOTE = ' + QuotedStr(FLote) + ' )'); if Length(FSerie) > 0 then SQL.Add(' AND ( SERIE = ' + QuotedStr(FSerie) + ' )'); if FNota > 0 then SQL.Add(' AND ( NOTA = ' + FormatFloat('000000', FNota) + ' )'); if Length(FProduto) > 0 then SQL.Add(' AND ( PRODUTO = ' + QuotedStr(FProduto) + ' )'); if Length(FRua) > 0 then SQL.Add(' AND ( RUA = ' + QuotedStr(FRua) + ' )'); if FNumero > 0 then SQL.Add(' AND ( NUMERO = ' + FormatFloat('000', FNumero) + ' )'); if FAndar > 0 then SQL.Add(' AND ( ANDAR = ' + FormatFloat('000', FAndar) + ' )'); if FApartamento > 0 then SQL.Add(' AND ( APARTAMENTO = ' + FormatFloat('000', FApartamento) + ' )'); if FSomenteAtivos then SQL.Add(' AND ( QTD_SALDO > 0 )'); SQL.Add('ORDER BY CGC, LOTE, SERIE, NOTA, PRODUTO, RUA, NUMERO, ANDAR, APARTAMENTO, DT_SALDO'); ParamByName('DT_INICIO').AsDateTime := FDtaMovimentacaoI; ParamByName('DT_TERMINO').AsDateTime := FDtaMovimentacaoF; Open; Result := Not IsEmpty; end; end; procedure TdmSldoArmazenagem.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add('SELECT * FROM STWARMTSAL'); SQL.Add('WHERE ( CGC = :CGC ) AND ( LOTE = :LOTE ) AND ( SERIE = :SERIE ) AND ( NOTA = :NOTA ) AND ( PRODUTO = :PRODUTO ) AND ( RUA = :RUA )'); SQL.Add(' AND ( NUMERO = :NUMERO ) AND ( ANDAR = :ANDAR ) AND ( APARTAMENTO = :APARTAMENTO ) AND ( DT_SALDO = :DT_SALDO )'); if FSomenteAtivos then SQL.Add(' AND ( QTD_SALDO > 0 )'); SQL.Add('ORDER BY CGC, LOTE, SERIE, NOTA, PRODUTO, RUA, NUMERO, ANDAR, APARTAMENTO, DT_SALDO'); ParamByName('CGC').AsString := FCliente; ParamByName('LOTE').AsString := FLote; ParamByName('SERIE').AsString := FSerie; ParamByName('NOTA').AsFloat := FNota; ParamByName('PRODUTO').AsString := FProduto; ParamByName('RUA').AsString := FRua; ParamByName('NUMERO').AsFloat := FNumero; ParamByName('ANDAR').AsFloat := FAndar; ParamByName('APARTAMENTO').AsFloat := FApartamento; ParamByName('DT_SALDO').AsDate := FDtaMovimentacao; end; end; procedure TdmSldoArmazenagem.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add('SELECT * FROM STWARMTSAL'); SQL.Add('ORDER BY CGC, LOTE, SERIE, NOTA, PRODUTO, RUA, NUMERO, ANDAR, APARTAMENTO, DT_SALDO'); end; end; end.
unit DuplicateRouteResponseUnit; interface uses REST.Json.Types, JSONNullableAttributeUnit, GenericParametersUnit, NullableBasicTypesUnit; type TDuplicateRouteResponse = class(TGenericParameters) private [JSONName('optimization_problem_id')] [Nullable] FOptimizationProblemId: NullableString; [JSONName('success')] FSuccess: boolean; public constructor Create; override; property OptimizationProblemId: NullableString read FOptimizationProblemId write FOptimizationProblemId; property Success: boolean read FSuccess write FSuccess; end; implementation { TDuplicateRouteResponse } constructor TDuplicateRouteResponse.Create; begin inherited; FOptimizationProblemId := NullableString.Null; end; end.
{* * Copyright © 2008 Kristian Høgsberg * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *} unit wayland_client; {$mode objfpc}{$H+} interface uses Classes, SysUtils, wayland_client_core, wayland_util, ctypes; type Pwl_display = ^Twl_display; Pwl_event_queue = ^Twl_event_queue; Pwl_proxy = ^Twl_proxy; Pwl_proxy_wrapper = ^Twl_proxy_wrapper; { Twl_proxy } Twl_proxy = object procedure MarshalArray(opcode: cint32; args: Pwl_argument); function Create(factory: Pwl_proxy; &interface: Pwl_interface): Pwl_proxy; static; function CreateWrapper: Pwl_proxy_wrapper; procedure Destroy; function MarshalArrayConstructor(opcode: cint32; args: Pwl_argument; &interface: Pwl_interface): Pwl_proxy; function MarshalArrayConstructorVersioned(opcode: cint32; args: Pwl_argument; &interface: Pwl_interface; version: cint32): Pwl_proxy; function AddListener(impl: PPointer; data: Pointer): cint; function GetListener: Pointer; function AddDispatcher(dispatcher: wl_dispatcher_func_t; dispatcher_data: pointer; data: pointer): cint; procedure SetUserData(Data: Pointer); function GetUserData: Pointer; function GetVersion: cuint32; function GetID: cuint32; function GetClass: PChar; procedure SetQueue(queue: Pwl_event_queue); end; Twl_event_queue = object procedure Destroy; end; { Twl_proxy_wrapper } Twl_proxy_wrapper = object(Twl_proxy) procedure WrapperDestroy; end; { Twl_display } Twl_display = object function Connect(Name: Pchar): Pwl_display; static; function ConnectTo(fd: cint): Pwl_display; static; procedure Disconnect; function GetFD: cint; function Dispatch: cint; function DispatchQueue(Queue: Pwl_event_queue): cint; function DispatchQueuePending: cint; function GetError: cint; function GetProtocolError(&interface: PPwl_interface; id: pcuint32): cuint32; function Flush: cint; function RoundtripQueue(Queue: Pwl_event_queue): cint; function Roundtrip: cint; function CreateQueue: Pwl_event_queue; function PrepareReadQueue(Queue: Pwl_event_queue): cint; function PrepareRead: cint; procedure CancelRead; function ReadEvents: cint; end; implementation { Twl_display } function Twl_display.Connect(Name: Pchar): Pwl_display; begin Result := wl_display_connect(Name); end; function Twl_display.ConnectTo(fd: cint): Pwl_display; begin Result := wl_display_connect_to_fd(fd); end; procedure Twl_display.Disconnect; begin wl_display_disconnect(@self); end; function Twl_display.GetFD: cint; begin Result := wl_display_get_fd(@self); end; function Twl_display.Dispatch: cint; begin Result := wl_display_dispatch(@self); end; function Twl_display.DispatchQueue(Queue: Pwl_event_queue): cint; begin Result := wl_display_dispatch_queue(@self, Queue); end; function Twl_display.DispatchQueuePending: cint; begin Result := wl_display_dispatch_pending(@self); end; function Twl_display.GetError: cint; begin Result := wl_display_get_error(@self); end; function Twl_display.GetProtocolError(&interface: PPwl_interface; id: pcuint32): cuint32; begin Result := wl_display_get_protocol_error(@self, &interface, id); end; function Twl_display.Flush: cint; begin Result := wl_display_flush(@self); end; function Twl_display.RoundtripQueue(Queue: Pwl_event_queue): cint; begin Result := wl_display_roundtrip_queue(@self, Queue); end; function Twl_display.Roundtrip: cint; begin Result := wl_display_roundtrip(@self); end; function Twl_display.CreateQueue: Pwl_event_queue; begin Result := wl_display_create_queue(@self); end; function Twl_display.PrepareReadQueue(Queue: Pwl_event_queue): cint; begin Result := wl_display_prepare_read_queue(@self, Queue); end; function Twl_display.PrepareRead: cint; begin Result := wl_display_prepare_read(@self); end; procedure Twl_display.CancelRead; begin wl_display_cancel_read(@self); end; function Twl_display.ReadEvents: cint; begin Result := wl_display_read_events(@self); end; { Twl_proxy_wrapper } procedure Twl_proxy_wrapper.WrapperDestroy; begin wl_proxy_wrapper_destroy(@Self); end; { Twl_proxy } procedure Twl_proxy.MarshalArray(opcode: cint32; args: Pwl_argument); begin wl_proxy_marshal_array(@Self, opcode, args); end; function Twl_proxy.Create(factory: Pwl_proxy; &interface: Pwl_interface): Pwl_proxy; begin Result := wl_proxy_create(factory, &interface); end; function Twl_proxy.CreateWrapper: Pwl_proxy_wrapper; begin Result := wl_proxy_create_wrapper(@Self); end; procedure Twl_proxy.Destroy; begin wl_proxy_destroy(@Self); end; function Twl_proxy.MarshalArrayConstructor(opcode: cint32; args: Pwl_argument; &interface: Pwl_interface): Pwl_proxy; begin Result := wl_proxy_marshal_array_constructor(@Self, opcode, args, &interface); end; function Twl_proxy.MarshalArrayConstructorVersioned(opcode: cint32; args: Pwl_argument; &interface: Pwl_interface; version: cint32): Pwl_proxy; begin Result := wl_proxy_marshal_array_constructor_versioned(@Self, opcode, args, &interface, version); end; function Twl_proxy.AddListener(impl: PPointer; data: Pointer): cint; begin Result := wl_proxy_add_listener(@Self, impl, data); end; function Twl_proxy.GetListener: Pointer; begin Result := wl_proxy_get_listener(@Self); end; function Twl_proxy.AddDispatcher(dispatcher: wl_dispatcher_func_t; dispatcher_data: pointer; data: pointer): cint; begin Result := wl_proxy_add_dispatcher(@Self, dispatcher,dispatcher_data, data); end; procedure Twl_proxy.SetUserData(Data: Pointer); begin wl_proxy_set_user_data(@Self, Data); end; function Twl_proxy.GetUserData: Pointer; begin Result := wl_proxy_get_user_data(@Self); end; function Twl_proxy.GetVersion: cuint32; begin Result := wl_proxy_get_version(@Self); end; function Twl_proxy.GetID: cuint32; begin Result := wl_proxy_get_id(@Self); end; function Twl_proxy.GetClass: PChar; begin Result := wl_proxy_get_class(@Self); end; procedure Twl_proxy.SetQueue(queue: Pwl_event_queue); begin wl_proxy_set_queue(@Self, queue); end; { Twl_event_queue } procedure Twl_event_queue.Destroy; begin wl_event_queue_destroy(@self); end; end.
unit SearchOption; interface uses DCL_intf, HashMap, SysUtils, Classes, StageOptionPartList, DBManager, SearchOption_Intf; type TTableOption = class(TAbsSearchOptionPart) private FTableName: String; public function GetValues(key: String): String; override; procedure SetValues(key, val: String); override; end; TSearchOption = class(TObject) private FOptHash: IStrIntfMap; //FSearchOptions: array of ISearchOptionPart; FSearchOptionPointer: Integer; FStageOptionList: TStageOptionList; FTableName: String; FDBManager: TAbsDBManager; FStageNames: TStringList; protected procedure Init; virtual; function GetOption(key: String): ISearchOptionPart; procedure SetTableName(tableName: String); procedure ClearStageNames; public constructor Create; destructor Destroy; procedure SetStageOptionList(stageOptions: TStageOptionList); procedure AddSearchOption(key: String; option: ISearchOptionPart); function GetStageName(stageNum: Integer): String; function GetStageNameList: TStringList; function Count: Integer; function GetQuery: string; overload; virtual; function GetQuery(stageNum: Integer): string; overload; virtual; function GetQueryListByManual: TStringList; virtual; function GetQueryListByAuto: TStringList; virtual; function GetQueryList(isAuto: Boolean): TStringList; virtual; property TableName: String read FTableName write SetTableName; property Options[key: String]: ISearchOptionPart read GetOption; function GetDBManager: TAbsDBManager; virtual; procedure SetDBManager(dbm: TAbsDBManager); virtual; function IsAutoDetected: Boolean; end; implementation uses QueryReader, Const_SearchOptionUnit, StageOptionPart; { TTableOption } function TTableOption.GetValues(key: String): String; begin if key = 'table.name' then result := FTableName; end; procedure TTableOption.SetValues(key, val: String); begin if key = 'table.name' then FTableName := val; end; { TSearchOption } procedure TSearchOption.SetTableName(tableName: String); var tableNameOpt: TAbsSearchOptionPart; begin tableNameOpt := TTableOption.Create; tableNameOpt.SetValues( 'table.name', tableName ); AddSearchOption( 'table', tableNameOpt ); FTableName := tableName; end; procedure TSearchOption.AddSearchOption(key: String; option: ISearchOptionPart); begin FOptHash.PutValue( key, option ); end; procedure TSearchOption.ClearStageNames; begin FreeAndNil( FStageNames ); FStageNames := TStringList.Create; end; function TSearchOption.Count: Integer; begin result := FOptHash.Size; end; constructor TSearchOption.Create; begin Init; end; destructor TSearchOption.Destroy; begin FOptHash.Clear; end; function TSearchOption.GetDBManager: TAbsDBManager; begin result := FDBManager; end; function TSearchOption.GetOption(key: String): ISearchOptionPart; begin result := FOptHash.GetValue( key ) as ISearchOptionPart; end; function TSearchOption.GetQuery(stageNum: Integer): string; var stgOpt: TStageOptionPart; begin if stageNum < 0 then begin stgOpt := TStageOptionPart.Create; ClearStageNames; FStageNames.Add( FTableName ); if stageNum = -10 then stgOpt.SetUse( true ) else stgOpt.SetUse( false ); end else begin stgOpt := FStageOptionList.GetStageOption( stageNum ); if stgOpt = nil then begin result := GetQuery( -1 ); exit; end; end; AddSearchOption( 'stage', stgOpt ); GetOption( 'stage_auto' ).SetValues( 'stage_auto.stagenum', IntToStr( stageNum ) ); result := GetQuery; end; function TSearchOption.GetQueryListByManual: TStringList; var sList: TStringList; i: Integer; begin sList := TStringList.Create; if FStageOptionList.IsUse = true then begin for i := 0 to FStageOptionList.Count - 1 do begin sList.Add( GetQuery( i ) ); end; end else begin sList.Add( GetQuery( -1 ) ); end; result := sList; end; function TSearchOption.GetQueryList(isAuto: Boolean): TStringList; begin if isAuto = true then begin result := GetQueryListByAuto; end else begin result := GetQueryListByManual; end; end; function TSearchOption.GetQueryListByAuto: TStringList; var i: Integer; stgOpt: TStageOptionPart; sList: TStringList; begin ClearStageNames; for i := 0 to High( ITEM_LIST_AUTO_STAGE_SEQ ) do begin FStageNames.Add( STAGE_NAME_LIST[ ITEM_LIST_AUTO_STAGE_SEQ[ i ] ] ); // end; stgOpt := TStageOptionPart.Create; stgOpt.SetUse( false ); AddSearchOption( 'stage', stgOpt ); sList := TStringList.Create; for i := 0 to High( ITEM_LIST_AUTO_STAGE_SEQ ) do begin GetOption( 'stage_auto' ).SetValues( 'stage_auto.stagenum', IntToStr( ITEM_LIST_AUTO_STAGE_SEQ[ i ] ) ); sList.Add( GetQuery ); end; result := sList; end; function TSearchOption.GetStageName(stageNum: Integer): String; begin result := FStageNames[ stageNum ]; end; function TSearchOption.GetStageNameList: TStringList; begin result := FStageNames; end; function TSearchOption.GetQuery: string; var sTagQuery: String; queryReader: TQueryReader; i: Integer; sList: TStringList; begin queryReader := TQueryReader.Create( FDBManager.GetDBMSName, 'insightviewer' ); sTagQuery := queryReader.GetQuery( 'template.viewer' ); sList := TStringList.Create; sList.Delimiter := '.'; for i := 0 to High( SOP_ITEM_SEQ ) do begin sList.DelimitedText := SOP_ITEM_SEQ[ i ]; sTagQuery := Options[ sList[ 0 ] ].InsertPartToQuery( sTagQuery, SOP_ITEM_SEQ[ i ], i ); end; queryReader.Free; result := sTagQuery; end; procedure TSearchOption.Init; begin FOptHash := TStrIntfHashMap.Create; end; function TSearchOption.IsAutoDetected: Boolean; var schOpt: ISearchOptionPart; begin schOpt := GetOption( 'stage_auto' ); result := schOpt.IsUse; end; procedure TSearchOption.SetDBManager(dbm: TAbsDBManager); begin FDBManager := dbm; end; procedure TSearchOption.SetStageOptionList(stageOptions: TStageOptionList); var i: Integer; begin FreeAndNil( FStageNames ); FStageNames := TStringList.Create; FStageOptionList := stageOptions; for i := 0 to FStageOptionList.Count - 1 do begin FStageNames.Add( FStageOptionList.GetStageOption( i ).StageName ); end; end; end.
unit Impressao_G800; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Edit, FMX.StdCtrls, FMX.Controls.Presentation, GEDIPrinter, //Esta unit inicializa o Modulo de impressao para G800 {$IFDEF __G800__} G800Interface, Data.Bind.GenData, Data.Bind.EngExt, Fmx.Bind.DBEngExt, System.Rtti, System.Bindings.Outputs, FMX.Colors, FMX.ListBox, Data.Bind.Components, Data.Bind.ObjectScope {$ENDIF} ; type TfrmImpressaoG800 = class(TForm) STATUS: TButton; PrototypeBindSource1: TPrototypeBindSource; BindingsList1: TBindingsList; LinkFillControlToField1: TLinkFillControlToField; ImageControl2: TImageControl; PanelMessage: TPanel; btnOK: TButton; lblMsg: TLabel; lblMsgCode: TLabel; CbBarCodeH: TComboBox; CbBarCodeW: TComboBox; CbQrCode: TComboBox; CbFont: TComboBox; CbSize: TComboBox; CbtnSublinhado: TColorButton; CbtnItalico: TColorButton; CbtnNegrito: TColorButton; cmdBarCode: TButton; cmdImpressaoG: TButton; Edit1: TEdit; lblMensagem: TLabel; lbTitulo2: TLabel; RdEsquerda: TRadioButton; RdCentro: TRadioButton; RdDireita: TRadioButton; Size: TLabel; cmdTexto: TButton; cmdImage: TButton; Label1: TLabel; Label3: TLabel; Label4: TLabel; BtnNegrito: TButton; BtnSublinhado: TButton; ImageControl1: TImageControl; BtnItalico: TButton; lbTitulo: TLabel; Font: TLabel; procedure cmdTesteImpressaoClick(Sender: TObject); procedure STATUSClick(Sender: TObject); procedure BtnNegritoClick(Sender: TObject); procedure BtnItalicoClick(Sender: TObject); procedure BtnSublinhadoClick(Sender: TObject); procedure cmdImpressaoGClick(Sender: TObject); procedure cmdImageClick(Sender: TObject); procedure RdEsquerdaChange(Sender: TObject); procedure RdCentroChange(Sender: TObject); procedure RdDireitaChange(Sender: TObject); procedure cmdTextoClick(Sender: TObject); procedure cmdBarCodeClick(Sender: TObject); private { Private declarations } function CentralizaTraco(strTitulo:string;NColunas:integer):string; public { Public declarations } procedure CleanText(limpaText: Boolean); end; var frmImpressaoG800: TfrmImpressaoG800; iCount:integer; pos: integer; neg: Boolean; ita: Boolean; sub: Boolean; textSize: Integer; bcHeight:integer; bcWidth:integer; const N_COLUNAS=32; implementation {$R *.fmx} procedure TfrmImpressaoG800.BtnItalicoClick(Sender: TObject); begin if CbtnItalico.Color = $FF000000 then begin CbtnItalico.Color:= $FF0000FF; ita:= True; end else begin CbtnItalico.Color := $FF000000; ita:= False; end; end; procedure TfrmImpressaoG800.CleanText(limpaText: Boolean); begin if limpaText then begin Edit1.Text := ''; RdCentro.IsChecked:=False; RdDireita.IsChecked:=False; RdEsquerda.IsChecked:=False; CbFont.ItemIndex := 0; CbSize.ItemIndex := 0; CbtnNegrito.Color := $FF000000; CbtnItalico.Color := $FF000000 ; CbtnSublinhado.Color := $FF000000; CbBarCodeW.ItemIndex := 0; CbBarCodeH.ItemIndex := 0; CbQrCode.ItemIndex := 0; Edit1.Text.Empty; end; end; procedure TfrmImpressaoG800.BtnNegritoClick(Sender: TObject); begin if CbtnNegrito.Color = $FF000000 then begin CbtnNegrito.Color := $FF0000FF; neg:=True; end else begin CbtnNegrito.Color := $FF000000; neg:=False; end; end; procedure TfrmImpressaoG800.BtnSublinhadoClick(Sender: TObject); begin if CbtnSublinhado.Color = $FF000000 then begin CbtnSublinhado.Color := $FF0000FF; sub:=True; end else begin CbtnSublinhado.Color := $FF000000; sub:=False; end; end; function TfrmImpressaoG800.CentralizaTraco(strTitulo:string;NColunas:integer):string; var i,iLen:integer; strAux:string; begin iLen:=(NColunas - length(strTitulo))div 2; if(NColunas <=0)then begin strAux:=strTitulo; end else begin strAux:=''; for I := 1 to iLen do strAux:=strAux+'='; strAux:=strAux+strTitulo; for I := 1 to NColunas - iLen -length(strTitulo)do strAux:=strAux+'='; end; result:=strAux; end; procedure TfrmImpressaoG800.cmdBarCodeClick(Sender: TObject); var qrCode2:string; code128:string; ean8:string; ean13:string; pdf417:string; i:integer; begin if CbBarCodeH.ItemIndex =0then begin bcHeight:=280; end else if CbBarCodeH.ItemIndex = 1 then begin bcHeight:=10; end else if CbBarCodeH.ItemIndex = 2 then begin bcHeight:=40; end else if CbBarCodeH.ItemIndex = 3 then begin bcHeight:=80; end else if CbBarCodeH.ItemIndex = 4 then begin bcHeight:=120; end else if CbBarCodeH.ItemIndex = 5 then begin bcHeight:=160; end else if CbBarCodeH.ItemIndex = 6 then begin bcHeight:=200; end else if CbBarCodeH.ItemIndex = 7 then begin bcHeight:=240; end else if CbBarCodeH.ItemIndex = 8 then begin bcHeight:=320; end else if CbBarCodeH.ItemIndex = 9 then begin bcHeight:=380; end; if CbBarCodeW.ItemIndex = 0 then begin bcWidth:=280; end else if CbBarCodeW.ItemIndex= 1 then begin bcWidth:=10; end else if CbBarCodeW.ItemIndex= 2 then begin bcWidth:=40; end else if CbBarCodeW.ItemIndex= 3 then begin bcWidth:=80; end else if CbBarCodeW.ItemIndex= 4 then begin bcWidth:=120; end else if CbBarCodeW.ItemIndex= 5 then begin bcWidth:=160; end else if CbBarCodeW.ItemIndex = 6 then begin bcWidth:=200; end else if CbBarCodeW.ItemIndex =7 then begin bcWidth:=240; end else if CbBarCodeW.ItemIndex= 8 then begin bcWidth:=320; end else if CbBarCodeW.ItemIndex= 9 then begin bcWidth:=380; end; //========= QRCODE qrCode2:=''; for i := 1 to 5 do qrCode2:=qrCode2+'12345678901234567890'; code128:='12345678901234567890'; ean8:='01234565'; ean13:='7891234567895'; pdf417:='000311111136511111125211111155'; if CbQrCode.ItemIndex = 0 then begin GertecPrinter.DrawBarCode(TJGEDI_PRNTR_e_BarCodeType.JavaClass.QR_CODE,bcHeight, bcWidth, qrCode2); end else if CbQrCode.ItemIndex = 1 then begin GertecPrinter.DrawBarCode(TJGEDI_PRNTR_e_BarCodeType.JavaClass.CODE_128,bcHeight, bcWidth, code128); end else if CbQrCode.ItemIndex = 2 then begin GertecPrinter.DrawBarCode(TJGEDI_PRNTR_e_BarCodeType.JavaClass.EAN_8,bcHeight, bcWidth, ean8); end else if CbQrCode.ItemIndex = 3 then begin GertecPrinter.DrawBarCode(TJGEDI_PRNTR_e_BarCodeType.JavaClass.EAN_13,bcHeight, bcWidth, ean13); end else if CbQrCode.ItemIndex = 4 then begin GertecPrinter.DrawBarCode(TJGEDI_PRNTR_e_BarCodeType.JavaClass.PDF_417,bcHeight, bcWidth, pdf417); end; GertecPrinter.printBlankLine(150); GertecPrinter.printOutput; end; procedure TfrmImpressaoG800.cmdImageClick(Sender: TObject); begin GertecPrinter.printImage( ImageControl1.Bitmap); GertecPrinter.printBlankLine(150); GertecPrinter.printOutput; end; procedure TfrmImpressaoG800.cmdImpressaoGClick(Sender: TObject); var i:integer; qrCode:string; begin try //========= GertecPrinter.textSize := 20; GertecPrinter.printString(CentralizaTraco('[Iniciando Impressao Imagem]',N_COLUNAS)); GertecPrinter.printOutput; GertecPrinter.printImage( ImageControl1.Bitmap); GertecPrinter.printBlankLine(50); GertecPrinter.printString(CentralizaTraco('[Fim Impressao Imagem]',N_COLUNAS)); //========= GertecPrinter.FlagBold := True; GertecPrinter.textSize := 30; GertecPrinter.PrintString(CENTRALIZADO,'CENTRALIZADO'); GertecPrinter.textSize := 40; GertecPrinter.PrintString(ESQUERDA,'ESQUERDA'); GertecPrinter.textSize := 20; GertecPrinter.PrintString(DIREITA,'DIREITA'); GertecPrinter.Alignment := CENTRALIZADO; GertecPrinter.PrintString(CentralizaTraco('[Escrita Negrito ('+inttostr(iCount)+')]',N_COLUNAS)); GertecPrinter.printBlankLine(20); GertecPrinter.FlagBold := False; GertecPrinter.FlagItalico := True; GertecPrinter.PrintString(CentralizaTraco('[Escrita Italico ('+inttostr(iCount)+')]',N_COLUNAS)); GertecPrinter.FlagItalico := False; GertecPrinter.printBlankLine(20); GertecPrinter.FlagSublinhado := True; GertecPrinter.PrintString(CentralizaTraco('[Escrita Sublinhado ('+inttostr(iCount)+')]',N_COLUNAS)); GertecPrinter.FlagSublinhado := False; GertecPrinter.printBlankLine(20); //========= GertecPrinter.FlagBold := True; GertecPrinter.PrintString(CentralizaTraco('[Codigo Barras CODE 128]',N_COLUNAS)); GertecPrinter.DrawBarCode(TJGEDI_PRNTR_e_BarCodeType.JavaClass.CODE_128,120,120,'12345678901234567890'); GertecPrinter.printBlankLine(20); //========= GertecPrinter.FlagBold := False; GertecPrinter.printString(CentralizaTraco('[Escrita Normal ('+inttostr(iCount)+')]',N_COLUNAS)); GertecPrinter.printOutput; GertecPrinter.printString(CentralizaTraco('[BlankLine 50]',N_COLUNAS)); GertecPrinter.printBlankLine(50); GertecPrinter.printString(CentralizaTraco('[Fim BlankLine 50]',N_COLUNAS)); //========= GertecPrinter.printString(CentralizaTraco('[Codigo Barras EAN13]',N_COLUNAS)); GertecPrinter.DrawBarCode(TJGEDI_PRNTR_e_BarCodeType.JavaClass.EAN_13,120,120,'7891234567895'); //========= GertecPrinter.printBlankLine(20); GertecPrinter.printString(CentralizaTraco('[Codigo Barras EAN8]',N_COLUNAS)); GertecPrinter.DrawBarCode(TJGEDI_PRNTR_e_BarCodeType.JavaClass.EAN_8,120,120,'01234565'); //========= GertecPrinter.printBlankLine(20); GertecPrinter.printString(CentralizaTraco('[Codigo Barras PDF417]',N_COLUNAS)); GertecPrinter.DrawBarCode(TJGEDI_PRNTR_e_BarCodeType.JavaClass.PDF_417,280,280,'003311112355111122421111254'); //========= QRCODE GertecPrinter.printBlankLine(20); GertecPrinter.printString(CentralizaTraco('[Codigo QRCode]',N_COLUNAS)); GertecPrinter.printBlankLine(20); qrCode:=''; for i := 1 to 5 do qrCode:=qrCode+'12345678901234567890'; GertecPrinter.DrawBarCode(TJGEDI_PRNTR_e_BarCodeType.JavaClass.QR_CODE,240,240,qrCode); GertecPrinter.printBlankLine(150); GertecPrinter.printOutput; inc(iCount); except on e: exception do begin GertecPrinter.printReInit; ShowMessage('Erro Impressao=>'+e.Message); end; end; end; procedure TfrmImpressaoG800.cmdTesteImpressaoClick(Sender: TObject); var i:integer; qrCode:string; begin try //========= GertecPrinter.printString(CentralizaTraco('[Iniciando Impressao Imagem]',N_COLUNAS)); GertecPrinter.printOutput; GertecPrinter.printImage( ImageControl1.Bitmap); GertecPrinter.printBlankLine(50); GertecPrinter.printString(CentralizaTraco('[Fim Impressao Imagem]',N_COLUNAS)); //========= GertecPrinter.FlagBold := True; GertecPrinter.textSize := 30; GertecPrinter.PrintString(CENTRALIZADO,'CENTRALIZADO'); GertecPrinter.textSize := 40; GertecPrinter.PrintString(ESQUERDA,'ESQUERDA'); GertecPrinter.textSize := 20; GertecPrinter.PrintString(DIREITA,'DIREITA'); GertecPrinter.Alignment := CENTRALIZADO; GertecPrinter.PrintString(CentralizaTraco('[Escrita Negrito ('+inttostr(iCount)+')]',N_COLUNAS)); GertecPrinter.printBlankLine(20); GertecPrinter.FlagBold := False; GertecPrinter.FlagItalico := True; GertecPrinter.PrintString(CentralizaTraco('[Escrita Italico ('+inttostr(iCount)+')]',N_COLUNAS)); GertecPrinter.FlagItalico := False; GertecPrinter.printBlankLine(20); GertecPrinter.FlagSublinhado := True; GertecPrinter.PrintString(CentralizaTraco('[Escrita Sublinhado ('+inttostr(iCount)+')]',N_COLUNAS)); GertecPrinter.FlagSublinhado := False; GertecPrinter.printBlankLine(20); //========= GertecPrinter.FlagBold := True; GertecPrinter.PrintString(CentralizaTraco('[Codigo Barras CODE 128]',N_COLUNAS)); GertecPrinter.DrawBarCode(TJGEDI_PRNTR_e_BarCodeType.JavaClass.CODE_128,120,120,'12345678901234567890'); GertecPrinter.printBlankLine(20); //========= GertecPrinter.FlagBold := False; GertecPrinter.printString(CentralizaTraco('[Escrita Normal ('+inttostr(iCount)+')]',N_COLUNAS)); GertecPrinter.printOutput; GertecPrinter.printString(CentralizaTraco('[BlankLine 50]',N_COLUNAS)); GertecPrinter.printBlankLine(50); GertecPrinter.printString(CentralizaTraco('[Fim BlankLine 50]',N_COLUNAS)); //========= GertecPrinter.printString(CentralizaTraco('[Codigo Barras EAN13]',N_COLUNAS)); GertecPrinter.DrawBarCode(TJGEDI_PRNTR_e_BarCodeType.JavaClass.EAN_13,120,120,'7891234567895'); //========= QRCODE GertecPrinter.printBlankLine(20); GertecPrinter.printString(CentralizaTraco('[Codigo QRCode]',N_COLUNAS)); GertecPrinter.printBlankLine(20); qrCode:=''; for i := 1 to 5 do qrCode:=qrCode+'12345678901234567890'; GertecPrinter.DrawBarCode(TJGEDI_PRNTR_e_BarCodeType.JavaClass.QR_CODE,240,240,qrCode); GertecPrinter.printBlankLine(150); GertecPrinter.printOutput; inc(iCount); except on e: exception do begin GertecPrinter.printReInit; ShowMessage('Erro Impressao=>'+e.Message); end; end; end; procedure TfrmImpressaoG800.cmdTextoClick(Sender: TObject); var TxtInput: string; begin if Edit1.Text = '' then begin ShowMessage('Digite um texto para imprimir'); end else begin if CbFont.ItemIndex = 0 then begin GertecPrinter.TextFamily := 0; end else if CbFont.ItemIndex = 1 then begin GertecPrinter.TextFamily := 1; end else if CbFont.ItemIndex = 2 then begin GertecPrinter.TextFamily := 2; end else if CbFont.ItemIndex = 3 then begin GertecPrinter.TextFamily := 3; end else if CbFont.ItemIndex = 4 then begin GertecPrinter.TextFamily := 4; end; TxtInput := Edit1.Text; if CbSize.ItemIndex = 0 then begin textSize:=60; end else if CbSize.ItemIndex = 1 then begin textSize:=20; end else if CbSize.ItemIndex = 2 then begin textSize:=30; end else if CbSize.ItemIndex = 3 then begin textSize:=40; end else if CbSize.ItemIndex = 4 then begin textSize:=50; end else if CbSize.ItemIndex = 5 then begin textSize:=70; end else if CbSize.ItemIndex = 6 then begin textSize:=80; end else if CbSize.ItemIndex = 7 then begin textSize:=90; end else if CbSize.ItemIndex = 8 then begin textSize:=100; end; GertecPrinter.textSize := textSize; if neg then begin GertecPrinter.FlagBold := True; end else begin GertecPrinter.FlagBold := False; end; if ita then begin GertecPrinter.FlagItalico := True; end else begin GertecPrinter.FlagItalico := False; end; if sub then begin GertecPrinter.FlagSublinhado := True; end else begin GertecPrinter.FlagSublinhado := False; end; if pos = 0 then begin GertecPrinter.PrintString(CENTRALIZADO,TxtInput); end else if pos = -1 then begin GertecPrinter.PrintString(ESQUERDA,TxtInput); end else if pos = 1 then begin GertecPrinter.PrintString(DIREITA,TxtInput); end else begin GertecPrinter.PrintString(CENTRALIZADO,TxtInput); end; GertecPrinter.printBlankLine(150); GertecPrinter.printOutput; end; end; procedure TfrmImpressaoG800.RdCentroChange(Sender: TObject); begin if RdCentro.Text = 'Centralizado' then begin pos:=0; end; end; procedure TfrmImpressaoG800.RdDireitaChange(Sender: TObject); begin if RdDireita.Text = 'Direita' then begin pos:=1; end; end; procedure TfrmImpressaoG800.RdEsquerdaChange(Sender: TObject); begin if RdEsquerda.Text = 'Esquerda' then begin pos:=-1; end; end; procedure TfrmImpressaoG800.STATUSClick(Sender: TObject); var result: string; begin result := GertecPrinter.StatusImpressora; ShowMessage( 'Status da Impressora'+#13#10#10 +result); end; end.
unit example; {$INCLUDE header.pas} implementation uses pisqpipe,windows; const MAX_BOARD=100; var board:array[0..MAX_BOARD-1,0..MAX_BOARD-1] of integer; seed:cardinal; procedure brain_init(); begin if (width<5)or(width>MAX_BOARD)or(height<5)or(height>MAX_BOARD) then begin pipeOut('ERROR size of the board'); exit; end; seed:=start_time; pipeOut('OK'); end; procedure brain_restart(); var x,y:integer; begin for x:=0 to width-1 do begin for y:=0 to height-1 do begin board[x][y]:=0; end; end; pipeOut('OK'); end; function isFree(x,y:integer):boolean; begin result:=(x>=0)and(y>=0)and(x<width)and(y<height)and(board[x][y]=0); end; procedure brain_my(x,y:integer); begin if isFree(x,y) then begin board[x][y]:=1; end else begin pipeOut('ERROR my move [%d,%d]',[x,y]); end; end; procedure brain_opponents(x,y:integer); begin if isFree(x,y) then begin board[x][y]:=2; end else begin pipeOut('ERROR opponent''s move [%d,%d]',[x,y]); end; end; procedure brain_block(x,y:integer); begin if isFree(x,y) then begin board[x][y]:=3; end else begin pipeOut('ERROR winning move [%d,%d]',[x,y]); end; end; function brain_takeback(x,y:integer):integer; begin if (x>=0)and(y>=0)and(x<width)and(y<height)and(board[x][y]<>0) then begin board[x][y]:=0; result:=0; end else result:=2; end; function rnd(n:cardinal):cardinal; begin seed:=word(314159*seed+2718281); result:=(seed * n) shr 16; end; procedure brain_turn(); var x,y,i:integer; begin i:=-1; repeat x:=rnd(width); y:=rnd(height); i:=i+1; if terminate>0 then exit; until isFree(x,y); if i>1 then pipeOut('DEBUG %d coordinates didn''t hit an empty field',[i]); do_mymove(x,y); end; procedure brain_end(); begin end; {$IFDEF DEBUG_EVAL} procedure brain_eval(x,y:integer); var dc:HDC; wnd:HWND; rc:TRECT; c:string; begin wnd:=GetForegroundWindow(); dc:= GetDC(wnd); GetClientRect(wnd,rc); str(board[x][y],c); TextOut(dc, rc.right-15, 3, PChar(c), 1); ReleaseDC(wnd,dc); end; {$ENDIF} initialization infotext:='name="Random", author="Petr Lastovicka", version="3.1", country="Czech Republic", www="http://web.quick.cz/lastp"' end.
(* * http 服务基本类型常量等 *) unit http_base; interface {$I in_iocp.inc} type // 请求方法 THttpMethod = ( hmUnknown, hmGet, hmPost, hmHead, hmConnect, hmDelete, hmPut, hmOptions, hmTrace ); // POST 文件的状态 THttpPostState = ( hpsUnknown, // 未知 hpsRequest, // 请求 hpsRecvData // 数据 ); // HTTP 表单类型 THttpContentType = ( hctUnknown, // 原始数据流 hctUrlEncoded, // application/x-www-form-urlencoded hctTextPlain, // text/plain hctMultiPart // multipart/form-data; boundary=... ); // 字符集(格式) THttpCharSet = ( hcsDefault, // 默认: CharSet=gb2312 hcsUTF8, // UTF-8 hcsURLEncode // UTF-8 URL Encode ); // form-data 的元素类型 TFormElementType = (fdtUnknown, fdtName, fdtFileName); // 变量类型 THttpFieldType = (hftString, hftInteger, hftFloat); // 请求头分类:30+5 个 // 为加快对 REQUEST_HEADERS 的查找,把常用的放前 TRequestHeaderType = ( rqhUnknown, rqhHost, rqhContentType, rqhContentLength, // 0..3 rqhConnection, rqhUserAgent, rqhCookie, rqhReferer, rqhRange, // 4..8 rqhIfMatch, rqhIfModifiedSince, rqhIfNoneMatch, rqhIfRange, // 9..12 rqhIfUnmodifiedSince, rqhDate, rqhUpgrade, rqhAccept, // 13..16 rqhAcceptCharset, rqhAcceptEncoding, rqhAcceptLang, rqhAcceptRanges, // 17..20 rqhAuthor, rqhCacheControl, rqhExpect, rqhFrom, rqhMaxForwards, // 21..25 rqhPragma, rqhProxyAuthor, rqhTE, rqhVia, rqhWarning, // 26..30 rqhWebSocketKey, rqhWebSocketProtocol, // webSocket, 31..32 rqhWebSocketVersion, rqhWebSocketExten, // webSocket, 33..34 rqhOrigin // webSocket, 33..34 ); // 响应头分类 TResponseHeaderType = ( rshUnknown, rshAcceptRanges, rshAge, rshAllow, rshCacheControl, // 0..4 rshConnection, rshContentEncoding, rshContentLang, rshContentLength, // 5..8 rshContentLocation, rshContentMD5, rshContentRange, rshContentType, // 9..12 rshDate, rshETag, rshExpires, rshLastModified, rshLocation, rshPragma, // 13..18 rshProxyAuthenticate, rshRefresh, rshRetryAfter, rshServer, // 19.22 rshSetCookie, rshTrailer, rshTransferEncoding, rshVary, rshVia, // 23..27 rshWarning, rshWWWAuthenticate, // 28..29 rshUpgrade, rshWebSocketAccept, rshWebSocketProtocol // webSocket ); // 文件/内容类型 PContentType = ^TContentType; TContentType = packed record Extension: String[10]; // 是单字节 ContentType: AnsiString; end; // 回车换行类型 TStrCRLF = array[0..1] of AnsiChar; PStrCRLF = ^TStrCRLF; TStrCRLF2 = array[0..3] of AnsiChar; PStrCRLF2 = ^TStrCRLF2; // Http 分块发送时的长度描述空间 TChunkSize = array[0..5] of AnsiChar; PChunkSize = ^TChunkSize; const CHAR_CR = AnsiChar(#13); // 回车 CHAR_LF = AnsiChar(#10); // 换行 CHAR_SP = AnsiChar(#32); // 空格 CHAR_TAB = AnsiChar(#9); // 制表符 CHAR_SC = AnsiChar(':'); // 分号 CHAR_SC2 = AnsiString(':'#32); // 分号 + 空格 QUE_MARK = AnsiChar('?'); // 问号 SEMICOLON = AnsiChar(';'); // 分号 STR_CRLF = AnsiString(#13#10); // 回车换行 STR_CRLF2 = AnsiString(#13#10#13#10); // 两个回车换行 HTTP_VER = AnsiString('HTTP/1.1'); // http 版本 HTTP_VER1 = AnsiString('HTTP/1.0'); // http 版本 {$IFDEF TRANSMIT_FILE} HTTP_SERVER_NAME = AnsiString('InIOCP/2.8t'); {$ELSE} HTTP_SERVER_NAME = AnsiString('InIOCP/2.8'); {$ENDIF} HTTP_SESSION_ID = AnsiString('InIOCP_SID'); HTTP_INVALID_SESSION = AnsiString('INVALID_SESSION'); // http/1.1 代理响应 HTTP_PROXY_RESPONSE = 'HTTP/1.1 200 Connection Established'#13#10'' + 'Proxy-agent: ' + HTTP_SERVER_NAME + #13#10#13#10; // 实体长度限制 20m MAX_CONTENT_LENGTH = 20480000; // 实体最大发送长度 2G MAX_TRANSMIT_LENGTH = 2147483646; // 字符集 HTTP_CHAR_SETS: array[THttpCharSet] of AnsiString = ( '; CharSet=gb2312', '; CharSet=utf-8', '; CharSet=utf-8' ); // http/1.1 命令表 METHOD_LIST: array[THttpMethod] of AnsiString = ( 'NONE', 'GET', 'POST', 'HEAD', 'CONNECT', 'DELETE', 'PUT', 'OPTIONS', 'TRACE' ); // 请求头名称(与 TRequestHeaderType 对应,用于查找 Header 类型) REQUEST_HEADERS: array[TRequestHeaderType] of AnsiString = ( 'NONE', 'HOST', 'CONTENT-TYPE', 'CONTENT-LENGTH', 'CONNECTION', 'USER-AGENT', 'COOKIE', 'REFERER', 'RANGE', 'IF-MATCH', 'IF-MODIFIED-SINCE', 'IF-NONE-MATCH', 'IF-RANGE', 'IF-UNMODIFIED-SINCE', 'DATE', 'UPGRADE', 'ACCEPT', 'ACCEPT-CHARSET', 'ACCEPT-ENCODING', 'ACCEPT-LANGUAGE', 'ACCEPT-RANGES', 'AUTHORIZATION', 'CACHE-CONTROL', 'EXPECT', 'FROM', 'MAX-FORWARDS', 'PRAGMA', 'PROXY-AUTHORIZATION', 'TE', 'VIA', 'WARNING', 'SEC-WEBSOCKET-KEY', 'SEC-WEBSOCKET-PROTOCOL', // WebSocket Protocol 'SEC-WEBSOCKET-VERSION', 'SEC-WEBSOCKET-EXTENSIONS', // WebSocket Protocol 'ORIGIN' // WebSocket Protocol ); // 响应头名称(与 TResponseHeaderType 对应,用于返回给客户端) RESPONSE_HEADERS: array[TResponseHeaderType] of AnsiString = ( 'None', 'Accept-Ranges', 'Age', 'Allow', 'Cache-Control', 'Connection', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-Location', 'Content-MD5', 'Content-Range', 'Content-Type', 'Date', 'Etag', 'Expires', 'Last-Modified', 'Location', 'Pragma', 'Proxy-Authenticate', 'Refresh', 'Retry-After', 'Server', 'Set-Cookie', 'Trailer', 'Transfer-Encoding', 'Vary', 'Via', 'Warning', 'WWW-Authenticate', 'Upgrade', 'Sec-WebSocket-Accept', 'Sec-WebSocket-Protocol' // WebSocket ); // 响应状态代码、含义 HTTP_STATES_100: array[0..1] of AnsiString = ( ' 100 Continue', ' 101 Switching Protocols' ); HTTP_STATES_200: array[0..6] of AnsiString = ( ' 200 OK', ' 201 Created', ' 202 Accepted', ' 203 Non-Authoritative Information', ' 204 No Content', ' 205 Reset Content', ' 206 Partial Content' ); HTTP_STATES_300: array[0..7] of AnsiString = ( ' 300 Multiple Choices', ' 301 Moved Permanently', ' 302 Found', ' 303 See Other', ' 304 Not Modified', ' 305 Use Proxy', ' 306 None', ' 307 Temporary Redirect' ); HTTP_STATES_400: array[0..17] of AnsiString = ( ' 400 Bad Request', ' 401 Unauthorized', ' 402 Payment Required', ' 403 Forbidden', ' 404 Not Found', ' 405 Method Not Allowed', ' 406 Not Acceptable', ' 407 Proxy Authentication Required', ' 408 Request Time-out', ' 409 Conflict', ' 410 Gone', ' 411 Length Required', ' 412 Precondition Failed', ' 413 Request Entity Too Large', ' 414 Request-URI Too Large', ' 415 Unsupported Media Type', ' 416 Requested range not satisfiable', ' 417 Expectation Failed' ); HTTP_STATES_500: array[0..5] of AnsiString = ( ' 500 Internal Server Error', ' 501 Not Implemented', ' 502 Bad Gateway', ' 503 Service Unavailable', ' 504 Gateway Time-out', ' 505 HTTP Version Not Supported' ); // 文件/内容类型(常用的置前) CONTENT_TYPES: array[0..321] of TContentType = ( (Extension: '.*'; ContentType: 'application/octet-stream'), (Extension: '.htm'; ContentType: 'text/html'), (Extension: '.html'; ContentType: 'text/html'), (Extension: '.css'; ContentType: 'text/css'), (Extension: '.jpg'; ContentType: 'image/jpeg'), (Extension: '.jpeg'; ContentType: 'image/jpeg'), (Extension: '.js'; ContentType: 'application/x-javascript'), (Extension: '.jsp'; ContentType: 'text/html'), (Extension: '.mp3'; ContentType: 'audio/mp3'), (Extension: '.mp4'; ContentType: 'video/mpeg4'), (Extension: '.mpeg'; ContentType: 'video/mpg'), (Extension: '.mpg'; ContentType: 'video/mpg'), (Extension: '.a11'; ContentType: 'application/x-a11'), (Extension: '.acp'; ContentType: 'audio/x-mei-aac'), (Extension: '.ai'; ContentType: 'application/postscript'), (Extension: '.aif'; ContentType: 'audio/aiff'), (Extension: '.aifc'; ContentType: 'audio/aiff'), (Extension: '.aiff'; ContentType: 'audio/aiff'), (Extension: '.anv'; ContentType: 'application/x-anv'), (Extension: '.apk'; ContentType: 'application/vnd.android.package-archive'), (Extension: '.asa'; ContentType: 'text/asa'), (Extension: '.asf'; ContentType: 'video/x-ms-asf'), (Extension: '.asp'; ContentType: 'text/asp'), (Extension: '.asx'; ContentType: 'video/x-ms-asf'), (Extension: '.au'; ContentType: 'audio/basic'), (Extension: '.avi'; ContentType: 'video/avi'), (Extension: '.awf'; ContentType: 'application/vnd.adobe.workflow'), (Extension: '.biz'; ContentType: 'text/xml'), (Extension: '.bmp'; ContentType: 'application/x-bmp'), (Extension: '.bot'; ContentType: 'application/x-bot'), (Extension: '.c4t'; ContentType: 'application/x-c4t'), (Extension: '.c90'; ContentType: 'application/x-c90'), (Extension: '.cal'; ContentType: 'application/x-cals'), (Extension: '.cat'; ContentType: 'application/vnd.ms-pki.seccat'), (Extension: '.cdf'; ContentType: 'application/x-netcdf'), (Extension: '.cdr'; ContentType: 'application/x-cdr'), (Extension: '.cel'; ContentType: 'application/x-cel'), (Extension: '.cer'; ContentType: 'application/x-x509-ca-cert'), (Extension: '.cg4'; ContentType: 'application/x-g4'), (Extension: '.cgm'; ContentType: 'application/x-cgm'), (Extension: '.cit'; ContentType: 'application/x-cit'), (Extension: '.class'; ContentType: 'java/*'), (Extension: '.cml'; ContentType: 'text/xml'), (Extension: '.cmp'; ContentType: 'application/x-cmp'), (Extension: '.cmx'; ContentType: 'application/x-cmx'), (Extension: '.cot'; ContentType: 'application/x-cot'), (Extension: '.crl'; ContentType: 'application/pkix-crl'), (Extension: '.crt'; ContentType: 'application/x-x509-ca-cert'), (Extension: '.csi'; ContentType: 'application/x-csi'), (Extension: '.cut'; ContentType: 'application/x-cut'), (Extension: '.dbf'; ContentType: 'application/x-dbf'), (Extension: '.dbm'; ContentType: 'application/x-dbm'), (Extension: '.dbx'; ContentType: 'application/x-dbx'), (Extension: '.dcd'; ContentType: 'text/xml'), (Extension: '.dcx'; ContentType: 'application/x-dcx'), (Extension: '.der'; ContentType: 'application/x-x509-ca-cert'), (Extension: '.dgn'; ContentType: 'application/x-dgn'), (Extension: '.dib'; ContentType: 'application/x-dib'), (Extension: '.dll'; ContentType: 'application/x-msdownload'), (Extension: '.doc'; ContentType: 'application/msword'), (Extension: '.dot'; ContentType: 'application/msword'), (Extension: '.drw'; ContentType: 'application/x-drw'), (Extension: '.dtd'; ContentType: 'text/xml'), (Extension: '.dwf'; ContentType: 'Model/vnd.dwf'), (Extension: '.dwg'; ContentType: 'application/x-dwg'), (Extension: '.dxb'; ContentType: 'application/x-dxb'), (Extension: '.dxf'; ContentType: 'application/x-dxf'), (Extension: '.edn'; ContentType: 'application/vnd.adobe.edn'), (Extension: '.emf'; ContentType: 'application/x-emf'), (Extension: '.eml'; ContentType: 'message/rfc822'), (Extension: '.ent'; ContentType: 'text/xml'), (Extension: '.epi'; ContentType: 'application/x-epi'), (Extension: '.eps'; ContentType: 'application/postscript'), (Extension: '.etd'; ContentType: 'application/x-ebx'), (Extension: '.exe'; ContentType: 'application/x-msdownload'), (Extension: '.fax'; ContentType: 'image/fax'), (Extension: '.fdf'; ContentType: 'application/vnd.fdf'), (Extension: '.fif'; ContentType: 'application/fractals'), (Extension: '.fo'; ContentType: 'text/xml'), (Extension: '.frm'; ContentType: 'application/x-frm'), (Extension: '.g4'; ContentType: 'application/x-g4'), (Extension: '.gbr'; ContentType: 'application/x-gbr'), (Extension: '.gif'; ContentType: 'image/gif'), (Extension: '.gl2'; ContentType: 'application/x-gl2'), (Extension: '.gp4'; ContentType: 'application/x-gp4'), (Extension: '.hgl'; ContentType: 'application/x-hgl'), (Extension: '.hmr'; ContentType: 'application/x-hmr'), (Extension: '.hpg'; ContentType: 'application/x-hpgl'), (Extension: '.hpl'; ContentType: 'application/x-hpl'), (Extension: '.hqx'; ContentType: 'application/mac-binhex40'), (Extension: '.hrf'; ContentType: 'application/x-hrf'), (Extension: '.hta'; ContentType: 'application/hta'), (Extension: '.htc'; ContentType: 'text/x-component'), (Extension: '.htt'; ContentType: 'text/webviewhtml'), (Extension: '.htx'; ContentType: 'text/html'), (Extension: '.icb'; ContentType: 'application/x-icb'), (Extension: '.ico'; ContentType: 'image/x-icon'), (Extension: '.iff'; ContentType: 'application/x-iff'), (Extension: '.ig4'; ContentType: 'application/x-g4'), (Extension: '.igs'; ContentType: 'application/x-igs'), (Extension: '.iii'; ContentType: 'application/x-iphone'), (Extension: '.img'; ContentType: 'application/x-img'), (Extension: '.ins'; ContentType: 'application/x-internet-signup'), (Extension: '.ipa'; ContentType: 'application/vnd.iphone'), (Extension: '.isp'; ContentType: 'application/x-internet-signup'), (Extension: '.IVF'; ContentType: 'video/x-ivf'), (Extension: '.java'; ContentType: 'java/*'), (Extension: '.jfif'; ContentType: 'image/jpeg'), (Extension: '.jpe'; ContentType: 'image/jpeg'), (Extension: '.la1'; ContentType: 'audio/x-liquid-file'), (Extension: '.lar'; ContentType: 'application/x-laplayer-reg'), (Extension: '.latex'; ContentType: 'application/x-latex'), (Extension: '.lavs'; ContentType: 'audio/x-liquid-secure'), (Extension: '.lbm'; ContentType: 'application/x-lbm'), (Extension: '.lmsff'; ContentType: 'audio/x-la-lms'), (Extension: '.ls'; ContentType: 'application/x-javascript'), (Extension: '.ltr'; ContentType: 'application/x-ltr'), (Extension: '.m1v'; ContentType: 'video/x-mpeg'), (Extension: '.m2v'; ContentType: 'video/x-mpeg'), (Extension: '.m3u'; ContentType: 'audio/mpegurl'), (Extension: '.m4e'; ContentType: 'video/mpeg4'), (Extension: '.mac'; ContentType: 'application/x-mac'), (Extension: '.man'; ContentType: 'application/x-troff-man'), (Extension: '.math'; ContentType: 'text/xml'), (Extension: '.mdb'; ContentType: 'application/msaccess'), (Extension: '.mfp'; ContentType: 'application/x-shockwave-flash'), (Extension: '.mht'; ContentType: 'message/rfc822'), (Extension: '.mhtml'; ContentType: 'message/rfc822'), (Extension: '.mi'; ContentType: 'application/x-mi'), (Extension: '.mid'; ContentType: 'audio/mid'), (Extension: '.midi'; ContentType: 'audio/mid'), (Extension: '.mil'; ContentType: 'application/x-mil'), (Extension: '.mml'; ContentType: 'text/xml'), (Extension: '.mnd'; ContentType: 'audio/x-musicnet-download'), (Extension: '.mns'; ContentType: 'audio/x-musicnet-stream'), (Extension: '.mocha'; ContentType: 'application/x-javascript'), (Extension: '.movie'; ContentType: 'video/x-sgi-movie'), (Extension: '.mp1'; ContentType: 'audio/mp1'), (Extension: '.mp2'; ContentType: 'audio/mp2'), (Extension: '.mp2v'; ContentType: 'video/mpeg'), (Extension: '.mpa'; ContentType: 'video/x-mpg'), (Extension: '.mpd'; ContentType: 'application/vnd.ms-project'), (Extension: '.mpe'; ContentType: 'video/x-mpeg'), (Extension: '.mpga'; ContentType: 'audio/rn-mpeg'), (Extension: '.mpp'; ContentType: 'application/vnd.ms-project'), (Extension: '.mps'; ContentType: 'video/x-mpeg'), (Extension: '.mpt'; ContentType: 'application/vnd.ms-project'), (Extension: '.mpv'; ContentType: 'video/mpg'), (Extension: '.mpv2'; ContentType: 'video/mpeg'), (Extension: '.mpw'; ContentType: 'application/vnd.ms-project'), (Extension: '.mpx'; ContentType: 'application/vnd.ms-project'), (Extension: '.mtx'; ContentType: 'text/xml'), (Extension: '.mxp'; ContentType: 'application/x-mmxp'), (Extension: '.net'; ContentType: 'image/pnetvue'), (Extension: '.nrf'; ContentType: 'application/x-nrf'), (Extension: '.nws'; ContentType: 'message/rfc822'), (Extension: '.odc'; ContentType: 'text/x-ms-odc'), (Extension: '.out'; ContentType: 'application/x-out'), (Extension: '.p10'; ContentType: 'application/pkcs10'), (Extension: '.p12'; ContentType: 'application/x-pkcs12'), (Extension: '.p7b'; ContentType: 'application/x-pkcs7-certificates'), (Extension: '.p7c'; ContentType: 'application/pkcs7-mime'), (Extension: '.p7m'; ContentType: 'application/pkcs7-mime'), (Extension: '.p7r'; ContentType: 'application/x-pkcs7-certreqresp'), (Extension: '.p7s'; ContentType: 'application/pkcs7-signature'), (Extension: '.pc5'; ContentType: 'application/x-pc5'), (Extension: '.pci'; ContentType: 'application/x-pci'), (Extension: '.pcl'; ContentType: 'application/x-pcl'), (Extension: '.pcx'; ContentType: 'application/x-pcx'), (Extension: '.pdf'; ContentType: 'application/pdf'), (Extension: '.pdx'; ContentType: 'application/vnd.adobe.pdx'), (Extension: '.pfx'; ContentType: 'application/x-pkcs12'), (Extension: '.pgl'; ContentType: 'application/x-pgl'), (Extension: '.pic'; ContentType: 'application/x-pic'), (Extension: '.pko'; ContentType: 'application/vnd.ms-pki.pko'), (Extension: '.pl'; ContentType: 'application/x-perl'), (Extension: '.plg'; ContentType: 'text/html'), (Extension: '.pls'; ContentType: 'audio/scpls'), (Extension: '.plt'; ContentType: 'application/x-plt'), (Extension: '.png'; ContentType: 'image/png'), (Extension: '.pot'; ContentType: 'application/vnd.ms-powerpoint'), (Extension: '.ppa'; ContentType: 'application/vnd.ms-powerpoint'), (Extension: '.ppm'; ContentType: 'application/x-ppm'), (Extension: '.pps'; ContentType: 'application/vnd.ms-powerpoint'), (Extension: '.ppt'; ContentType: 'application/vnd.ms-powerpoint'), (Extension: '.pr'; ContentType: 'application/x-pr'), (Extension: '.prf'; ContentType: 'application/pics-rules'), (Extension: '.prn'; ContentType: 'application/x-prn'), (Extension: '.prt'; ContentType: 'application/x-prt'), (Extension: '.ps'; ContentType: 'application/postscript'), (Extension: '.ptn'; ContentType: 'application/x-ptn'), (Extension: '.pwz'; ContentType: 'application/vnd.ms-powerpoint'), (Extension: '.r3t'; ContentType: 'text/vnd.rn-realtext3d'), (Extension: '.ra'; ContentType: 'audio/vnd.rn-realaudio'), (Extension: '.ram'; ContentType: 'audio/x-pn-realaudio'), (Extension: '.ras'; ContentType: 'application/x-ras'), (Extension: '.rat'; ContentType: 'application/rat-file'), (Extension: '.rdf'; ContentType: 'text/xml'), (Extension: '.rec'; ContentType: 'application/vnd.rn-recording'), (Extension: '.red'; ContentType: 'application/x-red'), (Extension: '.rgb'; ContentType: 'application/x-rgb'), (Extension: '.rjs'; ContentType: 'application/vnd.rn-realsystem-rjs'), (Extension: '.rjt'; ContentType: 'application/vnd.rn-realsystem-rjt'), (Extension: '.rlc'; ContentType: 'application/x-rlc'), (Extension: '.rle'; ContentType: 'application/x-rle'), (Extension: '.rm'; ContentType: 'application/vnd.rn-realmedia'), (Extension: '.rmf'; ContentType: 'application/vnd.adobe.rmf'), (Extension: '.rmi'; ContentType: 'audio/mid'), (Extension: '.rmj'; ContentType: 'application/vnd.rn-realsystem-rmj'), (Extension: '.rmm'; ContentType: 'audio/x-pn-realaudio'), (Extension: '.rmp'; ContentType: 'application/vnd.rn-rn_music_package'), (Extension: '.rms'; ContentType: 'application/vnd.rn-realmedia-secure'), (Extension: '.rmvb'; ContentType: 'application/vnd.rn-realmedia-vbr'), (Extension: '.rmx'; ContentType: 'application/vnd.rn-realsystem-rmx'), (Extension: '.rnx'; ContentType: 'application/vnd.rn-realplayer'), (Extension: '.rp'; ContentType: 'image/vnd.rn-realpix'), (Extension: '.rpm'; ContentType: 'audio/x-pn-realaudio-plugin'), (Extension: '.rsml'; ContentType: 'application/vnd.rn-rsml'), (Extension: '.rt'; ContentType: 'text/vnd.rn-realtext'), (Extension: '.rtf'; ContentType: 'application/msword'), (Extension: '.rv'; ContentType: 'video/vnd.rn-realvideo'), (Extension: '.sam'; ContentType: 'application/x-sam'), (Extension: '.sat'; ContentType: 'application/x-sat'), (Extension: '.sdp'; ContentType: 'application/sdp'), (Extension: '.sdw'; ContentType: 'application/x-sdw'), (Extension: '.sis'; ContentType: 'application/vnd.symbian.install'), (Extension: '.sisx'; ContentType: 'application/vnd.symbian.install'), (Extension: '.sit'; ContentType: 'application/x-stuffit'), (Extension: '.slb'; ContentType: 'application/x-slb'), (Extension: '.sld'; ContentType: 'application/x-sld'), (Extension: '.slk'; ContentType: 'drawing/x-slk'), (Extension: '.smi'; ContentType: 'application/smil'), (Extension: '.smil'; ContentType: 'application/smil'), (Extension: '.smk'; ContentType: 'application/x-smk'), (Extension: '.snd'; ContentType: 'audio/basic'), (Extension: '.sol'; ContentType: 'text/plain'), (Extension: '.sor'; ContentType: 'text/plain'), (Extension: '.spc'; ContentType: 'application/x-pkcs7-certificates'), (Extension: '.spl'; ContentType: 'application/futuresplash'), (Extension: '.spp'; ContentType: 'text/xml'), (Extension: '.ssm'; ContentType: 'application/streamingmedia'), (Extension: '.sst'; ContentType: 'application/vnd.ms-pki.certstore'), (Extension: '.stl'; ContentType: 'application/vnd.ms-pki.stl'), (Extension: '.stm'; ContentType: 'text/html'), (Extension: '.sty'; ContentType: 'application/x-sty'), (Extension: '.svg'; ContentType: 'text/xml'), (Extension: '.swf'; ContentType: 'application/x-shockwave-flash'), (Extension: '.tdf'; ContentType: 'application/x-tdf'), (Extension: '.tg4'; ContentType: 'application/x-tg4'), (Extension: '.tga'; ContentType: 'application/x-tga'), (Extension: '.tif'; ContentType: 'image/tiff'), (Extension: '.tiff'; ContentType: 'image/tiff'), (Extension: '.tld'; ContentType: 'text/xml'), (Extension: '.top'; ContentType: 'drawing/x-top'), (Extension: '.torrent'; ContentType: 'application/x-bittorrent'), (Extension: '.tsd'; ContentType: 'text/xml'), (Extension: '.txt'; ContentType: 'text/plain'), (Extension: '.uin'; ContentType: 'application/x-icq'), (Extension: '.uls'; ContentType: 'text/iuls'), (Extension: '.vcf'; ContentType: 'text/x-vcard'), (Extension: '.vda'; ContentType: 'application/x-vda'), (Extension: '.vdx'; ContentType: 'application/vnd.visio'), (Extension: '.vml'; ContentType: 'text/xml'), (Extension: '.vpg'; ContentType: 'application/x-vpeg005'), (Extension: '.vsd'; ContentType: 'application/vnd.visio'), (Extension: '.vss'; ContentType: 'application/vnd.visio'), (Extension: '.vst'; ContentType: 'application/vnd.visio'), (Extension: '.vsw'; ContentType: 'application/vnd.visio'), (Extension: '.vsx'; ContentType: 'application/vnd.visio'), (Extension: '.vtx'; ContentType: 'application/vnd.visio'), (Extension: '.vxml'; ContentType: 'text/xml'), (Extension: '.wav'; ContentType: 'audio/wav'), (Extension: '.wax'; ContentType: 'audio/x-ms-wax'), (Extension: '.wb1'; ContentType: 'application/x-wb1'), (Extension: '.wb2'; ContentType: 'application/x-wb2'), (Extension: '.wb3'; ContentType: 'application/x-wb3'), (Extension: '.wbmp'; ContentType: 'image/vnd.wap.wbmp'), (Extension: '.wiz'; ContentType: 'application/msword'), (Extension: '.wk3'; ContentType: 'application/x-wk3'), (Extension: '.wk4'; ContentType: 'application/x-wk4'), (Extension: '.wkq'; ContentType: 'application/x-wkq'), (Extension: '.wks'; ContentType: 'application/x-wks'), (Extension: '.wm'; ContentType: 'video/x-ms-wm'), (Extension: '.wma'; ContentType: 'audio/x-ms-wma'), (Extension: '.wmd'; ContentType: 'application/x-ms-wmd'), (Extension: '.wmf'; ContentType: 'application/x-wmf'), (Extension: '.wml'; ContentType: 'text/vnd.wap.wml'), (Extension: '.wmv'; ContentType: 'video/x-ms-wmv'), (Extension: '.wmx'; ContentType: 'video/x-ms-wmx'), (Extension: '.wmz'; ContentType: 'application/x-ms-wmz'), (Extension: '.wp6'; ContentType: 'application/x-wp6'), (Extension: '.wpd'; ContentType: 'application/x-wpd'), (Extension: '.wpg'; ContentType: 'application/x-wpg'), (Extension: '.wpl'; ContentType: 'application/vnd.ms-wpl'), (Extension: '.wq1'; ContentType: 'application/x-wq1'), (Extension: '.wr1'; ContentType: 'application/x-wr1'), (Extension: '.wri'; ContentType: 'application/x-wri'), (Extension: '.wrk'; ContentType: 'application/x-wrk'), (Extension: '.ws'; ContentType: 'application/x-ws'), (Extension: '.ws2'; ContentType: 'application/x-ws'), (Extension: '.wsc'; ContentType: 'text/scriptlet'), (Extension: '.wsdl'; ContentType: 'text/xml'), (Extension: '.wvx'; ContentType: 'video/x-ms-wvx'), (Extension: '.x_b'; ContentType: 'application/x-x_b'), (Extension: '.x_t'; ContentType: 'application/x-x_t'), (Extension: '.xap'; ContentType: 'application/x-silverlight-app'), (Extension: '.xdp'; ContentType: 'application/vnd.adobe.xdp'), (Extension: '.xdr'; ContentType: 'text/xml'), (Extension: '.xfd'; ContentType: 'application/vnd.adobe.xfd'), (Extension: '.xfdf'; ContentType: 'application/vnd.adobe.xfdf'), (Extension: '.xhtml'; ContentType: 'text/html'), (Extension: '.xls'; ContentType: 'application/vnd.ms-excel'), (Extension: '.xlw'; ContentType: 'application/x-xlw'), (Extension: '.xml'; ContentType: 'text/xml'), (Extension: '.xpl'; ContentType: 'audio/scpls'), (Extension: '.xq'; ContentType: 'text/xml'), (Extension: '.xql'; ContentType: 'text/xml'), (Extension: '.xquery'; ContentType: 'text/xml'), (Extension: '.xsd'; ContentType: 'text/xml'), (Extension: '.xsl'; ContentType: 'text/xml'), (Extension: '.xslt'; ContentType: 'text/xml'), (Extension: '.xwd'; ContentType: 'application/x-xwd') ); implementation end.
unit VisualClassesHandler; interface uses VoyagerInterfaces, Classes, IniClasses, Controls, VisualClassManager, VCLUtils; type TVisualClassesHandler = class( TInterfacedObject, IMetaURLHandler, IURLHandler ) // IMetaURLHandler private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; // IURLHandler private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( const URLHandler : IMasterURLHandler ); private fMasterURLHandler : IMasterURLHandler; fCurrClass : TVisualClass; fCurrClassId : integer; end; const tidMetaHandler_VisualClassesHandler = 'VisualClassesHandler'; const evnAnswerVisualClassData = 7000; type TValueType = (vtInteger, vtBoolean, vtString); type TVisualClassItem = record ClassId : integer; ValueName : string; Section : string; case ValueType : TValueType of vtInteger : ( IntValue : integer; IntDefValue : integer ); vtBoolean : ( BoolValue : boolean; BoolDefValue : boolean ); vtString : ( StrValue : string[255]; StrDefValue : string[255] ); end; // Useful functions. (The best way to use this.) function ReadInteger( ClassId : integer; Section, Value : string; DefValue : integer; MasterHandler : IURLHandler ) : integer; function ReadBoolean( ClassId : integer; Section, Value : string; DefValue : boolean; MasterHandler : IURLHandler ) : boolean; function ReadString ( ClassId : integer; Section, Value : string; DefValue : string; MasterHandler : IURLHandler ) : string; implementation uses VoyagerEvents, LocalCacheManager; // TVisualClassesHandler function TVisualClassesHandler.getName : string; begin result := tidMetaHandler_VisualClassesHandler; end; function TVisualClassesHandler.getOptions : TURLHandlerOptions; begin result := [hopNonVisual]; end; function TVisualClassesHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TVisualClassesHandler.Instantiate : IURLHandler; begin result := self; end; function TVisualClassesHandler.HandleURL( URL : TURL ) : TURLHandlingResult; begin result := urlNotHandled; end; function TVisualClassesHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; var Item : TVisualClassItem absolute info; //ClassesPath : string; begin if EventId = evnAnswerVisualClassData then begin if fCurrClassId <> Item.ClassId then begin fCurrClassId := Item.ClassId; fCurrClass := LocalCacheManager.ClassManager.ClassById[fCurrClassId]; end; case Item.ValueType of vtInteger : if fCurrClass <> nil then Item.IntValue := fCurrClass.ReadInteger( Item.Section, Item.ValueName, Item.IntDefValue ) else Item.IntValue := Item.IntDefValue; vtBoolean : if fCurrClass <> nil then Item.BoolValue := fCurrClass.ReadBool( Item.Section, Item.ValueName, Item.BoolDefValue ) else Item.BoolValue := Item.BoolDefValue; vtString : if fCurrClass <> nil then Item.StrValue := fCurrClass.ReadString( Item.Section, Item.ValueName, Item.StrDefValue ) else Item.StrValue := Item.StrDefValue; end; result := evnHandled; end else begin result := evnNotHandled; if EventId = evnShutDown then fMasterURLHandler := nil //.rag end; end; function TVisualClassesHandler.getControl : TControl; begin result := nil; end; procedure TVisualClassesHandler.setMasterURLHandler( const URLHandler : IMasterURLHandler ); begin fMasterURLHandler := URLHandler; end; // Useful functions function ReadInteger( ClassId : integer; Section, Value : string; DefValue : integer; MasterHandler : IURLHandler ) : integer; var Item : TVisualClassItem; begin Item.ClassId := ClassId; Item.ValueName := Value; Item.Section := Section; Item.ValueType := vtInteger; Item.IntDefValue := DefValue; MasterHandler.HandleEvent( evnAnswerVisualClassData, Item ); result := Item.IntValue; end; function ReadBoolean( ClassId : integer; Section, Value : string; DefValue : boolean; MasterHandler : IURLHandler ) : boolean; var Item : TVisualClassItem; begin Item.ClassId := ClassId; Item.ValueName := Value; Item.Section := Section; Item.ValueType := vtBoolean; Item.BoolDefValue := DefValue; MasterHandler.HandleEvent( evnAnswerVisualClassData, Item ); result := Item.BoolValue; end; function ReadString( ClassId : integer; Section, Value : string; DefValue : string; MasterHandler : IURLHandler ) : string; var Item : TVisualClassItem; begin Item.ClassId := ClassId; Item.ValueName := Value; Item.Section := Section; Item.ValueType := vtString; Item.StrDefValue := DefValue; MasterHandler.HandleEvent( evnAnswerVisualClassData, Item ); result := Item.StrValue; end; end.
unit UDMAuth; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, UFuncoes; type TDMAuth = class(TDataModule) Conexao: TFDConnection; QrGlobal: TFDQuery; private { Private declarations } public { Public declarations } class function validUser(const aUser, aPass: String; out UserID: Integer; out Roles: String): boolean; end; var DMAuth: TDMAuth; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TDMAuth } class function TDMAuth.validUser(const aUser, aPass: String; out UserID: Integer; out Roles: String): boolean; var LocalInstance: TDMAuth; senha: String; I: Integer; xSql: String; begin result:=False; Senha:=UFuncoes.criptografaCesar(aPass,3,False); LocalInstance:= TDMAuth.Create(nil); xSql:='Select * from USUARIO where SENHA='+QuotedStr(Senha); Try Try LocalInstance.QrGlobal.Close; LocalInstance.QrGlobal.SQL.Text:=xSql; LocalInstance.QrGlobal.Open(); result:=not LocalInstance.QrGlobal.IsEmpty; if result then Begin UserID:=LocalInstance.QrGlobal.FieldByName('ID').AsInteger; for I := 16 to LocalInstance.QrGlobal.Fields.Count-1 do Begin if LocalInstance.QrGlobal.Fields[i].AsString='V' then Roles:=Roles+(LocalInstance.QrGlobal.Fields[i].FieldName)+'|'; End; End; Except result:=False; End; Finally LocalInstance.QrGlobal.Close; LocalInstance.Conexao.Close; LocalInstance.Free; End; end; end.
{******************************************************************************* 作者: dmzn@163.com 2007-10-09 描述: 系统服务器常量定义 *******************************************************************************} unit USysService; {$I Link.inc} interface uses Windows, Classes, SysUtils, FZSale_Intf; const {*结果动作*} cAction_None = $20; //无动作 cAction_Jump = $21; //跳转 cAction_Hint = $22; //提示 cAction_Warn = $23; //警告 cAction_Error = $25; //错误 cLevel_Master = $22; //店长 cLevel_Employer = $29; //员工 cChannel_DB = $0010; //数据通道 cChannel_Conn = $0022; //连接通道 cService_DB = 'SrvDB'; //数据服务 cService_Conn = 'SrvConn'; //连接服务 function MakeSrvResult: SrvResult; //结果对象 resourcestring {*执行结果*} cAction_Succ = 'Succ'; cAction_Fail = 'Fail'; {*终端版本*} cVersion_DBSync = '111030'; cVersion_Client = '111030'; implementation //Desc: 生成结果对象并初始化 function MakeSrvResult: SrvResult; begin Result := SrvResult.Create; with Result do begin Re_sult := False; Action := cAction_None; DataStr := ''; DataInt := 0; end; end; end.
{*********************************************************} {* VPSQLDS.PAS 1.03 *} {*********************************************************} {* ***** BEGIN LICENSE BLOCK ***** *} {* Version: MPL 1.1 *} {* *} {* The contents of this file are subject to the Mozilla Public License *} {* Version 1.1 (the "License"); you may not use this file except in *} {* compliance with the License. You may obtain a copy of the License at *} {* http://www.mozilla.org/MPL/ *} {* *} {* Software distributed under the License is distributed on an "AS IS" basis, *} {* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License *} {* for the specific language governing rights and limitations under the *} {* License. *} {* *} {* The Original Code is TurboPower Visual PlanIt *} {* *} {* The Initial Developer of the Original Code is TurboPower Software *} {* *} {* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *} {* TurboPower Software Inc. All Rights Reserved. *} {* *} {* Contributor(s): *} {* Hannes Danzl *} {* *} {* ***** END LICENSE BLOCK ***** *} {This unit was provided by Hannes Danzl and is used here with permission } // implements a Visual PlanIt datastore for SQL databases. uses interfaced // tdataset descendants to create datasets of different dbengines and // descendants of TBaseSQLDialect for being as independent from the sql // dialect as possible unit VPSQLDS; interface uses classes, VPSQLDialect, db, sysutils, vpDBDs, VPDbIntf, dialogs, vpConst, vpBase, vpData, vpBaseDS, vpException; type // the datastore class; for easier extension and flexibilitiy, the datastore // handles every VPI table as an internal store; these stores are created // in the CreateStores method and linked into the fStores Stringlist. The // objects are TBaseSQLDialect descendants. Access from an app to this stores // is over the Stores property TVPSQLDataStore = class(TVpCustomDBDataStore) protected // internal list of stores and the according objects; // for every "dataset" an internal store of type TBaseSQLDialect is // created, it's DBEngine is assigned the correct value fStores: TStringlist; // see ConnectionParams fConnectionParams: TStrings; // see Session fSession: TComponent; // see SQLDialect fSQLDialect: String; // see DBEngine fDBEngine: String; // see Stores function GetStore(StoreName: String): TVpBaseSQLDialect; // see ConnectionParams procedure SetConnectionParams(const Value: TStrings); virtual; // see Session procedure SetSession(const Value: TComponent); virtual; // see SQLDialect procedure SetSQLDialect(const Value: String); virtual; // see DBEngine procedure SetDBEngine(const Value: String); virtual; // creates one store (internal use) function CreateStore(DBEngine: String): TVpBaseSQLDialect; virtual; // (should) create all stores procedure CreateStores; virtual; // frees all stores procedure FreeStores; virtual; // calls the TVpBaseSQLDialect.CreateTable method for the correct store procedure CreateTable(aTableName: String); virtual; // sets ConnectionParams and Session for all stores; typically called before // Connected is set to true procedure SetSessionAndParams; virtual; // returns the Dataset of the Resource store function GetResourceTable : TDataset; override; // returns the Dataset of the Events store function GetEventsTable : TDataset; override; // returns the Dataset of the Contacts store function GetContactsTable : TDataset; override; // returns the Dataset of the Tasks store function GetTasksTable : TDataset; override; // handles AutoConnect and AutoCreate properties procedure Loaded; override; // connects the datastore to the database procedure SetConnected(const Value: boolean);override; public // constructor constructor Create(aOwner:TComponent); override; // destructor destructor Destroy; override; // returns the next id for a store by doing an equivalent of select max(id) from table // and increasing the number by one function GetNextID(TableName: string): Integer; override; // post changes to the store procedure PostResources; override; // post changes to the store procedure PostEvents; override; // post changes to the store procedure PostContacts; override; // post changes to the store procedure PostTasks; override; // purge the given resource procedure PurgeResource(Res: TVpResource); override; // purge all items of the store belonging to the given resource procedure PurgeContacts(Res: TVpResource); override; // purge all items of the store belonging to the given resource procedure PurgeEvents(Res: TVpResource); override; // purge all items of the store belonging to the given resource procedure PurgeTasks(Res: TVpResource); override; // returns the named store property Stores[StoreName: String]: TVpBaseSQLDialect read GetStore; published // DBEninge to use; see swhDatabaseIntf.pas for more info property DBEngine: String read fDBEngine write SetDBEngine; // SQL Dialect to use; see swhSQLDialect.pas for more info property SQLDialect: String read fSQLDialect write SetSQLDialect; // optional connection parameters for creating the dataset or alternatively // use the Session property property ConnectionParams: TStrings read fConnectionParams write SetConnectionParams; // an untyped session that is passed through to the ISQLDataset; it's the // responsisbility of the dataset to handle it property Session: TComponent read fSession write SetSession; end; procedure Register; implementation procedure Register; begin RegisterComponents('Visual PlanIt', [TVPSQLDataStore]); end; { TVPSQLDataStore } procedure TVPSQLDataStore.CreateTable(aTableName: String); var aDs: TDataset; aTable: TVpBaseSQLDialect; fDefs: TFieldDefs; begin aDs:=TDataset.Create(nil); fDefs:=TFieldDefs.Create(ads); try CreateFieldDefs(aTableName, fDefs); assert(FDefs.Count>0); aTable:=Stores[aTableName]; if aTable<>nil then aTable.CreateTable(aTableName, FDefs, nil); finally fDefs.Free; aDs.free; end; end; function TVPSQLDataStore.GetStore(StoreName: String): TVpBaseSQLDialect; begin result := nil; if fStores.IndexOf(StoreName) > -1 then result := TVpBaseSQLDialect(fStores.Objects[fStores.IndexOf(StoreName)]); end; function TVPSQLDataStore.CreateStore(DBEngine: String): TVpBaseSQLDialect; begin result:=TVpBaseSQLDialect(sSQLDialectFactory.CreateInstance(SQLDialect)); Result.DBEngine:=DBEngine; end; procedure TVPSQLDataStore.SetDBEngine(const Value: String); begin fDBEngine := Value; end; procedure TVPSQLDataStore.CreateStores; var aStore: TVpBaseSQLDialect; begin aStore := CreateStore(fDbEngine); fStores.AddObject(ResourceTableName, aStore); aStore := CreateStore(fDbEngine); fStores.AddObject(EventsTableName, aStore); aStore := CreateStore(fDbEngine); fStores.AddObject(ContactsTableName, aStore); aStore := CreateStore(fDbEngine); fStores.AddObject(TasksTableName, aStore); aStore := CreateStore(fDbEngine); // CreateFieldDefs('_Temp', aStore.Fields); fStores.AddObject('_Temp', aStore); end; constructor TVPSQLDataStore.Create(aOwner: TComponent); begin inherited; fStores := TStringlist.Create; fConnectionParams := TStringlist.Create; end; destructor TVPSQLDataStore.Destroy; begin FreeStores; fStores.free; fConnectionParams.free; inherited; end; procedure TVPSQLDataStore.FreeStores; begin while fStores.Count > 0 do // Iterate begin if fStores.Objects[0] <> nil then fStores.Objects[0].free; fStores.Delete(0); end; end; procedure TVPSQLDataStore.SetConnectionParams(const Value: TStrings); begin fConnectionParams.Assign(Value); SetSessionAndParams; end; procedure TVPSQLDataStore.SetSessionAndParams; var j: Integer; begin for j:=0 to fStores.Count-1 do begin TVpBaseSQLDialect(fStores.Objects[j]).Session:=fSession; TVpBaseSQLDialect(fStores.Objects[j]).ConnectionParams:=fConnectionParams; end; end; procedure TVPSQLDataStore.SetSession(const Value: TComponent); begin fSession := Value; SetSessionAndParams; end; procedure TVPSQLDataStore.SetSQLDialect(const Value: String); begin fSQLDialect := Value; end; procedure TVPSQLDataStore.SetConnected(const Value: boolean); var j: Integer; aStore: TVpBaseSQLDialect; begin { Don't connect at designtime } if csDesigning in ComponentState then Exit; { Don't try to connect until we're all loaded up } if csLoading in ComponentState then Exit; FreeStores; CreateStores; SetSessionAndParams; try for j := 0 to fStores.Count-1 do // Iterate begin if (fStores[j]<>'') and (fStores[j][1]<>'_') then try aStore:=Stores[fStores[j]]; aStore.Close; aStore.SQL:=StringReplace(aStore.SelectSQL, '%TableName%', fStores[j], [rfIgnoreCase]); aStore.Open; except if AutoCreate then begin TVpBaseSQLDialect(fStores.Objects[j]).EnsureDatabaseExists; CreateTable(fStores[j]); aStore.SQL:=StringReplace(aStore.SelectSQL, '%TableName%', fStores[j], [rfIgnoreCase]); aStore.Open; end; end; end; // for inherited; Load; except on e: exception do showmessage(e.message); end; end; procedure TVPSQLDataStore.Loaded; begin inherited; if not (csDesigning in ComponentState) then Connected := AutoConnect; end; function TVPSQLDataStore.GetContactsTable: TDataset; begin result:=Stores[ContactsTableName].Dataset; end; function TVPSQLDataStore.GetEventsTable: TDataset; begin result:=Stores[EventsTableName].Dataset; end; function TVPSQLDataStore.GetResourceTable: TDataset; begin result:=Stores[ResourceTableName].Dataset; end; function TVPSQLDataStore.GetTasksTable: TDataset; begin result:=Stores[TasksTableName].Dataset; end; function TVPSQLDataStore.GetNextID(TableName: string): Integer; var FldName : string; begin try if TableName = ResourceTableName then FldName := 'ResourceID' else FldName := 'RecordID'; Stores['_Temp'].Close; Stores['_Temp'].SQL := 'Select Max(' + FldName + ') as LastID from ' + TableName; Stores['_Temp'].Open; result := Stores['_Temp'].Dataset.FieldByName('LastID').AsInteger + 1; if result < 0 then result := 0; finally Stores['_Temp'].Close; end; end; {=====} procedure TVPSQLDataStore.PostResources; var TableName: String; begin TableName:=ResourceTableName; Stores[TableName].SQL := StringReplace( Stores[TableName].SelectSQL, '%TableName%', TableName, [rfIgnoreCase]); Stores[TableName].Open; inherited; end; {=====} procedure TVPSQLDataStore.PostEvents; var TableName: String; begin TableName:=EventsTableName; Stores[TableName].SQL := StringReplace( Stores[TableName].SelectSQL, '%TableName%', TableName, [rfIgnoreCase]); Stores[TableName].Open; inherited; end; {=====} procedure TVPSQLDataStore.PostContacts; var TableName: String; begin TableName:=ContactsTableName; Stores[TableName].SQL := StringReplace( Stores[TableName].SelectSQL, '%TableName%', TableName, [rfIgnoreCase]); Stores[TableName].Open; inherited; end; {=====} procedure TVPSQLDataStore.PostTasks; var TableName: String; begin TableName:=TasksTableName; Stores[TableName].SQL := StringReplace( Stores[TableName].SelectSQL, '%TableName%', TableName, [rfIgnoreCase]); Stores[TableName].Open; inherited; end; {=====} procedure TVPSQLDataStore.PurgeResource(Res: TVpResource); begin Res.Deleted := true; PostResources; Load; end; {=====} procedure TVPSQLDataStore.PurgeEvents(Res: TVpResource); begin Stores[EventsTableName].sql := 'delete from ' + EventsTableName + ' where ResourceID = ' + IntToStr(Res.ResourceID); Stores[EventsTableName].ExecSQL; Res.Schedule.ClearEvents; end; {=====} procedure TVPSQLDataStore.PurgeContacts(Res: TVpResource); begin Stores[ContactsTableName].sql := 'delete from ' + ContactsTableName + ' where ResourceID = ' + IntToStr(Res.ResourceID); Stores[ContactsTableName].ExecSQL; Res.Contacts.ClearContacts; end; {=====} procedure TVPSQLDataStore.PurgeTasks(Res: TVpResource); begin Stores[TasksTableName].sql := 'delete from ' + TasksTableName + ' where ResourceID = ' + IntToStr(Res.ResourceID); Stores[TasksTableName].ExecSQL; Res.Tasks.ClearTasks; end; {=====} end.
//Exercicio 16: Faça um algoritmo que verifique a validade de uma senha fornecida pelo usuário para ter acesso a um //terminal de consulta.A senha é um conjunto de caracteres que são: "fatecbt". O algoritmo deve imprimir mensagem de //permissão ou negação de acesso. { Solução em Portugol Algoritmo Exercicio 16 ; Var senha: caracter; Inicio exiba("Digite a senha: "); leia(senha); se(senha = "fatecbt"); então exiba("Senha correta. Acesso liberado."); fimse; se(senha <> "fatecbt"); então exiba("Senha incorreta. Acesso negado."); fimse; Fim. } // Solução em Pascal Program Exercicio; uses crt; var senha: string; begin clrscr; writeln('Digite a senha: '); readln(senha); if(senha = 'fatecbt') then writeln('Senha correta. Acesso liberado.'); if(senha <> 'fatecbt') then writeln('Senha incorreta. Acesso negado.'); repeat until keypressed; end.
{ $Id: GUITestRunner.pas,v 1.126 2016/02/09 14:44:15 kostitsin Exp $ } {: DUnit: An XTreme testing framework for Delphi programs. @author The DUnit Group. @version $Revision: 1.126 $ 2001/03/08 uberto } (* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is DUnit. * * The Initial Developers of the Original Code are Kent Beck, Erich Gamma, * and Juancarlo A±ez. * Portions created The Initial Developers are Copyright (C) 1999-2000. * Portions created by The DUnit Group are Copyright (C) 2000-2004. * All rights reserved. * * Contributor(s): * Kent Beck <kentbeck@csi.com> * Erich Gamma <Erich_Gamma@oti.com> * Juanco Aсez <juanco@users.sourceforge.net> * Chris Morris <chrismo@users.sourceforge.net> * Jeff Moore <JeffMoore@users.sourceforge.net> * Kenneth Semeijn <dunit@designtime.demon.nl> * Uberto Barbini <uberto@usa.net> * Brett Shearer <BrettShearer@users.sourceforge.net> * Kris Golko <neuromancer@users.sourceforge.net> * The DUnit group at SourceForge <http://dunit.sourceforge.net> * *) unit GUITestRunner; {$Include l3Define.inc} interface uses TestFramework, Windows, Math, Graphics, Controls, Forms, TestNameList, ComCtrls, ExtCtrls, StdCtrls, ImgList, Buttons, Menus, ActnList, Classes, IniFiles, ToolWin, OvcBase, afwControlPrim, afwBaseControl, afwControl, nevControl, evCustomEditorWindowPrim, evEditorWindow, evCustomEditorWindowModelPart, evMultiSelectEditorWindow, evCustomEditorModelPart, evCustomEditor, evEditorWithOperations, evCustomMemo, evCustomEdit, TestTreeSeacher, evEdit, StdActns, l3WinControlCanvas, evCustomEditorWindow, vtCtrls, elCustomEdit, elCustomButtonEdit, ctButtonEdit, ctAbstractEdit, AbstractDropDown, DropDownTree, EditableBox, FakeBox, vtComboBoxQS ; const {: Section of the dunit.ini file where GUI information will be stored } cnConfigIniSection = 'GUITestRunner Config'; {: Color constants for the progress bar and failure details panel } clOK = clGreen; clFAILURE = clFuchsia; clERROR = clRed; {: Indexes of the color images used in the test tree and failure list } imgNONE = 0; imgRUNNING = 1; imgRUN = 2; imgHASPROPS = 3; imgFAILED = 4; imgERROR = 5; {: Indexes of the images used for test tree checkboxes } imgDISABLED = 1; imgPARENT_DISABLED = 2; imgENABLED = 3; csClearEtalonScriptName = 'ClearEtalons.script'; {$IFDEF Archi} csClearDataBase = 'Очистить тестовую базу.script'; {$ENDIF Archi} type TDictionary = (dCommon, dDictionaries); TDictionaryMenuItem = class(TMenuItem) private f_Dictionary: TDictionary; public constructor Create(anOwner: TComponent; aDictionary: TDictionary); reintroduce; public property Dictionary: TDictionary read f_Dictionary; end; type {: Function type used by the TDUnitDialog.ApplyToTests method @param item The ITest instance on which to act @return true if processing should continue, false otherwise } TTestFunc = function (anItem: ITest): Boolean of object; TGUITestRunner = class(TForm, ITestListener, ITestListenerX) StateImages: TImageList; RunImages: TImageList; DialogActions: TActionList; SelectAllAction: TAction; DeselectAllAction: TAction; SelectFailedAction: TAction; MainMenu: TMainMenu; TestTreeMenu: TMenuItem; SelectAllItem: TMenuItem; DeselectAllItem: TMenuItem; SelectFailedItem: TMenuItem; FileMenu: TMenuItem; SaveConfigurationAction: TAction; AutoSaveAction: TAction; SaveConfigurationItem: TMenuItem; AutoSaveItem: TMenuItem; RestoreSavedAction: TAction; RestoreSavedConfigurationItem: TMenuItem; ViewMenu: TMenuItem; HideErrorBoxItem: TMenuItem; BodyPanel: TPanel; ErrorBoxVisibleAction: TAction; TopPanel: TPanel; TreePanel: TPanel; TestTree: TTreeView; ResultsPanel: TPanel; ProgressPanel: TPanel; ResultsView: TListView; FailureListView: TListView; ErrorBoxPanel: TPanel; ErrorBoxSplitter: TSplitter; ResultsSplitter: TSplitter; AutoChangeFocusItem: TMenuItem; TopProgressPanel: TPanel; ProgressBar: TProgressBar; pnlProgresslabel: TPanel; ScorePanel: TPanel; ScoreLabel: TPanel; ScoreBar: TProgressBar; pmTestTree: TPopupMenu; pmiSelectAll: TMenuItem; pmiDeselectAll: TMenuItem; pmiSelectFailed: TMenuItem; HideTestNodesAction: TAction; CollapseLowestSuiteNodesItem: TMenuItem; CollapseLowestSuiteNodes1: TMenuItem; HideTestNodesOnOpenAction: TAction; HideTestNodesItem: TMenuItem; ExpandAllNodesAction: TAction; TestTreeMenuSeparator: TMenuItem; ExpandAllItem: TMenuItem; TestTreeLocalMenuSeparator: TMenuItem; ExpandAll2: TMenuItem; lblTestTree: TLabel; RunAction: TAction; ExitAction: TAction; BreakOnFailuresAction: TAction; BreakonFailuresItem: TMenuItem; ShowTestedNodeAction: TAction; SelectTestedNodeItem: TMenuItem; ErrorMessagePopup: TPopupMenu; CopyFailureMessage: TMenuItem; CopyMessageToClipboardAction: TAction; ActionsMenu: TMenuItem; CopyMessagetoCllipboardItem: TMenuItem; LbProgress: TLabel; UseRegistryAction: TAction; UseRegistryItem: TMenuItem; ErrorMessageRTF: TRichEdit; SelectCurrentAction: TAction; DeselectCurrentAction: TAction; SelectCurrent1: TMenuItem; DeselectCurrent1: TMenuItem; ActionsImages: TImageList; CloseItem: TMenuItem; RunItem: TMenuItem; StopAction: TAction; StopActionItem: TMenuItem; ToolBar1: TToolBar; SelectAllButton: TToolButton; DeselectAllButton: TToolButton; ToolButton1: TToolButton; SelectFailedButton: TToolButton; ToolButton2: TToolButton; SelectCurrentButton: TToolButton; DeselectCurrentButton: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; Alt_R_RunAction: TAction; Alt_S_StopAction: TAction; N1: TMenuItem; DeselectCurrent2: TMenuItem; SelectCurrent2: TMenuItem; N2: TMenuItem; CopyProcnameToClipboardAction: TAction; N3: TMenuItem; Copytestnametoclipboard1: TMenuItem; N4: TMenuItem; Copytestnametoclipboard2: TMenuItem; RunSelectedTestAction: TAction; N5: TMenuItem; Runcurrenttest1: TMenuItem; N6: TMenuItem; Runcurrenttest2: TMenuItem; RunSelectedTestItem: TMenuItem; RunSelectedTestButton: TToolButton; GoToNextSelectedTestAction: TAction; GoToPrevSelectedTestAction: TAction; N7: TMenuItem; GoToNextSelectedNode1: TMenuItem; GoToPreviousSelectedNode1: TMenuItem; N8: TMenuItem; GoToNextSelectedNode2: TMenuItem; GoToPreviousSelectedNode2: TMenuItem; FailIfNoChecksExecuted: TMenuItem; FailIfNoChecksExecutedAction: TAction; FailTestCaseIfMemoryLeaked: TMenuItem; FailTestCaseIfMemoryLeakedAction: TAction; TestCaseProperty: TPopupMenu; TestCaseProperties: TMenuItem; N10: TMenuItem; FailNoCheckExecutedMenuItem: TMenuItem; FailsOnMemoryLeakMenuItem: TMenuItem; N11: TMenuItem; TestCasePopup: TMenuItem; FailsOnMemoryRecoveryMenuItem: TMenuItem; AllowedLeakSizeMemuItem: TMenuItem; ShowTestCaseswithRunTimeProperties: TMenuItem; ShowTestCasesWithRunTimePropertiesAction: TAction; N9: TMenuItem; WarnOnFailTestOverride: TMenuItem; WarnOnFailTestOverrideAction: TAction; N12: TMenuItem; TestCasePropertiesAction: TAction; PropertyPopUpAction: TAction; N13: TMenuItem; Previous1: TMenuItem; Next1: TMenuItem; RunSelectedTest1: TMenuItem; RunSelectedTestAltAction: TAction; N14: TMenuItem; ReportMemoryLeakTypeOnShutdown: TMenuItem; IgnoreMemoryLeakInSetUpTearDown: TMenuItem; IgnoreMemoryLeakInSetUpTearDownAction: TAction; ReportMemoryLeakTypeOnShutdownAction: TAction; TestCaseIgnoreSetUpTearDownLeaksMenuItem: TMenuItem; ToolButton6: TToolButton; ToolButton7: TToolButton; FindBtn: TToolButton; FindDirBtn: TToolButton; N15: TMenuItem; FindPM: TMenuItem; acFindNode: TAction; acFindDirection: TAction; NeedSelectBtn: TToolButton; acNeedSelect: TAction; acNeedSelectAll: TAction; btnNeedSelectAll: TToolButton; ToolButton8: TToolButton; btnShowFolder: TToolButton; acShowFolder: TAction; acFolderMode: TAction; FolderNodeBtm: TToolButton; acSelectExcluded: TAction; acDeselectExcluded: TAction; ToolButton9: TToolButton; SelectExcludedBtn: TToolButton; DeselectExcluded: TToolButton; acDeleteEtalons: TAction; ToolButton12: TToolButton; DeleteEtalonsBtn: TToolButton; acOpenExcludeFile: TFileOpen; ToolButton10: TToolButton; OpenFileExcludeBtn: TToolButton; LoadExcludeListPM: TMenuItem; acOpenTestList: TFileOpen; OpenTestListBtn: TToolButton; OpenTestListPM: TMenuItem; acSelect2Current: TAction; Select2CurrentBtn: TToolButton; acInvertTests: TAction; InvertTestsBtn: TToolButton; acRandomTests: TAction; RandomBtn: TToolButton; ToolButton13: TToolButton; Save2FileBTN: TToolButton; acSaveSelected: TFileSaveAs; SaveSelectedPM: TMenuItem; PresetsPM: TMenuItem; RunScirpt: TMenuItem; RunScriptAction: TFileOpen; MacrosPM: TMenuItem; ToolButton11: TToolButton; PrevSelectedTestsBtn: TToolButton; NextSelectedTestsBtn: TToolButton; N16: TMenuItem; FolderModePM: TMenuItem; RandomPM: TMenuItem; N17: TMenuItem; N18: TMenuItem; NeedSelectPM: TMenuItem; acReReadAutoTests: TAction; ToolButton14: TToolButton; ReReadAutoTestsBtn: TToolButton; evFindEdit: TvtComboBoxQS; acOpenScript: TAction; N19: TMenuItem; N20: TMenuItem; LoadOperationBTN: TToolButton; acLoadOperation: TAction; CompileAction: TAction; ToolButton15: TToolButton; btnDebugger: TToolButton; acDebugger: TAction; ClearDBBtn: TToolButton; acClearDaaBase: TAction; procedure FormCreate(Sender: TObject); procedure TestTreeClick(Sender: TObject); procedure FailureListViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure FailureListViewClick(Sender: TObject); procedure TestTreeKeyPress(Sender: TObject; var Key: Char); procedure SelectAllActionExecute(Sender: TObject); procedure DeselectAllActionExecute(Sender: TObject); procedure SelectFailedActionExecute(Sender: TObject); procedure SaveConfigurationActionExecute(Sender: TObject); procedure RestoreSavedActionExecute(Sender: TObject); procedure AutoSaveActionExecute(Sender: TObject); procedure ErrorBoxVisibleActionExecute(Sender: TObject); procedure ErrorBoxSplitterMoved(Sender: TObject); procedure ErrorBoxPanelResize(Sender: TObject); procedure HideTestNodesActionExecute(Sender: TObject); procedure HideTestNodesOnOpenActionExecute(Sender: TObject); procedure ExpandAllNodesActionExecute(Sender: TObject); procedure RunActionExecute(Sender: TObject); procedure ExitActionExecute(Sender: TObject); procedure BreakOnFailuresActionExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ShowTestedNodeActionExecute(Sender: TObject); procedure CopyMessageToClipboardActionExecute(Sender: TObject); procedure UseRegistryActionExecute(Sender: TObject); procedure RunActionUpdate(Sender: TObject); procedure CopyMessageToClipboardActionUpdate(Sender: TObject); procedure SelectCurrentActionExecute(Sender: TObject); procedure DeselectCurrentActionExecute(Sender: TObject); procedure StopActionExecute(Sender: TObject); procedure StopActionUpdate(Sender: TObject); procedure TestTreeChange(Sender: TObject; Node: TTreeNode); procedure CopyProcnameToClipboardActionExecute(Sender: TObject); procedure CopyProcnameToClipboardActionUpdate(Sender: TObject); procedure RunSelectedTestActionExecute(Sender: TObject); procedure RunSelectedTestActionUpdate(Sender: TObject); procedure TestTreeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GoToNextSelectedTestActionExecute(Sender: TObject); procedure GoToPrevSelectedTestActionExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure FailIfNoChecksExecutedActionExecute(Sender: TObject); procedure FailTestCaseIfMemoryLeakedActionExecute(Sender: TObject); procedure ShowTestCasesWithRunTimePropertiesActionExecute( Sender: TObject); procedure WarnOnFailTestOverrideActionExecute(Sender: TObject); procedure TestCasePropertiesActionExecute(Sender: TObject); procedure Previous1Click(Sender: TObject); procedure Next1Click(Sender: TObject); procedure TestCasePropertiesMeasureItem(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer); procedure TestCasePropertiesDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); procedure FailNoCheckExecutedMenuItemDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); procedure AllowedLeakSizeMemuItemDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); procedure FailsOnMemoryRecoveryMenuItemDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); procedure FailsOnMemoryLeakMenuItemDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); procedure pmTestTreePopup(Sender: TObject); procedure FailNoCheckExecutedMenuItemClick(Sender: TObject); procedure AllowedLeakSizeMemuItemClick(Sender: TObject); procedure FailsOnMemoryLeakMenuItemClick(Sender: TObject); procedure FailsOnMemoryRecoveryMenuItemClick(Sender: TObject); procedure RunSelectedTestAltActionExecute(Sender: TObject); procedure Previous1DrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); procedure RunSelectedTest1DrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); procedure Next1DrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); procedure ReportMemoryLeakTypeOnShutdownActionExecute(Sender: TObject); procedure IgnoreMemoryLeakInSetUpTearDownActionExecute( Sender: TObject); procedure TestCaseIgnoreSetUpTearDownLeaksMenuItemClick(Sender: TObject); procedure TestCaseIgnoreSetUpTearDownLeaksMenuItemDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); procedure acFindNodeUpdate(Sender: TObject); procedure acFindNodeExecute(Sender: TObject); procedure acFindDirectionExecute(Sender: TObject); procedure TestTreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure acShowFolderExecute(Sender: TObject); procedure acFolderModeUpdate(Sender: TObject); procedure TestTreeCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); procedure acSelectExcludedExecute(Sender: TObject); procedure acDeselectExcludedExecute(Sender: TObject); procedure acDeleteEtalonsExecute(Sender: TObject); procedure acOpenExcludeFileAccept(Sender: TObject); procedure acOpenExcludeFileBeforeExecute(Sender: TObject); procedure acOpenTestListAccept(Sender: TObject); procedure acOpenTestListBeforeExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ExitActionUpdate(Sender: TObject); procedure acSelect2CurrentExecute(Sender: TObject); procedure acInvertTestsExecute(Sender: TObject); procedure acRandomTestsUpdate(Sender: TObject); procedure acSaveSelectedAccept(Sender: TObject); procedure RunScriptActionAccept(Sender: TObject); procedure RunScriptActionUpdate(Sender: TObject); procedure acReReadAutoTestsExecute(Sender: TObject); procedure acOpenScriptExecute(Sender: TObject); procedure acOpenScriptUpdate(Sender: TObject); procedure TestTreeDblClick(Sender: TObject); procedure acLoadOperationExecute(Sender: TObject); procedure CompileActionUpdate(Sender: TObject); procedure CompileActionExecute(Sender: TObject); procedure acDebuggerExecute(Sender: TObject); procedure acClearDaaBaseExecute(Sender: TObject); procedure acDebuggerUpdate(Sender: TObject); private FNoCheckExecutedPtyOverridden: Boolean; FMemLeakDetectedPtyOverridden: Boolean; FIgnoreSetUpTearDownLeakPtyOverridden: Boolean; FPopupY: Integer; FPopupX: Integer; FTestTreeSeacher: TTestTreeSeacher; FInitDirForExclude : string; FInitDirForError : string; FClearEtalonPM: TMenuItem; FLoadOperation: TLoadOperation; FWasStarted: Boolean; {$IFDEF Archi} FClearBaseMenuItem: TMenuItem; {$ENDIF Archi} procedure DoDeselectAllActionExecute(Sender: TObject); procedure CheckMenuItem(const aMenuItem: TMenuItem); // Для "вылавливания" нужных пунктов меню... procedure ResetProgress; procedure MenuLooksInactive(ACanvas: TCanvas; ARect: TRect; Selected: Boolean; ATitle: string; TitlePosn: UINT; PtyOveridesGUI: boolean); procedure MenuLooksActive(ACanvas: TCanvas; ARect: TRect; Selected: Boolean; ATitle: string; TitlePosn: UINT); function GetPropertyName(const Caption: string): string; procedure CheckDirection(Sender: TObject; Key: Word); procedure ChangeState4Test(anEnable, anExcluded: Boolean); procedure CheckStartParams; procedure ReadSubMenuItems(aMenuItem: TMenuItem; aExt: string; aSubDir: string; anEvent: TNotifyEvent; aStartIndex: Integer); procedure ReadSubDirs(aMenuItem: TMenuItem; aExt: string; aSubDir: string; anEvent: TNotifyEvent); procedure OnSelectPreset(Sender: TObject); procedure OnSelectMacros(Sender: TObject); procedure Try2RemeberInHistory; function CheckParentDir(Sender: TObject; aParentPM: TMenuItem): String; procedure InitLogicalOperation; procedure UpdateLogicalOpearation; procedure LoadItemFlagsFromFile(aFileName: AnsiString); procedure SetLoadOperation(const Value: TLoadOperation); protected FSuite: ITest; FTestResult: TTestResult; FRunning: Boolean; FTests: TInterfaceList; FSelectedTests: TInterfaceList; FTotalTime: Int64; FRunTimeStr: string; FNoChecksStr: string; FMemLeakStr: string; FMemGainStr: string; FMemBytesStr: string; FIgnoreLeakStr: string; FBytes: string; FErrorCount: Integer; FFailureCount: Integer; FStrMaxLen: Integer; FValMaxLen: Integer; FUpdateTimer: TTimer; FTimerExpired: Boolean; FTotalTestsCount: Integer; f_DisableClose : Boolean; f_InternalStart: Boolean; procedure Setup; procedure SetUpStateImages; procedure SetSuite(value: ITest); procedure ClearResult; procedure DisplayFailureMessage(Item :TListItem); procedure ClearFailureMessage; function AddFailureItem(failure: TTestFailure): TListItem; procedure UpdateStatus(const fullUpdate:Boolean); procedure FillTestTree(RootNode: TTreeNode; ATest: ITest); overload; procedure FillTestTree(ATest: ITest); overload; function GetTestFileName(aTest: ITest): string; procedure OpenFile(const aFileName: string); function DictionariesPath(aDictionary: TDictionary): string; procedure LoadDictionariesMenu; procedure DictionaryMenuItemClick(aSender: TObject); procedure UpdateNodeImage(aNode: TTreeNode); procedure UpdateNodeState(aNode: TTreeNode); procedure SetNodeState(aNode: TTreeNode; anEnabled: Boolean); procedure SwitchNodeState(aNode: TTreeNode); procedure UpdateTestTreeState; procedure MakeNodeVisible(aNode :TTreeNode); procedure SetTreeNodeImage(Node :TTReeNode; imgIndex :Integer); procedure SelectNode(node: TTreeNode); function GetNodeEnabled(aNode: TTreeNode): Boolean; {function} procedure SetNodeEnabled(aNode: TTreeNode; aValue: Boolean){: Boolean}; function TestToNode(aTest: ITest) :TTreeNode; function SelectedTest :ITest; procedure ListSelectedTests; function EnableTest(aTest: ITest): Boolean; function DisableTest(aTest: ITest): Boolean; function InvertTest(aTest: ITest): Boolean; procedure ApplyToTests(aRoot: TTreeNode; const aFunc: TTestFunc; aStopOnSelect: Boolean); procedure EnableUI(enable :Boolean); procedure RunTheTest(aTest: ITest; aRandom: Boolean); procedure InitTree; virtual; function IniFileName :string; function GetIniFile( const FileName : string ) : tCustomIniFile; procedure LoadRegistryAction; procedure SaveRegistryAction; public function NodeToTest(aNode: TTreeNode) :ITest; procedure LoadFormPlacement; procedure ShowDebugForm; protected procedure SaveFormPlacement; procedure SaveConfiguration; procedure LoadConfiguration; procedure LoadSuiteConfiguration; procedure AutoSaveConfiguration; function NodeIsGrandparent(aNode: TTreeNode): Boolean; procedure CollapseNonGrandparentNodes(aRootNode: TTreeNode); procedure ProcessClickOnStateIcon; procedure ClearStatusMessage; procedure CopyTestNametoClipboard(ANode: TTreeNode); procedure SetupCustomShortcuts; procedure SetupGUINodes; function SelectNodeIfTestEnabled(aNode: TTreeNode): boolean; procedure OnUpdateTimer(Sender: TObject); public {: implement the ITestListener interface } procedure AddSuccess(const test: ITest); procedure AddError(failure: TTestFailure); procedure AddFailure(failure: TTestFailure); function ShouldRunTest(aTest: ITest): Boolean; procedure StartSuite(suite: ITest); virtual; procedure EndSuite(suite: ITest); virtual; procedure StartTest(aTest: ITest); virtual; procedure EndTest(aTest: ITest); virtual; procedure TestingStarts; procedure TestingEnds(TestResult :TTestResult); procedure Status(test :ITest; const Msg : AnsiString); procedure Warning(test :ITest; const Msg : string); procedure ToFront; property LoadOperation: TLoadOperation read FLoadOperation write SetLoadOperation; {: The number of errors in the last test run } property ErrorCount: Integer read FErrorCount; {: The number of failures in the last test run } property FailureCount: Integer read FFailureCount; {: The test suite to be run in this runner } property Suite: ITest read FSuite write SetSuite; {: The result of the last test run } property TestResult : TTestResult read FTestResult write FTestResult; property DisableClose: Boolean read f_DisableClose write f_DisableClose; class procedure RunTest(test: ITest); class procedure RunRegisteredTests; end; procedure RunTest(test: ITest); procedure RunRegisteredTests; procedure RunTestModeless(test: ITest); procedure RunRegisteredTestsModeless; // Run all tests in unattended mode, i.e. automatically function RunRegisteredTestsModelessUnattended: Integer; implementation uses {$IFDEF FASTMM} {$IFNDEF VER180} {$IFNDEF CLR} {$IFNDEF ManualLeakReportingControl} {$I FastMM4Options.inc} {$ENDIF} FastMM4, {$ENDIF} {$ENDIF} {$ENDIF} FolderSupport, {$If not defined(NoScripts)} TestForm4Scripts, {$IfEnd} KTestRunner, Registry, SysUtils, Clipbrd, Dialogs, ShellAPI, MacroTest, l3Base, l3Filer, l3Types, l3FileUtils, l3BatchService, afwFacade {$IfDef InsiderTest} , tfwScriptDebugger {$EndIf InsiderTest} , vcmInsiderTest ; {$BOOLEVAL OFF} // Required or you'll get an AV {$R *.DFM} const csDictionaryMenuItemCaption: array[TDictionary] of AnsiString = ('Common', 'Dictionaries'); csDictionarySubDir: array[TDictionary] of AnsiString = ('Common\', 'Dictionary\'); csDictionaryExt = '*.script'; const cnIndexDown = 12; cnIndexUp = 13; csHintStr : array [cnIndexDown..cnIndexUp] of string = ('Искать вниз', 'Искать вверх'); csPresetsSubDir = 'Presets\'; csPresetsExt = '*.txt'; csMacrosSubDir = 'Macros\'; csMacrosExt = '*.script'; cnStartLogicalIndex = 31; csLogicalHintArray : array [TLoadOperation] of string = ('Очищать список', 'Пересечение списков', 'Объединение списков', 'Вычитание списков'); type TProgressBarCrack = class(TProgressBar); procedure RunTest(test: ITest); begin with TGUITestRunner.Create(nil) do begin try Suite := test; ShowModal; finally Free; end; end; end; procedure RunTestModeless(test: ITest); var GUI :TGUITestRunner; begin Application.CreateForm(TGUITestRunner, GUI); GUI.Suite := test; GUI.Show; end; procedure RunRegisteredTests; begin RunTest(registeredTests) end; procedure RunRegisteredTestsModeless; begin RunTestModeless(registeredTests) end; // Run all tests in unattended mode, i.e. automatically function RunRegisteredTestsModelessUnattended: Integer; var GUI :TGUITestRunner; begin // Create and show the GUI runner form Application.CreateForm(TGUITestRunner, GUI); GUI.Suite := registeredTests; GUI.Show; GUI.RunActionExecute(GUI.RunItem); // Process messages until the tests have finished repeat try Application.HandleMessage; except Application.HandleException(Application); end; until TGUITestRunner(Application.MainForm).RunAction.Enabled; // Return the number of errors and failures and free the runner form Result := GUI.ErrorCount + GUI.FailureCount; GUI.Free; end; { TGUITestRunner } procedure TGUITestRunner.InitTree; begin FTests.Clear; FillTestTree(Suite); Setup; if HideTestNodesOnOpenAction.Checked then HideTestNodesAction.Execute else ExpandAllNodesAction.Execute; TestTree.Selected := TestTree.Items.GetFirstNode; end; function TGUITestRunner.NodeToTest(aNode: TTreeNode): ITest; var l_Index: Integer; begin Assert(Assigned(aNode)); l_Index := Integer(aNode.Data); if IsNodeFolder(aNode) then Result := nil // Папка... else begin Assert((l_Index >= 0) and (l_Index < FTests.Count)); Result := FTests[l_Index] as ITest; end; end; procedure TGUITestRunner.OnUpdateTimer(Sender: TObject); begin FTimerExpired := True; FUpdateTimer.Enabled := False; end; function TGUITestRunner.TestToNode(aTest: ITest): TTreeNode; begin Assert(Assigned(aTest)); Result := aTest.GUIObject as TTreeNode; Assert(Assigned(Result)); end; function TGUITestRunner.ShouldRunTest(aTest: ITest): Boolean; begin if FSelectedTests = nil then Result := aTest.Enabled else Result := FSelectedTests.IndexOf(aTest as ITest) >= 0; end; procedure TGUITestRunner.StartTest(aTest: ITest); var l_Node: TTreeNode; begin if f_InternalStart then Exit; Assert(Assigned(TestResult)); Assert(Assigned(aTest)); l_Node := TestToNode(aTest); Assert(Assigned(l_Node)); SetTreeNodeImage(l_Node, imgRunning); if ShowTestedNodeAction.Checked then begin MakeNodeVisible(l_Node); TestTree.Update; end; ClearStatusMessage; UpdateStatus(False); end; procedure TGUITestRunner.EndTest(aTest: ITest); begin if f_InternalStart then Exit; UpdateStatus(False); end; procedure TGUITestRunner.TestingStarts; begin FTotalTime := 0; UpdateStatus(True); TProgressBarCrack(ScoreBar).Color := clOK; TProgressBarCrack(ScoreBar).RecreateWnd; end; procedure TGUITestRunner.AddSuccess(const test: ITest); var OverridesGUI: Boolean; HasRunTimePropsSet: Boolean; begin assert(assigned(test)); if not IsTestMethod(test) then SetTreeNodeImage(TestToNode(Test), imgRun) else begin OverridesGUI := ((FailIfNoChecksExecuted.Checked and not Test.FailsOnNoChecksExecuted) or (FailTestCaseIfMemoryLeaked.Checked and not Test.FailsOnMemoryLeak)) or (FailTestCaseIfMemoryLeaked.Checked and Test.IgnoreSetUpTearDownLeaks and not IgnoreMemoryLeakInSetUpTearDown.Checked); HasRunTimePropsSet := ((Test.FailsOnNoChecksExecuted and not FailIfNoChecksExecuted.Checked) or (Test.FailsOnMemoryLeak and not FailTestCaseIfMemoryLeaked.Checked) or (FailTestCaseIfMemoryLeaked.Checked and Test.IgnoreSetUpTearDownLeaks) or (Test.AllowedMemoryLeakSize <> 0)); if OverridesGUI then FTestResult.Overrides := FTestResult.Overrides + 1; if f_InternalStart then Exit; if (WarnOnFailTestOverride.Checked and OverridesGUI) or (ShowTestCaseswithRunTimeProperties.Checked and HasRunTimePropsSet) then SetTreeNodeImage(TestToNode(Test), imgHASPROPS) else SetTreeNodeImage(TestToNode(Test), imgRun); end; end; procedure TGUITestRunner.AddError(failure: TTestFailure); var ListItem: TListItem; begin ListItem := AddFailureItem(failure); ListItem.ImageIndex := imgERROR; TProgressBarCrack(ScoreBar).Color := clERROR; TProgressBarCrack(ScoreBar).RecreateWnd; if f_InternalStart then Exit; SetTreeNodeImage(TestToNode(failure.failedTest), imgERROR); UpdateStatus(False); end; procedure TGUITestRunner.AddFailure(failure: TTestFailure); var ListItem: TListItem; begin ListItem := AddFailureItem(failure); ListItem.ImageIndex := imgFAILED; if TestResult.errorCount = 0 then begin TProgressBarCrack(ScoreBar).Color := clFAILURE; TProgressBarCrack(ScoreBar).RecreateWnd; end; if f_InternalStart then Exit; SetTreeNodeImage(TestToNode(failure.failedTest), imgFAILED); UpdateStatus(False); end; function TGUITestRunner.IniFileName: string; const TEST_INI_FILE = 'dunit.ini'; begin result := ExtractFilePath(Application.ExeName) + TEST_INI_FILE end; procedure TGUITestRunner.LoadFormPlacement; begin with GetIniFile( IniFileName ) do try Self.SetBounds( ReadInteger(cnConfigIniSection, 'Left', Left), ReadInteger(cnConfigIniSection, 'Top', Top), ReadInteger(cnConfigIniSection, 'Width', Width), ReadInteger(cnConfigIniSection, 'Height', Height) ); if ReadBool(cnConfigIniSection, 'Maximized', False ) then WindowState := wsMaximized; finally Free; end; end; procedure TGUITestRunner.SaveFormPlacement; begin with GetIniFile(IniFileName) do try WriteBool(cnConfigIniSection, 'AutoSave', AutoSaveAction.Checked); if WindowState <> wsMaximized then begin WriteInteger(cnConfigIniSection, 'Left', Left); WriteInteger(cnConfigIniSection, 'Top', Top); WriteInteger(cnConfigIniSection, 'Width', Width); WriteInteger(cnConfigIniSection, 'Height', Height ); end; WriteBool(cnConfigIniSection, 'Maximized', WindowState = wsMaximized ); finally Free end; end; procedure TGUITestRunner.LoadConfiguration; var i : Integer; l_Count : Integer; l_Item : String; l_SelType : Integer; begin LoadRegistryAction; LoadFormPlacement; LoadSuiteConfiguration; with GetIniFile(IniFileName) do try with AutoSaveAction do Checked := ReadBool(cnConfigIniSection, 'AutoSave', Checked); { center splitter location } with ResultsPanel do Height := ReadInteger(cnConfigIniSection, 'ResultsPanel.Height', Height); { error splitter location } with ErrorBoxPanel do Height := ReadInteger(cnConfigIniSection, 'ErrorMessage.Height', Height); with ErrorBoxVisibleAction do Checked := ReadBool(cnConfigIniSection, 'ErrorMessage.Visible', Checked); ErrorBoxSplitter.Visible := ErrorBoxVisibleAction.Checked; ErrorBoxPanel.Visible := ErrorBoxVisibleAction.Checked; { failure list configuration } with FailureListView do for i := 0 to Columns.Count-1 do Columns[i].Width := Max(4, ReadInteger(cnConfigIniSection, Format('FailureList.ColumnWidth[%d]', [i]), Columns[i].Width) ); { other options } acShowFolder.Checked := ReadBool(cnConfigIniSection, csRegistryShowFolder, acShowFolder.Checked); HideTestNodesOnOpenAction.Checked := ReadBool(cnConfigIniSection, 'HideTestNodesOnOpen', HideTestNodesOnOpenAction.Checked); BreakOnFailuresAction.Checked := ReadBool(cnConfigIniSection, 'BreakOnFailures', BreakOnFailuresAction.Checked); FailIfNoChecksExecutedAction.Checked := ReadBool(cnConfigIniSection, 'FailOnNoChecksExecuted', FailIfNoChecksExecutedAction.Checked); FailTestCaseIfMemoryLeakedAction.Checked := ReadBool(cnConfigIniSection, 'FailOnMemoryLeaked', FailTestCaseIfMemoryLeakedAction.Checked); IgnoreMemoryLeakInSetUpTearDownAction.Checked := ReadBool(cnConfigIniSection, 'IgnoreSetUpTearDownLeaks', IgnoreMemoryLeakInSetUpTearDownAction.Checked); ReportMemoryLeakTypeOnShutdownAction.Checked := ReadBool(cnConfigIniSection, 'ReportMemoryLeakTypes', ReportMemoryLeakTypeOnShutdownAction.Checked); WarnOnFailTestOverrideAction.Checked := ReadBool(cnConfigIniSection, 'WarnOnFailTestOverride', WarnOnFailTestOverrideAction.Checked); ShowTestedNodeAction.Checked := ReadBool(cnConfigIniSection, 'SelectTestedNode', ShowTestedNodeAction.Checked); FInitDirForExclude := ReadString(cnConfigIniSection, 'InitDirForExclude', GetAppTestSetPath); FInitDirForError := ReadString(cnConfigIniSection, 'InitDirForError', GetAppTestSetPath); acRandomTests.Checked := ReadBool(cnConfigIniSection, 'RandomExecuting', False); LoadOperation := TLoadOperation(ReadInteger(cnConfigIniSection, 'LoadListFlagsOperation', Ord(lo_Clear))); acDebugger.Checked := ReadBool(cnConfigIniSection, 'ShowDebugger', True); l_Count := ReadInteger(cnConfigIniSection, 'HistorySize', 0); if l_Count > 0 then for i := 0 to l_Count - 1 do begin l_Item := ReadString(cnConfigIniSection, Format('History[%d]', [i]), ''); if l_Item <> '' then evFindEdit.Items.Add(l_Item); end; // for i := 0 to l_Count - 1 do FPopupX := ReadInteger(cnConfigIniSection, 'PopupX', 350); FPopupY := ReadInteger(cnConfigIniSection, 'PopupY', 30); l_SelType := ReadInteger(cnConfigIniSection, 'SelectTestFind', 0); case l_SelType of 0:; 1: acNeedSelect.Checked := True; 2: acNeedSelectAll.Checked := True; end; // case l_SelType of finally Free; end; if Suite <> nil then UpdateTestTreeState; end; procedure TGUITestRunner.AutoSaveConfiguration; begin if AutoSaveAction.Checked then SaveConfiguration; end; procedure TGUITestRunner.SaveConfiguration; var i : Integer; l_SelType : Integer; begin if Suite <> nil then Suite.SaveConfiguration(IniFileName, UseRegistryAction.Checked, True); SaveFormPlacement; SaveRegistryAction; with GetIniFile(IniFileName) do try { center splitter location } WriteInteger(cnConfigIniSection, 'ResultsPanel.Height', ResultsPanel.Height); { error box } WriteInteger(cnConfigIniSection, 'ErrorMessage.Height', ErrorBoxPanel.Height); WriteBool(cnConfigIniSection, 'ErrorMessage.Visible', ErrorBoxVisibleAction.Checked); { failure list configuration } with FailureListView do for i := 0 to Columns.Count - 1 do WriteInteger(cnConfigIniSection, Format('FailureList.ColumnWidth[%d]', [i]), Columns[i].Width); { other options } WriteBool(cnConfigIniSection, csRegistryShowFolder, acShowFolder.Checked); WriteBool(cnConfigIniSection, 'HideTestNodesOnOpen', HideTestNodesOnOpenAction.Checked); WriteBool(cnConfigIniSection, 'BreakOnFailures', BreakOnFailuresAction.Checked); WriteBool(cnConfigIniSection, 'FailOnNoChecksExecuted', FailIfNoChecksExecutedAction.Checked); WriteBool(cnConfigIniSection, 'FailOnMemoryLeaked', FailTestCaseIfMemoryLeakedAction.Checked); WriteBool(cnConfigIniSection, 'IgnoreSetUpTearDownLeaks', IgnoreMemoryLeakInSetUpTearDownAction.Checked); WriteBool(cnConfigIniSection, 'ReportMemoryLeakTypes', ReportMemoryLeakTypeOnShutdownAction.Checked); WriteBool(cnConfigIniSection, 'SelectTestedNode', ShowTestedNodeAction.Checked); WriteBool(cnConfigIniSection, 'WarnOnFailTestOverride', WarnOnFailTestOverrideAction.Checked); WriteBool(cnConfigIniSection, 'RandomExecuting', acRandomTests.Checked); WriteInteger(cnConfigIniSection, 'PopupX', FPopupX); WriteInteger(cnConfigIniSection, 'PopupY', FPopupY); WriteInteger(cnConfigIniSection, 'LoadListFlagsOperation', Ord(LoadOperation)); WriteString(cnConfigIniSection, 'InitDirForError', FInitDirForError); WriteString(cnConfigIniSection, 'InitDirForExclude', FInitDirForExclude); WriteBool(cnConfigIniSection, 'ShowDebugger', acDebugger.Checked); if acNeedSelect.Checked then l_SelType := 1 else if acNeedSelectAll.Checked then l_SelType := 2 else l_SelType := 0; WriteInteger(cnConfigIniSection, 'SelectTestFind', l_SelType); WriteInteger(cnConfigIniSection, 'HistorySize', evFindEdit.Items.Count); for i := 0 to evFindEdit.Items.Count - 1 do WriteString(cnConfigIniSection, Format('History[%d]', [i]), evFindEdit.Items[i].AsString); finally Free; end; end; procedure TGUITestRunner.TestingEnds(TestResult :TTestResult); begin FTotalTime := TestResult.TotalTime; end; procedure TGUITestRunner.UpdateNodeState(aNode: TTreeNode); begin Assert(Assigned(aNode)); UpdateNodeImage(aNode); if aNode.HasChildren then begin aNode := aNode.GetFirstChild; while aNode <> nil do begin UpdateNodeState(aNode); aNode := aNode.getNextSibling; end; end; end; procedure TGUITestRunner.SetNodeState(aNode: TTreeNode; anEnabled: Boolean); var l_Test : ITest; l_MostSeniorChanged : TTreeNode; begin Assert(aNode <> nil); // update ancestors if enabling SetNodeEnabled(aNode, anEnabled); l_MostSeniorChanged := aNode; if anEnabled then begin while aNode.Parent <> nil do begin aNode := aNode.Parent; if not GetNodeEnabled(aNode) then begin // changed SetNodeEnabled(aNode, True); l_MostSeniorChanged := aNode; UpdateNodeImage(aNode); end end; end; TestTree.Items.BeginUpdate; try UpdateNodeState(l_MostSeniorChanged); finally TestTree.Items.EndUpdate; end end; procedure TGUITestRunner.SwitchNodeState(aNode: TTreeNode); begin Assert(aNode <> nil); SetNodeState(aNode, not GetNodeEnabled(aNode)); end; procedure TGUITestRunner.UpdateTestTreeState; var node :TTreeNode; begin if TestTree.Items.Count > 0 then begin TestTree.Items.BeginUpdate; try node := TestTree.Items.GetFirstNode; while node <> nil do begin UpdateNodeState(node); node := node.getNextSibling; end finally TestTree.Items.EndUpdate; end; end; end; procedure TGUITestRunner.UpdateStatus(const fullUpdate:Boolean); var i :Integer; TestNumber: Integer; function FormatElapsedTime(milli: Int64):string; var h,nn,ss,zzz: Cardinal; begin h := milli div 3600000; milli := milli mod 3600000; nn := milli div 60000; milli := milli mod 60000; ss := milli div 1000; milli := milli mod 1000; zzz := milli; Result := Format('%d:%2.2d:%2.2d.%3.3d', [h, nn, ss, zzz]); end; begin if ResultsView.Items.Count = 0 then Exit; if fullUpdate then begin FTotalTestsCount := Suite.countEnabledTestCases; if Assigned(Suite) then ResultsView.Items[0].SubItems[0] := IntToStr(FTotalTestsCount) else ResultsView.Items[0].SubItems[0] := ''; end; if TestResult <> nil then begin // Save the test number as we use it a lot TestNumber := TestResult.runCount; if fullUpdate or FTimerExpired or ((TestNumber and 15) = 0) then begin with ResultsView.Items[0] do begin SubItems[1] := IntToStr(TestNumber); SubItems[2] := IntToStr(TestResult.failureCount); SubItems[3] := IntToStr(TestResult.errorCount); SubItems[4] := IntToStr(TestResult.Overrides); SubItems[5] := FormatElapsedTime(TestResult.TotalTime); SubItems[6] := FormatElapsedTime(max(TestResult.TotalTime, FTotalTime)); end; with TestResult do begin ScoreBar.Position := TestNumber - (failureCount + errorCount); ProgressBar.Position := TestNumber; // There is a possibility for zero tests if (TestNumber = 0) and (Suite.CountEnabledTestCases = 0) then LbProgress.Caption := '100%' else LbProgress.Caption := IntToStr((100 * ScoreBar.Position) div ScoreBar.Max) + '%'; end; if FTimerExpired and (TestNumber < FTotalTestsCount) then begin FTimerExpired := False; FUpdateTimer.Enabled := True; end; end; // Allow just the results pane to catch up ResultsPanel.Update; end else begin with ResultsView.Items[0] do begin if (SubItems[0] = '0') or (subItems[0] = '') then begin for i := 1 to 6 do SubItems[i] := '' end else begin if SubItems[0] <> subItems[1] then for i := 1 to 6 do SubItems[i] := '' else begin SubItems[5] := FormatElapsedTime(SelectedTest.ElapsedTestTime); SubItems[6] := FormatElapsedTime(Max(SelectedTest.ElapsedTestTime, FTotalTime)); end; end; end; ResetProgress; end; if fullUpdate then begin // Allow the whole display to catch up and check for key strokes Update; Application.ProcessMessages; end; end; procedure TGUITestRunner.ResetProgress; begin TProgressBarCrack(ScoreBar).ParentColor := True; TProgressBarCrack(ScoreBar).RecreateWnd; ScoreBar.Position := 0; ProgressBar.Position := 0; LbProgress.Caption := ''; end; function TGUITestRunner.AddFailureItem(failure: TTestFailure): TListItem; var item : TListItem; node : TTreeNode; begin assert(assigned(failure)); item := FailureListView.Items.Add; if not f_InternalStart then item.data := Pointer(TestToNode(failure.failedTest)); item.Caption := failure.failedTest.Name; item.SubItems.Add(failure.thrownExceptionName); item.SubItems.Add(failure.thrownExceptionMessage); item.SubItems.Add( failure.LocationInfo + ' ' + failure.AddressInfo ); item.SubItems.Add(failure.StackTrace); if not f_InternalStart then begin node := testToNode(failure.failedTest); while node <> nil do begin node.Expand(false); node := node.Parent; end; end; // if not f_InternalStart then Result := item; end; procedure TGUITestRunner.FillTestTree(RootNode: TTreeNode; ATest: ITest); var i : Integer; l_FolderNode : TTreeNode; l_TestTests : IInterfaceList; begin if ATest = nil then Exit; if acShowFolder.Checked then l_FolderNode := AddFolderNode(TestTree, RootNode, ATest.Folder) else l_FolderNode := RootNode; RootNode := TestTree.Items.AddChild(l_FolderNode, ATest.GetDisplayName); RootNode.Data := TObject(FTests.Add(ATest)); l_TestTests := ATest.Tests; for i := 0 to l_TestTests.count - 1 do FillTestTree(RootNode, l_TestTests[i] as ITest); end; procedure TGUITestRunner.FillTestTree(ATest: ITest); begin TestTree.Items.Clear; FTests.Clear; FillTestTree(nil, Suite); end; procedure TGUITestRunner.SetTreeNodeImage(Node :TTReeNode; imgIndex :Integer); begin while Node <> nil do begin if imgIndex > Node.ImageIndex then begin Node.ImageIndex := imgIndex; Node.SelectedIndex := imgIndex; end; if imgIndex = imgRunning then Node := nil else Node := Node.Parent; end; end; procedure TGUITestRunner.SetSuite(value: ITest); begin FSuite := value; if FSuite <> nil then begin LoadSuiteConfiguration; EnableUI(True); InitTree; end else EnableUI(False) end; procedure TGUITestRunner.DisplayFailureMessage(Item: TListItem); var l_Color : TColor; l_Test : ITest; l_Status : string; begin TestTree.Selected := TTreeNode(Item.Data); if TestTree.Selected = nil then Exit; l_Test := NodeToTest(TestTree.Selected); if l_Test = nil then Exit; l_Color := clFAILURE; if Item.ImageIndex >= imgERROR then l_Color := clERROR; with ErrorMessageRTF do begin Clear; SelAttributes.Size := Self.Font.Size; SelAttributes.Style := [fsBold]; SelText := Item.Caption + ': '; SelAttributes.Color := l_Color; SelAttributes.Style := [fsBold]; SelText := Item.SubItems[0]; Lines.Add(''); SelAttributes.Color := clWindowText; SelAttributes.Style := []; SelText := 'at ' + Item.SubItems[2]; if Item.SubItems[1] <> '' then begin SelAttributes.Color := clWindowText; Lines.Add(''); SelAttributes.Size := 12; SelAttributes.Style := []; SelText := Item.SubItems[1]; SelAttributes.Size := self.Font.Size; end; l_Status := l_Test.Status; if l_Status <> '' then begin Lines.Add(''); Lines.Add(''); SelAttributes.Style := [fsBold]; Lines.Add('Status Messages'); SelAttributes.Style := []; Lines.Add(l_Status); end; if Item.SubItems[3] <> '' then begin Lines.Add(''); SelAttributes.Style := [fsBold]; Lines.Add('StackTrace'); SelAttributes.Style := []; SelText := Item.SubItems[3]; end; end end; procedure TGUITestRunner.ClearFailureMessage; begin ErrorMessageRTF.Clear; end; procedure TGUITestRunner.ClearResult; begin if FTestResult <> nil then begin FTestResult.Free; FTestResult := nil; ClearFailureMessage; end; end; procedure TGUITestRunner.SetUp; var i: Integer; node: TTreeNode; begin FailureListView.Items.Clear; ResetProgress; Update; if (ResultsView.Items[0] <> nil) then with ResultsView.Items[0] do begin if Suite <> nil then begin i := Suite.countEnabledTestCases; SubItems[0] := IntToStr(i); ProgressBar.Max := i end else begin SubItems[0] := ''; ProgressBar.Max:= 10000; end; ScoreBar.Max := ProgressBar.Max; SubItems[1] := ''; SubItems[2] := ''; SubItems[3] := ''; SubItems[4] := ''; SubItems[5] := ''; SubItems[6] := ''; end;//ResultsView.Items[0] for i := 0 to TestTree.Items.Count - 1 do begin node := TestTree.Items[i]; node.ImageIndex := imgNONE; node.SelectedIndex := imgNONE; end; UpdateTestTreeState; end; procedure TGUITestRunner.EnableUI(enable: Boolean); begin SelectAllAction.Enabled := enable; DeselectAllAction.Enabled := enable; SelectFailedAction.Enabled := enable; SelectCurrentAction.Enabled := enable; DeselectCurrentAction.Enabled := enable; HideTestNodesAction.Enabled := enable; ExpandAllNodesAction.Enabled := enable; end; procedure TGUITestRunner.FormCreate(Sender: TObject); begin inherited; InitLogicalOperation; FWasStarted := False; acShowFolder.Checked := False; FTests := TInterfaceList.Create; LoadConfiguration; {$IfDef XE} {$Else} TimeSeparator := ':'; {$EndIf} SetUpStateImages; SetupCustomShortcuts; TestTree.Items.Clear; EnableUI(false); ClearFailureMessage; FUpdateTimer := TTimer.Create(Self); FUpdateTimer.Interval := 200; FUpdateTimer.Enabled := False; FUpdateTimer.OnTimer := OnUpdateTimer; Setup; {$IFDEF VER180} //FastMM built in already FailTestCaseIfMemoryLeakedAction.Enabled := True; ReportMemoryLeaksOnShutdown := ReportMemoryLeakTypeOnShutdownAction.Checked; {$ELSE} {$IFDEF FASTMM} FailTestCaseIfMemoryLeakedAction.Enabled := True; {$IFDEF ManualLeakReportingControl} ReportMemoryLeaksOnShutdown := ReportMemoryLeakTypeOnShutdownAction.Checked; {$ELSE} ReportMemoryLeakTypeOnShutdownAction.Checked := False; ReportMemoryLeakTypeOnShutdownAction.Enabled := False; {$ENDIF} {$ELSE} FailTestCaseIfMemoryLeakedAction.Enabled := False; ReportMemoryLeakTypeOnShutdownAction.Checked := False; ReportMemoryLeakTypeOnShutdownAction.Enabled := False; {$ENDIF} {$ENDIF} if not FailTestCaseIfMemoryLeakedAction.Enabled then FailTestCaseIfMemoryLeakedAction.Checked := False; IgnoreMemoryLeakInSetUpTearDownAction.Enabled := FailTestCaseIfMemoryLeakedAction.Checked; if not IgnoreMemoryLeakInSetUpTearDownAction.Enabled then IgnoreMemoryLeakInSetUpTearDownAction.Checked := False; evFindEdit.TextSource.Document.IsValid; FTestTreeSeacher := TTestTreeSeacher.Create(TestTree.Items); {$IFNDEF Archi} ClearDBBtn.Visible := False; {$ENDIF Archi} {$IfDef InsiderTest} BorderIcons := BorderIcons - [biSystemMenu]; DefaultMonitor := dmDesktop; RunScriptAction.OnUpdate := RunScriptActionUpdate; {$EndIf InsiderTest} LoadDictionariesMenu; ReadSubDirs(PresetsPM, csPresetsExt, csPresetsSubDir, OnSelectPreset); ReadSubDirs(MacrosPM, csMacrosExt, csMacrosSubDir, OnSelectMacros); FClearEtalonPM := nil; {$IfNDef NoScripts} LinkTestForm(Self); {$EndIf NoScripts} end; procedure TGUITestRunner.FormDestroy(Sender: TObject); begin FreeAndNil(FUpdateTimer); ClearResult; AutoSaveConfiguration; Suite := nil; FTests.Free; FTests := nil; FClearEtalonPM := nil; FreeAndNil(FTestTreeSeacher); {$IfNDef NoScripts} UnLinkTestForm; {$EndIf NoScripts} inherited; end; procedure TGUITestRunner.FormShow(Sender: TObject); begin { Set up the GUI nodes in the test nodes. We do it here because the form, the tree and all its tree nodes get recreated in TCustomForm.ShowModal in D8+ so we cannot do it sooner. } SetupGUINodes; CheckStartParams; end; procedure TGUITestRunner.TestTreeClick(Sender: TObject); begin if FRunning then Exit; ProcessClickOnStateIcon; TestTreeChange(Sender, TestTree.Selected); end; procedure TGUITestRunner.TestTreeChange(Sender: TObject; Node: TTreeNode); var i : Integer; begin if (Node <> nil) and (Node = TestTree.Selected) then begin FailureListView.Selected := nil; for i := 0 to FailureListView.Items.Count - 1 do begin if TTreeNode(FailureListView.Items[i].Data) = Node then begin FailureListView.Selected := FailureListView.Items[i]; Break; end; end; UpdateStatus(True); end; end; procedure TGUITestRunner.FailureListViewClick(Sender: TObject); begin if FailureListView.Selected <> nil then TestTree.Selected := TTreeNode(FailureListView.Selected.data); end; procedure TGUITestRunner.FailureListViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin if not Selected then ClearFailureMessage else DisplayFailureMessage(Item); end; function TGUITestRunner.DisableTest(aTest: ITest): Boolean; begin if aTest <> nil then aTest.Enabled := False; Result := True; end; function TGUITestRunner.EnableTest(aTest: ITest): Boolean; begin if aTest <> nil then aTest.Enabled := True; Result := True; end; procedure TGUITestRunner.ApplyToTests(aRoot :TTreeNode; const aFunc :TTestFunc; aStopOnSelect: Boolean); var l_NeedStop: Boolean; procedure lp_DoApply(aRootNode: TTreeNode); var l_Test: ITest; l_Node: TTreeNode; begin if aRootNode <> nil then begin l_Test := NodeToTest(aRootNode); if aFunc(l_Test) then begin l_Node := aRootNode.GetFirstChild; while l_Node <> nil do begin lp_DoApply(l_Node); if aStopOnSelect and ((TestTree.Selected = l_Node) or l_NeedStop) then begin l_NeedStop := True; Break; end; // if aStopOnSelect and ((TestTree.Selected = l_Node) or l_NeedStop) then l_Node := l_Node.GetNextSibling; end; // while l_Node <> nil do end; // if aFunc(l_Test) then end; // if aRootNode <> nil then end; begin TestTree.Items.BeginUpdate; try l_NeedStop := False; lp_DoApply(aRoot) finally TestTree.Items.EndUpdate end; UpdateTestTreeState; end; procedure TGUITestRunner.TestTreeKeyPress(Sender: TObject; var Key: Char); var I: Integer; l_Sel: Boolean; begin if (Key = ' ') and (TestTree.SelectionCount > 0) then begin l_Sel := GetNodeEnabled(TestTree.Selections[0]); for I := 0 to TestTree.SelectionCount - 1 do SetNodeState(TestTree.Selections[I], not l_Sel); UpdateStatus(True); end; end; procedure TGUITestRunner.SelectAllActionExecute(Sender: TObject); begin ClearTestNamesList; ApplyToTests(TestTree.Items.GetFirstNode, EnableTest, False); UpdateStatus(True); end; procedure TGUITestRunner.DeselectAllActionExecute(Sender: TObject); begin ClearTestNamesList; DoDeselectAllActionExecute(Sender); end; procedure TGUITestRunner.SelectFailedActionExecute(Sender: TObject); var i : Integer; l_Node : TTreeNode; begin { deselect all } ApplyToTests(TestTree.Items[0], DisableTest, False); { select failed } for i := 0 to FailureListView.Items.Count - 1 do begin l_Node := TTreeNode(FailureListView.Items[i].Data); SetNodeState(l_Node, True); end; UpdateStatus(True); end; procedure TGUITestRunner.SaveConfigurationActionExecute(Sender: TObject); begin SaveConfiguration end; procedure TGUITestRunner.RestoreSavedActionExecute(Sender: TObject); begin LoadConfiguration end; procedure TGUITestRunner.AutoSaveActionExecute(Sender: TObject); begin with AutoSaveAction do Checked := not Checked; AutoSaveConfiguration; end; procedure TGUITestRunner.ErrorBoxVisibleActionExecute(Sender: TObject); begin with ErrorBoxVisibleAction do begin Checked := not Checked; ErrorBoxSplitter.Visible := Checked; ErrorBoxPanel.Visible := Checked; if Checked then begin // Solve bugs with Delphi4 resizing with constraints ErrorBoxSplitter.Top := ErrorBoxPanel.Top - 8; end end; end; procedure TGUITestRunner.ErrorBoxSplitterMoved(Sender: TObject); begin // Solve bugs with Delphi4 resizing with constraints ErrorBoxSplitter.Top := ErrorBoxPanel.Top - 8; Self.Update; end; procedure TGUITestRunner.ErrorBoxPanelResize(Sender: TObject); begin // Solve bugs with Delphi4 resizing with constraints ErrorBoxSplitter.Top := ErrorBoxPanel.Top - 8; end; function TGUITestRunner.NodeIsGrandparent(aNode: TTreeNode): Boolean; var l_ChildNode: TTreeNode; begin Result := False; if IsNodeFolder(aNode) then Exit; if aNode.HasChildren then begin l_ChildNode := aNode.GetFirstChild; while l_ChildNode <> nil do begin Result := l_ChildNode.HasChildren or Result; l_ChildNode := aNode.GetNextChild(l_ChildNode); end; end; end; procedure TGUITestRunner.CollapseNonGrandparentNodes(aRootNode: TTreeNode); var l_ChildNode: TTreeNode; begin if not NodeIsGrandparent(aRootNode) then aRootNode.Collapse(false); l_ChildNode := aRootNode.GetFirstChild; while l_ChildNode <> nil do begin CollapseNonGrandparentNodes(l_ChildNode); l_ChildNode := aRootNode.GetNextChild(l_ChildNode); end; end; procedure TGUITestRunner.HideTestNodesActionExecute(Sender: TObject); var l_Node: TTreeNode; begin inherited; if TestTree.Items.Count = 0 then Exit; TestTree.Items.BeginUpdate; try l_Node := TestTree.Items[0]; if l_Node <> nil then begin l_Node.Expand(true); CollapseNonGrandparentNodes(l_Node); SelectNode(l_Node); end; finally TestTree.Items.EndUpdate; end; end; procedure TGUITestRunner.HideTestNodesOnOpenActionExecute(Sender: TObject); begin HideTestNodesOnOpenAction.Checked := not HideTestNodesOnOpenAction.Checked; end; procedure TGUITestRunner.ExpandAllNodesActionExecute(Sender: TObject); begin TestTree.FullExpand; if (TestTree.Selected <> nil) then MakeNodeVisible(TestTree.Selected) else if(TestTree.Items.Count > 0) then TestTree.Selected := TestTree.Items[0]; end; procedure TGUITestRunner.RunTheTest(aTest: ITest; aRandom: Boolean); begin if aTest = nil then Exit; if FRunning then begin // warning: we're reentering this method if FRunning is true Assert(FTestResult <> nil); FTestResult.Stop; Exit; end; afw.TryActivateKeyboardLayout; Tl3BatchService.Instance.EnterBatchMode; try FRunning := True; try RunAction.Enabled := False; StopAction.Enabled := True; CopyMessageToClipboardAction.Enabled := False; EnableUI(False); AutoSaveConfiguration; ClearResult; TestResult := TTestResult.Create; try TestResult.addListener(self); TestResult.BreakOnFailures := BreakOnFailuresAction.Checked; TestResult.FailsIfNoChecksExecuted := FailIfNoChecksExecutedAction.Checked; TestResult.FailsIfMemoryLeaked := FailTestCaseIfMemoryLeakedAction.Checked; TestResult.IgnoresMemoryLeakInSetUpTearDown := IgnoreMemoryLeakInSetUpTearDownAction.Checked; aTest.Run(TestResult, aRandom); finally FErrorCount := TestResult.ErrorCount; FFailureCount := TestResult.FailureCount; TestResult.Free; TestResult := nil; end; finally FRunning := False; EnableUI(True); end; finally Tl3BatchService.Instance.LeaveBatchMode; end;//try..finally end; procedure TGUITestRunner.RunActionExecute(Sender: TObject); begin f_InternalStart := False; if Suite = nil then Exit; Setup; RunTheTest(Suite, acRandomTests.Checked); end; procedure TGUITestRunner.ExitActionExecute(Sender: TObject); begin if FTestResult <> nil then FTestResult.Stop; Self.ModalResult := mrCancel; Close; end; procedure TGUITestRunner.BreakOnFailuresActionExecute(Sender: TObject); begin with BreakOnFailuresAction do Checked := not Checked; end; procedure TGUITestRunner.FailIfNoChecksExecutedActionExecute(Sender: TObject); begin with FailIfNoChecksExecutedAction do Checked := not Checked; end; procedure TGUITestRunner.FailTestCaseIfMemoryLeakedActionExecute(Sender: TObject); begin with FailTestCaseIfMemoryLeakedAction do begin Checked := not Checked; IgnoreMemoryLeakInSetUpTearDownAction.Enabled := Checked; if not Checked then IgnoreMemoryLeakInSetUpTearDownAction.Checked := False; end; end; procedure TGUITestRunner.ShowTestCasesWithRunTimePropertiesActionExecute( Sender: TObject); begin with ShowTestCasesWithRunTimePropertiesAction do begin Checked := not Checked; if Checked then WarnOnFailTestOverrideAction.Checked := False; end; end; procedure TGUITestRunner.WarnOnFailTestOverrideActionExecute( Sender: TObject); begin with WarnOnFailTestOverrideAction do begin Checked := not Checked; if Checked then ShowTestCasesWithRunTimePropertiesAction.Checked := False; end; end; procedure TGUITestRunner.ShowTestedNodeActionExecute(Sender: TObject); begin with ShowTestedNodeAction do Checked := not Checked; end; procedure TGUITestRunner.SetUpStateImages; begin TestTree.Images := RunImages; TestTree.StateImages := StateImages; FailureListView.SmallImages := RunImages; end; procedure TGUITestRunner.LoadSuiteConfiguration; begin if Suite <> nil then Suite.LoadConfiguration(IniFileName, UseRegistryAction.Checked, True); end; procedure TGUITestRunner.MakeNodeVisible(aNode: TTreeNode); begin aNode.MakeVisible end; procedure TGUITestRunner.ProcessClickOnStateIcon; var l_HitInfo : THitTests; l_Node : TTreeNode; l_PointPos : TPoint; begin GetCursorPos(l_PointPos); l_PointPos := TestTree.ScreenToClient(l_PointPos); with l_PointPos do begin l_HitInfo := TestTree.GetHitTestInfoAt(X, Y); l_Node := TestTree.GetNodeAt(X, Y); end; if (l_Node <> nil) and (HtOnStateIcon in l_HitInfo) then SwitchNodeState(l_Node); end; procedure TGUITestRunner.UpdateNodeImage(aNode: TTreeNode); begin if not GetNodeEnabled(aNode) then aNode.StateIndex := imgDISABLED else if (aNode.Parent <> nil) and (aNode.Parent.StateIndex <= imgPARENT_DISABLED) then aNode.StateIndex := imgPARENT_DISABLED else aNode.StateIndex := imgENABLED; end; procedure TGUITestRunner.CopyMessageToClipboardActionExecute(Sender: TObject); begin ErrorMessageRTF.SelectAll; ErrorMessageRTF.CopyToClipboard; end; procedure TGUITestRunner.UseRegistryActionExecute(Sender: TObject); begin with UseRegistryAction do Checked := not Checked; end; function TGUITestRunner.GetIniFile(const FileName: string) : tCustomIniFile; begin if UseRegistryAction.Checked then Result := TRegistryIniFile.Create(GetDUnitRegistryKey + FileName) else Result := TIniFile.Create(FileName); end; procedure TGUITestRunner.LoadRegistryAction; begin with TIniFile.Create(IniFileName) do try UseRegistryAction.Checked := ReadBool(cnConfigIniSection, 'UseRegistry', UseRegistryAction.Checked); finally Free; end; end; procedure TGUITestRunner.SaveRegistryAction; begin if UseRegistryAction.Checked then DeleteFile( IniFileName ); with TIniFile.Create(IniFileName) do try WriteBool(cnConfigIniSection, 'UseRegistry', UseRegistryAction.Checked); finally Free; end; end; procedure TGUITestRunner.RunActionUpdate(Sender: TObject); begin RunAction.Enabled := not FRunning and Assigned( Suite ) and (Suite.CountEnabledTestCases > 0); end; procedure TGUITestRunner.CopyMessageToClipboardActionUpdate(Sender: TObject); begin CopyMessageToClipboardAction.Enabled := FailureListView.Selected <> nil; end; procedure TGUITestRunner.SelectCurrentActionExecute(Sender: TObject); begin ApplyToTests(TestTree.Selected, EnableTest, False); SetNodeState(TestTree.Selected, True); UpdateStatus(True); end; procedure TGUITestRunner.DeselectCurrentActionExecute(Sender: TObject); begin ApplyToTests(TestTree.Selected, DisableTest, False); UpdateStatus(True); end; procedure TGUITestRunner.StopActionExecute(Sender: TObject); begin if FTestResult <> nil then FTestResult.Stop; end; procedure TGUITestRunner.StopActionUpdate(Sender: TObject); begin StopAction.Enabled := FRunning and (FTestResult <> nil); end; procedure TGUITestRunner.Status(test: ITest; const Msg: AnsiString); begin if ErrorMessageRTF.Lines.Count = 0 then ErrorMessageRTF.Lines.Add(test.Name + ':'); ErrorMessageRTF.Lines.Add(Msg); ErrorMessageRTF.Update; end; procedure TGUITestRunner.Warning(test: ITest; const Msg: string); begin if ErrorMessageRTF.Lines.Count = 0 then ErrorMessageRTF.Lines.Add(test.Name + ':'); ErrorMessageRTF.Lines.Add(Msg); ErrorMessageRTF.Update; end; procedure TGUITestRunner.ClearStatusMessage; begin ErrorMessageRTF.Lines.Clear; end; procedure TGUITestRunner.CopyProcnameToClipboardActionExecute( Sender: TObject); begin CopyTestNametoClipboard(TestTree.Selected); end; procedure TGUITestRunner.CopyTestNametoClipboard(ANode: TTreeNode); begin if Assigned(ANode) then begin Clipboard.AsText := ANode.Text; end; end; procedure TGUITestRunner.CopyProcnameToClipboardActionUpdate( Sender: TObject); begin (Sender as TAction).Enabled := Assigned(TestTree.Selected); end; function TGUITestRunner.SelectedTest: ITest; begin if TestTree.Selected = nil then Result := nil else begin Result := NodeToTest(TestTree.Selected); if Result = nil then Result := NodeToTest(TestTree.Selected.Parent); end; end; procedure TGUITestRunner.ListSelectedTests; var aTest: ITest; aNode: TTreeNode; begin FSelectedTests.Free; FSelectedTests := nil; FSelectedTests := TInterfaceList.Create; aNode := TestTree.Selected; while Assigned(aNode) do begin aTest := NodeToTest(aNode); if aTest <> nil then FSelectedTests.Add(aTest as ITest); aNode := aNode.Parent; end; end; procedure TGUITestRunner.RunSelectedTestActionExecute(Sender: TObject); begin f_InternalStart := False; Setup; ListSelectedTests; ProgressBar.Max := 1; ScoreBar.Max := 1; RunTheTest(Suite, False); {$IFDEF VER130} FreeAndNil(FSelectedTests); {$ELSE} FSelectedTests.Free; FSelectedTests := nil; {$ENDIF} end; procedure TGUITestRunner.RunSelectedTestActionUpdate(Sender: TObject); var aTest :ITest; begin ATest := SelectedTest; RunSelectedTestAction.Enabled := (aTest <> nil) and (aTest.CountTestCases = 1); end; class procedure TGUITestRunner.RunTest(test: ITest); var myform: TGUITestRunner; begin Application.CreateForm(TGUITestRunner, MyForm); with MyForm do begin try suite := test; ShowModal; finally MyForm.Free; end; end; end; class procedure TGUITestRunner.RunRegisteredTests; begin RunTest(RegisteredTests); end; procedure TGUITestRunner.EndSuite(suite: ITest); begin UpdateStatus(True); end; procedure TGUITestRunner.StartSuite(suite: ITest); begin end; procedure TGUITestRunner.TestTreeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var NewNode: TTreeNode; begin { a version of this code was in the pmTestTreePopup event, but it created an intermittent bug. OnPopup is executed if any of the ShortCut keys belonging to items on the popup menu are used. This caused weird behavior, with the selected node suddenly changing to whatever was under the mouse cursor (or AV-ing if the mouse cursor wasn't over the DUnit form) when the user executed one of the keyboard shortcuts. It was intermittent most likely because the ShortCuts belonged to Main Menu items as well (shared from the Action.ShortCut), and the bug dependended on the Popup menu items receiving the ShortCut Windows message first. This code ensures that node selection occurs prior to the popup menu appearing when the user right-clicks on a non-selected tree node. } if (Button = mbRight) and (htOnItem in TestTree.GetHitTestInfoAt(X, Y)) then begin NewNode := TestTree.GetNodeAt(X, Y); if TestTree.Selected <> NewNode then TestTree.Selected := NewNode; end; end; procedure TGUITestRunner.GoToNextSelectedTestActionExecute( Sender: TObject); var aNode: TTreeNode; begin if TestTree.Selected <> nil then begin aNode := TestTree.Selected.GetNext; while aNode <> nil do begin if SelectNodeIfTestEnabled(aNode) then break else aNode := aNode.GetNext; end; end; end; function TGUITestRunner.SelectNodeIfTestEnabled(aNode: TTreeNode): boolean; var l_Test: ITest; begin l_Test := NodeToTest(aNode); if (l_Test <> nil) and (l_Test.Enabled) and (IsTestMethod(l_Test)) then begin Result := True; SelectNode(aNode); end else Result := False; end; procedure TGUITestRunner.GoToPrevSelectedTestActionExecute( Sender: TObject); var aNode: TTreeNode; begin if TestTree.Selected <> nil then begin aNode := TestTree.Selected.GetPrev; while aNode <> nil do begin if SelectNodeIfTestEnabled(aNode) then break else aNode := aNode.GetPrev; end; end; end; procedure TGUITestRunner.SelectNode(node: TTreeNode); begin node.Selected := true; MakeNodeVisible(node); end; procedure TGUITestRunner.SetupCustomShortcuts; begin { the following shortcuts are not offered as an option in the form designer, but can be set up here } GoToNextSelectedTestAction.ShortCut := ShortCut(VK_RIGHT, [ssCtrl]); GoToPrevSelectedTestAction.ShortCut := ShortCut(VK_LEFT, [ssCtrl]); end; procedure TGUITestRunner.SetupGUINodes; var l_Node: TTreeNode; l_Test: ITest; begin { Set up the GUI nodes in the test nodes. We do it here because the form, the tree and all its tree nodes get recreated in TCustomForm.ShowModal in D8+ so we cannot do it sooner. This method is also called after loading test libraries } l_Node := TestTree.Items.GetFirstNode; while Assigned(l_Node) do begin // Get and check the test for the tree node l_Test := NodeToTest(l_Node); if l_Test <> nil then // Save the tree node in the test and get the next tree node l_Test.GUIObject := l_Node; l_Node := l_Node.GetNext; end; end; const PopupTitle = 'TestCase Run-Time Applied Properties'; PopupPrevious= ' Previous'; PopupRun = ' Run Selected Test'; PopupNext = ' Next'; NoChecksStrT = ' FailsOnNoChecksExecuted := True '; NoChecksStrF = ' FailsOnNoChecksExecuted := False'; MemLeakStrT = ' FailsOnMemoryLeak := True '; MemLeakStrF = ' FailsOnMemoryLeak := False'; MemGainStrT = ' FailsOnMemoryRecovery := True '; MemGainStrF = ' FailsOnMemoryRecovery := False'; MemBytesStr0 = ' AllowedMemoryLeakSize ' ; IgnoreStrT = ' IgnoreSetUpTearDownLeaks := True '; IgnoreStrF = ' IgnoreSetUpTearDownLeaks := False'; procedure TGUITestRunner.TestCasePropertiesActionExecute(Sender: TObject); var l_Node: TTreeNode; l_Test: ITest; begin if TestTree.Selected <> nil then begin l_Node := TestTree.Selected; if (l_Node <> nil) then begin l_Test := NodeToTest(l_Node); if (l_Test <> nil) and IsTestMethod(l_Test) then begin if l_Test.FailsOnNoChecksExecuted then FNoChecksStr := NoChecksStrT else FNoChecksStr := NoChecksStrF; fNoCheckExecutedPtyOverridden := FailIfNoChecksExecutedAction.Checked and (not l_Test.FailsOnNoChecksExecuted); if l_Test.FailsOnMemoryLeak then FMemLeakStr := MemLeakStrT else FMemLeakStr := MemLeakStrF; fMemLeakDetectedPtyOverridden := FailTestCaseIfMemoryLeakedAction.Checked and (not l_Test.FailsOnMemoryLeak); if (l_Test.FailsOnMemoryLeak and l_Test.FailsOnMemoryRecovery) then FMemGainStr := MemGainStrT else FMemGainStr := MemGainStrF; if (l_Test.IgnoreSetUpTearDownLeaks) and l_Test.FailsOnMemoryLeak then FIgnoreLeakStr := IgnoreStrT else FIgnoreLeakStr := IgnoreStrF; FIgnoreSetUpTearDownLeakPtyOverridden := l_Test.IgnoreSetUpTearDownLeaks and l_Test.FailsOnMemoryLeak and (not IgnoreMemoryLeakInSetUpTearDownAction.Checked); FBytes := ':= ' + IntToStr(l_Test.AllowedMemoryLeakSize) + ' Bytes'; FMemBytesStr := MemBytesStr0 + FBytes; TestCaseProperty.Popup(Self.Left + FPopupX,Self.Top + FPopupY); end; // if IsTestMethod(l_Test) then end; l_Test := nil; end; end; procedure TGUITestRunner.Previous1Click(Sender: TObject); begin GoToPrevSelectedTestActionExecute(Self); TestCasePropertiesActionExecute(self); end; procedure TGUITestRunner.Next1Click(Sender: TObject); begin GoToNextSelectedTestActionExecute(Self); TestCasePropertiesActionExecute(self); end; procedure TGUITestRunner.TestCasePropertiesMeasureItem(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer); var ImageSize: TSize; begin if GetTextExtentPoint32(ACanvas.Handle, PChar(PopupTitle), Length(PopupTitle), ImageSize) then begin Width := ImageSize.cx + 60; Height := ImageSize.cy + 4; end; end; procedure TGUITestRunner.MenuLooksInactive(ACanvas: TCanvas; ARect: TRect; Selected: Boolean; ATitle: string; TitlePosn: UINT; PtyOveridesGUI: boolean); var Count: integer; SecondPart: string; SecondRect: TRect; begin if TitlePosn = DT_CENTER then ACanvas.Font.Style := [fsBold]; if Selected then ACanvas.Font.Color := clBlack; if PtyOveridesGUI then ACanvas.Brush.Color := clYellow else ACanvas.Brush.Color := TColor($C0FCC0); //Sort of Moneygreen ACanvas.FillRect(ARect); Count := Pos(':=', ATitle); if Count = 0 then DrawText(ACanvas.Handle, PChar(ATitle), Length(ATitle), ARect, DT_VCENTER or DT_SINGLELINE or DT_NOCLIP or DT_NOPREFIX or TitlePosn) else begin DrawText(ACanvas.Handle, PChar(ATitle), Count-1, ARect, DT_VCENTER or DT_SINGLELINE or DT_NOCLIP or DT_NOPREFIX or TitlePosn); SecondPart := Copy(ATitle, Count, Length(ATitle)); SecondRect := ARect; SecondRect.Left := 5 * ((ARect.Right - ARect.Left) div 8); DrawText(ACanvas.Handle, PChar(SecondPart), Length(SecondPart), SecondRect, DT_VCENTER or DT_SINGLELINE or DT_NOCLIP or DT_NOPREFIX or TitlePosn) end; end; procedure TGUITestRunner.MenuLooksActive(ACanvas: TCanvas; ARect: TRect; Selected: Boolean; ATitle: string; TitlePosn: UINT); begin ACanvas.FillRect(ARect); DrawText(ACanvas.Handle, PChar(ATitle), Length(ATitle), ARect, DT_VCENTER or DT_SINGLELINE or DT_NOCLIP or DT_NOPREFIX or TitlePosn); end; procedure TGUITestRunner.TestCasePropertiesDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); begin MenuLooksInactive(ACanvas, ARect, Selected, PopupTitle, DT_CENTER, False); end; procedure TGUITestRunner.Previous1DrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); begin MenuLooksActive(ACanvas, ARect, Selected, PopupPrevious, DT_LEFT); end; procedure TGUITestRunner.RunSelectedTest1DrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); begin MenuLooksActive(ACanvas, ARect, Selected, PopupRun, DT_LEFT); end; procedure TGUITestRunner.Next1DrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); begin MenuLooksActive(ACanvas, ARect, Selected, PopupNext, DT_LEFT); end; procedure TGUITestRunner.FailNoCheckExecutedMenuItemDrawItem( Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); begin MenuLooksInactive(ACanvas, ARect, Selected, FNoChecksStr, DT_LEFT, fNoCheckExecutedPtyOverridden); end; procedure TGUITestRunner.FailsOnMemoryLeakMenuItemDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); begin MenuLooksInactive(ACanvas, ARect, Selected, FMemLeakStr, DT_LEFT, fMemLeakDetectedPtyOverridden); end; procedure TGUITestRunner.FailsOnMemoryRecoveryMenuItemDrawItem( Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); begin MenuLooksInactive(ACanvas, ARect, Selected, FMemGainStr, DT_LEFT, False); end; procedure TGUITestRunner.AllowedLeakSizeMemuItemDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); begin MenuLooksInactive(ACanvas, ARect, Selected, FMemBytesStr, DT_LEFT, False); end; procedure TGUITestRunner.TestCaseIgnoreSetUpTearDownLeaksMenuItemDrawItem( Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); begin MenuLooksInactive(ACanvas, ARect, Selected, FIgnoreLeakStr, DT_LEFT, FIgnoreSetUpTearDownLeakPtyOverridden); end; procedure TGUITestRunner.pmTestTreePopup(Sender: TObject); var l_Node: TTreeNode; l_Test: ITest; begin if TestTree.Selected <> nil then begin l_Node := TestTree.Selected; if (l_Node <> nil) then begin l_Test := NodeToTest(l_Node); TestCasePopup.Enabled := (l_Test <> nil) and IsTestMethod(l_Test); end; l_Test := nil; end; end; function TGUITestRunner.GetPropertyName(const Caption: string): string; var TempStr: string; PosSpace: integer; begin TempStr := Trim(Caption); PosSpace := Pos(' ',TempStr); if (PosSpace > 1) then result := Copy(TempStr, 1, PosSpace-1); end; procedure TGUITestRunner.FailNoCheckExecutedMenuItemClick(Sender: TObject); begin Clipboard.AsText := GetPropertyName(NoChecksStrT); end; procedure TGUITestRunner.FailsOnMemoryLeakMenuItemClick(Sender: TObject); begin Clipboard.AsText := GetPropertyName(MemLeakStrT); end; procedure TGUITestRunner.AllowedLeakSizeMemuItemClick(Sender: TObject); begin Clipboard.AsText := GetPropertyName(MemBytesStr0); end; procedure TGUITestRunner.FailsOnMemoryRecoveryMenuItemClick( Sender: TObject); begin Clipboard.AsText := GetPropertyName(MemGainStrT); end; procedure TGUITestRunner.TestCaseIgnoreSetUpTearDownLeaksMenuItemClick( Sender: TObject); begin Clipboard.AsText := GetPropertyName(IgnoreStrT); end; procedure TGUITestRunner.RunSelectedTestAltActionExecute(Sender: TObject); begin RunSelectedTestActionExecute(Self); TestCasePropertiesActionExecute(Self); end; procedure TGUITestRunner.IgnoreMemoryLeakInSetUpTearDownActionExecute( Sender: TObject); begin with IgnoreMemoryLeakInSetUpTearDownAction do Checked := not Checked; end; procedure TGUITestRunner.ReportMemoryLeakTypeOnShutdownActionExecute( Sender: TObject); begin with ReportMemoryLeakTypeOnShutdownAction do begin Checked := not Checked; {$IFDEF VER180} ReportMemoryLeaksOnShutdown := Checked; {$ELSE} {$IFDEF FASTMM} {$IFDEF ManualLeakReportingControl} ReportMemoryLeaksOnShutdown := Checked; {$ENDIF} {$ENDIF} {$ENDIF} end; // with end; procedure TGUITestRunner.acFindNodeUpdate(Sender: TObject); begin (Sender as TAction).Enabled := evFindEdit.TextLen > 0; end; procedure TGUITestRunner.acFindNodeExecute(Sender: TObject); var l_FirstSelNode: TTreeNode; begin FTestTreeSeacher.aFolderMode := acShowFolder.Checked and acFolderMode.Checked; FTestTreeSeacher.aFoundNode := TestTree.Selected; if evFindEdit.Modified then begin FTestTreeSeacher.aFindStr := evFindEdit.Buffer; evFindEdit.Modified := False; Try2RemeberInHistory; end; // if evFindEdit.Modified then if FTestTreeSeacher.Find then begin TestTree.Selected := FTestTreeSeacher.aFoundNode; if acNeedSelect.Checked or acNeedSelectAll.Checked then // А здесь мы делаем выделяем все... begin TestTree.Items.BeginUpdate; try SelectCurrentActionExecute(TestTree.Selected); if acNeedSelectAll.Checked then begin l_FirstSelNode := TestTree.Selected; FTestTreeSeacher.aFoundNode := TestTree.Selected; while FTestTreeSeacher.Find do begin TestTree.Selected := FTestTreeSeacher.aFoundNode; SelectCurrentActionExecute(TestTree.Selected); end; // while FTestTreeSeacher.Find do TestTree.Selected := l_FirstSelNode; end; //if acNeedSelectAll.Checked then finally TestTree.Items.EndUpdate; end; GoToNextSelectedTestActionExecute(Sender); end; // if acNeedSelect.Checked then end // if FTestTreeSeacher.Find then else ShowMessage('Тест с подходящим названием не найден!'); TestTree.SetFocus; end; procedure TGUITestRunner.acFindDirectionExecute(Sender: TObject); begin if acFindDirection.ImageIndex = cnIndexDown then acFindDirection.ImageIndex := cnIndexUp else acFindDirection.ImageIndex := cnIndexDown; acFindDirection.Caption := csHintStr[acFindDirection.ImageIndex]; acFindDirection.Hint := csHintStr[acFindDirection.ImageIndex]; FTestTreeSeacher.aFindDown := acFindDirection.ImageIndex = cnIndexDown; end; procedure TGUITestRunner.CheckDirection(Sender: TObject; Key: Word); begin if (Key = 38) and FTestTreeSeacher.aFindDown then acFindDirectionExecute(Sender); if (Key = 40) and not FTestTreeSeacher.aFindDown then acFindDirectionExecute(Sender); end; procedure TGUITestRunner.TestTreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin acNeedSelectAll.Checked := False; if Shift = [] then if acFindNode.Enabled and ((Key = 40) or (Key = 38)) then begin CheckDirection(Sender, Key); if (FTestTreeSeacher.aFindStatus <> fsNotFound) then begin acFindNodeExecute(Sender); if FTestTreeSeacher.aFindStatus = fsFound then Key := 0; end; // if (Key = 13) or (Key = 40) or (Key = 38) then end; end; procedure TGUITestRunner.acShowFolderExecute(Sender: TObject); begin InitTree; SetupGUINodes; end; function TGUITestRunner.GetNodeEnabled(aNode: TTreeNode): Boolean; var i : Integer; l_Test : ITest; begin l_Test := NodeToTest(aNode); if l_Test = nil then begin Result := False; for i := 0 to aNode.Count - 1 do begin if GetNodeEnabled(aNode[i]) then begin Result := True; Break; end; // if GetNodeEnabled(aNode[k]) then end; // for i := 0 to aNode.Count - 1 do end else Result := l_Test.Enabled; end; {function} procedure TGUITestRunner.SetNodeEnabled(aNode: TTreeNode; aValue: Boolean){: Boolean}; var l_Test: ITest; begin l_Test := NodeToTest(aNode); if l_Test <> nil then l_Test.Enabled := aValue; end; procedure TGUITestRunner.acFolderModeUpdate(Sender: TObject); var l_Action: TAction; begin l_Action := (Sender as TAction); if evFindEdit.TextLen > 0 then begin l_Action.Enabled := acShowFolder.Checked; if not acShowFolder.Checked then l_Action.Checked := False; end // if not FShowFolder then else l_Action.Enabled := False; end; procedure TGUITestRunner.TestTreeCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); var l_Test: ITest; begin DefaultDraw := True; if not (cdsSelected in State) then if acShowFolder.Checked and IsNodeFolder(Node) then if CheckFolderExcluded(Node.Text) then Sender.Canvas.Font.Color := clRed else Sender.Canvas.Font.Color := clBlue else if Node.Level > 0 then begin l_Test := NodeToTest(Node); if (l_Test <> nil) and CheckTestExcluded(l_Test.Name, l_Test.Folder) then Sender.Canvas.Font.Color := clRed; if Node.Level > 1 then begin l_Test := NodeToTest(Node.Parent); if (l_Test <> nil) and CheckTestExcluded(l_Test.Name, l_Test.Folder) then Sender.Canvas.Font.Color := clRed; end; // if Node.Level > 1 then end; end; procedure TGUITestRunner.acSelectExcludedExecute(Sender: TObject); begin ChangeState4Test(True, True); end; procedure TGUITestRunner.ChangeState4Test(anEnable, anExcluded: Boolean); var l_NextNode : TTreeNode; function lp_HasChecked(const aNode: TTreeNode): Boolean; var i: Integer; begin Result := False; for i := 0 to aNode.Count - 1 do if aNode[i].StateIndex = imgENABLED then begin Result := True; Break; end; // if aNode[i].StateIndex = imgENABLED then end; procedure lp_CheckParent(const aNode: TTreeNode); var l_Node : TTreeNode; begin l_Node := aNode; while l_Node <> nil do begin if not anEnable and lp_HasChecked(l_Node) then Break; SetNodeEnabled(l_Node, anEnable); l_Node := l_Node.Parent; end; // while l_Node <> l_NextNode then end; procedure lp_SelectChildren(const aNode: TTreeNode); var l_Node : TTreeNode; begin l_NextNode := aNode.GetNextSibling; if btnShowFolder.Down and (l_NextNode = nil) then begin l_NextNode := aNode.Parent; l_NextNode := l_NextNode.GetNextSibling; if l_NextNode <> nil then l_NextNode := l_NextNode.GetNext; end; // if FolderNodeBtm.Checked and (l_NextNode = nil) then l_Node := aNode; while l_Node <> l_NextNode do begin SetNodeEnabled(l_Node, anEnable); l_Node := l_Node.GetNext; if IsNodeFolder(l_Node) then Break; end; // while l_Node <> l_NextNode then lp_CheckParent(aNode); end; var l_TopNode : TTreeNode; l_Test : ITest; begin TestTree.Items.BeginUpdate; try l_TopNode := TestTree.Items[0]; l_NextNode := l_TopNode.GetNext; // Корневой узел не рассматриваем... while l_NextNode <> nil do begin if anExcluded and IsNodeFolder(l_NextNode) then if CheckFolderExcluded(l_NextNode.Text) then lp_SelectChildren(l_NextNode) else l_NextNode := l_NextNode.GetNext else begin if IsNodeFolder(l_NextNode) then l_NextNode := l_NextNode.GetNext else begin l_Test := NodeToTest(l_NextNode); if anExcluded then if CheckTestExcluded(l_Test.Name, l_Test.Folder) then lp_SelectChildren(l_NextNode) else l_NextNode := l_NextNode.GetNext else if NeedRunTest(l_Test.Name) then lp_SelectChildren(l_NextNode) else l_NextNode := l_NextNode.GetNext; end; end;//anExcluded and IsNodeFolder(l_NextNode) end; // while l_Node <> nil do // if anEnable then // SetNodeEnabled(l_TopNode, anEnable); UpdateNodeState(l_TopNode); finally TestTree.Items.EndUpdate; end; UpdateStatus(True); end; procedure TGUITestRunner.acDeselectExcludedExecute(Sender: TObject); begin ChangeState4Test(False, True); end; procedure TGUITestRunner.acDeleteEtalonsExecute(Sender: TObject); var l_Test : ITest; l_TopNode : TTreeNode; l_NextNode : TTreeNode; l_TestName : AnsiString; l_ParentTest : ITest; begin if FClearEtalonPM <> nil then begin TestTree.Items.BeginUpdate; try FClearEtalonPM.OnClick(FClearEtalonPM); finally TestTree.Items.EndUpdate; end; end // if FClearEtalonPM then else begin TestTree.Items.BeginUpdate; try l_TopNode := TestTree.Items[0]; l_NextNode := l_TopNode.GetNext; // Корневой узел не рассматриваем... l_ParentTest := nil; while l_NextNode <> nil do begin if not IsNodeFolder(l_NextNode) and (l_NextNode.HasChildren or (l_ParentTest <> nil)) then begin l_Test := NodeToTest(l_NextNode); if l_Test.HasScriptChildren then l_ParentTest := l_Test else if l_Test.Enabled then begin l_TestName := FindDocID(l_Test.Name); if l_TestName = '' then l_TestName := l_Test.Name; l_Test.ClearEtalons; DeleteEtalons(l_TestName, l_Test.GetSubFolder, l_ParentTest <> nil); if l_ParentTest <> nil then DeleteEtalons(CorrectScriptKPageName(l_Test), l_Test.GetSubFolder, l_ParentTest <> nil); end; // if l_Test.Enabled then end; // if not IsNodeFolder(l_NextNode) and l_NextNode.HasChildren then l_NextNode := l_NextNode.GetNext; end; // while l_NextNode <> nil do finally TestTree.Items.EndUpdate; end; end; end; procedure TGUITestRunner.acOpenExcludeFileAccept(Sender: TObject); begin with (Sender as TFileOpen) do begin LoadExcludedFromFile(Dialog.FileName); FInitDirForExclude := ExtractFileDir(Dialog.FileName); end; // with (Sender as TFileOpen) do end; procedure TGUITestRunner.acOpenExcludeFileBeforeExecute(Sender: TObject); begin with (Sender as TFileOpen) do Dialog.InitialDir := FInitDirForExclude; end; procedure TGUITestRunner.acOpenTestListAccept(Sender: TObject); begin with (Sender as TFileOpen) do begin LoadItemFlagsFromFile(Dialog.FileName); FInitDirForError := ExtractFileDir(Dialog.FileName); end; // with (Sender as TFileOpen) do end; procedure TGUITestRunner.CheckStartParams; begin CheckFileParam; CheckNeedRandom; ChangeState4Test(True, False); LoadDocumentIDList; end; procedure TGUITestRunner.acOpenTestListBeforeExecute(Sender: TObject); begin with (Sender as TFileOpen) do Dialog.InitialDir := FInitDirForError; end; procedure TGUITestRunner.FormClose(Sender: TObject; var Action: TCloseAction); begin {$IfDef InsiderTest} if DisableClose then Action := caNone; {$EndIf InsiderTest} end; procedure TGUITestRunner.ExitActionUpdate(Sender: TObject); begin {$IfDef InsiderTest} ExitAction.Visible := false; ExitAction.Enabled := false; {$EndIf InsiderTest} end; procedure TGUITestRunner.acSelect2CurrentExecute(Sender: TObject); begin ApplyToTests(TestTree.Items.GetFirstNode, EnableTest, True); UpdateStatus(True); end; function TGUITestRunner.InvertTest(aTest: ITest): Boolean; begin if aTest <> nil then begin if (aTest.GUIObject as TTreeNode).Level > 0 then aTest.Enabled := not aTest.Enabled; end; // if aTest <> nil then Result := True; end; procedure TGUITestRunner.acInvertTestsExecute(Sender: TObject); begin ApplyToTests(TestTree.Items.GetFirstNode, InvertTest, False); UpdateStatus(True); end; procedure TGUITestRunner.acRandomTestsUpdate(Sender: TObject); begin (Sender as TAction).Enabled := True; end; procedure TGUITestRunner.acSaveSelectedAccept(Sender: TObject); var l_Test : ITest; l_Out : Tl3CustomFiler; l_Node : TTreeNode; begin l_Out := Tl3CustomDosFiler.Make((Sender as TFileSaveAs).Dialog.FileName, l3_fmWrite); try l_Out.Open; try l_Node := TestTree.Items[0]; l_Node := l_Node.GetNext; // Корневой узел не рассматриваем... while l_Node <> nil do begin l_Test := NodeToTest(l_Node); if (l_Test <> nil) and GetNodeEnabled(l_Node) and IsTestMethod(l_Test) then begin l_Test := NodeToTest(l_Node.Parent); if l_Test.HasScriptChildren then l_Test := NodeToTest(l_Node); l_Out.WriteLn(l_Test.Name); end; // if (l_Test <> nil) and (l_Test.Enabled) and (IsTestMethod(l_Test)) then l_Node := l_Node.GetNext; end; // while l_Node <> nil do finally l_Out.Close; end;//try..finally finally FreeAndNil(l_Out); end;//try..finally end; function TGUITestRunner.GetTestFileName(aTest: ITest): string; var l_Node : TTreeNode; l_Test : ITest; l_FileName: String; begin Result := ''; l_Test := aTest; if Assigned(l_Test) then begin l_FileName := NormalDir(FileFromCurrent('Auto', True, False)) + l_Test.Name; if FileExists(l_FileName) then Result := l_FileName else begin if (l_Test.Name = 'DoIt') and (l_Test.GuiObject <> nil) then begin l_Node := (l_Test.GuiObject as TTreeNode).Parent; l_Test := NodeToTest(l_Node); end; // if (l_Test.Name = 'DoIt') and (l_Test.GuiObject <> nil) then l_FileName := NormalDir(FileFromCurrent('Scripts', True, False)) + l_Test.Name + '.script'; if FileExists(l_FileName) then Result := l_FileName; end; // if not FileExists(Result) then end; // if Assigned(l_Test) then end; procedure TGUITestRunner.OpenFile(const aFileName: string); const c_ErrFNF = 'File not found!'; var a_Result: array[0..MAX_PATH - 1] of Char; begin if not FileExists(aFileName) then raise Exception.Create(c_ErrFNF); if FindExecutable(PChar(ExtractFileName(aFileName)), PChar(ExtractFileDir(aFileName)), a_Result) > 32 then ShellExecute(0, nil, PChar(aFileName), nil, PChar(ExtractFilePath(aFileName)), SW_SHOWNORMAL) else ShellExecute(0, nil, 'notepad', PChar(aFileName), PChar(ExtractFilePath(aFileName)), SW_SHOWNORMAL); end; procedure TGUITestRunner.acOpenScriptExecute(Sender: TObject); var l_Test: ITest; l_FileName: string; begin l_Test := NodeToTest(TestTree.Selected); l_FileName := GetTestFileName(l_Test); //ShellExecute(0, nil, 'notepad', PChar(l_FileName), PChar(ExtractFilePath(l_FileName)), SW_SHOWNORMAL); OpenFile(l_FileName); end; procedure TGUITestRunner.TestTreeDblClick(Sender: TObject); begin acOpenScript.Execute; end; function TGUITestRunner.DictionariesPath(aDictionary: TDictionary): string; begin Result := NormalDir(FileFromCurrent(csDictionarySubDir[aDictionary], True, False)); end; procedure TGUITestRunner.DictionaryMenuItemClick(aSender: TObject); var l_FileName: string; l_ParentItem: TDictionaryMenuItem; begin Assert(aSender is TMenuItem); Assert(TMenuItem(aSender).Parent is TDictionaryMenuItem); l_ParentItem := TDictionaryMenuItem(TMenuItem(aSender).Parent); l_FileName := DictionariesPath(l_ParentItem.Dictionary) + TMenuItem(aSender).Caption; if FileExists(l_FileName) then OpenFile(l_FileName) else ShowMessageFmt('Словарь %s не найден. Возможно, он был удалён.'#13#10'Попробуйте перечитать тесты.', [l_FileName]); end; procedure TGUITestRunner.LoadDictionariesMenu; function l_GetDictionaryMenuItem(aDict: TDictionary): TMenuItem; var I: Integer; begin for I := 0 to MainMenu.Items.Count - 1 do if MainMenu.Items[I] is TDictionaryMenuItem then if TDictionaryMenuItem(MainMenu.Items[I]).Dictionary = aDict then begin Result := MainMenu.Items[I]; Exit; end; Result := TDictionaryMenuItem.Create(Self, aDict); Result.Caption := csDictionaryMenuItemCaption[aDict]; MainMenu.Items.Add(Result); end; var l_Dict: TDictionary; l_MenuItem: TMenuItem; begin for l_Dict := Low(TDictionary) to High(TDictionary) do begin l_MenuItem := l_GetDictionaryMenuItem(l_Dict); l_MenuItem.Clear; ReadSubDirs(l_MenuItem, csDictionaryExt, csDictionarySubDir[l_Dict], DictionaryMenuItemClick); end; end; procedure TGUITestRunner.acOpenScriptUpdate(Sender: TObject); var l_Node: TTreeNode; l_Test: ITest; l_Result: Boolean; begin l_Result := Assigned(TestTree.Selected); if l_Result then begin l_Test := NodeToTest(TestTree.Selected); l_Result := Length(GetTestFileName(l_Test)) > 0; end; (Sender as TAction).Enabled := l_Result; end; procedure TGUITestRunner.OnSelectPreset(Sender: TObject); var l_ParentDir : string; l_PresetName : string; begin l_ParentDir := CheckParentDir(Sender, PresetsPM); FInitDirForError := FileFromCurrent(csPresetsSubDir, True, false) + l_ParentDir; l_PresetName := FInitDirForError + (Sender as TMenuItem).Caption; LoadItemFlagsFromFile(l_PresetName); end; procedure TGUITestRunner.RunScriptActionAccept(Sender: TObject); begin with (Sender as TFileOpen) do begin {$IfDef InsiderTest} if g_DebuggerForm <> nil then begin g_DebuggerForm.LoadScriptFromFile(Dialog.FileName); g_DebuggerForm.Show; g_DebuggerForm.RunScript; end; // if g_DebuggerForm <> nil then {$ENDIF InsiderTest} end; // with (Sender as TFileOpen) do end; procedure TGUITestRunner.RunScriptActionUpdate(Sender: TObject); begin {$IfDef InsiderTest} (Sender as TCustomAction).Visible := g_DebuggerForm <> nil; {$ELSE} (Sender as TCustomAction).Visible := False; {$ENDIF InsiderTest} end; procedure TGUITestRunner.OnSelectMacros(Sender: TObject); var l_ParentDir : string; l_PresetName : string; {$IFDEF RunInDebugger} l_MacrosName : string; l_DirForMacros : string; {$ELSE} l_Test : ITest; {$ENDIF RunInDebugger} begin l_PresetName := CheckParentDir(Sender, MacrosPM); {$IFDEF RunInDebugger} l_DirForMacros := FileFromCurrent('Macros\', True, false) + l_PresetName; l_MacrosName := l_DirForMacros + (Sender as TMenuItem).Caption; if g_DebuggerForm <> nil then begin g_DebuggerForm.LoadScriptFromFile(l_MacrosName); g_DebuggerForm.Show; g_DebuggerForm.RunScript; end; // if g_DebuggerForm <> nil then {$ELSE} f_InternalStart := True; l_ParentDir := CheckParentDir(Sender, PresetsPM); {$IfDef NoScripts} Assert(false); {$Else NoScripts} l_Test := TMacroTest.Create(l_PresetName + (Sender as TMenuItem).Caption, ''); try RunTheTest(l_Test, False); finally l_Test := nil; end; {$EndIf NoScripts} {$ENDIF RunInDebugger} end; procedure TGUITestRunner.ReadSubMenuItems(aMenuItem: TMenuItem; aExt, aSubDir: string; anEvent: TNotifyEvent; aStartIndex: Integer); var l_Index: Integer; function l_PresetAdd(const aFileName: string): Boolean; var l_Item : TMenuItem; l_PresetName : string; begin l_PresetName := ExtractFileName(aFileName); l_Item := TMenuItem.Create(Self); l_Item.AutoHotkeys := maManual; l_Item.Caption := l_PresetName; aMenuItem.Insert(l_Index, l_Item); l_Item.OnClick := anEvent; CheckMenuItem(l_Item); Result := True; Inc(l_Index); end; var l_Dir : String; l_FPStub : Pointer; begin l_Index := aStartIndex; aMenuItem.AutoHotkeys := maManual; l_Dir := FileFromCurrent(aSubDir, True, false); l_FPStub := l3LocalStub(@l_PresetAdd); try ProcessFilesWithMask(l_Dir, aExt, TFileProcessingFunc(l_FPStub)); finally l3FreeLocalStub(l_FPStub); end; aMenuItem.Visible := aMenuItem.Count > 0; end; procedure TGUITestRunner.acReReadAutoTestsExecute(Sender: TObject); var i : Integer; l_List : IInterfaceList; l_Count : Integer; l_Test : ITest; l_TestSuite: ITestSuite; l_RootSuite: ITestSuite; begin l_RootSuite := RegisteredTests; Assert(l_RootSuite <> nil); l_List := l_RootSuite.Tests; try l_Count := l_List.Count - 1; for i := 0 to l_Count do begin l_Test := ITest(l_List[i]); if Supports(l_Test, ITestSuite, l_TestSuite) then l_TestSuite.ReReadAbstractTests; end; // for i := 0 to l_Count do finally l_List := nil; end; InitTree; SetupGUINodes; LoadDictionariesMenu; end; procedure TGUITestRunner.Try2RemeberInHistory; const cnItemCount = 19; var l_Index: Integer; begin if not evFindEdit.Items.FindData(evFindEdit.Buffer, l_Index) then begin if evFindEdit.Items.Count > cnItemCount then evFindEdit.Items.DeleteLast; evFindEdit.Items.Add(evFindEdit.Text); end; // if not evFindEdit.Items.FindData(evFindEdit.Buffer, l_Index) then end; procedure TGUITestRunner.ReadSubDirs(aMenuItem: TMenuItem; aExt, aSubDir: string; anEvent: TNotifyEvent); var l_Index: Integer; function l_DirAdd(const aDirName: string): Boolean; var l_Item: TMenuItem; begin l_Item := TMenuItem.Create(Self); l_Item.AutoHotkeys := maManual; l_Item.Caption := aDirName; aMenuItem.Insert(l_Index, l_Item); ReadSubDirs(l_Item, aExt, aSubDir + aDirName + '\', anEvent); Result := True; Inc(l_Index); end; var l_Dir : String; l_FPStub : Pointer; begin l_Index := 0; aMenuItem.AutoHotkeys := maManual; l_Dir := FileFromCurrent(aSubDir, True, false); l_FPStub := l3LocalStub(@l_DirAdd); try ProcessSubDirectories(l_Dir, TFileProcessingFunc(l_FPStub)); finally l3FreeLocalStub(l_FPStub); end; ReadSubMenuItems(aMenuItem, aExt, aSubDir, anEvent, l_Index); aMenuItem.Visible := aMenuItem.Count > 0; end; function TGUITestRunner.CheckParentDir(Sender: TObject; aParentPM: TMenuItem): String; var l_Item: TMenuItem; begin Result := ''; l_Item := Sender as TMenuItem; while aParentPM <> l_Item.Parent do begin l_Item := l_Item.Parent; if l_Item = nil then Break; Result := Result + l_Item.Caption + '\'; end; // while PresetsPM <> l_Item.Parent do end; procedure TGUITestRunner.CheckMenuItem(const aMenuItem: TMenuItem); begin if aMenuItem.Caption = csClearEtalonScriptName then FClearEtalonPM := aMenuItem; {$IFDEF Archi} if aMenuItem.Caption = csClearDataBase then FClearBaseMenuItem := aMenuItem; {$ENDIF Archi} end; procedure TGUITestRunner.acLoadOperationExecute(Sender: TObject); begin if FLoadOperation < High(TLoadOperation) then Inc(FLoadOperation) else FLoadOperation := Low(TLoadOperation); UpdateLogicalOpearation; end; procedure TGUITestRunner.InitLogicalOperation; begin LoadOperation := lo_Clear; UpdateLogicalOpearation; end; procedure TGUITestRunner.UpdateLogicalOpearation; begin with acLoadOperation do begin ImageIndex := cnStartLogicalIndex + Ord(FLoadOperation); Caption := csLogicalHintArray[FLoadOperation]; Hint := csLogicalHintArray[FLoadOperation]; end; end; procedure TGUITestRunner.LoadItemFlagsFromFile(aFileName: AnsiString); begin ApplyToTests(TestTree.Items.GetFirstNode, DisableTest, False); UpdateStatus(True); LoadTestNamesFromFile(aFileName, FLoadOperation); ChangeState4Test(True, False); end; procedure TGUITestRunner.SetLoadOperation(const Value: TLoadOperation); begin FLoadOperation := Value; UpdateLogicalOpearation; end; procedure TGUITestRunner.DoDeselectAllActionExecute(Sender: TObject); begin ApplyToTests(TestTree.Items.GetFirstNode, DisableTest, False); UpdateStatus(True); end; procedure TGUITestRunner.CompileActionUpdate(Sender: TObject); begin {$If not defined(NoScripts)} CompileAction.Enabled := RunAction.Enabled; {$Else } CompileAction.Visible := false; {$IfEnd} end; procedure TGUITestRunner.CompileActionExecute(Sender: TObject); begin {$If not defined(NoScripts)} vcmInsiderTest.g_CompileOnly := true; try {$IfEnd} RunAction.Execute; {$If not defined(NoScripts)} finally vcmInsiderTest.g_CompileOnly := false; end;//try..finally {$IfEnd} end; procedure TGUITestRunner.acDebuggerExecute(Sender: TObject); begin {$IfDef InsiderTest} if g_DebuggerForm <> nil then if (Sender as TAction).Checked then g_DebuggerForm.Show else g_DebuggerForm.Hide; {$EndIf InsiderTest} end; procedure TGUITestRunner.ShowDebugForm; begin acDebuggerExecute(acDebugger); end; procedure TGUITestRunner.ToFront; begin if not IsWritingToK then if not FWasStarted then SetFocus; FWasStarted := True; end; procedure TGUITestRunner.acClearDaaBaseExecute(Sender: TObject); begin {$IFDEF Archi} if FClearBaseMenuItem <> nil then FClearBaseMenuItem.OnClick(FClearBaseMenuItem); {$ENDIF Archi} end; procedure TGUITestRunner.acDebuggerUpdate(Sender: TObject); begin {$IfDef InsiderTest} if g_DebuggerForm <> nil then if (Sender as TAction).Checked <> g_DebuggerForm.Visible then (Sender as TAction).Checked := g_DebuggerForm.Visible; {$EndIf InsiderTest} end; { TDictionaryMenuItem } constructor TDictionaryMenuItem.Create(anOwner: TComponent; aDictionary: TDictionary); begin inherited Create(anOwner); f_Dictionary := aDictionary; end; end.
(* * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Initial Developer of this code is John Hansen. * Portions created by John Hansen are Copyright (C) 2009 John Hansen. * All Rights Reserved. * *) unit uGlobals; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface const // remote commands kRemoteKeysReleased = $0000; kRemotePBMessage1 = $0100; kRemotePBMessage2 = $0200; kRemotePBMessage3 = $0400; kRemoteOutAForward = $0800; kRemoteOutBForward = $1000; kRemoteOutCForward = $2000; kRemoteOutABackward = $4000; kRemoteOutBBackward = $8000; kRemoteOutCBackward = $0001; kRemoteSelProgram1 = $0002; kRemoteSelProgram2 = $0004; kRemoteSelProgram3 = $0008; kRemoteSelProgram4 = $0010; kRemoteSelProgram5 = $0020; kRemoteStopOutOff = $0040; kRemotePlayASound = $0080; {$IFDEF FPC} const MB_ICONASTERISK = $00000040; {$ENDIF} const K_RCX = 'RCX'; K_CYBER = 'CyberMaster'; K_SCOUT = 'Scout'; K_RCX2 = 'RCX2'; K_SPY = 'Spybot'; K_SWAN = 'Swan'; K_NXT = 'NXT'; const rtRCX = 0; rtCybermaster = 1; rtScout = 2; rtRCX2 = 3; rtSpy = 4; rtSwan = 5; rtNXT = 6; const SU_RCX = rtRCX; SU_CYBERMASTER = rtCybermaster; SU_SCOUT = rtScout; SU_RCX2 = rtRCX2; SU_SPYBOTIC = rtSpy; SU_SWAN = rtSwan; SU_NXT = rtNXT; var UserDataLocalPath : string; SymFileLibraryPath : string; var LocalBrickType : integer; LocalStandardFirmware : Boolean; var GlobalAbort : boolean; function IsNXT : boolean; function IsSwan : boolean; function IsRCX2 : boolean; function IsRCX : boolean; function IsScout : boolean; function IsSpybotic : boolean; function GetJoystickButtonScript(const i : byte; bPress : boolean) : string; {$IFNDEF FPC} function GetSpecialFolderPath(folder : integer) : string; {$ENDIF} implementation uses {$IFNDEF FPC} SHFolder, Windows, {$ENDIF} SysUtils; function IsNXT : boolean; begin result := (LocalBrickType = SU_NXT); end; function IsSwan : boolean; begin result := (LocalBrickType = SU_SWAN); end; function IsRCX2 : boolean; begin result := (LocalBrickType = SU_RCX2) or (LocalBrickType = SU_SWAN); end; function IsRCX : boolean; begin result := (LocalBrickType = SU_RCX) or (LocalBrickType = SU_RCX2) or (LocalBrickType = SU_SWAN); end; function IsScout : boolean; begin result := (LocalBrickType = SU_SCOUT); end; function IsSpybotic : boolean; begin result := (LocalBrickType = SU_SPYBOTIC); end; function GetJoystickButtonScript(const i : byte; bPress : boolean) : string; const name_postfix : array[boolean] of string = ('r', 'p'); begin Result := UserDataLocalPath+Format('joybtn%2.2d%s.rops', [i, name_postfix[bPress]]); end; {$IFNDEF FPC} function GetSpecialFolderPath(folder : integer) : string; const SHGFP_TYPE_CURRENT = 0; var path: array [0..MAX_PATH] of char; begin if SUCCEEDED(SHGetFolderPath(0,folder,0,SHGFP_TYPE_CURRENT,@path[0])) then Result := path else Result := ''; end; {$ENDIF} initialization {$IFNDEF FPC} UserDataLocalPath := GetSpecialFolderPath(CSIDL_APPDATA{CSIDL_LOCAL_APPDATA})+'\JoCar Consulting\BricxCC\3.3\'; SymFileLibraryPath := GetSpecialFolderPath(CSIDL_APPDATA{CSIDL_LOCAL_APPDATA})+'\JoCar Consulting\BricxCC\3.3\sym\'; {$ELSE} UserDataLocalPath := IncludeTrailingPathDelimiter(ExpandFilename('~')); SymFileLibraryPath := IncludeTrailingPathDelimiter(ExpandFilename('~')) + IncludeTrailingPathDelimiter('sym'); {$ENDIF} end.
unit evFixedHAFMacroReplacer; { $Id: evFixedHAFMacroReplacer.pas,v 1.1 2010/06/23 18:05:55 lulin Exp $ } // $Log: evFixedHAFMacroReplacer.pas,v $ // Revision 1.1 2010/06/23 18:05:55 lulin // {RequestLink:219124975}. // // Revision 1.3 2010/03/02 13:34:33 lulin // {RequestLink:193823544}. // // Revision 1.2 2010/03/02 11:15:09 lulin // {RequestLink:193823544}. // // Revision 1.1 2009/09/23 12:12:16 lulin // - модуль Инфарм перенесён на модель. // // Revision 1.1 2008/12/29 07:39:06 oman // - fix: MacroReplacer для картинок (К-122675365) // // {$Include evDefine.inc } interface uses l3Interfaces, l3InternalInterfaces, evCustomHAFMacroReplacer ; type TevFixedHAFMacroReplacer = class(TevCustomHAFMacroReplacer) private f_Name: Il3CString; f_FullName: Il3CString; protected function DoReplace(const aText: Il3CString): Il3CString; override; {-} function DoUnfold(const aMacroName: Il3CString; const aValue: Il3CString): Il3CString; override; {-} procedure Cleanup; override; {-} public constructor Create(const aParent: Il3HAFMacroReplacer; const aName, aFullName: Il3CString); reintroduce; {-} class function Make(const aParent: Il3HAFMacroReplacer; const aName, aFullName: Il3CString): Il3HAFMacroReplacer; reintroduce; {-} end; implementation uses l3String, l3Base, nevInterfaces, evHAFPainterMacros ; { TevFixedHAFMacroReplacer } procedure TevFixedHAFMacroReplacer.Cleanup; begin f_Name := nil; f_FullName := nil; inherited; end; constructor TevFixedHAFMacroReplacer.Create( const aParent: Il3HAFMacroReplacer; const aName, aFullName: Il3CString); begin inherited Create(aParent); f_Name := aName; f_FullName := aFullName; end; function TevFixedHAFMacroReplacer.DoUnfold( const aMacroName: Il3CString; const aValue: Il3CString): Il3CString; begin if l3Same(aMacroName, l3CStr(SDocName)) then Result := f_Name else if l3Same(aMacroName, l3CStr(SDocFullName)) then Result := f_FullName else if l3Same(aMacroName, l3CStr(SDocRedactionDate)) then Result := nil else if l3Same(aMacroName, l3CStr(SInternalNumber)) then Result := str_nevpmUndefinedSize.AsCStr else if l3Same(aMacroName, l3CStr(SDataSize)) then Result := str_nevpmUndefinedTopic.AsCStr else Result := aValue; end; class function TevFixedHAFMacroReplacer.Make( const aParent: Il3HAFMacroReplacer; const aName, aFullName: Il3CString): Il3HAFMacroReplacer; var l_Inst: TevFixedHAFMacroReplacer; begin l_Inst := Create(aParent, aName, aFullName); try Result := l_Inst; finally l3Free(l_Inst); end; end; function TevFixedHAFMacroReplacer.DoReplace( const aText: Il3CString): Il3CString; begin Result := CheckMacro(l3CStr(SDocName), aText); Result := CheckMacro(l3CStr(SDocFullName), Result); Result := CheckMacro(l3CStr(SDocRedactionDate), Result); Result := CheckMacro(l3CStr(SInternalNumber), Result); Result := CheckMacro(l3CStr(SDataSize), Result); end; end.
// Handles the settings of the Code Formatter // Original Author: Egbert van Nes (http://www.dow.wau.nl/aew/People/Egbert_van_Nes.html) // Contributors: Thomas Mueller (http://www.dummzeuch.de) // Jens Borrisholt (Jens@borrisholt.dk) - Cleaning up the code, and making it aware of several language features unit GX_CodeFormatterSettings; {$I GX_CondDefine.inc} interface uses Classes, GX_CodeFormatterTypes, GX_CodeFormatterTokens; type TFeedBegin = (Unchanged, Hanging, NewLine); {: how to use the captialization file } // TFillMode = ( // fmUnchanged, {: do not use the capitalization file } // fmAddNewWord, {: add new words, but do not use for capitalization } // fmUse, {: use for capitalization, but do not add words } // fmExceptDirect, {: exclude directives } // fmAddUse, {: add new words, and use for capitalization } // fmAddUseExcept); {: add new words, but do not use for capitalization, exclude directivs } // this could probably be replaced by: // TFillModeOptions = (fmAddNew, fmUse, fmExceptDirectives } // TFillMode = set of TFillMode // which would make it more readable TCapfileMode = (cmAddNew, cmUse, cmExceptDirectives); TCapfileModeSet = set of TCapfileMode; type {: stores all possible settings for the formatting engine } TCodeFormatterEngineSettings = record SpaceOperators: TSpaceSet; {: spaces around operators } SpaceColon: TSpaceSet; {: spaces around colons ":" } SpaceSemiColon: TSpaceSet; {: spaces around semicolons ";" } SpaceComma: TSpaceSet; {: spaces around commas "," } SpaceLeftBr: TSpaceSet; {: spaces around left brackets "(" } SpaceRightBr: TSpaceSet; {: spaces around right brackets ")" } SpaceLeftHook: TSpaceSet; {: spaces around left square bracket "[" } SpaceRightHook: TSpaceSet; {: spaces around right square bracket "]" } SpaceEqualOper: TSpaceSet; {: spaces around equal operator "=" } UpperCompDirectives: Boolean; {: uppercase compiler directives } UpperNumbers: Boolean; {: uppercase (hex) numbers } ReservedCase: TCase; {: case for reserved words } StandDirectivesCase: TCase; {: case for standard directives } IdentifiersCase: TCase; {: case for identifiers } ChangeIndent: Boolean; NoIndentElseIf: Boolean; IndentBegin: Boolean; IndentTry: Boolean; IndentTryElse: Boolean; IndentCaseElse: Boolean; IndentComments: Boolean; IndentCompDirectives: Boolean; BlankProc: Boolean; {: blank line between main procedures } BlankSubProc: Boolean; {: blank line between sub procedures } RemoveDoubleBlank: Boolean; {: remove double blank lines } SpacePerIndent: Integer; {: number of spaces per indent } FeedRoundBegin: TFeedBegin; {: how to handle linefeeds around begin } FeedRoundTry: TFeedBegin; {: how to handle linefeeds around try } FeedBeforeEnd: Boolean; FeedAfterThen: Boolean; ExceptSingle: Boolean; FeedAfterVar: Boolean; FeedEachUnit: Boolean; NoFeedBeforeThen: Boolean; FeedElseIf: Boolean; {: line feed between else and if } FillNewWords: TCapfileModeSet; {: how to use the capitalization file } FeedAfterSemiColon: Boolean; StartCommentOut: String; {: special comment to start unformatted section } EndCommentOut: String; {: special comment to end unformatted section } CommentFunction: Boolean; {: add a function comment } CommentUnit: Boolean; {: add a unit comment } WrapLines: Boolean; {: wrap long lines } WrapPosition: Byte; {: wrap position for long lines } AlignCommentPos: Byte; {: position to align comments } AlignComments: Boolean; {: turn on comment alignment } AlignVarPos: Byte; {: position to align variant/constant declarations (the colon) } AlignVar: Boolean; {: turn on variable/constant alignment } end; type TConfigPrecedenceEnum = (cpDirective, cpIniFile, cpMyConfig); type TConfigPrecedenceArr = array[1..3] of TConfigPrecedenceEnum; TOneToThree = 1..3; function IntToConfigPrecedence(_Value: Integer): TConfigPrecedenceEnum; type TCodeFormatterSettings = class private FSettings: TCodeFormatterEngineSettings; FCapNames: TStringList; FCapFile: string; FUseCapFile: Boolean; FShowDoneDialog: Boolean; FConfigPrecedence: TConfigPrecedenceArr; function GetConfigPrecedence(_Idx: TOneToThree): TConfigPrecedenceEnum; procedure SetConfigPrecedence(_Idx: TOneToThree; const _Value: TConfigPrecedenceEnum); procedure SetSettings(const _Value: TCodeFormatterEngineSettings); public constructor Create; destructor Destroy; override; procedure HandleCapitalization(_Word: TPascalToken); property Settings: TCodeFormatterEngineSettings read FSettings write SetSettings; property CapNames: TStringList read FCapNames; property ConfigPrecedence[_Idx: TOneToThree]: TConfigPrecedenceEnum read GetConfigPrecedence write SetConfigPrecedence; property SpaceOperators: TSpaceSet read FSettings.SpaceOperators; property SpaceColon: TSpaceSet read FSettings.SpaceColon; property SpaceSemiColon: TSpaceSet read FSettings.SpaceSemiColon; property SpaceComma: TSpaceSet read FSettings.SpaceComma; property SpaceLeftBr: TSpaceSet read FSettings.SpaceLeftBr; property SpaceRightBr: TSpaceSet read FSettings.SpaceRightBr; property SpaceLeftHook: TSpaceSet read FSettings.SpaceLeftHook; property SpaceRightHook: TSpaceSet read FSettings.SpaceRightHook; property SpaceEqualOper: TSpaceSet read FSettings.SpaceEqualOper; property UpperCompDirectives: Boolean read FSettings.UpperCompDirectives; property UpperNumbers: Boolean read FSettings.UpperNumbers; property ReservedCase: TCase read FSettings.ReservedCase; property StandDirectivesCase: TCase read FSettings.StandDirectivesCase; property IdentifiersCase: TCase read FSettings.IdentifiersCase; property ChangeIndent: Boolean read FSettings.ChangeIndent; property NoIndentElseIf: Boolean read FSettings.NoIndentElseIf; property IndentBegin: Boolean read FSettings.IndentBegin; property IndentTry: Boolean read FSettings.IndentTry; property IndentTryElse: Boolean read FSettings.IndentTryElse; property IndentCaseElse: Boolean read FSettings.IndentCaseElse; property IndentComments: Boolean read FSettings.IndentComments; property IndentCompDirectives: Boolean read FSettings.IndentCompDirectives; property BlankProc: Boolean read FSettings.BlankProc; property BlankSubProc: Boolean read FSettings.BlankSubProc; property RemoveDoubleBlank: Boolean read FSettings.RemoveDoubleBlank; property SpacePerIndent: Integer read FSettings.SpacePerIndent; property FeedRoundBegin: TFeedBegin read FSettings.FeedRoundBegin; property FeedRoundTry: TFeedBegin read FSettings.FeedRoundTry; property FeedBeforeEnd: Boolean read FSettings.FeedBeforeEnd; property FeedAfterThen: Boolean read FSettings.FeedAfterThen; property ExceptSingle: Boolean read FSettings.ExceptSingle; property FeedAfterVar: Boolean read FSettings.FeedAfterVar; property FeedEachUnit: Boolean read FSettings.FeedEachUnit; property NoFeedBeforeThen: Boolean read FSettings.NoFeedBeforeThen; property FeedElseIf: Boolean read FSettings.FeedElseIf; property FillNewWords: TCapfileModeSet read FSettings.FillNewWords; property FeedAfterSemiColon: Boolean read FSettings.FeedAfterSemiColon; property StartCommentOut: String read FSettings.StartCommentOut; property EndCommentOut: String read FSettings.EndCommentOut; property CommentFunction: Boolean read FSettings.CommentFunction; property CommentUnit: Boolean read FSettings.CommentUnit; property WrapLines: Boolean read FSettings.WrapLines; property WrapPosition: Byte read FSettings.WrapPosition; property AlignCommentPos: Byte read FSettings.AlignCommentPos; property AlignComments: Boolean read FSettings.AlignComments; property AlignVarPos: Byte read FSettings.AlignVarPos; property AlignVar: Boolean read FSettings.AlignVar; // settings for the wizard property CapitalizationFile: string read FCapFile write FCapFile; property UseCapitalizationFile: Boolean read FUseCapFile write FUseCapFile; end; function IntToCapfileMode(_Value: Integer): TCapfileModeSet; function CapfileModeToInt(_Mode: TCapfileModeSet): Integer; implementation uses SysUtils, GX_GenericUtils, GX_CodeFormatterDefaultSettings; { TCodeFormatterSettings } constructor TCodeFormatterSettings.Create; begin inherited; FCapNames := TStringList.Create; FCapNames.Sorted := True; FCapNames.CaseSensitive := False; FCapNames.Duplicates:= dupIgnore; FShowDoneDialog := True; FSettings := BorlandDefaults; FConfigPrecedence[1] := cpDirective; FConfigPrecedence[2] := cpIniFile; FConfigPrecedence[3] := cpMyConfig; end; destructor TCodeFormatterSettings.Destroy; begin FCapNames.Free; inherited; end; function TCodeFormatterSettings.GetConfigPrecedence(_Idx: TOneToThree): TConfigPrecedenceEnum; begin Result := FConfigPrecedence[_Idx]; end; procedure TCodeFormatterSettings.HandleCapitalization(_Word: TPascalToken); var Expression: TGXUnicodeString; Found: Boolean; Idx: Integer; CommentedIdx: Integer; begin if not (_Word.GetExpression(Expression)) then Exit; Found := False; if (cmAddNew in Settings.FillNewWords) and (_Word.ReservedType in (NoReservedTypes - StandardDirectives)) then begin // Add new words to CapNames if configured and they aren't there yet Found := CapNames.Find(String(Expression), Idx); if not Found then begin if not CapNames.Find('*' + String(Expression), CommentedIdx) then CapNames.Add(String(Expression)); end; end; // Use CapNames to set capitalization if (cmUse in Settings.FillNewWords) or ( (cmExceptDirectives in Settings.FillNewWords) and not (_Word.ReservedType in StandardDirectives)) then begin if not Found then Found := CapNames.Find(String(Expression), Idx); if Found then begin _Word.SetExpression(CapNames[Idx]); _Word.ExpressionCase := rfUnchanged; end; end; end; procedure TCodeFormatterSettings.SetConfigPrecedence(_Idx: TOneToThree; const _Value: TConfigPrecedenceEnum); begin FConfigPrecedence[_Idx] := _Value; end; procedure TCodeFormatterSettings.SetSettings(const _Value: TCodeFormatterEngineSettings); begin FSettings := _Value; end; function IntToCapfileMode(_Value: Integer): TCapfileModeSet; begin case _Value of 1: Result := [cmAddNew]; 2: Result := [cmUse]; 3: Result := [cmUse, cmExceptDirectives]; 4: Result := [cmAddNew, cmUse]; 5: Result := [cmAddNew, cmUse, cmExceptDirectives]; else Result := []; // invalid end; end; function CapfileModeToInt(_Mode: TCapfileModeSet): Integer; begin if _Mode = [cmAddNew] then Result := 1 else if _Mode = [cmUse] then Result := 2 else if _Mode = [cmUse, cmExceptDirectives] then Result := 3 else if _Mode = [cmAddNew, cmUse] then Result := 4 else if _Mode = [cmAddNew, cmUse, cmExceptDirectives] then Result := 5 else Result := 0; end; function IntToConfigPrecedence(_Value: Integer): TConfigPrecedenceEnum; begin if (_Value < Ord(Low(TConfigPrecedenceEnum))) or (_Value > Ord(High(TConfigPrecedenceEnum))) then Result := cpDirective else Result := TConfigPrecedenceEnum(_Value); end; end.
{ Author: William Yang Website: http://www.pockhero.com Last Update: 2013/07/23 A clickable label opens URL in system's Internet browser. } /// <summary> /// A clickable label opens URL in system's Internet browser. /// </summary> /// <remarks> /// A clickable label opens URL in system's Internet browser with full Mouse /// Hover, Mouse Down effect. /// </remarks> unit Graphix.WebLabel; interface uses System.Classes, System.UIConsts, System.Types, System.UITypes, FMX.Types, FMX.Controls, FMX.Objects; type /// <summary> /// TextSettings for Font /// </summary> /// <remarks> /// TTextSettings with Font and FontColor exposed as published properties. /// </remarks> TFontTextSettings = class(TTextSettings) published property Font; property FontColor; end; TWebLabel = class(TText) private FAutoOpen: Boolean; FOnOpenURL: TNotifyEvent; FURL: String; FFontActive: TFontTextSettings; FFontHover: TFontTextSettings; FFontDown: TFontTextSettings; FFontNormal: TFontTextSettings; FIsPressed: Boolean; FFontSettings: TStyledSettings; procedure SetURL(const Value: String); procedure SetFontActive(const Value: TFontTextSettings); procedure SetFontDown(const Value: TFontTextSettings); procedure SetFontHover(const Value: TFontTextSettings); procedure SetFontNormal(const Value: TFontTextSettings); procedure SetIsPressed(const Value: Boolean); function GetColor: TAlphaColor; function GetFont: TFont; procedure SetColor(const Value: TAlphaColor); procedure SetFont(const Value: TFont); procedure SetFontSettings(const Value: TStyledSettings); protected procedure Click; override; procedure FontChanged(Sender: TObject); override; procedure UpdateFont; procedure DoMouseEnter; override; procedure DoMouseLeave; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published /// <remarks> /// Sets URLLabel's Font Color, alias to FontNormal.FontColor /// </remarks> property Color: TAlphaColor read GetColor write SetColor; /// <remarks> /// Sets URLLabel's Font, alias to FontNormal.Font /// </remarks> property Font: TFont read GetFont write SetFont; /// <summary> /// AutoOpens url in browser /// </summary> property AutoOpen: Boolean read FAutoOpen write FAutoOpen default True; /// <summary> /// Is URLLabel pressed /// </summary> property IsPressed: Boolean read FIsPressed write SetIsPressed default False; /// <summary> /// On URL Open event /// </summary> property OnOpenURL: TNotifyEvent read FOnOpenURL write FOnOpenURL; /// <summary> /// URL to be opened /// </summary> property URL: String read FURL write SetURL; /// <summary> /// Default font for all states /// </summary> property FontNormal: TFontTextSettings read FFontNormal write SetFontNormal; /// <summary> /// Font for mouse over effect /// </summary> property FontHover: TFontTextSettings read FFontHover write SetFontHover; /// <summary> /// Font for mouse down effect /// </summary> property FontDown: TFontTextSettings read FFontDown write SetFontDown; /// <summary> /// Font for active effect /// </summary> // property FontActive: TFontTextSettings read FFontActive write SetFontActive; /// <summary> /// When URLLabel effect changes, what font settings to be applied. /// </summary> /// <remarks> /// <para> /// Default is [TStyledSetting.ssFamily, TStyledSetting.ssStyle, /// TStyledSetting.ssFontColor] /// </para> /// <para> /// If you need to change font size on mouse over, then add ssSize. /// </para> /// </remarks> property FontSettings: TStyledSettings read FFontSettings write SetFontSettings; end; procedure Register; implementation uses {$IFDEF MSWINDOWS} Winapi.ShellAPI, Winapi.Windows; {$ENDIF MSWINDOWS} {$IFDEF POSIX} Posix.Stdlib; {$ENDIF POSIX} procedure Register; begin RegisterComponents('Graphix', [TWebLabel]); end; { TWebLabel } procedure TWebLabel.Click; begin inherited; if AutoOpen then begin {$IFDEF MSWINDOWS} ShellExecute(0, 'OPEN', PChar(FURL), '', '', SW_SHOWNORMAL); {$ENDIF MSWINDOWS} {$IFDEF POSIX} _system(PAnsiChar('open ' + AnsiString(FURL))); {$ENDIF POSIX} end; if Assigned(OnOpenURL) then OnOpenURL(Self); end; constructor TWebLabel.Create(AOwner: TComponent); begin inherited; AutoCapture := True; CanFocus := True; Cursor := crHandpoint; FAutoOpen := True; FFontNormal := TFontTextSettings.Create(Self); FFontHover := TFontTextSettings.Create(Self); FFontDown := TFontTextSettings.Create(Self); FFontSettings := [TStyledSetting.ssFamily, TStyledSetting.ssStyle, TStyledSetting.ssFontColor]; // FFontActive := TFontTextSettings.Create; FFontNormal.Assign((Self as ITextSettings).TextSettings); FFontNormal.FontColor := claBlue; // FFontNormal.Font.Style := Font.Style+[TFontStyle.fsUnderline]; FFontHover.Assign(FFontNormal); FFontHover.FontColor := claDarkcyan; FFontHover.Font.Style := Font.Style + [TFontStyle.fsUnderline]; FFontDown.Assign(FFontHover); FFontDown.FontColor := claDarkGray; // StyledSettings := StyledSettings-[TStyledSetting.ssFontColor, TStyledSetting.ssStyle]; end; destructor TWebLabel.Destroy; begin // FFontActive.Free; FFontHover.Free; FFontDown.Free; FFontNormal.Free; inherited; end; procedure TWebLabel.DoMouseEnter; begin inherited; UpdateFont; end; procedure TWebLabel.DoMouseLeave; begin inherited; UpdateFont; end; procedure TWebLabel.FontChanged(Sender: TObject); begin inherited; // UpdateFont; end; function TWebLabel.GetColor: TAlphaColor; begin Result := FFontNormal.FontColor; end; function TWebLabel.GetFont: TFont; begin Result := FFontNormal.Font; end; procedure TWebLabel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; FIsPressed := True; UpdateFont; end; procedure TWebLabel.MouseMove(Shift: TShiftState; X, Y: Single); begin inherited; if (ssLeft in Shift) and IsPressed then begin IsPressed := LocalRect.Contains(PointF(X, Y)); end; end; procedure TWebLabel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; if Button = TMouseButton.mbLeft then begin FIsPressed := False; UpdateFont; end; end; procedure TWebLabel.SetColor(const Value: TAlphaColor); begin FFontNormal.FontColor := Value; UpdateFont; end; procedure TWebLabel.SetFont(const Value: TFont); begin FFontNormal.Font := Value; UpdateFont; end; procedure TWebLabel.SetFontActive(const Value: TFontTextSettings); begin FFontActive.Assign(Value); UpdateFont; end; procedure TWebLabel.SetFontDown(const Value: TFontTextSettings); begin FFontDown.Assign(Value); UpdateFont; end; procedure TWebLabel.SetFontHover(const Value: TFontTextSettings); begin FFontHover.Assign(Value); UpdateFont; end; procedure TWebLabel.SetFontNormal(const Value: TFontTextSettings); begin FFontNormal.Assign(Value); UpdateFont; end; procedure TWebLabel.SetFontSettings(const Value: TStyledSettings); begin FFontSettings := Value; end; procedure TWebLabel.SetIsPressed(const Value: Boolean); begin FIsPressed := Value; end; procedure TWebLabel.SetURL(const Value: String); begin FURL := Value; end; procedure TWebLabel.UpdateFont; begin if IsPressed then (Self as ITextSettings).TextSettings.AssignNoStyled(FFontDown, AllStyledSettings - FFontSettings) else if IsMouseOver then (Self as ITextSettings).TextSettings.AssignNoStyled(FFontHover, AllStyledSettings - FFontSettings) else (Self as ITextSettings).TextSettings.AssignNoStyled(FFontNormal, AllStyledSettings - FFontSettings); end; initialization RegisterFMXClasses([TWebLabel]); end.
{******************************************************************************* 作者: dmzn@163.com 2008-08-07 描述: 系统数据库常量定义 备注: *.自动创建SQL语句,支持变量:$Inc,自增;$Float,浮点;$Integer=sFlag_Integer; $Decimal=sFlag_Decimal;$Image,二进制流 *******************************************************************************} unit USysDB; {$I Link.inc} interface uses SysUtils, Classes; const cSysDatabaseName: array[0..4] of String = ( 'Access', 'SQL', 'MySQL', 'Oracle', 'DB2'); //db names type TSysDatabaseType = (dtAccess, dtSQLServer, dtMySQL, dtOracle, dtDB2); //db types PSysTableItem = ^TSysTableItem; TSysTableItem = record FTable: string; FNewSQL: string; end; //系统表项 var gSysTableList: TList = nil; //系统表数组 gSysDBType: TSysDatabaseType = dtSQLServer; //系统数据类型 //------------------------------------------------------------------------------ const //自增字段 sField_Access_AutoInc = 'Counter'; sField_SQLServer_AutoInc = 'Integer IDENTITY (1,1) PRIMARY KEY'; //小数字段 sField_Access_Decimal = 'Float'; sField_SQLServer_Decimal = 'Decimal(15, 5)'; //图片字段 sField_Access_Image = 'OLEObject'; sField_SQLServer_Image = 'Image'; //日期相关 sField_SQLServer_Now = 'getDate()'; //帐户状态 sFlag_Normal = 1; //帐户正常 sFlag_Freeze = 2; //帐户冻结 sFlag_Invalid = 3; //帐户作废 ResourceString {*权限项*} sPopedom_Read = 'A'; //浏览 sPopedom_Add = 'B'; //添加 sPopedom_Edit = 'C'; //修改 sPopedom_Delete = 'D'; //删除 sPopedom_Preview = 'E'; //预览 sPopedom_Print = 'F'; //打印 sPopedom_Export = 'G'; //导出 {*相关标记*} sFlag_Yes = 'Y'; //是 sFlag_No = 'N'; //否 sFlag_Enabled = 'Y'; //启用 sFlag_Disabled = 'N'; //禁用 sFlag_Male = '1'; //男 sFlag_Female = '0'; //女 sFlag_Integer = 'I'; //整数 sFlag_Decimal = 'D'; //小数 sFlag_SyncW = 'N'; //等待同步 sFlag_Syncing = 'S'; //同步中 sFlag_Synced = 'D'; //done sFlag_BillNew = 'N'; //新订单 sFlag_BillLock = 'L'; //终端锁定 sFlag_BillCancel = 'C'; //终端取消 sFlag_BillAccept = 'A'; //代理确认 sFlag_BillDeliver = 'D'; //代理发货 sFlag_BillTakeDeliv = 'T'; //终端收货 sFlag_BillDone = 'O'; //订单结束 sFlag_ReportTitle = 'RepTitle'; //报表头 sFlag_ReportEnding = 'RepEnd'; //报表尾 {*数据表*} sTable_SysDict = 'Sys_Dict'; //系统字典表 sTable_SysLog = 'Sys_EventLog'; //系统日志表 sTable_SysExtInfo = 'Sys_ExtInfo'; //系统扩展信息 sTable_MITAdmin = 'MIT_Admin'; //中间件管理员 sTable_MITDB = 'MIT_DBConfig'; //数据库配置表 sTable_Terminal = 'HX_Terminal'; //终端账户表 sTable_TerminalUser = 'HX_T_Users'; //终端用户表 sTable_MACRebind = 'HX_T_MACRebind'; //MAC绑定请求 sTable_DL_Style = 'HX_Style'; //款式表 sTable_DL_Product = 'HX_Product'; //商品表 sTable_DL_Size = 'HX_Size'; //尺寸 sTable_DL_Color = 'HX_Color'; //颜色 sTable_DL_Brand = 'HX_Brand'; //品牌 sTable_DL_Noties = 'HX_Notices'; //通告 sTable_DL_Order = 'HX_TerminalOrder'; //订单 sTable_DL_OrderDtl = 'HX_TerminalOrderDetail'; //订单明细 sTable_DL_TermSale = 'HX_TerminalSaleRecord'; //终端销售 sTable_Product = 'HX_T_Product'; //商品表 sTable_Sale = 'HX_T_Sale'; //销售记录 sTable_SaleDtl = 'HX_T_SaleDtl'; //销售明细 sTable_AutoWan = 'HX_T_AutoWarn'; //库存预警 sTable_Order = 'HX_T_Order'; //订单表 sTable_OrderDtl = 'HX_T_OrderDtl'; //订单明细 sTable_Return = 'HX_T_Return'; //退单表 sTable_ReturnDtl = 'HX_T_ReturnDtl'; //退单明细 sTable_OrderDeal = 'HX_T_OrderDeal'; //订单收货 sTable_OrderAdjust = 'HX_T_OrderAdjust'; //订单调整 sTable_Member = 'HX_T_Member'; //会员信息 sTable_MemberSet = 'HX_T_MemberSet'; //会员设定 {*新建表*} sSQL_NewMITAdmin = 'Create Table $Table(A_UserID varChar(15),' + 'A_Name varChar(32), A_Pwd varChar(15), A_Create DateTime,' + 'A_Update DateTime)'; {----------------------------------------------------------------------------- 系统用户表: MITAdmin *.A_UserID: 用户账户 *.A_Name: 用户名 *.A_Pwd: 密码 *.A_Create: 创建时间 *.A_Update: 更新时间 -----------------------------------------------------------------------------} sSQL_NewMITDB = 'Create Table $Table(D_Agent varChar(15), D_Name varChar(80),' + 'D_Host varChar(32), D_Port Integer, D_DBName varChar(32),' + 'D_User varChar(15), D_Pwd varChar(15), D_ConnStr varChar(220),' + 'D_Create DateTime, D_Update DateTime, D_Invalid Char(1))'; {----------------------------------------------------------------------------- 数据库配置: DBConfig *.D_Agent: 代理商 *.D_Name: 代理商名 *.D_Host: 主机地址 *.D_DBName: 数据库名 *.D_Port: 端口 *.D_User: 登录用户 *.D_Pwd: 登录密码 *.D_ConnStr: 连接 *.D_Create: 创建时间 *.D_Update: 更新时间 *.D_Invalid: 是否失效 -----------------------------------------------------------------------------} sSQL_NewSysDict = 'Create Table $Table(D_ID $Inc, D_Name varChar(15),' + 'D_Desc varChar(30), D_Value varChar(100), D_Memo varChar(20),' + 'D_ParamA $Float, D_ParamB varChar(50), D_Index Integer Default 0)'; {----------------------------------------------------------------------------- 系统字典: MITDict *.D_ID: 编号 *.D_Name: 名称 *.D_Desc: 描述 *.D_Value: 取值 *.D_Memo: 相关信息 *.D_ParamA: 浮点参数 *.D_ParamB: 字符参数 *.D_Index: 显示索引 -----------------------------------------------------------------------------} sSQL_NewExtInfo = 'Create Table $Table(I_ID $Inc, I_Group varChar(20),' + 'I_ItemID varChar(20), I_Item varChar(30), I_Info varChar(500),' + 'I_ParamA $Float, I_ParamB varChar(50), I_Index Integer Default 0)'; {----------------------------------------------------------------------------- 扩展信息表: ExtInfo *.I_ID: 编号 *.I_Group: 信息分组 *.I_ItemID: 信息标识 *.I_Item: 信息项 *.I_Info: 信息内容 *.I_ParamA: 浮点参数 *.I_ParamB: 字符参数 *.I_Memo: 备注信息 *.I_Index: 显示索引 -----------------------------------------------------------------------------} sSQL_NewSysLog = 'Create Table $Table(L_ID $Inc, L_Date DateTime,' + 'L_Man varChar(32),L_Group varChar(20), L_ItemID varChar(20),' + 'L_KeyID varChar(20), L_Event varChar(220))'; {----------------------------------------------------------------------------- 系统日志: SysLog *.L_ID: 编号 *.L_Date: 操作日期 *.L_Man: 操作人 *.L_Group: 信息分组 *.L_ItemID: 信息标识 *.L_KeyID: 辅助标识 *.L_Event: 事件 -----------------------------------------------------------------------------} sSQL_NewTerminalUser = 'Create Table $Table(U_ID $Inc, U_Name varChar(32),' + 'U_Pwd varChar(16), U_Phone varChar(20), U_TerminalId varChar(15),' + 'U_Type Char(1), U_Invalid Char(1))'; {----------------------------------------------------------------------------- 终端用户表: TerminalUser *.U_ID: 编号 *.U_Name: 账户名 *.U_Pwd: 密码 *.U_Phone: 电话 *.U_TerminalId: 终端店 *.U_Type: 类型(店长,店员) *.U_Invalid: 是否停用 -----------------------------------------------------------------------------} sSQL_NewMACRebind = 'Create Table $Table(M_ID $Inc, M_MAC varChar(32),' + 'M_TerminalId varChar(15), M_ReqTime DateTime,' + 'M_Allow Char(1) Default ''N'',M_AllowMan Char(32), M_AllowTime DateTime)'; {----------------------------------------------------------------------------- MAC绑定申请表: MACRebind *.M_ID: 编号 *.M_MAC: MAC地址 *.M_TerminalId: 终端标识 *.M_Allow: 是否通过 *.M_AllowMan: 审核人 *.M_AllowTime:审核时间 -----------------------------------------------------------------------------} sSQL_NewProduct = 'Create Table $Table(R_ID $Inc, R_Sync Char(1),' + 'P_ID varChar(15), P_Color varChar(15), P_Size varChar(15),' + 'P_Number Integer, P_Price $Float, P_InPrice $Float, P_OldPrice $Float,' + 'P_TerminalId varChar(15), P_LastIn DateTime)'; {----------------------------------------------------------------------------- 商品表: Product *.R_ID: 编号 *.R_Sync: 同步 *.P_ID: 商品标识 *.P_Color: 颜色 *.P_Size: 大小 *.P_Number: 库存量 *.P_Price: 零售价 *.P_InPrice: 进货价 *.P_OldPrice: 调价前售价 *.P_TerminalId: 终端标识 *.P_LastIn: 最后入库时间 -----------------------------------------------------------------------------} sSQL_NewSale = 'Create Table $Table(R_ID $Inc, R_Sync Char(1), S_ID varChar(15),' + 'S_TerminalId varChar(15), S_Number Integer, S_Money $Float,' + 'S_Member varChar(15), S_Deduct $Float, S_DeMoney $Float,' + 'S_Man varChar(32), S_Date DateTime)'; {----------------------------------------------------------------------------- 销售记录: Sale *.R_ID: 编号 *.R_Sync: 同步 *.S_ID: 销售编号 *.S_TerminalId: 终端标识 *.S_Number: 销售件数 *.S_Money: 销售钱数 *.S_Member: 会员号 *.S_Deduct: 折扣比 *.S_DeMoney: 优惠金 *.S_Man: 销售人 *.S_Date: 销售时间 -----------------------------------------------------------------------------} sSQL_NewSaleDtl = 'Create Table $Table(R_ID $Inc, R_Sync Char(1), D_SaleID varChar(15),' + 'D_Product varChar(15), D_Number Integer, D_Price $Float,' + 'D_Member varChar(15), D_Deduct $Float, D_DeMoney $Float)'; {----------------------------------------------------------------------------- 销售明细: SaleDtl *.R_ID: 编号 *.R_Sync: 同步 *.D_SaleID: 销售编号 *.D_Product: 产品编号 *.D_Number: 销售件数 *.D_Price: 销售单价 *.D_Member: 会员号 *.D_Deduct: 折扣比 *.D_DeMoney: 优惠金 -----------------------------------------------------------------------------} sSQL_NewAutoWarn = 'Create Table $Table(R_ID $Inc, R_Sync Char(1),' + 'W_TerminalId varChar(15), W_Product varChar(15), W_AvgNum Integer,' + 'W_Status Char(1))'; {----------------------------------------------------------------------------- 库存预警: AutoWarn *.R_ID: 编号 *.R_Sync:同步 *.W_TerminalId: 终端 *.W_Product: 产品编号 *.W_AvgNum: 平均销量 *.W_Status: 记录状态 -----------------------------------------------------------------------------} sSQL_NewOrder = 'Create Table $Table(R_ID $Inc, O_ID varChar(15),' + 'O_TerminalId varChar(15), O_Number Integer, O_DoneNum Integer,' + ' O_Man varChar(32), O_Date DateTime, O_ActDate DateTime, O_Status Char(1))'; {----------------------------------------------------------------------------- 订单表: Order *.R_ID: 编号 *.O_ID: 订单号 *.O_TerminalId: 终端 *.O_Number: 订单总数 *.O_DoneNum: 完成数 *.O_Man: 下单人 *.O_Date: 下单时间 *.O_ActDate: 动作时间 *.O_Status: 订单状态 -----------------------------------------------------------------------------} sSQL_NewOrderDtl = 'Create Table $Table(R_ID $Inc, D_Order varChar(15),' + 'D_Product varChar(15), D_Number Integer, D_Price $Float,' + 'D_HasIn Integer, D_InDate DateTime)'; {----------------------------------------------------------------------------- 订单明细: OrderDtl *.R_ID: 编号 *.D_Order: 订单号 *.D_Product: 产品 *.D_Number: 订单件数 *.D_Price: 订货价 *.D_HasIn: 已入库 *.D_InDate: 上次入库时间 -----------------------------------------------------------------------------} sSQL_NewOrderDeal = 'Create Table $Table(R_ID $Inc, D_Order varChar(15),' + 'D_Product varChar(15), D_Number Integer, D_Price $Float,' + 'D_Man varChar(32), D_Date DateTime, D_Memo varChar(80))'; {----------------------------------------------------------------------------- 订单收货: OrderDeal *.R_ID: 编号 *.D_Order: 订单号 *.D_Product: 产品 *.D_Number: 收货数 *.D_Price: 收货价 *.D_Man: 收货人 *.D_Date: 收货时间 *.D_Memo: 备注信息 -----------------------------------------------------------------------------} sSQL_NewOrderAdjust = 'Create Table $Table(R_ID $Inc, A_Order varChar(15),' + 'A_Product varChar(15), A_Number Integer, A_NewNum Integer,' + 'A_Man varChar(32), A_Date DateTime, A_Memo varChar(80))'; {----------------------------------------------------------------------------- 订单调整: OrderAdjust *.R_ID: 编号 *.A_Order: 订单号 *.A_Product: 产品 *.A_Number: 原订货量 *.A_NewNum: 新订货量 *.A_Man: 修改人 *.A_Date: 修改时间 *.A_Memo: 备注信息 -----------------------------------------------------------------------------} sSQL_NewReturn = 'Create Table $Table(R_ID $Inc, T_ID varChar(15),' + 'T_TerminalId varChar(15), T_Number Integer, T_DoneNum Integer,' + 'T_Man varChar(32), T_Date DateTime, T_ActMan varChar(32),' + 'T_ActDate DateTime, T_Memo varChar(500), T_Status Char(1))'; {----------------------------------------------------------------------------- 退货单: Return *.R_ID: 编号 *.T_ID: 退货号 *.T_TerminalId: 终端 *.T_Number: 退货总数 *.T_DoneNum: 实际收货 *.T_Man: 下单人 *.T_Date: 下单时间 *.T_ActMan: 动作人 *.T_ActDate: 动作时间 *.T_Status: 状态 -----------------------------------------------------------------------------} sSQL_NewReturnDtl = 'Create Table $Table(R_ID $Inc, D_Return varChar(15),' + 'D_Product varChar(15), D_Number Integer, D_Price $Float,' + 'D_HasIn Integer, D_InDate DateTime)'; {----------------------------------------------------------------------------- 退货单明细: ReturnDtl *.R_ID: 编号 *.D_Return: 退货单 *.D_Product: 产品 *.D_Number: 退货件数 *.D_Price: 代理批发价 *.D_HasIn: 已入库 *.D_InDate: 上次入库时间 -----------------------------------------------------------------------------} sSQL_NewMember = 'Create Table $Table(R_ID $Inc, R_Sync Char(1),' + 'M_TerminalId varChar(15), M_ID varChar(15), M_Card varChar(15),' + 'M_IDCard varChar(20), M_Name varChar(32), M_Sex Char(1), ' + 'M_BirthDay DateTime, M_Phone varChar(32), M_Addr varChar(80),' + 'M_BuyTime Integer, M_BuyMoney $Float, M_DeMoney $Float, M_Type Char(1),' + 'M_Limit Char(1), M_Man varChar(32), M_Date DateTime, M_Memo varChar(80))'; {----------------------------------------------------------------------------- 会员表: Member *.R_ID: 编号 *.R_Sync: 同步 *.M_TerminalId: 终端 *.M_ID: 会员号 *.M_Card: 卡号 *.M_IDCard: 身份证 *.M_Name: 姓名 *.M_Sex: 性别 *.M_BirthDay: 生日 *.M_Phone: 电话 *.M_Addr: 地址 *.M_BuyTime: 购物次数 *.M_BuyMoney: 购物金额 *.M_DeMoney:优惠金额 *.M_Type: 会员类型(金卡,普通) *.M_Limit: 单店有效(是,否) *.M_Man: 办卡人 *.M_Date: 办卡时间 *.M_Memo: 备注信息 -----------------------------------------------------------------------------} sSQL_NewMemberSet = 'Create Table $Table(R_ID $Inc, R_Sync Char(1),' + 'S_TerminalId varChar(15), S_Type Char(15), S_Money $Float,' + 'S_Deduct $Float, S_AddMan varChar(32), S_AddDate DateTime,' + 'S_ModifyMan varChar(32), S_ModifyDate DateTime)'; {----------------------------------------------------------------------------- 会员设定: Memberset *.R_ID: 编号 *.R_Sync: 同步 *.S_TerminalId: 终端 *.S_Type: 会员类型 *.S_Money: 金额 *.S_Deduct: 折扣 *.S_AddMan: 添加人 *.S_AddDate: 添加时间 *.S_ModifyMan: 修改人 *.S_ModifyDate: 修改时间 -----------------------------------------------------------------------------} implementation //------------------------------------------------------------------------------ //Desc: 添加系统表项 procedure AddSysTableItem(const nTable,nNewSQL: string); var nP: PSysTableItem; begin New(nP); gSysTableList.Add(nP); nP.FTable := nTable; nP.FNewSQL := nNewSQL; end; //Desc: 系统表 procedure InitSysTableList; begin gSysTableList := TList.Create; AddSysTableItem(sTable_SysLog, sSQL_NewSysLog); AddSysTableItem(sTable_SysExtInfo, sSQL_NewExtInfo); AddSysTableItem(sTable_MITAdmin, sSQL_NewMITAdmin); AddSysTableItem(sTable_MITDB, sSQL_NewMITDB); AddSysTableItem(sTable_SysDict, sSQL_NewSysDict); AddSysTableItem(sTable_TerminalUser, sSQL_NewTerminalUser); AddSysTableItem(sTable_MACRebind, sSQL_NewMACRebind); AddSysTableItem(sTable_Product, sSQL_NewProduct); AddSysTableItem(sTable_Sale, sSQL_NewSale); AddSysTableItem(sTable_SaleDtl, sSQL_NewSaleDtl); AddSysTableItem(sTable_AutoWan, sSQL_NewAutoWarn); AddSysTableItem(sTable_Order, sSQL_NewOrder); AddSysTableItem(sTable_OrderDtl, sSQL_NewOrderDtl); AddSysTableItem(sTable_OrderDeal, sSQL_NewOrderDeal); AddSysTableItem(sTable_OrderAdjust, sSQL_NewOrderAdjust); AddSysTableItem(sTable_Return, sSQL_NewReturn); AddSysTableItem(sTable_ReturnDtl, sSQL_NewReturnDtl); AddSysTableItem(sTable_Member, sSQL_NewMember); AddSysTableItem(sTable_MemberSet, sSQL_NewMemberSet); end; //Desc: 清理系统表 procedure ClearSysTableList; var nIdx: integer; begin for nIdx:= gSysTableList.Count - 1 downto 0 do begin Dispose(PSysTableItem(gSysTableList[nIdx])); gSysTableList.Delete(nIdx); end; FreeAndNil(gSysTableList); end; initialization InitSysTableList; finalization ClearSysTableList; end.
unit kwArchiOpenDocument; {* *Формат:* Номер_документа Внутренний_номер Открыть *Описание:* Открывает документ по номеру. Позволяет установить флаг внутренний/внешний при задании номера документа. *Пример:* [code] 10003000 true Открыть [code] *Результат:* Открывает Конституцию РФ *Примечания:* Константы номеров документов в тестах, залитых в тестовую базу, находятся в файле: [code] w:\archi\source\projects\Archi\TestSet\Dictionary\DocumentConst.script" [code] В скриптах напрямую практически не используется, так как есть более удобные функции в файле: [code] w:\archi\source\projects\Archi\TestSet\Dictionary\MainFormUtils.script" [code] } // Модуль: "w:\archi\source\projects\Archi\Archi_Insider_Test_Support\kwArchiOpenDocument.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "TkwArchiOpenDocument" MUID: (4DE6299E021A) {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3IntfUses , tfwRegisterableWord , tfwScriptingInterfaces ; type TkwArchiOpenDocument = class(TtfwRegisterableWord) {* *Формат:* Номер_документа Внутренний_номер Открыть *Описание:* Открывает документ по номеру. Позволяет установить флаг внутренний/внешний при задании номера документа. *Пример:* [code] 10003000 true Открыть [code] *Результат:* Открывает Конституцию РФ *Примечания:* Константы номеров документов в тестах, залитых в тестовую базу, находятся в файле: [code] w:\archi\source\projects\Archi\TestSet\Dictionary\DocumentConst.script" [code] В скриптах напрямую практически не используется, так как есть более удобные функции в файле: [code] w:\archi\source\projects\Archi\TestSet\Dictionary\MainFormUtils.script" [code] } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; end;//TkwArchiOpenDocument {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3ImplUses , arArchiTestsAdapter //#UC START# *4DE6299E021Aimpl_uses* //#UC END# *4DE6299E021Aimpl_uses* ; class function TkwArchiOpenDocument.GetWordNameForRegister: AnsiString; begin Result := 'Открыть'; end;//TkwArchiOpenDocument.GetWordNameForRegister procedure TkwArchiOpenDocument.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_4DE6299E021A_var* //#UC END# *4DAEEDE10285_4DE6299E021A_var* begin //#UC START# *4DAEEDE10285_4DE6299E021A_impl* if aCtx.rEngine.IsTopString then aCtx.rCaller.Check(arOpenByNumberAsString(aCtx.rEngine.PopDelphiString, true)) else if aCtx.rEngine.IsTopBool then begin if aCtx.rEngine.PopBool then aCtx.rCaller.Check(arOpenDocumentByNumber(aCtx.rEngine.PopInt, 0, True)) else aCtx.rCaller.Check(arOpenDocumentByNumber(aCtx.rEngine.PopInt, 0, False)); end//aCtx.rEngine.IsTopBool else aCtx.rCaller.Check(arOpenDocumentByNumber(aCtx.rEngine.PopInt, 0, False)); //#UC END# *4DAEEDE10285_4DE6299E021A_impl* end;//TkwArchiOpenDocument.DoDoIt initialization TkwArchiOpenDocument.RegisterInEngine; {* Регистрация TkwArchiOpenDocument } {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) end.
unit bprUtils; interface {$ifdef fpc}{$mode delphi}{$h+}{$endif} {$ifdef MSWindows} uses Windows; {$endif} type { TList } TList=class(TObject) private fCount : Integer; fData : array of TObject; function GetItem(i: Integer): TObject; public procedure Clear(FreeItems: Boolean=false); procedure Add(AItem: TObject); procedure Insert(AItem: TObject; Index: Integer); procedure Remove(AItem: TObject); procedure Delete(idx: Integer); function IndexOf(AItem: TObject): Integer; property Item[i: Integer]: TObject read GetItem; default; property Count: Integer read fCount; end; // time utils type TBugReportDate = record year, month, day : Word; hour, min, sec, mls : Word; end; procedure GetTime(var rp: TBugReportDate); function GetMlsTicks: LongWord; implementation {$ifdef MSWindows} procedure GetTime(var rp: TBugReportDate); var st : TSystemTime; begin GetSystemTime(st); rp.year:=st.wYear; rp.month:=st.wMonth; rp.day:=st.wDay; rp.hour:=st.wHour; rp.min:=st.wMinute; rp.sec:=st.wSecond; rp.mls:=st.wMilliseconds; end; function GetMlsTicks: LongWord; begin Result:=Windows.GetTickCount; end; {$endif} { TList } function TList.GetItem(i: Integer): TObject; begin if (i<0) or (i>=fCount) then Result:=nil else Result:=fData[i]; end; procedure TList.Clear(FreeItems: Boolean); var i : Integer; begin if FreeItems then for i:=0 to fCount-1 do fData[i].Free; fCount:=0; end; procedure TList.Add(AItem: TObject); begin Insert(AItem, fCount); end; procedure TList.Remove(AItem: TObject); var i : Integer; begin i := IndexOf(AItem); if i>=0 then Delete(i); end; procedure TList.Delete(idx: Integer); var i : Integer; begin if (idx<0) or (idx>fCount) then Exit; for i:=idx to fCount-1 do fData[i]:=fData[i+1]; dec(fCount); end; function TList.IndexOf(AItem: TObject): Integer; var i : Integer; begin for i:=0 to fCount-1 do if fData[i]=AItem then begin Result:=i; Exit; end; Result:=-1; end; procedure TList.Insert(AItem: TObject; Index: Integer); var i : Integer; begin if (Index<0) then Exit; if fCount=length(fData) then begin if fCount=0 then SetLength(fData, 4) else SetLength(fData, fCount*2) end; for i:=fCount+1 downto Index do fData[i]:=fData[i-1]; fData[Index]:=AItem; inc(fCount); end; end.
object FormSensorOptions: TFormSensorOptions Left = 396 Top = 127 BorderStyle = bsDialog Caption = 'Настройки (по датчику)' ClientHeight = 292 ClientWidth = 427 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] FormStyle = fsStayOnTop OldCreateOrder = False Position = poDesktopCenter PixelsPerInch = 96 TextHeight = 13 object BtnOk: TButton Left = 348 Top = 9 Width = 75 Height = 25 Caption = 'OK' Default = True TabOrder = 3 OnClick = BtnOkClick end object BtnCancel: TButton Left = 348 Top = 40 Width = 75 Height = 25 Cancel = True Caption = 'Отмена' ModalResult = 2 TabOrder = 4 end object BtnApply: TButton Left = 348 Top = 71 Width = 75 Height = 25 Caption = 'Применить' TabOrder = 5 OnClick = BtnApplyClick end object GroupBox1: TGroupBox Left = 3 Top = 1 Width = 340 Height = 181 Caption = ' Параметры слежения за скачками давления ' Font.Charset = RUSSIAN_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False TabOrder = 0 object PageControl1: TPageControl Left = 4 Top = 18 Width = 332 Height = 159 ActivePage = TabSheet1 Font.Charset = RUSSIAN_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'Arial' Font.Style = [] ParentFont = False TabOrder = 0 object TabSheet1: TTabSheet Caption = 'Повышение давления' object cbHigh: TCheckBox Left = 4 Top = 0 Width = 209 Height = 17 Caption = 'Отслеживать повышение давления' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 0 end object rbtnHighManual: TRadioButton Left = 3 Top = 20 Width = 245 Height = 17 Caption = 'Допустимое отклонение задается вручную' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 1 end object rbtnHighAuto: TRadioButton Left = 3 Top = 39 Width = 321 Height = 17 Caption = 'Допустимое отклонение рассчитывается автоматом' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 3 end object pnlAutoHigh: TPanel Left = 14 Top = 57 Width = 308 Height = 70 BevelOuter = bvLowered Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 4 object StaticText8: TStaticText Left = 6 Top = 48 Width = 203 Height = 17 Caption = 'Диапазон допуска от до' TabOrder = 5 end object StaticText6: TStaticText Left = 7 Top = 5 Width = 186 Height = 17 Caption = 'Автомат - коэффициент инертности' TabOrder = 0 end object edHighAlpha: TComboBox Left = 194 Top = 2 Width = 81 Height = 21 ItemHeight = 13 MaxLength = 5 TabOrder = 1 Items.Strings = ( '0.9000' '0.9200' '0.9500' '0.9800' '0.9900' '0.9920' '0.9950' '0.9980' '0.9990' '0.9992' '0.9995' '0.9998' '0.9999') end object StaticText7: TStaticText Left = 7 Top = 27 Width = 185 Height = 17 Caption = 'Автомат - коэффициент умножения' TabOrder = 2 end object edHighScale: TComboBox Left = 194 Top = 24 Width = 63 Height = 21 ItemHeight = 13 MaxLength = 5 TabOrder = 3 Items.Strings = ( '2' '3' '4' '5' '6' '7' '8' '9' '10') end object edHighMin: TEdit Left = 128 Top = 46 Width = 52 Height = 21 TabOrder = 4 end object edHighMax: TEdit Left = 208 Top = 46 Width = 52 Height = 21 TabOrder = 6 end end object edHigh: TEdit Left = 246 Top = 18 Width = 52 Height = 23 TabOrder = 2 end end object TabSheet2: TTabSheet Caption = 'Понижение давления' ImageIndex = 1 object cbLow: TCheckBox Left = 4 Top = 0 Width = 209 Height = 17 Caption = 'Отслеживать понижение давления' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 0 end object rbtnLowManual: TRadioButton Left = 3 Top = 20 Width = 245 Height = 17 Caption = 'Допустимое отклонение задается вручную' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 1 end object rbtnLowAuto: TRadioButton Left = 3 Top = 39 Width = 321 Height = 17 Caption = 'Допустимое отклонение рассчитывается автоматом' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 3 end object pnlAutoLow: TPanel Left = 14 Top = 57 Width = 308 Height = 70 BevelOuter = bvLowered Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 4 object StaticText9: TStaticText Left = 6 Top = 48 Width = 203 Height = 17 Caption = 'Диапазон допуска от до' TabOrder = 5 end object StaticText10: TStaticText Left = 7 Top = 5 Width = 186 Height = 17 Caption = 'Автомат - коэффициент инертности' TabOrder = 0 end object edLowAlpha: TComboBox Left = 194 Top = 2 Width = 81 Height = 21 ItemHeight = 13 MaxLength = 5 TabOrder = 1 Items.Strings = ( '0.9000' '0.9200' '0.9500' '0.9800' '0.9900' '0.9920' '0.9950' '0.9980' '0.9990' '0.9992' '0.9995' '0.9998' '0.9999') end object StaticText11: TStaticText Left = 7 Top = 27 Width = 185 Height = 17 Caption = 'Автомат - коэффициент умножения' TabOrder = 2 end object edLowScale: TComboBox Left = 194 Top = 24 Width = 63 Height = 21 ItemHeight = 13 MaxLength = 5 TabOrder = 3 Items.Strings = ( '2' '3' '4' '5' '6' '7' '8' '9' '10') end object edLowMin: TEdit Left = 128 Top = 46 Width = 52 Height = 21 TabOrder = 4 end object edLowMax: TEdit Left = 208 Top = 46 Width = 52 Height = 21 TabOrder = 6 end end object edLow: TEdit Left = 246 Top = 18 Width = 52 Height = 23 TabOrder = 2 end end end object cbUseAlpha: TCheckBox Left = 7 Top = 181 Width = 209 Height = 17 Caption = 'Слежение по сглаженному графику' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 1 Visible = False end end object GroupBox2: TGroupBox Left = 3 Top = 183 Width = 340 Height = 38 Caption = ' График ' Font.Charset = RUSSIAN_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False TabOrder = 1 object StaticText2: TStaticText Left = 7 Top = 64 Width = 182 Height = 17 Caption = 'Сглаживание в режиме просмотра' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 3 Visible = False end object edMinGraphHeight: TEdit Left = 219 Top = 12 Width = 57 Height = 21 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 2 end object StaticText3: TStaticText Left = 6 Top = 16 Width = 212 Height = 17 Caption = 'Мин. высота графика при автомасштабе' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 4 end object edAlphaArc: TComboBox Left = 195 Top = 60 Width = 81 Height = 21 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ItemHeight = 13 MaxLength = 5 ParentFont = False TabOrder = 1 Visible = False Items.Strings = ( '0.9000' '0.9200' '0.9500' '0.9800' '0.9900') end object StaticText5: TStaticText Left = 7 Top = 42 Width = 177 Height = 17 Caption = 'Сглаживание в режиме слежения' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 5 Visible = False end object edAlphaSpy: TComboBox Left = 195 Top = 38 Width = 81 Height = 21 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ItemHeight = 13 MaxLength = 5 ParentFont = False TabOrder = 0 Visible = False Items.Strings = ( '0.9000' '0.9200' '0.9500' '0.9800' '0.9900') end end object GroupBox3: TGroupBox Left = 3 Top = 222 Width = 340 Height = 64 Caption = ' Датчик ' Font.Charset = RUSSIAN_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False TabOrder = 2 object StaticText1: TStaticText Left = 6 Top = 18 Width = 298 Height = 17 Caption = 'Возможна задержка поступления данных до (сек)' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 0 end object edMaxNoDataTime: TEdit Left = 237 Top = 14 Width = 37 Height = 21 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 1 end object StaticText4: TStaticText Left = 6 Top = 41 Width = 224 Height = 17 Caption = 'Положение датчика на НПП (км)' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 2 end object edKilometer: TEdit Left = 153 Top = 37 Width = 51 Height = 21 Enabled = False Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 3 end end end
unit pydbbr; {$mode objfpc}{$H+} interface uses Classes, SysUtils, BaseDebugManager, Debugger, process,IDEMsgIntf,simpleipc; type Tpydbthread = class; { TVDbg } Tpydbr = class(TDebugger) protected dbth: Tpydbthread; function GetSupportedCommands: TDBGCommands; override; function RequestCommand(const ACommand: TDBGCommand; const AParams: array of const): boolean; override; public class function Caption: string; override; function CreateBreakPoints: TDBGBreakPoints; override; function CreateLineInfo: TDBGLineInfo; override; function DoEvaluate(const AExpression: string; var AResult: string): boolean; end; { Tpydbthread } Tpydbthread = class(TThread) protected procedure start_process; procedure Execute; override; public cpydbr: Tpydbr; pdbpro,uipro: TProcess; mainfile: string; commands: TStringList; is_command_blocked, working_in_com_list: boolean; docurent_line,output_num: integer; docurent_source,last_output,msg: string; outputmsglist:TStringList; kill: boolean; ipcserver:TSimpleIPCServer; ipcclient:TSimpleIPCClient; procedure analys_input(const prooutput: string); constructor Create(pydbr: Tpydbr; file_name: string); procedure add_breakpoint(Source: string; line_num: integer); procedure execute_command(const com_to_execute: string); procedure set_breakpoint; function readinput(Process: TProcess): string; procedure SendInput(Process: TProcess; str: string); destructor Destroy; override; function wait_for_pdb: string; function wait_for_command: string; procedure add_command(command: string); procedure pause_ide; procedure contiue_ide; procedure Stop_ide; procedure error_ide; procedure docurent_ide; procedure addmessage_ide; function get_docurent_line(str: string): integer; end; implementation { Tpydbthread } procedure Tpydbthread.start_process; var pro_arg: string; begin pdbpro := TProcess.Create(nil); pro_arg := 'python -i -m pdb ' + mainfile; pdbpro.CommandLine := pro_arg; pdbpro.Options := [poUsePipes, poNoConsole]; pdbpro.Execute; {uipro:=TProcess.Create(nil); uipro.CommandLine:='G:\dev\laz4py\temp3\p643254y.exe'; uipro.Execute; } {ipcclient:=TSimpleIPCClient.Create(Nil); ipcclient.ServerID:='1545487'; ipcclient.Connect; ipcserver:=TSimpleIPCServer.Create(Nil); ipcserver.ServerID:='19826378'; ipcserver.Global:=True; ipcserver.StartServer;} end; constructor Tpydbthread.Create(pydbr: Tpydbr; file_name: string); var i: integer; begin FreeOnTerminate := True; inherited Create(False); cpydbr := pydbr; mainfile := file_name; is_command_blocked := False; working_in_com_list := False; kill := False; output_num:=0; commands := TStringList.Create; outputmsglist:=TStringList.Create; end; procedure Tpydbthread.analys_input(const prooutput: string); begin if (pos('Uncaught exception', prooutput) > 0) then begin Synchronize(@error_ide); Exit; end; if (pos('The program finished and will be restarted', prooutput) > 0) then begin Synchronize(@Stop_ide); Exit; end; docurent_source := Trim(Copy(prooutput, 2, Pos('(', prooutput) - 2)); docurent_line := get_docurent_line(prooutput); add_breakpoint(docurent_source, 6); if (FileExists(docurent_source)) then begin add_breakpoint('break on: ' + docurent_source, 100); Synchronize(@docurent_ide); Exit; end; if (pos('(Pdb)', prooutput) > 0) then Synchronize(@pause_ide) else Synchronize(@error_ide); end; procedure Tpydbthread.Execute; var is_ready: boolean; prooutput, com_to_execute: string; begin start_process; is_ready := False; wait_for_pdb(); set_breakpoint(); wait_for_pdb(); SendInput(pdbpro, 'c' + LineEnding); docurent_line := -1; while (not kill) do begin analys_input(wait_for_pdb()); execute_command(wait_for_command()); end; end; procedure Tpydbthread.add_breakpoint(Source: string; line_num: integer); var strl: TStringList; begin strl := TStringList.Create; strl.LoadFromFile('G:\dev\laz4py\laz4py3\vdbg.txt'); strl.Add(Source); strl.Add(IntToStr(line_num)); strl.SaveToFile('G:\dev\laz4py\laz4py3\vdbg.txt'); end; procedure Tpydbthread.execute_command(const com_to_execute: string); begin SendInput(pdbpro, com_to_execute); end; procedure Tpydbthread.set_breakpoint; var breakpointstr: string; i: integer; begin for i := 0 to cpydbr.BreakPoints.Count - 1 do begin breakpointstr := breakpointstr + 'b ' + cpydbr.BreakPoints[i].Source + ':' + IntToStr(cpydbr.BreakPoints[i].Line); if not (i = cpydbr.BreakPoints.Count - 1) then breakpointstr := breakpointstr + ';;'; end; breakpointstr := breakpointstr + LineEnding; if Length(breakpointstr) > 0 then SendInput(pdbpro, breakpointstr); add_breakpoint(breakpointstr, 10); end; function Tpydbthread.readinput(Process: TProcess): string; var Buffer: string; BytesAvailable: DWord; BytesRead: longint; Outputstr: string; begin if Process.Running then begin BytesAvailable := Process.Output.NumBytesAvailable; BytesRead := 0; while BytesAvailable > 0 do begin SetLength(Buffer, BytesAvailable); BytesRead := Process.OutPut.Read(Buffer[1], BytesAvailable); Outputstr := Outputstr + copy(Buffer, 1, BytesRead); BytesAvailable := Process.Output.NumBytesAvailable; end; end; last_output:=Outputstr; outputmsglist.AddText(Outputstr); Inc(output_num); //Synchronize(@addmessage_ide); // if not(Outputstr='') then // ipcclient.SendStringMessage(Outputstr); Result := Outputstr; end; procedure Tpydbthread.SendInput(Process: TProcess; str: string); var InputStrings: string; begin if Process.Running then begin InputStrings := str; Process.Input.Write(InputStrings[1], length(InputStrings)); end; end; destructor Tpydbthread.Destroy; begin pdbpro.Terminate(0); pdbpro.Free; inherited Destroy; end; function Tpydbthread.wait_for_pdb: string; var proinput: string; begin proinput := readinput(pdbpro); while ((Pos('(Pdb)', proinput) < 1) and (not kill)) do begin proinput := proinput + readinput(pdbpro); Sleep(100); end; add_breakpoint(proinput, 10); Result := proinput; end; function Tpydbthread.wait_for_command: string; var found: boolean; server_msg:String; begin found := False; while not found do begin working_in_com_list := True; while ((is_command_blocked) and (not kill)) do Sleep(100); {if ipcserver.PeekMessage(100,True) then begin Result:=ipcserver.StringMessage; found:=True; end; } if commands.Count > 0 then begin Result := commands.Strings[0]; commands.Delete(0); found := True; end; working_in_com_list := False; Sleep(100); end; end; procedure Tpydbthread.add_command(command: string); begin is_command_blocked := True; while working_in_com_list do Sleep(100); commands.Add(command); is_command_blocked := False; end; procedure Tpydbthread.pause_ide; begin cpydbr.SetState(dsPause); end; procedure Tpydbthread.contiue_ide; begin cpydbr.SetState(dsRun); end; procedure Tpydbthread.Stop_ide; begin cpydbr.SetState(dsStop); end; procedure Tpydbthread.error_ide; begin cpydbr.SetState(dsError); end; procedure Tpydbthread.docurent_ide; var loc: TDBGLocationRec; begin loc.SrcFullName := docurent_source; loc.SrcLine := docurent_line; cpydbr.DoCurrent(loc); cpydbr.SetState(dsPause); end; procedure Tpydbthread.addmessage_ide; var i:Integer; begin IDEMessagesWindow.BeginBlock; for i:=0 to outputmsglist.Count-1 do IDEMessagesWindow.AddMsg(last_output,IntToStr(output_num),output_num); IDEMessagesWindow.EndBlock; end; function Tpydbthread.get_docurent_line(str: string): integer; var par1, par2: integer; num_string: string; line_num: integer; begin par1 := Pos('(', str); par2 := Pos(')', str); num_string := Trim(Copy(str, par1 + 1, par2 - par1 - 1)); if TryStrToInt(num_string, line_num) then Result := StrToInt(num_string) else Result := -1; end; function Tpydbr.GetSupportedCommands: TDBGCommands; begin Result := [dcRun, dcPause, dcStop, dcStepInto, dcBreak, dcEvaluate, dcStepOver]; end; function Tpydbr.RequestCommand(const ACommand: TDBGCommand; const AParams: array of const): boolean; var strl: TStringList; F: TextFile; loc: TDBGLocationRec; str: string; begin if ACommand = dcStop then begin SetState(dsStop); dbth.pdbpro.Free; Exit(False); end; {if ACommand = dcEvaluate then begin str := string(AParams[0].VAnsiString); //AParams[1].VAnsiString:=Pointer(str); {if length(str) < 100 then begin AssignFile(F, 'G:\dev\laz4py\laz4py3\vdbg.txt'); Rewrite(F); WriteLn(F, str + LineEnding); CloseFile(F); Exit(True); end; } Exit(True); end; } if ((ACommand = dcRun) and (State = dsStop)) then begin str := string(FileName); dbth := Tpydbthread.Create(Self, ExtractFilePath(FileName) + 'main.py'); //loc.FuncName := 'project1.lpr'; //loc.SrcFullName := 'G:\dev\laz4py\laz4py_testpro\main.py'; //loc.SrcLine := 8; //DoCurrent(loc); SetState(dsRun); Exit(True); end; if ((ACommand = dcRun) and (State = dsPause)) then begin dbth.add_command('c' + LineEnding); end; if ((ACommand = dcStepOver) and (State = dsPause)) then dbth.add_command('n' + LineEnding); if ((ACommand = dcStepInto) and (State = dsPause)) then dbth.add_command('s' + LineEnding); if (ACommand = dcEvaluate) then begin Result := DoEvaluate(string(AParams[0].VAnsiString), string(AParams[1].VPointer^)); end; end; class function Tpydbr.Caption: string; begin Result := 'python debuger'; end; function Tpydbr.DoEvaluate(const AExpression: string; var AResult: string): boolean; var i,num_of_out:Integer; anystrlist:TStringList; begin AResult :='failed to get value'; dbth.add_command('p '+AExpression+LineEnding); num_of_out:=dbth.output_num; anystrlist:=TStringList.Create; i:=0; while ((i<4) and(num_of_out=dbth.output_num)) do begin Inc(i); Sleep(500); end; anystrlist.AddText(dbth.last_output); AResult:=anystrlist.Strings[0]; anystrlist.Free; Result := True; end; function Tpydbr.CreateBreakPoints: TDBGBreakPoints; begin Result := inherited CreateBreakPoints; end; function Tpydbr.CreateLineInfo: TDBGLineInfo; begin Result := inherited CreateLineInfo; end; initialization RegisterDebugger(Tpydbr); end.
{ Double Commander ------------------------------------------------------------------------- Quick Look thumbnail provider Copyright (C) 2015 Alexander Koblov (alexx2000@mail.ru) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA } unit uQuickLook; {$mode objfpc}{$H+} {$modeswitch objectivec1} interface uses Classes, SysUtils; implementation uses DynLibs, FileUtil, Types, Graphics, MacOSAll, CocoaAll, uThumbnails, uDebug, uClassesEx, uGraphics {$IF (FPC_FULLVERSION >= 30000)} , CGImage {$ENDIF} ; const libQuickLook = '/System/Library/Frameworks/QuickLook.framework/Versions/Current/QuickLook'; var QuickLook: TLibHandle = NIlHandle; var QLThumbnailImageCreate: function(allocator: CFAllocatorRef; url: CFURLRef; maxThumbnailSize: CGSize; options: CFDictionaryRef): CGImageRef; cdecl; function GetThumbnail(const aFileName: String; aSize: TSize): Graphics.TBitmap; var ImageData: NSData; Bitmap: TTiffImage; NewImage: NSImage = nil; WorkStream: TBlobStream; maxThumbnailSize: CGSize; ImageRef: CGImageRef = nil; BitmapImageRep: NSBitmapImageRep; theFileNameUrlRef: CFURLRef = nil; theFileNameCFRef: CFStringRef = nil; begin theFileNameCFRef:= CFStringCreateWithFileSystemRepresentation(nil, PAnsiChar(aFileName)); theFileNameUrlRef:= CFURLCreateWithFileSystemPath(nil, theFileNameCFRef, kCFURLPOSIXPathStyle, False); try maxThumbnailSize.width:= aSize.cx; maxThumbnailSize.height:= aSize.cy; ImageRef:= QLThumbnailImageCreate(kCFAllocatorDefault, theFileNameUrlRef, maxThumbnailSize, nil); if ImageRef = nil then Exit(nil); BitmapImageRep:= NSBitmapImageRep.alloc(); BitmapImageRep.initWithCGImage(ImageRef); // Create NSImage NewImage:= NSImage.alloc(); NewImage.initWithSize(BitmapImageRep.size); NewImage.addRepresentation(BitmapImageRep); BitmapImageRep.release(); // Get image data in TIFF format Bitmap:= TTiffImage.Create; ImageData:= NewImage.TIFFRepresentation; WorkStream:= TBlobStream.Create(ImageData.Bytes, ImageData.Length); try Bitmap.LoadFromStream(WorkStream); Result:= TBitmap.Create; try BitmapAssign(Result, Bitmap); except FreeAndNil(Result); end; finally Bitmap.Free; WorkStream.Free; end; NewImage.release(); CFRelease(ImageRef); finally if Assigned(theFileNameCFRef) then CFRelease(theFileNameCFRef); if Assigned(theFileNameUrlRef) then CFRelease(theFileNameUrlRef); end; end; procedure Initialize; begin QuickLook:= LoadLibrary(libQuickLook); if (QuickLook <> NilHandle) then begin Pointer(QLThumbnailImageCreate):= GetProcAddress(QuickLook, 'QLThumbnailImageCreate'); if Assigned(QLThumbnailImageCreate) then begin // Register thumbnail provider TThumbnailManager.RegisterProvider(@GetThumbnail); DCDebug('Initialize QuickLook: Success'); end; end; end; procedure Finalize; begin if (QuickLook <> NilHandle) then FreeLibrary(QuickLook); end; initialization Initialize; finalization Finalize; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Collections, RemObjects.Elements.EUnit; type DictionaryTest = public class (Test) private Data: Dictionary<CodeClass, String>; public method Setup; override; method &Add; method Clear; method ContainsKey; method ContainsValue; method &Remove; method Item; method Keys; method Values; method Count; method ForEach; method NilValue; end; implementation method DictionaryTest.Setup; begin Data := new Dictionary<CodeClass, String>; Data.Add(new CodeClass(1), "One"); Data.Add(new CodeClass(2), "Two"); Data.Add(new CodeClass(3), "Three"); end; method DictionaryTest.&Add; begin Assert.AreEqual(Data.Count, 3); Data.Add(new CodeClass(4), "Four"); Assert.AreEqual(Data.Count, 4); Assert.IsTrue(Data.ContainsKey(new CodeClass(4))); Assert.IsTrue(Data.ContainsValue("Four")); Data.Add(new CodeClass(-1), nil); Assert.AreEqual(Data.Count, 5); Assert.IsTrue(Data.ContainsKey(new CodeClass(-1))); Assert.IsTrue(Data.ContainsValue(nil)); Assert.Throws(->Data.Add(new CodeClass(4), "")); //no duplicates end; method DictionaryTest.Clear; begin Assert.AreEqual(Data.Count, 3); Data.Clear; Assert.AreEqual(Data.Count, 0); end; method DictionaryTest.ContainsKey; begin Assert.IsTrue(Data.ContainsKey(new CodeClass(1))); Assert.IsTrue(Data.ContainsKey(new CodeClass(2))); Assert.IsTrue(Data.ContainsKey(new CodeClass(3))); Assert.IsFalse(Data.ContainsKey(new CodeClass(4))); end; method DictionaryTest.ContainsValue; begin Assert.IsTrue(Data.ContainsValue("One")); Assert.IsTrue(Data.ContainsValue("Two")); Assert.IsTrue(Data.ContainsValue("Three")); Assert.IsFalse(Data.ContainsValue("Four")); Assert.IsFalse(Data.ContainsValue("one")); Assert.IsFalse(Data.ContainsValue(nil)); end; method DictionaryTest.&Remove; begin Assert.IsTrue(Data.Remove(new CodeClass(1))); Assert.IsFalse(Data.ContainsKey(new CodeClass(1))); Assert.IsFalse(Data.ContainsValue("One")); Assert.IsFalse(Data.Remove(new CodeClass(1))); end; method DictionaryTest.Item; begin var C := new CodeClass(1); Assert.IsNotNil(Data.Item[C]); Assert.IsNotNil(Data[C]); Assert.AreEqual(Data.Item[C], "One"); Assert.AreEqual(Data[C], "One"); Assert.Throws(->Data.Item[new CodeClass(55)]); Data[C] := "First"; Assert.AreEqual(Data.Item[C], "First"); //if key doesn't exists it should be added Assert.AreEqual(Data.Count, 3); Data[new CodeClass(4)] := "Four"; Assert.AreEqual(Data.Count, 4); Assert.IsTrue(Data.ContainsKey(new CodeClass(4))); Assert.IsTrue(Data.ContainsValue("Four")); end; method DictionaryTest.Keys; begin var Expected := new Sugar.Collections.List<CodeClass>; Expected.Add(new CodeClass(1)); Expected.Add(new CodeClass(2)); Expected.Add(new CodeClass(3)); var Actual := Data.Keys; Assert.AreEqual(length(Actual), 3); //elements order is not defined for i: Integer := 0 to length(Actual) - 1 do Assert.IsTrue(Expected.Contains(Actual[i])); end; method DictionaryTest.Values; begin var Expected := new Sugar.Collections.List<String>; Expected.Add("One"); Expected.Add("Two"); Expected.Add("Three"); var Actual := Data.Values; Assert.AreEqual(length(Actual), 3); for i: Integer := 0 to length(Actual) - 1 do Assert.IsTrue(Expected.Contains(Actual[i])); end; method DictionaryTest.Count; begin Assert.AreEqual(Data.Count, 3); Assert.IsTrue(Data.Remove(new CodeClass(1))); Assert.AreEqual(Data.Count, 2); Data.Add(new CodeClass(1), "One"); Assert.AreEqual(Data.Count, 3); Data.Clear; Assert.AreEqual(Data.Count, 0); end; method DictionaryTest.ForEach; begin var Item1 := new KeyValuePair<String, String>("Key", "Value"); var Item2 := new KeyValuePair<String, String>("Key", "Value"); Assert.IsTrue(Item1.Equals(Item2)); Data.Add(new CodeClass(-1), nil); var Expected := new Sugar.Collections.List<KeyValuePair<CodeClass, String>>; Expected.Add(new KeyValuePair<CodeClass, String>(new CodeClass(1),"One")); Expected.Add(new KeyValuePair<CodeClass, String>(new CodeClass(2),"Two")); Expected.Add(new KeyValuePair<CodeClass, String>(new CodeClass(3),"Three")); Expected.Add(new KeyValuePair<CodeClass, String>(new CodeClass(-1), nil)); var &Index: Integer := 0; Data.ForEach(x -> begin Assert.IsTrue(Expected.Contains(x)); &Index := &Index + 1; end); Assert.AreEqual(&Index, 4); end; method DictionaryTest.NilValue; begin Data.Add(new CodeClass(-1), nil); Assert.IsTrue(Data.ContainsValue(nil)); Assert.IsNil(Data[new CodeClass(-1)]); Assert.AreEqual(Data[new CodeClass(1)], "One"); Data[new CodeClass(1)] := nil; Assert.AreEqual(Data.Item[new CodeClass(1)], nil); end; end.
unit calculators; //ported from \fpc\ide\fpcalc.pas with many modifications //ported by Zaher Dirkey Zaher at parmaja dot com {$mode objfpc}{$H+} interface uses SysUtils, StrUtils, Math; type TCalcState = (csFirst, csValid, csError); { TFPCalculator } TCalculator = class(TObject) private FMaxDecimals: Integer; FMaxDigits: Integer; procedure GetDisplay(var R: Extended); procedure SetDisplay(R: Extended; ShouldKeepZeroes: boolean); procedure Error; protected Started: Boolean; Status: TCalcState; Number: string; Sign: Char; CurrentOperator, LastOperator: Char; LastResult, Operand: Extended; HaveMemory: Boolean; Memory: Extended; DispNumber: Extended; HexShown: Boolean; public constructor Create; function Process(Key: string): boolean; virtual; procedure Clear; virtual; procedure Reset; virtual; procedure Log(const S: string); virtual; procedure Refresh; virtual; property MaxDecimals: Integer read FMaxDecimals write FMaxDecimals default 10; property MaxDigits: Integer read FMaxDigits write FMaxDigits default 30; end; implementation constructor TCalculator.Create; begin inherited Create; FMaxDecimals := 10; FMaxDigits := 30; Clear; HexShown := False; end; procedure TCalculator.GetDisplay(var R: Extended); begin R := DispNumber; end; procedure TCalculator.Refresh; begin end; procedure TCalculator.Reset; begin Clear; HaveMemory := False; Memory := 0; end; procedure TCalculator.Log(const s: string); begin end; procedure TCalculator.SetDisplay(R: Extended; ShouldKeepZeroes: Boolean); var S: string; i, KeepZeroes: Integer; p: Integer; begin DispNumber := R; KeepZeroes := 0; p := pos('.', Number); if (ShouldKeepZeroes and (p > 0)) then begin for i := Length(Number) downto p + 1 do if Number[i] = '0' then inc(KeepZeroes) else break; end; S := FloatToStrF(R, ffGeneral, MaxDecimals, MaxDigits); if KeepZeroes > 0 then S := S + AddChar('0', S, KeepZeroes); if S[1] <> '-' then Sign := ' ' else begin Delete(S, 1, 1); Sign := '-'; end; if Length(S) > MaxDigits + 1 + MaxDecimals then Error else begin if RightStr(S, 1) = '.' then S := LeftStr(S, Length(S) - 1); Number := S; end; end; procedure TCalculator.Error; begin Status := csError; Number := 'Error'; Sign := ' '; Refresh; end; function TCalculator.Process(Key: string): boolean; var R: Extended; X: cardinal; procedure CheckFirst; begin if Status = csFirst then begin Status := csValid; SetDisplay(0, False); end; end; var s: string; begin Result := True; Key := UpperCase(Key); if (Status = csError) and (Key <> 'C') then Key := ' '; R := 0; if HexShown then begin GetDisplay(R); SetDisplay(R, False); HexShown := False; if Key = 'H' then Key := ' '; end; if Key = 'X^Y' then Key := '^' else if Key = #13 then Key := '=' else if Key = #7 then Key := 'C' else if Key = #27 then Key := 'AC' else if (Key = '_') or (Key = #241) then Key := '+/-'; if Length(Key) > 1 then begin { if Status = csFirst then} begin { Status := csValid;} GetDisplay(R); if Key = 'AC' then Clear else if Key = 'ON' then Reset else if Key = '1/X' then begin if R = 0 then Error else SetDisplay(1 / R, False); end else if Key = 'SQRT' then begin if R < 0 then Error else SetDisplay(sqrt(R), False) end else if Key = 'LOG' then begin if R <= 0 then Error else SetDisplay(ln(R), False) end else if Key = 'X^2' then SetDisplay(R * R, False) else if (Key = '+/-') then begin if Sign = ' ' then Sign := '-' else Sign := ' '; GetDisplay(R); SetDisplay(-R, True); end else if Key = 'M+' then begin Memory := Memory + R; HaveMemory := True; end else if Key = 'M-' then begin Memory := Memory - R; HaveMemory := True; end else if Key = 'MR' then begin CheckFirst; SetDisplay(Memory, False) end else if Key = 'MC' then begin Memory := 0; HaveMemory := False; end; end; end else case Key[1] of '0'..'9': if Length(Number) < MaxDigits then begin CheckFirst; if Number = '0' then Number := ''; Number := Number + Key; DispNumber := StrToFloat(Number); //SetDisplay(StrToFloat(Number), True); end; '.': begin CheckFirst; if Pos('.', Number) = 0 then Number := Number + '.'; end; #8: begin CheckFirst; if Length(Number) = 1 then Number := '0' else Number := LeftStr(Number, Length(Number) - 1); SetDisplay(StrToFloat(Number), True); { !!! } end; 'H': begin GetDisplay(R); X := trunc(abs(R)); Number := IntToHex(longint(X), 8); HexShown := True; end; 'C': begin CheckFirst; SetDisplay(0, True); end; '^', '+', '-', '*', '/', '%', '=': begin if (Key[1] = '=') and (Status = csFirst) then //for repeat last operator begin Status := csValid; R := LastResult; CurrentOperator := LastOperator; end else GetDisplay(R); if (Status = csValid) then begin Started := True; if CurrentOperator = '=' then s := ' ' else s := CurrentOperator; Log(s + FloatToStrF(R, ffGeneral, MaxDecimals, MaxDigits)); Status := csFirst; LastOperator := CurrentOperator; LastResult := R; if Key = '%' then begin case CurrentOperator of '+', '-': R := Operand * R / 100; '*', '/': R := R / 100; end; end; case CurrentOperator of '^': if (Operand = 0) and (R <= 0) then Error else SetDisplay(Power(Operand, R), False); '+': SetDisplay(Operand + R, False); '-': SetDisplay(Operand - R, False); '*': SetDisplay(Operand * R, False); '/': if R = 0 then Error else SetDisplay(Operand / R, False); end; if (Key[1] = '=') then Log('=' + Number); end; CurrentOperator := Key[1]; GetDisplay(Operand); end; else Result := False; end; Refresh; end; procedure TCalculator.Clear; begin if Started then Log(AddChar('-', '', MaxDigits + 1 + MaxDecimals)); Started := False; Status := csFirst; Number := '0'; Sign := ' '; CurrentOperator := '='; end; end.
unit VariantWrapper; (* Описываем абстрактный тип Variant'a, который "оборачивает" в себя другой Variant, добиваясь расширенной функциональности. Например, мы ставим размерности величин, а сама величина - Variant, содержащий либо целое, либо действительное, либо комплексное, или вовсе кватернион. По идее, таких "оберток" может быть несколько - сначала размерность, а потом множестенные значения, а потом комплексное число. также "вытаскиваем наружу" с помощью небольшого "хака" функции для работы с variant'ами, используемые компилятором - _varAdd, _varSub и т.д., что позволяет заметно ускорить выполнение *) interface uses classes,TypInfo,variants; type TAbstractWrapperData = class(TPersistent) //чтобы можно было и запоминать в файле public procedure FastAssign(source: TAbstractWrapperData); virtual; procedure Release; virtual; //возратить в пул - должно быть //значительно быстрее create/free class function GetInstance: TAbstractWrapperData; virtual; //вместо Create procedure DoNegate; virtual; abstract; //взять обратный знак procedure DoAdd(const Right: TAbstractWrapperData); virtual; abstract; procedure DoSubtract(const Right: TAbstractWrapperData); virtual; procedure DoMultiply(const Right: TAbstractWrapperData); virtual; abstract; procedure DoDivide(const Right: TAbstractWrapperData); virtual; abstract; function GetAsString: string; virtual; abstract; end; TWrapperDataClass=class of TAbstractWrapperData; TAbstractWrapperVariantType = class(TPublishableVariantType) protected function LeftPromotion(const V: TVarData; const Operator: TVarOp; out RequiredVarType: TVarType): Boolean; override; function GetInstance(const V: TVarData): TObject; override; public procedure Clear(var V: TVarData); override; procedure Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); override; procedure Cast(var Dest: TVarData; const Source: TVarData); override; procedure CastTo(var Dest: TVarData; const Source: TVarData; const AVarType: TVarType); override; procedure UnaryOp(var Right: TVarData; const Operator: Integer); override; procedure BinaryOp(var Left: TVarData; const Right: TVarData; const Operator: TVarOp); override; end; TWrapperVarData = record VType: TVarType; Reserved1, Reserved2, Reserved3: Word; Data: TAbstractWrapperData; Reserved4: LongInt; end; procedure CallVarAdd(var Left: Variant; const Right: Variant); procedure CallVarSub(var Left: Variant; const Right: Variant); procedure CallVarMul(var Left: Variant; const Right: Variant); procedure CallVarDiv(var Left: Variant; const Right: Variant); var numberOfGuesses: Integer; implementation uses sysUtils; procedure CallVarAdd(var Left: Variant; const Right: Variant); asm jmp Variants.@VarAdd; end; procedure CallVarSub(var Left: Variant; const Right: Variant); asm jmp Variants.@VarSub; end; procedure CallVarMul(var Left: Variant; const Right: Variant); asm jmp Variants.@VarMul; end; procedure CallVarDiv(var Left: Variant; const Right: Variant); asm jmp Variants.@VarrDiv; end; (* TAbstractWrapperData *) procedure TAbstractWrapperData.Release; begin Destroy; end; class function TAbstractWrapperData.getInstance: TAbstractWrapperData; begin Result:=Create; end; procedure TAbstractWrapperData.DoSubtract(const Right: TAbstractWrapperData); begin Right.DoNegate; DoAdd(Right); Right.DoNegate; //вернули, как было. Не очень красиво, лучше бы копию сделать, //но тогда нужно уметь создавать клон TAbstractWrapperData end; procedure TAbstractWrapperData.FastAssign(source: TAbstractWrapperData); begin Assign(source); end; (* TAbstractWrapperVariantType *) function TAbstractWrapperVariantType.GetInstance(const V: TVarData): TObject; begin Result:=TWrapperVarData(V).Data; end; procedure TAbstractWrapperVariantType.Clear(var V: TVarData); begin // inc(NumberOfGuesses); V.VType:=varEmpty; // FreeAndNil(TWrapperVarData(V).Data); // TWrapperVarData(V).Data.Free; //очевидно, и переписывания в конкр. классах не нужно TWrapperVarData(V).Data.Release; end; procedure TAbstractWrapperVariantType.Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); var WrapperClass: TWrapperDataClass; //задается в Create конкретного класса begin // if Indirect and VarDataIsByRef(Source) then // VarDataCopyNoInd(Dest, Source) // else // для custom variant'а никогда не будет передачи по ссылке // inc(numberOfGuesses); with TWrapperVarData(Dest) do begin VType := VarType; WrapperClass:=TWrapperDataClass(TWrapperVarData(Source).Data.ClassType); Data:=WrapperClass.GetInstance; //нужно при создании конкретного VariantType указать WrapperClass! Data.FastAssign(TWrapperVarData(Source).Data); end; end; procedure TAbstractWrapperVariantType.Cast(var Dest: TVarData; const Source: TVarData); begin //преобразуем другие Variant'ы в наш, это по сути "создание минимального контекста" end; procedure TAbstractWrapperVariantType.CastTo(var Dest: TVarData; const Source: TVarData; const AVarType: TVarType); begin //преобразуем наш Variant в другие типы end; procedure TAbstractWrapperVariantType.UnaryOp(var Right: TVarData; const Operator: Integer); begin //унарный минус и, возможно, логическое not. if Right.vtype=VarType then if Operator=opNegate then TWrapperVarData(Right).Data.DoNegate else RaiseInvalidOp else RaiseInvalidOp; end; procedure TAbstractWrapperVariantType.BinaryOp(var Left: TVarData; const Right: TVarData; const Operator: TVarOp); //var CastedRight: TVarData; begin //сложить, вычесть, умножить, поделить, остаток от деления и битовые операции (сдвиги, лог. и пр) (* if Right.vType<>VarType then Cast(CastedRight,Right) else CastedRight:=Right; *) // try case Left.VType of varString: case Operator of opAdd: Variant(Left) := Variant(Left) + TWrapperVarData(Right).Data.GetAsString; // Variant(Left) := Variant(Left) + TWrapperVarData(CastedRight).Data.GetAsString; else RaiseInvalidOp; end; else if Left.VType = VarType then case Operator of opAdd: // TWrapperVarData(Left).data.DoAdd(TWrapperVarData(CastedRight).Data); TWrapperVarData(Left).data.DoAdd(TWrapperVarData(Right).Data); opSubtract: // TWrapperVarData(Left).data.DoSubtract(TWrapperVarData(CastedRight).Data); TWrapperVarData(Left).data.DoSubtract(TWrapperVarData(Right).Data); opMultiply: // TWrapperVarData(Left).data.DoMultiply(TWrapperVarData(CastedRight).Data); TWrapperVarData(Left).data.DoMultiply(TWrapperVarData(Right).Data); opDivide: TWrapperVarData(Left).data.DoDivide(TWrapperVarData(Right).Data); // TWrapperVarData(Left).data.DoDivide(TWrapperVarData(CastedRight).Data); else RaiseInvalidOp; end else RaiseInvalidOp; end; // finally // if Right.VType<>VarType then // VarDataClear(CastedRight); //поскольку мы обращаемся с ним не как с Variant'ом, // //счетчик ссылок не работает, надо ручками его удалить! // end; end; function TAbstractWrapperVariantType.LeftPromotion(const V: TVarData; const Operator: TVarOp; out RequiredVarType: TVarType): Boolean; begin //во что преобразовать переменную слева от бинарной операции, чтобы действие могло выполниться if (Operator = opAdd) and VarDataIsStr(V) then RequiredVarType := varString else RequiredVarType := VarType; Result := True; //слева допускаем только строку, иначе "ассимилируем" end; end.
inherited dmConfiguracoes: TdmConfiguracoes OldCreateOrder = True inherited qryManutencao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO CONFIGURACOES' ' (MODULO, CLAUSULA, TPO_CLAUSULA, VLR_CLAUSULA, OPERADOR, DT_AL' + 'TERACAO)' 'VALUES' ' (:MODULO, :CLAUSULA, :TPO_CLAUSULA, :VLR_CLAUSULA, :OPERADOR, ' + ':DT_ALTERACAO)') SQLDelete.Strings = ( 'DELETE FROM CONFIGURACOES' 'WHERE' ' MODULO = :Old_MODULO AND CLAUSULA = :Old_CLAUSULA') SQLUpdate.Strings = ( 'UPDATE CONFIGURACOES' 'SET' ' MODULO = :MODULO, CLAUSULA = :CLAUSULA, TPO_CLAUSULA = :TPO_CL' + 'AUSULA, VLR_CLAUSULA = :VLR_CLAUSULA, OPERADOR = :OPERADOR, DT_A' + 'LTERACAO = :DT_ALTERACAO' 'WHERE' ' MODULO = :Old_MODULO AND CLAUSULA = :Old_CLAUSULA') SQLRefresh.Strings = ( 'SELECT MODULO, CLAUSULA, TPO_CLAUSULA, VLR_CLAUSULA, OPERADOR, D' + 'T_ALTERACAO FROM CONFIGURACOES' 'WHERE' ' MODULO = :Old_MODULO AND CLAUSULA = :Old_CLAUSULA') SQLLock.Strings = ( 'SELECT NULL FROM CONFIGURACOES' 'WHERE' 'MODULO = :Old_MODULO AND CLAUSULA = :Old_CLAUSULA' 'FOR UPDATE WITH LOCK') SQL.Strings = ( 'SELECT' ' CF.MODULO, ' ' CF.CLAUSULA, ' ' CF.TPO_CLAUSULA, ' ' CF.VLR_CLAUSULA, ' ' CF.OPERADOR, ' ' CF.DT_ALTERACAO,' ' CASE CF.TPO_CLAUSULA' ' WHEN '#39'L'#39' THEN' ' CASE CF.VLR_CLAUSULA' ' WHEN '#39'T'#39' THEN '#39'SIM'#39 ' ELSE '#39'N'#195'O'#39 ' END' ' WHEN '#39'P'#39' THEN '#39'********'#39 ' ELSE CF.VLR_CLAUSULA' ' END VISUALIZACAO' 'FROM CONFIGURACOES CF') object qryManutencaoMODULO: TStringField FieldName = 'MODULO' Required = True end object qryManutencaoCLAUSULA: TStringField FieldName = 'CLAUSULA' Required = True Size = 120 end object qryManutencaoTPO_CLAUSULA: TStringField FieldName = 'TPO_CLAUSULA' Size = 1 end object qryManutencaoVLR_CLAUSULA: TStringField FieldName = 'VLR_CLAUSULA' Size = 120 end object qryManutencaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryManutencaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryManutencaoVISUALIZACAO: TStringField FieldName = 'VISUALIZACAO' ReadOnly = True Size = 120 end end inherited qryLocalizacao: TIBCQuery SQL.Strings = ( 'SELECT' ' CF.MODULO, ' ' CF.CLAUSULA, ' ' CF.TPO_CLAUSULA, ' ' CF.VLR_CLAUSULA, ' ' CF.OPERADOR, ' ' CF.DT_ALTERACAO,' ' CASE CF.TPO_CLAUSULA' ' WHEN '#39'L'#39' THEN' ' CASE CF.VLR_CLAUSULA' ' WHEN '#39'T'#39' THEN '#39'SIM'#39 ' ELSE '#39'N'#195'O'#39 ' END' ' WHEN '#39'P'#39' THEN '#39'********'#39 ' ELSE CF.VLR_CLAUSULA' ' END VISUALIZACAO' 'FROM CONFIGURACOES CF') object qryLocalizacaoMODULO: TStringField FieldName = 'MODULO' Required = True end object qryLocalizacaoCLAUSULA: TStringField FieldName = 'CLAUSULA' Required = True Size = 120 end object qryLocalizacaoTPO_CLAUSULA: TStringField FieldName = 'TPO_CLAUSULA' Size = 1 end object qryLocalizacaoVLR_CLAUSULA: TStringField FieldName = 'VLR_CLAUSULA' Size = 120 end object qryLocalizacaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryLocalizacaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryLocalizacaoVISUALIZACAO: TStringField FieldName = 'VISUALIZACAO' ReadOnly = True Size = 120 end end end
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clResourceState; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, Windows; {$ELSE} System.Classes, Winapi.Windows; {$ENDIF} type TclProcessStatus = (psUnknown, psSuccess, psFailed, psErrors, psProcess, psTerminated); TclResourceStateList = class; TclResourceStateItem = class(TCollectionItem) private FResourcePos: Int64; FBytesToProceed: Int64; FStatus: TclProcessStatus; FBytesProceed: Int64; procedure SetResourcePos(const Value: Int64); function GetResourceState: TclResourceStateList; procedure SetBytesProceed(const Value: Int64); procedure SetBytesToProceed(const Value: Int64); public procedure Assign(Source: TPersistent); override; property ResourceState: TclResourceStateList read GetResourceState; property ResourcePos: Int64 read FResourcePos write SetResourcePos; property BytesToProceed: Int64 read FBytesToProceed write SetBytesToProceed; property BytesProceed: Int64 read FBytesProceed write SetBytesProceed; property Status: TclProcessStatus read FStatus write FStatus; end; TclResourceStateList = class(TCollection) private FResourceSize: Int64; FLastStatus: TclProcessStatus; FSpeedCount: TLargeInteger; FStartCount: TLargeInteger; FSpeed: Double; FElapsedTime: Double; FBytesProceedSinceStart: Int64; FOnChanged: TNotifyEvent; function GetItem(Index: Integer): TclResourceStateItem; procedure SetItem(Index: Integer; const Value: TclResourceStateItem); function GetBytesProceed: Int64; function GetLastStatus: TclProcessStatus; procedure UpdateStatistic(); function GetRemainingTime: Double; class function GetFrequency: TLargeInteger; protected procedure DoChanged(); virtual; procedure Update(Item: TCollectionItem); override; public constructor Create; procedure InitStatistic; procedure Assign(Source: TPersistent); override; procedure UpdateProceed(AItem: TclResourceStateItem; ABytesProceed: Int64); procedure UpdateStatus(AItem: TclResourceStateItem; AStatus: TclProcessStatus); procedure Init(AThreadCount, AResourceSize: Int64); function Add: TclResourceStateItem; property Items[Index: Integer]: TclResourceStateItem read GetItem write SetItem; default; property BytesProceed: Int64 read GetBytesProceed; property ResourceSize: Int64 read FResourceSize write FResourceSize; property LastStatus: TclProcessStatus read GetLastStatus; property Speed: Double read FSpeed; property ElapsedTime: Double read FElapsedTime; property RemainingTime: Double read GetRemainingTime; property OnChanged: TNotifyEvent read FOnChanged write FOnChanged; end; implementation { TclResourceStateList } function TclResourceStateList.Add(): TclResourceStateItem; begin Result := TclResourceStateItem(inherited Add()); end; procedure TclResourceStateList.Assign(Source: TPersistent); begin InitStatistic(); FResourceSize := 0; if (Source is TclResourceStateList) then begin FResourceSize := (Source as TclResourceStateList).ResourceSize; end; inherited Assign(Source); end; constructor TclResourceStateList.Create; begin inherited Create(TclResourceStateItem); end; procedure TclResourceStateList.InitStatistic(); var i: Integer; begin for i := 0 to Count - 1 do begin Items[i].FStatus := psUnknown; end; FLastStatus := psUnknown; FSpeedCount := 0; FStartCount := 0; FSpeed := 0; FElapsedTime := 0; FBytesProceedSinceStart := GetBytesProceed(); QueryPerformanceCounter(FStartCount); end; function TclResourceStateList.GetBytesProceed: Int64; var i: Integer; begin Result := 0; for i := 0 to Count - 1 do begin Result := Result + Items[i].BytesProceed; end; end; function TclResourceStateList.GetItem(Index: Integer): TclResourceStateItem; begin Result := TclResourceStateItem(inherited GetItem(Index)); end; function TclResourceStateList.GetLastStatus: TclProcessStatus; function CheckStatus(ACheckStatus: TclProcessStatus; var AResStatus: TclProcessStatus): Boolean; var i: Integer; begin for i := 0 to Count - 1 do begin AResStatus := Items[i].Status; Result := (AResStatus = ACheckStatus); if Result then Exit; end; AResStatus := psUnknown; Result := False; end; function CreckItemsStatus(): TclProcessStatus; begin if CheckStatus(psProcess, Result) then Exit; if CheckStatus(psTerminated, Result) then Exit; if CheckStatus(psFailed, Result) then Exit; if CheckStatus(psErrors, Result) then Exit; if CheckStatus(psSuccess, Result) then Exit; end; begin Result := CreckItemsStatus(); if (Result in [psUnknown, psSuccess]) and (FLastStatus <> psUnknown) then begin Result := FLastStatus; end; end; procedure TclResourceStateList.Init(AThreadCount, AResourceSize: Int64); var i: Integer; ResPos, Proceed: Int64; StateItem: TclResourceStateItem; begin InitStatistic(); if (Count > 0) then Exit; FResourceSize := AResourceSize; ResPos := 0; Proceed := 0; for i := 0 to AThreadCount - 1 do begin StateItem := Add(); if (FResourceSize > 0) then begin ResPos := i * (FResourceSize div AThreadCount); if (i < (AThreadCount - 1)) then begin Proceed := (FResourceSize div AThreadCount); end else begin Proceed := FResourceSize - ResPos; end; end; StateItem.ResourcePos := ResPos; StateItem.BytesToProceed := Proceed; end; end; procedure TclResourceStateList.SetItem(Index: Integer; const Value: TclResourceStateItem); begin inherited SetItem(Index, Value); end; procedure TclResourceStateList.Update(Item: TCollectionItem); begin inherited Update(Item); if (Count = 0) then begin InitStatistic(); end; DoChanged(); end; procedure TclResourceStateList.UpdateProceed(AItem: TclResourceStateItem; ABytesProceed: Int64); begin if (AItem <> nil) then begin AItem.FBytesProceed := ABytesProceed; end; UpdateStatistic(); DoChanged(); end; procedure TclResourceStateList.UpdateStatus(AItem: TclResourceStateItem; AStatus: TclProcessStatus); begin if (AItem <> nil) then begin AItem.FStatus := AStatus; end else begin FLastStatus := AStatus; end; DoChanged(); end; var FrequencyValue: TLargeInteger = 0; class function TclResourceStateList.GetFrequency(): TLargeInteger; begin if (FrequencyValue = 0) then begin QueryPerformanceFrequency(FrequencyValue); end; Result := FrequencyValue; end; procedure TclResourceStateList.UpdateStatistic(); var NewCount: TLargeInteger; begin FSpeed := 0; FElapsedTime := 0; if QueryPerformanceCounter(NewCount) and (GetFrequency() > 0) then begin FSpeed := (BytesProceed - FBytesProceedSinceStart) / ((NewCount - FStartCount) / GetFrequency()); FSpeedCount := NewCount; FElapsedTime := (FSpeedCount - FStartCount) / GetFrequency(); end; end; function TclResourceStateList.GetRemainingTime: Double; begin if (ResourceSize > 0) and (Speed > 0) then begin Result := (ResourceSize - BytesProceed) / Speed; end else begin Result := 0; end; end; procedure TclResourceStateList.DoChanged; begin if Assigned(FOnChanged) then begin FOnChanged(Self); end; end; { TclResourceStateItem } procedure TclResourceStateItem.Assign(Source: TPersistent); var Src: TclResourceStateItem; begin if (Source is TclResourceStateItem) then begin Src := (Source as TclResourceStateItem); FResourcePos := Src.ResourcePos; FBytesToProceed := Src.BytesToProceed; FStatus := Src.Status; FBytesProceed := Src.BytesProceed; end else begin inherited Assign(Source); end; end; function TclResourceStateItem.GetResourceState: TclResourceStateList; begin Result := (Collection as TclResourceStateList); end; procedure TclResourceStateItem.SetBytesProceed(const Value: Int64); begin if (Value > -1) then begin FBytesProceed := Value; end; end; procedure TclResourceStateItem.SetBytesToProceed(const Value: Int64); begin if (Value > -1) then begin FBytesToProceed := Value; end; end; procedure TclResourceStateItem.SetResourcePos(const Value: Int64); begin if (Value > -1) then begin FResourcePos := Value; end; end; end.
unit DateForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DateL; type TForm1 = class(TForm) ButtonAddDates: TButton; ButtonAddButton: TButton; ListBox1: TListBox; ComboBox1: TComboBox; procedure ButtonAddDatesClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ButtonAddButtonClick(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure FormDestroy(Sender: TObject); private ListI: TDateListI; ListW: TDateListW; public procedure UpdateList; end; var Form1: TForm1; implementation {$R *.DFM} uses Dates; procedure TForm1.ButtonAddDatesClick(Sender: TObject); var I: Integer; Date: TDate; begin Randomize; for I := 1 to 10 do begin Date := TDate.Create (1900 + Random (200), 1 + Random (12), 1 + Random (28)); ListI.Add (Date); end; for I := 1 to 10 do begin Date := TDate.Create (1900 + Random (200), 1 + Random (12), 1 + Random (28)); ListW.Add (Date); end; UpdateList; end; procedure TForm1.FormCreate(Sender: TObject); begin ListI := TDateListI.Create; ListW := TDateListW.Create; ComboBox1.ItemIndex := 0; end; procedure TForm1.ButtonAddButtonClick(Sender: TObject); begin ListW.Add (TDate(TButton.Create (nil))); TList(ListI).Add (TButton.Create (nil)); UpdateList; end; procedure TForm1.UpdateList; var I: Integer; begin ListBox1.Clear; try if ComboBox1.ItemIndex = 0 then for I := 0 to ListI.Count - 1 do Listbox1.Items.Add ( ListI [I].GetText) else for I := 0 to ListW.Count - 1 do Listbox1.Items.Add ( ListW [I].GetText); except on E: Exception do Listbox1.Items.Add ('Error: ' + E.Message); end; end; procedure TForm1.ComboBox1Change(Sender: TObject); begin UpdateList; end; procedure TForm1.FormDestroy(Sender: TObject); begin // delete lists ListW.Free; ListI.Free; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.53 3/10/05 3:23:16 PM RLebeau Updated WriteDirect() to access the Intercept property directly. Rev 1.52 11/12/2004 11:30:16 AM JPMugaas Expansions for IPv6. Rev 1.51 11/11/04 12:03:46 PM RLebeau Updated DoConnectTimeout() to recognize IdTimeoutDefault Rev 1.50 6/18/04 1:06:58 PM RLebeau Bug fix for ReadTimeout property Rev 1.49 5/4/2004 9:57:34 AM JPMugaas Removed some old uncommented code and reenabled some TransparentProxy code since it compile in DotNET. Rev 1.48 2004.04.18 12:52:02 AM czhower Big bug fix with server disconnect and several other bug fixed that I found along the way. Rev 1.47 2004.04.08 3:56:34 PM czhower Fixed bug with Intercept byte count. Also removed Bytes from Buffer. Rev 1.46 2004.03.12 8:01:00 PM czhower Exception update Rev 1.45 2004.03.07 11:48:42 AM czhower Flushbuffer fix + other minor ones found Rev 1.44 2004.03.01 5:12:32 PM czhower -Bug fix for shutdown of servers when connections still existed (AV) -Implicit HELP support in CMDserver -Several command handler bugs -Additional command handler functionality. Rev 1.43 2/21/04 9:25:50 PM RLebeau Fix for BBG #66 Added FLastSocketError member to TIdConnectThread Rev 1.42 2004.02.03 4:16:48 PM czhower For unit name changes. Rev 1.41 12/31/2003 9:51:56 PM BGooijen Added IPv6 support Rev 1.40 2003.12.28 1:05:58 PM czhower .Net changes. Rev 1.39 11/21/2003 12:05:18 AM BGooijen Terminated isn't public in TThread any more, made it public here now Rev 1.38 10/28/2003 9:15:44 PM BGooijen .net Rev 1.37 10/18/2003 1:42:46 PM BGooijen Added include Rev 1.36 2003.10.14 1:26:56 PM czhower Uupdates + Intercept support Rev 1.35 2003.10.11 5:48:36 PM czhower -VCL fixes for servers -Chain suport for servers (Super core) -Scheduler upgrades -Full yarn support Rev 1.34 10/9/2003 8:09:10 PM SPerry bug fixes Rev 1.33 10/5/2003 11:02:36 PM BGooijen Write buffering Rev 1.32 05/10/2003 23:01:02 HHariri Fix for connect problem when IP address specified as opposed to host Rev 1.31 2003.10.02 8:23:42 PM czhower DotNet Excludes Rev 1.30 2003.10.02 10:16:28 AM czhower .Net Rev 1.29 2003.10.01 9:11:18 PM czhower .Net Rev 1.28 2003.10.01 5:05:14 PM czhower .Net Rev 1.27 2003.10.01 2:46:38 PM czhower .Net Rev 1.26 2003.10.01 2:30:38 PM czhower .Net Rev 1.22 10/1/2003 12:14:14 AM BGooijen DotNet: removing CheckForSocketError Rev 1.21 2003.10.01 1:37:34 AM czhower .Net Rev 1.19 2003.09.30 1:22:58 PM czhower Stack split for DotNet Rev 1.18 2003.07.14 1:57:22 PM czhower -First set of IOCP fixes. -Fixed a threadsafe problem with the stack class. Rev 1.17 2003.07.14 12:54:32 AM czhower Fixed graceful close detection if it occurs after connect. Rev 1.16 2003.07.10 4:34:58 PM czhower Fixed AV, added some new comments Rev 1.15 7/4/2003 08:26:46 AM JPMugaas Optimizations. Rev 1.14 7/1/2003 03:39:48 PM JPMugaas Started numeric IP function API calls for more efficiency. Rev 1.13 6/30/2003 10:25:18 AM BGooijen removed unnecessary assignment to FRecvBuffer.Size Rev 1.12 6/29/2003 10:56:28 PM BGooijen Removed .Memory from the buffer, and added some extra methods Rev 1.11 2003.06.25 4:28:32 PM czhower Formatting and fixed a short circuit clause. Rev 1.10 6/3/2003 11:43:52 PM BGooijen Elimintated some code Rev 1.9 4/16/2003 3:31:26 PM BGooijen Removed InternalCheckForDisconnect, added .Connected Rev 1.8 4/14/2003 11:44:20 AM BGooijen CheckForDisconnect calls ReadFromSource now Rev 1.7 4/2/2003 3:24:56 PM BGooijen Moved transparantproxy from ..stack to ..socket Rev 1.6 3/5/2003 11:04:32 PM BGooijen Fixed Intercept, but the part in WriteBuffer doesn't look really nice yet Rev 1.5 3/3/2003 11:31:58 PM BGooijen fixed stack overflow in .CheckForDisconnect Rev 1.4 2/26/2003 1:15:40 PM BGooijen FBinding is now freed in IdIOHandlerSocket, instead of in IdIOHandlerStack Rev 1.3 2003.02.25 1:36:12 AM czhower Rev 1.2 2002.12.06 11:49:34 PM czhower Rev 1.1 12-6-2002 20:10:18 BGooijen Added IPv6-support Rev 1.0 11/13/2002 08:45:16 AM JPMugaas } unit IdIOHandlerStack; interface {$i IdCompilerDefines.inc} uses Classes, IdGlobal, IdSocketHandle, IdIOHandlerSocket, IdExceptionCore, IdStack, SysUtils; type TIdIOHandlerStack = class(TIdIOHandlerSocket) protected procedure ConnectClient; override; function ReadDataFromSource(var VBuffer: TIdBytes): Integer; override; function WriteDataToTarget(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; override; public procedure CheckForDisconnect(ARaiseExceptionIfDisconnected: Boolean = True; AIgnoreBuffer: Boolean = False); override; function Connected: Boolean; override; function Readable(AMSec: Integer = IdTimeoutDefault): Boolean; override; published property ReadTimeout; end; implementation uses {$IFDEF USE_VCL_POSIX} Posix.SysSelect, Posix.SysTime, {$ENDIF} IdAntiFreezeBase, IdResourceStringsCore, IdResourceStrings, IdStackConsts, IdException, IdTCPConnection, IdComponent, IdIOHandler; type TIdConnectThread = class(TThread) protected FBinding: TIdSocketHandle; FLastSocketError: Integer; FExceptionMessage: string; FExceptionOccured: Boolean; procedure Execute; override; procedure DoTerminate; override; public constructor Create(ABinding: TIdSocketHandle); reintroduce; property Terminated; end; { TIdIOHandlerStack } function TIdIOHandlerStack.Connected: Boolean; begin ReadFromSource(False, 0, False); Result := inherited Connected; end; procedure TIdIOHandlerStack.ConnectClient; procedure DoConnectTimeout(ATimeout: Integer); var LSleepTime: Integer; LThread: TIdConnectThread; begin if ATimeout = IdTimeoutDefault then begin ATimeout := IdTimeoutInfinite; end; LThread := TIdConnectThread.Create(Binding); try // IndySleep if TIdAntiFreezeBase.ShouldUse then begin LSleepTime := IndyMin(GAntiFreeze.IdleTimeOut, 125); end else begin LSleepTime := 125; end; if ATimeout = IdTimeoutInfinite then begin while not LThread.Terminated do begin IndySleep(LSleepTime); TIdAntiFreezeBase.DoProcess; end; end else begin while (ATimeout > 0) and (not LThread.Terminated) do begin IndySleep(IndyMin(ATimeout, LSleepTime)); TIdAntiFreezeBase.DoProcess; Dec(ATimeout, IndyMin(ATimeout, LSleepTime)); end; end; if LThread.Terminated then begin if LThread.FExceptionOccured then begin if LThread.FLastSocketError <> 0 then begin raise EIdSocketError.CreateError(LThread.FLastSocketError, LThread.FExceptionMessage); end; EIdConnectException.Toss(LThread.FExceptionMessage); end; end else begin LThread.Terminate; Close; LThread.WaitFor; EIdConnectTimeout.Toss(RSConnectTimeout); end; finally LThread.Free; end; end; var LHost: String; LPort: Integer; LIP: string; LIPVersion : TIdIPVersion; begin inherited ConnectClient; if Assigned(FTransparentProxy) then begin if FTransparentProxy.Enabled then begin LHost := FTransparentProxy.Host; LPort := FTransparentProxy.Port; LIPVersion := FTransparentProxy.IPVersion; end else begin LHost := Host; LPort := Port; LIPVersion := IPVersion; end; end else begin LHost := Host; LPort := Port; LIPVersion := IPVersion; end; if LIPVersion = Id_IPv4 then begin if not GStack.IsIP(LHost) then begin if Assigned(OnStatus) then begin DoStatus(hsResolving, [LHost]); end; LIP := GStack.ResolveHost(LHost, LIPVersion); end else begin LIP := LHost; end; end else begin //IPv6 LIP := MakeCanonicalIPv6Address(LHost); if LIP='' then begin //if MakeCanonicalIPv6Address failed, we have a hostname if Assigned(OnStatus) then begin DoStatus(hsResolving, [LHost]); end; LIP := GStack.ResolveHost(LHost, LIPVersion); end else begin LIP := LHost; end; end; Binding.SetPeer(LIP, LPort, LIPVersion); // Connect //note for status events, we check specifically for them here //so we don't do a string conversion in Binding.PeerIP. if Assigned(OnStatus) then begin DoStatus(hsConnecting, [Binding.PeerIP]); end; if ConnectTimeout = 0 then begin if TIdAntiFreezeBase.ShouldUse then begin DoConnectTimeout(120000); // 2 Min end else begin Binding.Connect; end; end else begin DoConnectTimeout(ConnectTimeout); end; if Assigned(FTransparentProxy) then begin if FTransparentProxy.Enabled then begin FTransparentProxy.Connect(Self, Host, Port, IPVersion); end; end; end; function TIdIOHandlerStack.Readable(AMSec: integer): boolean; begin Result := Binding.Readable(AMSec); end; function TIdIOHandlerStack.WriteDataToTarget(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; begin Assert(Binding<>nil); Result := Binding.Send(ABuffer, AOffset, ALength); end; // Reads any data in tcp/ip buffer and puts it into Indy buffer // This must be the ONLY raw read from Winsock routine // This must be the ONLY call to RECV - all data goes thru this method function TIdIOHandlerStack.ReadDataFromSource(var VBuffer: TIdBytes): Integer; begin Assert(Binding<>nil); Result := Binding.Receive(VBuffer); end; procedure TIdIOHandlerStack.CheckForDisconnect( ARaiseExceptionIfDisconnected: Boolean; AIgnoreBuffer: Boolean); var LDisconnected: Boolean; begin // ClosedGracefully // Server disconnected // IOHandler = nil // Client disconnected if ClosedGracefully then begin if BindingAllocated then begin Close; // Call event handlers to inform the user that we were disconnected DoStatus(hsDisconnected); //DoOnDisconnected; end; LDisconnected := True; end else begin LDisconnected := not BindingAllocated; end; // Do not raise unless all data has been read by the user if LDisconnected then begin if (InputBufferIsEmpty or AIgnoreBuffer) and ARaiseExceptionIfDisconnected then begin RaiseConnClosedGracefully; end; end; end; { TIdConnectThread } constructor TIdConnectThread.Create(ABinding: TIdSocketHandle); begin FBinding := ABinding; inherited Create(False); end; procedure TIdConnectThread.Execute; begin try FBinding.Connect; except on E: Exception do begin FExceptionOccured := True; FExceptionMessage := E.Message; if E is EIdSocketError then begin if (EIdSocketError(E).LastError <> Id_WSAEBADF) and (EIdSocketError(E).LastError <> Id_WSAENOTSOCK) then begin FLastSocketError := EIdSocketError(E).LastError; end; end; end; end; end; procedure TIdConnectThread.DoTerminate; begin // Necessary as caller checks this Terminate; inherited; end; initialization TIdIOHandlerStack.SetDefaultClass; end.
unit FFSBtnEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,EditBtn; type TFFSBtnEdit = class(TCustomEdit) private FUnitSize : integer; FRightAlign:boolean; FButton: TEditButton; FEditorEnabled: Boolean; FOnClickBtn:TNotifyEvent; FFlat: boolean; FEtched: boolean; FFocusBorder: boolean; FMouseInControl: boolean; FReturnIsTab:boolean; function GetMinHeight: Integer; procedure SetEditRect; procedure SetGlyph(value:tBitmap); function GetGlyph:TBitmap; procedure SetCaption(value:string); function GetCaption:string; procedure SetRightAlign(const Value : boolean); procedure SetFlat(const Value : boolean); procedure SetEtched(const Value : boolean); procedure DrawControlBorder(DC:HDC); procedure DrawButtonBorder; procedure DrawBorders; function Is3DBorderControl: Boolean; function Is3DBorderButton: Boolean; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure CMEnter(var Message: TCMGotFocus); message CM_ENTER; procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure WMPaste(var Message: TWMPaste); message WM_PASTE; procedure WMCut(var Message: TWMCut); message WM_CUT; procedure WMPaint(var Msg: TWMPAINT); message WM_PAINT; procedure WMNCPaint (var Message: TMessage); message WM_NCPAINT; protected procedure BtnClick (Sender: TObject); virtual; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key:char); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Button: TEditButton read FButton; published property AutoSelect; property AutoSize; property BorderStyle; property Color; property Ctl3D; property DragCursor; property DragMode; property EditorEnabled: Boolean read FEditorEnabled write FEditorEnabled default True; property ReturnIsTab:boolean read fReturnIsTab write fReturnIsTab; property Enabled; property Font; property Flat:boolean read fFlat write SetFlat; property Etched:boolean read fEtched write SetEtched; property FocusBorder:boolean read fFocusBorder write fFocusBorder; property Glyph:TBitmap read GetGlyph write SetGlyph; property ButtonCaption:string read GetCaption write SetCaption; property MaxLength; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property RightAlign:boolean read fRightAlign write SetRightAlign; property ShowHint; property TabOrder; property TabStop; property Text; property Visible; property Height; property Width; 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; {$IFDEF WIN32} property OnStartDrag; {$ENDIF} property OnClickBtn: TNotifyEvent read FOnClickBtn write FOnClickBtn; end; procedure Register; implementation constructor TFFSBtnEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FButton := TEditButton.Create (Self); FButton.Width := 15; FButton.Height := 17; FButton.Visible := True; FButton.Parent := Self; FButton.FocusControl := Self; FButton.OnClick := BtnClick; FButton.ParentCtl3D := False; Text := '0'; ControlStyle := ControlStyle - [csSetCaption]; FEditorEnabled := True; FRightAlign := False; FUnitSize:=0; end; destructor TFFSBtnEdit.Destroy; begin FButton := nil; inherited Destroy; end; procedure TFFSBtnEdit.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); { Params.Style := Params.Style and not WS_BORDER; } if fRightAlign then Params.Style := Params.Style or ES_MULTILINE or WS_CLIPCHILDREN or ES_RIGHT else Params.Style := Params.Style or ES_MULTILINE or WS_CLIPCHILDREN; end; procedure TFFSBtnEdit.CreateWnd; begin inherited CreateWnd; SetEditRect; end; procedure TFFSBtnEdit.SetGlyph(value:TBitmap); begin FButton.Glyph:=Value; end; function TFFSBtnEdit.GetGlyph:TBitmap; begin Result:=FButton.Glyph; end; procedure TFFSBtnEdit.SetCaption(value:string); begin FButton.ButtonCaption:=value; end; function TFFSBtnEdit.GetCaption:string; begin result:=FButton.ButtonCaption; end; procedure TFFSBtnEdit.SetEditRect; var Loc: TRect; begin SendMessage(Handle, EM_GETRECT, 0, LongInt(@Loc)); Loc.Bottom := ClientHeight + 1; {+1 is workaround for windows paint bug} Loc.Right := ClientWidth - FButton.Width - 3 - fUnitsize; if self.BorderStyle=bsNone then begin Loc.Top := 2; Loc.Left := 2; end else begin Loc.Top := 1; Loc.Left := 1; end; SendMessage(Handle, EM_SETRECTNP, 0, LongInt(@Loc)); SendMessage(Handle, EM_GETRECT, 0, LongInt(@Loc)); {debug} end; procedure TFFSBtnEdit.WMSize(var Message: TWMSize); var MinHeight: Integer; Dist,FlatCorr:integer; begin inherited; if (BorderStyle=bsNone) then Dist:=2 else Dist:=5; if fFlat then Dist:=3; if fFlat then FlatCorr:=1 else FlatCorr:=0; MinHeight := GetMinHeight; { text edit bug: if size to less than minheight, then edit ctrl does not display the text } if Height < MinHeight then Height := MinHeight else if FButton <> nil then begin if NewStyleControls and Ctl3D then FButton.SetBounds(Width - FButton.Width - Dist,1+ FlatCorr, FButton.Width+FlatCorr, Height - Dist-FlatCorr) else FButton.SetBounds (Width - FButton.Width, 1, FButton.Width, Height - 3); SetEditRect; end; end; function TFFSBtnEdit.GetMinHeight: Integer; var DC: HDC; SaveFont: HFont; I: Integer; SysMetrics, Metrics: TTextMetric; begin DC := GetDC(0); GetTextMetrics(DC, SysMetrics); SaveFont := SelectObject(DC, Font.Handle); GetTextMetrics(DC, Metrics); SelectObject(DC, SaveFont); ReleaseDC(0, DC); I := SysMetrics.tmHeight; if I > Metrics.tmHeight then I := Metrics.tmHeight; {Result := Metrics.tmHeight + I div 4 + GetSystemMetrics(SM_CYBORDER) * 4 +2;} Result := Metrics.tmHeight + I div 4 {+ GetSystemMetrics(SM_CYBORDER) * 4}; end; procedure TFFSBtnEdit.BtnClick (Sender: TObject); begin if assigned(FOnClickBtn) then FOnClickBtn(Sender); end; procedure TFFSBtnEdit.WMPaste(var Message: TWMPaste); begin if not FEditorEnabled or ReadOnly then Exit; inherited; end; procedure TFFSBtnEdit.WMCut(var Message: TWMPaste); begin if not FEditorEnabled or ReadOnly then Exit; inherited; end; procedure TFFSBtnEdit.CMExit(var Message: TCMExit); begin inherited; DrawBorders; end; procedure TFFSBtnEdit.CMEnter(var Message: TCMGotFocus); begin if AutoSelect and not (csLButtonDown in ControlState) then SelectAll; inherited; DrawBorders; end; procedure TFFSBtnEdit.CMMouseEnter(var Message: TMessage); begin inherited; if not FMouseInControl and Enabled then begin FMouseInControl := True; DrawBorders; end; end; procedure TFFSBtnEdit.CMMouseLeave(var Message: TMessage); begin inherited; if FMouseInControl and Enabled then begin FMouseInControl := False; DrawBorders; end; end; procedure TFFSBtnEdit.SetRightAlign(const Value: boolean); begin if fRightAlign<>value then begin fRightAlign:=value; recreatewnd; end; end; procedure TFFSBtnEdit.SetFlat(const Value: boolean); begin if fFlat<>value then begin fFlat:=value; fButton.Ctl3D := False;//fbutton.fButton.flat:=fFlat; if fFlat then BorderStyle:=bsNone; Invalidate; if not fFlat then recreatewnd; end; end; procedure TFFSBtnEdit.SetEtched(const Value: boolean); begin if fEtched<>value then begin fEtched:=value; //fButton.fButton.Etched:=value; Invalidate; end; end; function TFFSBtnEdit.Is3DBorderControl: Boolean; begin if csDesigning in ComponentState then Result:=false else Result:=FMouseInControl or (Screen.ActiveControl = Self); result:=result and fFocusBorder; end; function TFFSBtnEdit.Is3DBorderButton: Boolean; begin if csDesigning in ComponentState then Result:=Enabled else Result:=FMouseInControl or (Screen.ActiveControl = Self); end; procedure TFFSBtnEdit.DrawControlBorder(DC: HDC); var ARect:TRect; BtnFaceBrush, WindowBrush: HBRUSH; begin if Is3DBorderControl then BtnFaceBrush:=CreateSolidBrush(GetSysColor(COLOR_BTNFACE)) else BtnFaceBrush:=CreateSolidBrush(ColorToRGB((parent as TWinControl).brush.color)); WindowBrush:=CreateSolidBrush(GetSysColor(COLOR_WINDOW)); try GetWindowRect(Handle, ARect); OffsetRect(ARect, -ARect.Left, -ARect.Top); if Is3DBorderControl then begin DrawEdge(DC, ARect, BDR_SUNKENOUTER, BF_RECT or BF_ADJUST); FrameRect(DC, ARect, BtnFaceBrush); InflateRect(ARect, -1, -1); FrameRect(DC, ARect, WindowBrush); end else begin DrawEdge(DC, ARect, BDR_SUNKENOUTER, BF_BOTTOM or BF_MONO or BF_ADJUST); //FrameRect(DC, ARect, BtnFaceBrush); //InflateRect(ARect, -1, -1); FrameRect(DC, ARect, BtnFaceBrush); InflateRect(ARect, -1, -1); FrameRect(DC, ARect, WindowBrush); end; finally DeleteObject(WindowBrush); DeleteObject(BtnFaceBrush); end; end; procedure TFFSBtnEdit.DrawButtonBorder; begin // fButton.Focused := Is3DBorderButton; end; procedure TFFSBtnEdit.DrawBorders; var DC: HDC; begin if not fFlat then exit; DC:=GetWindowDC(Handle); try DrawControlBorder(DC); DrawButtonBorder; finally ReleaseDC(DC, Handle); end; end; procedure TFFSBtnEdit.WMPaint(var Msg: TWMPAINT); begin inherited; DrawBorders; end; procedure TFFSBtnEdit.WMNCPaint(var Message: TMessage); begin inherited; DrawBorders; end; procedure TFFSBtnEdit.KeyDown(var Key: Word; Shift: TShiftState); begin if (Key = vk_return) and FReturnIsTab then begin postmessage(self.handle,wm_keydown,VK_TAB,0); key:=0; end; inherited; end; procedure TFFSBtnEdit.KeyPress(var Key: char); begin if (key=#13) and FReturnIsTab then key:=#0 else inherited Keypress(key); end; procedure Register; begin RegisterComponents('FFS Controls', [TFFSBtnEdit]); end; end.
program AnonymousThreads; {$MODE DELPHI} {$IFDEF MSWINDOWS} {$APPTYPE CONSOLE} {$ENDIF} uses {$IFDEF UNIX} cthreads, {$ENDIF} Classes, Quick.Commons, Quick.Console, SysUtils, Quick.Threads; type TMyProcs = class class procedure DoWork; class procedure DoTerminate; end; class procedure TMyProcs.DoWork; var i : Integer; begin for i := 0 to 10 do cout('Working %d',[i],etTrace); cout('executed thread',etSuccess); end; class procedure TMyProcs.DoTerminate; begin cout('terminated thread',etSuccess); cout('PRESS <ENTER> TO EXIT',TLogEventType.etInfo); end; begin try console.LogVerbose := LOG_DEBUG; TAnonymousThread.Execute(TMyProcs.DoWork) .OnTerminate(TMyProcs.DoTerminate).Start; cout('Press <Enter> to exit',TLogEventType.etWarning); ConsoleWaitForEnterKey; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.
{$MODE OBJFPC} program CountMod; const InputFile = 'COUNTMOD.INP'; OutputFile = 'COUNTMOD.OUT'; var fi, fo: TextFile; a, b: array[1..4] of Int64; procedure Enter; var i: Integer; begin for i := 1 to 4 do ReadLn(fi, a[i], b[i]); end; function DoMulMod(a, b, m: Int64): Int64; var t: Int64; begin if b = 0 then Exit(0); t := DoMulMod(a, b div 5, m) mod m; Result := (5 * t + (b mod 5) * a) mod m; end; function MulMod(a, b, m: Int64): Int64; begin if b < 0 then begin a := -a; b := -b; end; Result := DoMulMod(a, b, m); end; function SolveDiophante(a, b, c: Int64; var lcm, x: Int64): Boolean; var m, n, r, q, xm, xn, xr, t: Int64; begin m := a; xm := 1; n := b; xn := 0; while n <> 0 do begin q := m div n; r := m - q * n; xr := xm - q * xn; m := n; xm := xn; n := r; xn := xr; end; Result := c mod m = 0; if not Result then Exit; t := c div m; x := MulMod(xm, t, b div m); lcm := Abs(a div m * b); end; //x mod a = b; x mod c = d function SolveSE(a, b, c, d: int64; var m, x: Int64): Boolean; var y: Int64; begin Result := SolveDiophante(a, -c, d - b, m, y); if not Result then Exit; x := (MulMod(a, y, m) + b) mod m; end; function Solve4: Int64; var a12, b12, a34, b34: Int64; x, m: Int64; begin if not SolveSE(a[1], b[1], a[2], b[2], a12, b12) then Exit(-1); if not SolveSE(a[3], b[3], a[4], b[4], a34, b34) then Exit(-1); if not SolveSE(a12, b12, a34, b34, m, x) then Exit(-1); Result := ((x mod m) + m) mod m; end; procedure SolveAll; var T, i: Integer; begin ReadLn(fi, T); for i := 1 to T do begin Enter; WriteLn(fo, Solve4); end; end; begin AssignFile(fi, InputFile); Reset(fi); AssignFile(fo, OutputFile); Rewrite(fo); try SolveAll; finally CloseFile(fi); CloseFile(fo); end; end.
{******************************************************************************} { } { Library: Fundamentals TLS } { File name: flcTLSOpaqueEncoding.pas } { File version: 5.02 } { Description: TLS Opaque Encoding } { } { Copyright: Copyright (c) 2008-2020, David J Butler } { All rights reserved. } { Redistribution and use in source and binary forms, with } { or without modification, are permitted provided that } { the following conditions are met: } { Redistributions of source code must retain the above } { copyright notice, this list of conditions and the } { following disclaimer. } { THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND } { CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED } { WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED } { WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A } { PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL } { THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, } { INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR } { CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, } { PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF } { USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) } { HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER } { IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING } { NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE } { USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE } { POSSIBILITY OF SUCH DAMAGE. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 2008/01/18 0.01 Initial development. } { 2020/05/09 5.02 Create flcTLSOpaqueEncoding unit from flcTLSUtils unit. } { } {******************************************************************************} {$INCLUDE flcTLS.inc} unit flcTLSOpaqueEncoding; interface uses flcStdTypes; function EncodeTLSWord16(var Buffer; const Size: Integer; const AVal: Integer): Integer; function DecodeTLSWord16(const Buffer; const Size: Integer; var AVal: Integer): Integer; function EncodeTLSLen16(var Buffer; const Size: Integer; const ALen: Integer): Integer; function EncodeTLSLen24(var Buffer; const Size: Integer; const ALen: Integer): Integer; function DecodeTLSLen16(const Buffer; const Size: Integer; var ALen: Integer): Integer; function DecodeTLSLen24(const Buffer; const Size: Integer; var ALen: Integer): Integer; function EncodeTLSOpaque16(var Buffer; const Size: Integer; const A: RawByteString): Integer; function EncodeTLSOpaque24(var Buffer; const Size: Integer; const A: RawByteString): Integer; function DecodeTLSOpaque16(const Buffer; const Size: Integer; var A: RawByteString): Integer; function DecodeTLSOpaque24(const Buffer; const Size: Integer; var A: RawByteString): Integer; implementation uses { TLS } flcTLSAlert, flcTLSErrors; function EncodeTLSWord16(var Buffer; const Size: Integer; const AVal: Integer): Integer; var P : PByte; begin Assert(AVal >= 0); Assert(AVal <= $FFFF); if Size < 2 then raise ETLSError.CreateAlertBufferEncode; P := @Buffer; P^ := (AVal and $FF00) shr 8; Inc(P); P^ := (AVal and $00FF); Result := 2; end; function DecodeTLSWord16(const Buffer; const Size: Integer; var AVal: Integer): Integer; var P : PByte; begin if Size < 2 then raise ETLSError.CreateAlertBufferDecode; P := @Buffer; AVal := P^ shl 8; Inc(P); Inc(AVal, P^); Result := 2; end; function EncodeTLSLen16(var Buffer; const Size: Integer; const ALen: Integer): Integer; begin Result := EncodeTLSWord16(Buffer, Size, ALen); end; function EncodeTLSLen24(var Buffer; const Size: Integer; const ALen: Integer): Integer; var P : PByte; begin Assert(ALen >= 0); Assert(ALen <= $FFFFFF); if Size < 3 then raise ETLSError.CreateAlertBufferEncode; P := @Buffer; P^ := (ALen and $FF0000) shr 16; Inc(P); P^ := (ALen and $00FF00) shr 8; Inc(P); P^ := (ALen and $0000FF); Result := 3; end; function DecodeTLSLen16(const Buffer; const Size: Integer; var ALen: Integer): Integer; begin Result := DecodeTLSWord16(Buffer, Size, ALen); end; function DecodeTLSLen24(const Buffer; const Size: Integer; var ALen: Integer): Integer; var P : PByte; begin if Size < 3 then raise ETLSError.CreateAlertBufferDecode; P := @Buffer; ALen := P^ shl 16; Inc(P); Inc(ALen, P^ shl 8); Inc(P); Inc(ALen, P^); Result := 3; end; function EncodeTLSOpaque16(var Buffer; const Size: Integer; const A: RawByteString): Integer; var P : PByte; N, L : Integer; begin N := Size; P := @Buffer; L := Length(A); EncodeTLSLen16(P^, N, L); Inc(P, 2); Dec(N, 2); Dec(N, L); if N < 0 then raise ETLSError.CreateAlertBufferEncode; if L > 0 then Move(Pointer(A)^, P^, L); Result := Size - N; end; function EncodeTLSOpaque24(var Buffer; const Size: Integer; const A: RawByteString): Integer; var P : PByte; N, L : Integer; begin N := Size; P := @Buffer; L := Length(A); EncodeTLSLen24(P^, N, L); Inc(P, 3); Dec(N, 3); Dec(N, L); if N < 0 then raise ETLSError.CreateAlertBufferEncode; if L > 0 then Move(Pointer(A)^, P^, L); Result := Size - N; end; function DecodeTLSOpaque16(const Buffer; const Size: Integer; var A: RawByteString): Integer; var P : PByte; N, L : Integer; begin N := Size; P := @Buffer; DecodeTLSLen16(P^, N, L); Inc(P, 2); Dec(N, 2); Dec(N, L); if N < 0 then raise ETLSError.CreateAlertBufferDecode; SetLength(A, L); if L > 0 then Move(P^, Pointer(A)^, L); Result := Size - N; end; function DecodeTLSOpaque24(const Buffer; const Size: Integer; var A: RawByteString): Integer; var P : PByte; N, L : Integer; begin N := Size; P := @Buffer; DecodeTLSLen24(P^, N, L); Inc(P, 3); Dec(N, 3); Dec(N, L); if N < 0 then raise ETLSError.CreateAlertBufferDecode; SetLength(A, L); if L > 0 then Move(P^, Pointer(A)^, L); Result := Size - N; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) Button1: TButton; SaveDialog1: TSaveDialog; Edit1: TEdit; Memo1: TMemo; Button2: TButton; OpenDialog1: TOpenDialog; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var StreamWrite: TStreamWriter; begin // 打开对话框 Self.SaveDialog1.Execute(Self.Handle); // 打开默认的目录 Self.SaveDialog1.DefaultExt := 'E:\'; try try // 创建TStreamWriter StreamWrite := TStreamWriter.Create(Self.SaveDialog1.FileName); // 写入数据 StreamWrite.WriteLine(Self.Edit1.Text); except on E: Exception do begin Self.Memo1.Lines.Add('加载文件出错!'); end; end; finally // 释放资源 FreeAndNil(StreamWrite); end; end; procedure TForm1.Button2Click(Sender: TObject); var Reader: TStreamReader; begin try // 执行打开文件对话框 Self.OpenDialog1.Execute(Self.Handle); // 获取打开的文件名,构造对象 Reader := TStreamReader.Create(Self.OpenDialog1.FileName, TEncoding.ANSI); while not Reader.EndOfStream do begin // 读取内容 设置memon的内容 Self.Memo1.Lines.Add(Reader.ReadLine); end; finally // 释放资源 FreeAndNil(Reader); end; end; end.
unit StockMinuteDataAccess; interface uses define_dealItem, define_datetime, BaseDataSet, QuickList_MinuteData, define_price, define_datasrc, define_stock_quotes; type TRT_StockMinuteData = record DealItem : PRT_DealItem; StockCode : string; IsDataChangedStatus: Byte; WeightMode : Byte; Minute : integer; MinuteDealData : TMinuteDataList; FirstDealDateTime : TDateTime; // 2 LastDealDateTime : TDateTime; // 2 最后记录交易时间 DataSource : TDealDataSource; end; TStockMinuteDataAccess = class(TBaseDataSetAccess) protected fStockMinuteData: TRT_StockMinuteData; function GetStockCode: AnsiString; procedure SetStockCode(const Value: AnsiString); function GetFirstDealDateTime: TDateTime; procedure SetFirstDealDateTime(const Value: TDateTime); function GetLastDealDateTime: TDateTime; procedure SetLastDealDateTime(const Value: TDateTime); procedure SetStockItem(AStockItem: PRT_DealItem); function GetWeightMode: TRT_WeightMode; procedure SetWeightMode(value: TRT_WeightMode); function GetRecordItem(AIndex: integer): Pointer; override; function GetRecordCount: Integer; override; public constructor Create(AStockItem: PRT_DealItem; ADataSrc: TDealDataSource; AWeightMode: TRT_WeightMode); reintroduce; destructor Destroy; override; class function DataTypeDefine: integer; override; function FindRecord(AStockDateTime: TDateTimeStock): PRT_Quote_Minute; function CheckOutRecord(AStockDateTime: TDateTimeStock): PRT_Quote_Minute; function NewRecord(AStockDateTime: TDateTimeStock): PRT_Quote_Minute; function MinuteDataByIndex(AIndex: integer): PRT_Quote_Minute; function DoGetRecords: integer; function DoGetStockOpenPrice(AIndex: integer): double; function DoGetStockClosePrice(AIndex: integer): double; function DoGetStockHighPrice(AIndex: integer): double; function DoGetStockLowPrice(AIndex: integer): double; procedure Sort; override; procedure Clear; override; property FirstDealDateTime: TDateTime read GetFirstDealDateTime; property LastDealDateTime: TDateTime read GetLastDealDateTime; property StockItem: PRT_DealItem read fStockMinuteData.DealItem write SetStockItem; property StockCode: AnsiString read GetStockCode write SetStockCode; property DataSource: TDealDataSource read fStockMinuteData.DataSource write fStockMinuteData.DataSource; property WeightMode: TRT_WeightMode read GetWeightMode write SetWeightMode; property Minute: integer read fStockMinuteData.Minute write fStockMinuteData.Minute; end; implementation uses QuickSortList, define_dealstore_file, SysUtils; constructor TStockMinuteDataAccess.Create(AStockItem: PRT_DealItem; ADataSrc: TDealDataSource; AWeightMode: TRT_WeightMode); begin if nil = AStockItem then begin inherited Create(DBType_Unknown, GetDealDataSourceCode(ADataSrc)); end else begin inherited Create(AStockItem.DBType, GetDealDataSourceCode(ADataSrc)); end; FillChar(fStockMinuteData, SizeOf(fStockMinuteData), 0); fStockMinuteData.DealItem := AStockItem; fStockMinuteData.MinuteDealData := TMinuteDataList.Create; fStockMinuteData.MinuteDealData.Clear; fStockMinuteData.MinuteDealData.Duplicates := QuickSortList.lstDupIgnore; fStockMinuteData.DataSource := ADataSrc; fStockMinuteData.WeightMode := Byte(AWeightMode); end; destructor TStockMinuteDataAccess.Destroy; begin Clear; FreeAndNil(fStockMinuteData.MinuteDealData); inherited; end; class function TStockMinuteDataAccess.DataTypeDefine: integer; begin Result := DataType_MinuteData; end; procedure TStockMinuteDataAccess.Clear; var i: integer; tmpMinuteData: PRT_Quote_Minute; begin if nil <> fStockMinuteData.MinuteDealData then begin for i := fStockMinuteData.MinuteDealData.Count - 1 downto 0 do begin tmpMinuteData := fStockMinuteData.MinuteDealData.MinuteData[i]; FreeMem(tmpMinuteData); end; fStockMinuteData.MinuteDealData.Clear; end; end; procedure TStockMinuteDataAccess.SetStockCode(const Value: AnsiString); begin fStockMinuteData.StockCode := Value; end; procedure TStockMinuteDataAccess.SetStockItem(AStockItem: PRT_DealItem); begin if nil <> AStockItem then begin if fStockMinuteData.DealItem <> AStockItem then begin end; end; fStockMinuteData.DealItem := AStockItem; if nil <> fStockMinuteData.DealItem then begin end; end; function TStockMinuteDataAccess.GetFirstDealDateTime: TDateTime; begin Result := fStockMinuteData.FirstDealDateTime; end; function TStockMinuteDataAccess.GetWeightMode: TRT_WeightMode; begin Result := TRT_WeightMode(fStockMinuteData.WeightMode); end; procedure TStockMinuteDataAccess.SetWeightMode(value: TRT_WeightMode); begin fStockMinuteData.WeightMode := Byte(value); end; procedure TStockMinuteDataAccess.SetFirstDealDateTime(const Value: TDateTime); begin fStockMinuteData.FirstDealDateTime := Value; end; function TStockMinuteDataAccess.GetLastDealDateTime: TDateTime; begin Result := fStockMinuteData.LastDealDateTime; end; procedure TStockMinuteDataAccess.SetLastDealDateTime(const Value: TDateTime); begin fStockMinuteData.LastDealDateTime := Value; end; function TStockMinuteDataAccess.GetRecordCount: Integer; begin Result := fStockMinuteData.MinuteDealData.Count; end; function TStockMinuteDataAccess.GetRecordItem(AIndex: integer): Pointer; begin Result := fStockMinuteData.MinuteDealData.MinuteData[AIndex]; end; function TStockMinuteDataAccess.GetStockCode: AnsiString; begin Result := fStockMinuteData.StockCode; if '' = Result then begin if nil <> fStockMinuteData.DealItem then begin Result := fStockMinuteData.DealItem.sCode; end; end; end; procedure TStockMinuteDataAccess.Sort; begin fStockMinuteData.MinuteDealData.Sort; end; function TStockMinuteDataAccess.CheckOutRecord(AStockDateTime: TDateTimeStock): PRT_Quote_Minute; begin //Result := nil; Result := FindRecord(AStockDateTime); if nil = Result then Result := NewRecord(AStockDateTime); end; function TStockMinuteDataAccess.NewRecord(AStockDateTime: TDateTimeStock): PRT_Quote_Minute; begin if fStockMinuteData.FirstDealDateTime = 0 then fStockMinuteData.FirstDealDateTime := AStockDateTime.Date.Value; if fStockMinuteData.FirstDealDateTime > AStockDateTime.Date.Value then fStockMinuteData.FirstDealDateTime := AStockDateTime.Date.Value; if fStockMinuteData.LastDealDateTime < AStockDateTime.Date.Value then fStockMinuteData.LastDealDateTime := AStockDateTime.Date.Value; Result := System.New(PRT_Quote_Minute); FillChar(Result^, SizeOf(TRT_Quote_Minute), 0); //Result.DealDate.Value := ADate; fStockMinuteData.MinuteDealData.AddMinuteData(AStockDateTime, Result); end; function TStockMinuteDataAccess.MinuteDataByIndex(AIndex: integer): PRT_Quote_Minute; begin Result := GetRecordItem(AIndex); end; function TStockMinuteDataAccess.FindRecord(AStockDateTime: TDateTimeStock): PRT_Quote_Minute; var tmpPos: integer; begin Result := nil; tmpPos := fStockMinuteData.MinuteDealData.IndexOf(AStockDateTime); if 0 <= tmpPos then Result := PRT_Quote_Minute(fStockMinuteData.MinuteDealData.MinuteData[tmpPos]); end; function TStockMinuteDataAccess.DoGetStockOpenPrice(AIndex: integer): double; begin Result := MinuteDataByIndex(AIndex).PriceRange.PriceOpen.Value; end; function TStockMinuteDataAccess.DoGetStockClosePrice(AIndex: integer): double; begin Result := MinuteDataByIndex(AIndex).PriceRange.PriceClose.Value; end; function TStockMinuteDataAccess.DoGetStockHighPrice(AIndex: integer): double; begin Result := MinuteDataByIndex(AIndex).PriceRange.PriceHigh.Value; end; function TStockMinuteDataAccess.DoGetStockLowPrice(AIndex: integer): double; begin Result := MinuteDataByIndex(AIndex).PriceRange.PriceLow.Value; end; function TStockMinuteDataAccess.DoGetRecords: integer; begin Result := Self.RecordCount; end; end.
{***********************************************************************} { File: VTNoData.pas } { } { Purpose: } { source file to demonstrate how to get started with VT (2) } { <-- Basic VT as a Tree (no node data used) --> } { } { Module Record: } { } { Date AP Details } { -------- -- -------------------------------------- } { 05-Nov-2002 TC Created (tomc@gripsystems.com) } {**********************************************************************} unit VTNoData; {$mode delphi} {$H+} interface uses delphicompat, LCLIntf, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, VirtualTrees, ExtCtrls, StdCtrls, LResources, LCLType; type TfrmVTNoData = class(TForm) imgMaster: TImageList; Panel1 : TPanel; VT : TVirtualStringTree; panBase : TPanel; Label1 : TLabel; chkCheckBoxes: TCheckBox; chkFullExpand: TCheckBox; chkShowLevel: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormActivate(Sender: TObject); procedure VTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure VTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: String); procedure VTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure VTInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure VTInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); procedure chkCheckBoxesClick(Sender: TObject); procedure chkFullExpandClick(Sender: TObject); procedure VTPaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); procedure chkShowLevelClick(Sender: TObject); procedure FormClose(Sender: TObject; var AAction: TCloseAction); private FCaptions : TStringList; end; implementation {.$R *.dfm} procedure TfrmVTNoData.FormCreate(Sender: TObject); begin {set up root values - level 0} FCaptions := TStringList.Create; FCaptions.CommaText := 'Animation,Auto,Miscellaneous,Paint,Selection,String'; VT.RootNodeCount := FCaptions.Count; end; procedure TfrmVTNoData.FormClose(Sender: TObject; var AAction: TCloseAction); begin AAction := caFree; end; procedure TfrmVTNoData.FormDestroy(Sender: TObject); begin FCaptions .Free; end; procedure TfrmVTNoData.VTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := 0; // note *** no node data used *** end; procedure TfrmVTNoData.VTInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); begin Node.CheckType := ctTriStateCheckBox; // we will have checkboxes throughout if ParentNode = nil then // top-level node is being initialised InitialStates := InitialStates + [ivsHasChildren]; // <- important line here end; procedure TfrmVTNoData.VTInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal); begin case Node.Index of 0: ChildCount := Ord( High( TVTAnimationOption )) + 1; 1: ChildCount := Ord( High( TVTAutoOption )) + 1; 2: ChildCount := Ord( High( TVTMiscOption )) + 1; 3: ChildCount := Ord( High( TVTPaintOption )) + 1; 4: ChildCount := Ord( High( TVTSelectionOption )) + 1; 5: ChildCount := Ord( High( TVTStringOption )) + 1; end; end; procedure TfrmVTNoData.VTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); begin if Kind in [ ikNormal, ikSelected ] then begin if Sender.GetNodeLevel( Node ) = 0 then ImageIndex := 30 else ImageIndex := 12; end; end; procedure TfrmVTNoData.VTPaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); begin if TextType = ttStatic then begin if Sender.GetNodeLevel( Node ) = 0 then TargetCanvas.Font.Color := clRed else TargetCanvas.Font.Color := clBlue; end; end; procedure TfrmVTNoData.VTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: String); const aAnimOpts : array[0..Ord(High(TVTAnimationOption ))] of string[25] = ( 'Animated Toggle', 'Advanced Animated Toggle' ); aAutoOpts : array[0..Ord(High(TVTAutoOption ))] of string[25] = ( 'DropExpand' , 'Expand' , 'Scroll' , 'ScrollOnExpand' , 'Sort' , 'SpanColumns' , 'TristateTracking' , 'HideButtons' , 'DeleteMovedNodes' , 'DisableAutoscrollOnFocus' , 'AutoChangeScale' , 'AutoFreeOnCollapse' , 'DisableAutoscrollOnEdit' , 'AutoBidiColumnOrdering' ); aMiscOpts : array[0..Ord(High(TVTMiscOption ))] of string[25] = ( 'AcceptOLEDrop' , 'CheckSupport' , 'Editable' , 'FullRepaintOnResize' , 'GridExtensions' , 'InitOnSave' , 'ReportMode' , 'ToggleOnDblClick' , 'WheelPanning' , 'ReadOnly' , 'VariableNodeHeight', 'FullRowDrag', 'NodeHeightResize', 'NodeHeightDblClickResize', 'EditOnClick', 'EditOnDblClick' ); aPaintOpts : array[0..Ord(High(TVTPaintOption ))] of string[25] = ( 'HideFocusRect' , 'HideSelection' , 'HotTrack' , 'PopupMode' , 'ShowBackground' , 'ShowButtons' , 'ShowDropmark' , 'ShowHorzGridLines' , 'ShowRoot' , 'ShowTreeLines' , 'ShowVertGridLines' , 'ThemeAware' , 'UseBlendedImages' , 'GhostedIfUnfocused', 'FullVertGridLines', // This option only has an effect if toShowVertGridLines is enabled too. 'AlwaysHideSelection', // Do not draw node selection, regardless of focused state. 'UseBlendedSelection', // Enable alpha blending for node selections. 'StaticBackground', 'ChildrenAbove', 'FixedIndent', 'UseExplorerTheme' ); aSelOpts : array[0..Ord(High(TVTSelectionOption))] of string[25] = ( 'DisableDrawSelection' , 'ExtendedFocus' , 'FullRowSelect' , 'LevelSelectConstraint' , 'MiddleClickSelect' , 'MultiSelect' , 'RightClickSelect' , 'SiblingSelectConstraint' , 'CenterScrollIntoView', 'SimpleDrawSelection' ); aStrOpts : array[0..Ord(High(TVTStringOption ))] of string[25] = ( 'SaveCaptions' , 'ShowStaticText' , 'AutoAcceptEditChange' ); var iLevel : integer; begin iLevel := Sender.GetNodeLevel( Node ); case iLevel of 0: Celltext := FCaptions[Node.Index]; {top-level} 1: case Node.Parent.Index of {options} 0: Celltext := aAnimOpts[Node.Index]; 1: Celltext := aAutoOpts[Node.Index]; 2: Celltext := aMiscOpts[Node.Index]; 3: Celltext := aPaintOpts[Node.Index]; 4: Celltext := aSelOpts[Node.Index]; 5: Celltext := aStrOpts[Node.Index]; end; end; if TextType = ttStatic then begin if chkShowLevel.checked then Celltext := Format( ' Index:%d, Level:%d', [Node.Index, iLevel] ) else Celltext := Format( ' Index:%d', [Node.Index] ); end; end; procedure TfrmVTNoData.chkCheckBoxesClick(Sender: TObject); begin with VT.TreeOptions do begin if chkCheckBoxes.checked then MiscOptions := MiscOptions + [toCheckSupport] else MiscOptions := MiscOptions - [toCheckSupport]; VT.Refresh; end; end; procedure TfrmVTNoData.chkFullExpandClick(Sender: TObject); begin if chkFullExpand.Checked then VT.FullExpand else VT.FullCollapse; end; procedure TfrmVTNoData.chkShowLevelClick(Sender: TObject); begin VT.refresh; end; procedure TfrmVTNoData.FormActivate(Sender: TObject); var r : TRect; begin {$ifdef LCLWin32} //todo: enable when SPI_GETWORKAREA is implemented {get size of desktop} SystemParametersInfo(SPI_GETWORKAREA, 0, @r, 0); Height := r.Bottom-Top; {$endif} end; initialization {$I VTNoData.lrs} end.
unit model.teste; interface uses attributes, Interfaces.base, Rtti; type [TNameTable('Teste')] TTeste = class(TTable) private FHabitantes: Integer; FDescricao: string; FRendaPerCapta: Currency; FId: Integer; FData: TDateTime; FEstado: string; procedure SetData(const Value: TDateTime); procedure SetDescricao(const Value: string); procedure SetEstado(const Value: string); procedure SetHabitantes(const Value: Integer); procedure SetId(const Value: Integer); procedure SetRendaPerCapta(const Value: Currency); public [TFieldPK] property Id: Integer read FId write SetId; property Estado: string read FEstado write SetEstado; property Descricao: string read FDescricao write SetDescricao; property Data: TDateTime read FData write SetData; property Habitantes: Integer read FHabitantes write SetHabitantes; property RendaPerCapta: Currency read FRendaPerCapta write SetRendaPerCapta; end; implementation { TTeste } procedure TTeste.SetData(const Value: TDateTime); begin FData := Value; end; procedure TTeste.SetDescricao(const Value: string); begin FDescricao := Value; end; procedure TTeste.SetEstado(const Value: string); begin FEstado := Value; end; procedure TTeste.SetHabitantes(const Value: Integer); begin FHabitantes := Value; end; procedure TTeste.SetId(const Value: Integer); begin FId := Value; end; procedure TTeste.SetRendaPerCapta(const Value: Currency); begin FRendaPerCapta := Value; end; end.
unit SimulacaoPagamento.Principal; interface uses SimulacaoPagamento.Interfaces, SimulacaoPagamento.Cartao, SimulacaoPagamento.Crediario, StrUtils, SysUtils; type TSimulacaoPagamento = class(TInterfacedObject, iSimulacaoPagamento) private FValor : Double; FParcelas : Integer; FCartao : iSimulacaoCartao; FCrediario : iSimulacaoCrediario; public constructor Create; destructor Destroy; override; class function New : iSimulacaoPagamento; function Valor ( aValue : Double ) : iSimulacaoPagamento; overload; function Valor ( aValue : String ) : iSimulacaoPagamento; overload; function Parcelas ( aValue : Integer ) : iSimulacaoPagamento; function TotalCartao : Double; function TotalCrediario : Double; function Cartao : iSimulacaoCartao; function Crediario : iSimulacaoCrediario; end; implementation { TSimulacaoPagamento } function TSimulacaoPagamento.Cartao: iSimulacaoCartao; begin Result := FCartao; end; constructor TSimulacaoPagamento.Create; begin FCartao := TSimulacaoPagamentoCartao.New(Self); FCrediario := TSimulacaoPagamentoCrediario.New(Self); end; function TSimulacaoPagamento.Crediario: iSimulacaoCrediario; begin Result := FCrediario; end; destructor TSimulacaoPagamento.Destroy; begin inherited; end; class function TSimulacaoPagamento.New: iSimulacaoPagamento; begin Result := Self.Create; end; function TSimulacaoPagamento.Parcelas(aValue: Integer): iSimulacaoPagamento; begin Result := Self; FParcelas := aValue; end; function TSimulacaoPagamento.TotalCartao: Double; begin Result := FValor + (FValor * 0.3); end; function TSimulacaoPagamento.TotalCrediario: Double; begin Result := FValor; if FCrediario.Juros then Result := FValor + (FValor * 0.5); end; function TSimulacaoPagamento.Valor(aValue: String): iSimulacaoPagamento; begin Result := Self; FValor := StrToCurr(aValue); end; function TSimulacaoPagamento.Valor(aValue: Double): iSimulacaoPagamento; begin Result := Self; FValor := aValue; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpBerApplicationSpecificParser; {$I ..\Include\CryptoLib.inc} interface uses ClpIAsn1StreamParser, ClpBerApplicationSpecific, ClpIBerApplicationSpecificParser, ClpIAsn1ApplicationSpecificParser, ClpIProxiedInterface; type TBerApplicationSpecificParser = class(TInterfacedObject, IAsn1ApplicationSpecificParser, IAsn1Convertible, IBerApplicationSpecificParser) strict private var F_tag: Int32; F_parser: IAsn1StreamParser; public constructor Create(tag: Int32; const parser: IAsn1StreamParser); function ReadObject(): IAsn1Convertible; inline; function ToAsn1Object(): IAsn1Object; inline; end; implementation { TBerApplicationSpecificParser } constructor TBerApplicationSpecificParser.Create(tag: Int32; const parser: IAsn1StreamParser); begin F_tag := tag; F_parser := parser; end; function TBerApplicationSpecificParser.ReadObject: IAsn1Convertible; begin result := F_parser.ReadObject(); end; function TBerApplicationSpecificParser.ToAsn1Object: IAsn1Object; begin result := TBerApplicationSpecific.Create(F_tag, F_parser.ReadVector()); end; end.
unit ElGroupBoxDemoMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ElImgFrm, StdCtrls, ElACtrls, ElBtnEdit, ElXPThemedControl, ElBtnCtl, ElCheckCtl, ElVCLUtils, ElSpin, ElImgLst, ExtCtrls, ElPanel, ElGroupBox, ElCheckItemGrp, ElClrCmb, ImgList, ElEdits, ElCombos; type TElGroupBoxDemoMainForm = class(TForm) Label8: TLabel; ElGroupBoxTextButtonEdit: TElButtonEdit; ElGRoupBoxImageForm: TElImageForm; ElGroupBoxUseImageFormCB: TElCheckBox; ElGroupBoxTextHTMLCB: TElCheckBox; sampleElGroupBox: TElGroupBox; ElGroupBoxBordersCheckGroup: TElCheckGroup; ElGroupBoxShowCheckBoxCB: TElCheckBox; ElGroupBoxShowFocusCB: TElCheckBox; Label6: TLabel; ElGroupBoxImageTypeCombo: TElComboBox; GroupBoxGlyphs: TElImageList; Label3: TLabel; ElGroupBoxCaptionColorCombo: TElColorCombo; procedure ElGroupBoxTextButtonEditButtonClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure ElGroupBoxTextHTMLCBClick(Sender: TObject); procedure ElGroupBoxUseImageFormCBClick(Sender: TObject); procedure ElGroupBoxBordersCheckGroupClick(Sender: TObject); procedure ElGroupBoxShowCheckBoxCBClick(Sender: TObject); procedure ElGroupBoxShowFocusCBClick(Sender: TObject); procedure ElGroupBoxImageTypeComboChange(Sender: TObject); procedure ElGroupBoxCaptionColorComboChange(Sender: TObject); private NotFirstTime : boolean; public { Public declarations } end; var ElGroupBoxDemoMainForm: TElGroupBoxDemoMainForm; implementation {$R *.DFM} procedure TElGroupBoxDemoMainForm.ElGroupBoxTextButtonEditButtonClick( Sender: TObject); begin sampleElGroupBox.Caption := ElGroupBoxTextButtonEdit.Text; end; procedure TElGroupBoxDemoMainForm.FormActivate(Sender: TObject); var i : integer; begin if not NotFirstTime then begin for i := 0 to 3 do ElGroupBoxBordersCheckGroup.Checked[i] := true; end; NotFirstTime := true; end; procedure TElGroupBoxDemoMainForm.ElGroupBoxTextHTMLCBClick( Sender: TObject); begin SampleElGroupBox.IsHTML := ElGroupBoxTextHTMLCB.Checked; end; procedure TElGroupBoxDemoMainForm.ElGroupBoxUseImageFormCBClick( Sender: TObject); begin if ElGroupBoxUseImageFormCB.Checked then ElGroupBoxImageForm.Backgroundtype := bgtTileBitmap else ElGroupBoxImageForm.Backgroundtype := bgtColorFill; end; procedure TElGroupBoxDemoMainForm.ElGroupBoxBordersCheckGroupClick( Sender: TObject); begin if ElGroupBoxBordersCheckGroup.Checked[0] then sampleElGroupBox.BorderSides := sampleElGroupBox.BorderSides + [ebsLeft] else sampleElGroupBox.BorderSides := sampleElGroupBox.BorderSides - [ebsLeft]; if ElGroupBoxBordersCheckGroup.Checked[1] then sampleElGroupBox.BorderSides := sampleElGroupBox.BorderSides + [ebsRight] else sampleElGroupBox.BorderSides := sampleElGroupBox.BorderSides - [ebsRight]; if ElGroupBoxBordersCheckGroup.Checked[2] then sampleElGroupBox.BorderSides := sampleElGroupBox.BorderSides + [ebsTop] else sampleElGroupBox.BorderSides := sampleElGroupBox.BorderSides - [ebsTop]; if ElGroupBoxBordersCheckGroup.Checked[3] then sampleElGroupBox.BorderSides := sampleElGroupBox.BorderSides + [ebsBottom] else sampleElGroupBox.BorderSides := sampleElGroupBox.BorderSides - [ebsBottom]; end; procedure TElGroupBoxDemoMainForm.ElGroupBoxShowCheckBoxCBClick( Sender: TObject); begin sampleElGroupBox.ShowCheckBox := ElGroupBoxShowCheckBoxCB.Checked; end; procedure TElGroupBoxDemoMainForm.ElGroupBoxShowFocusCBClick( Sender: TObject); begin sampleElgroupBox.ShowFocus := ElGroupBoxShowFocusCB.Checked; end; procedure TElGroupBoxDemoMainForm.ElGroupBoxImageTypeComboChange( Sender: TObject); begin case ElGroupBoxImageTypeCombo.ItemIndex of 0: begin sampleElGroupBox.UseCustomGlyphs := false; sampleElGroupBox.UseImageList := false; end; 1: begin sampleElGroupBox.UseCustomGlyphs := true; sampleElGroupBox.UseImageList := false; end; 2: begin sampleElGroupBox.UseCustomGlyphs := false; sampleElGroupBox.UseImageList := true; end; end; end; procedure TElGroupBoxDemoMainForm.ElGroupBoxCaptionColorComboChange( Sender: TObject); begin sampleElGroupBox.CaptionColor := ElGroupBoxCaptionColorCombo.SelectedColor; end; end.
unit ConTroller; interface const L=8; type TConTroller=class Commands: array[1..L] of Integer; Number: Integer; LastCommand: Integer; constructor Create; function Encode(Command: String): Integer; procedure Search(ECommand: Integer); procedure Run(tNumber: Integer); end; implementation uses SysUtils, Math, Windows, Messages; procedure MonitorState(isOn: boolean); var i:Integer; begin if isOn then i:=-1 else i:=2; SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, i); end; { TConTroller } constructor TConTroller.Create; begin LastCommand:=0; { 00000000111111111000101001110101 play 00000000111111110010001011011101 stop 00000000111111111000000001111111 last 00000000111111111010001001011101 next 00000000111111110101100010100111 ff 00000000111111110110000010011111 + 00000000111111110111101010000101 - 00000000111111111110101000010101 mute } Commands[1]:=16747125; Commands[2]:=16720605; Commands[3]:=16744575; Commands[4]:=16753245; Commands[5]:=16734375; Commands[6]:=16743045; Commands[7]:=16736415; Commands[8]:=16771605; end; function TConTroller.Encode(Command: String): Integer; var i: Integer; begin if Length(Command)<32 then Abort; LastCommand:=0; for i:=1 to 32 do LastCommand:=LastCommand+StrToInt(Command[i])*Round(Power(2,32-i)); Encode:=LastCommand; Search(LastCommand); end; procedure TConTroller.Search(ECommand: Integer); var i: Integer; begin for i:=1 to L do if ECommand=Commands[i] then begin Number:=i; Break; end; Run(Number); end; procedure TConTroller.Run(tNumber: Integer); var h: HWND; wParam: Integer; begin wParam:=0; h:=FindWindow('WMPlayerApp', nil); case tNumber of 1: wParam:=$4978; //Play/pause 2: wParam:=$4979; //Stop 3: wParam:=$497A; //Last song 4: wParam:=$497B; //Next song 5: wParam:=$497D; //FF 6: wParam:=$4980; //Vol+ 7: wParam:=$497F; //Vol- 8: wParam:=$4981; //Mute 9: MonitorState(state); else wParam:=0; end; SendMessage(h, WM_COMMAND, wParam,0); end; end.
program ejercicio8; type str40 = String[40]; docente = record dni : Integer; nombre : str40; email : str40; end; proyecto = record codigoUnico : Integer; titulo : str40 docenteC : docente; cantAlumnos : Integer; nomEsculea : str40; localidad : str40; end; procedure leerDocente(var d: docente); begin with d do begin write('Ingrese el DNI del DOCENTE: '); readln(dni); write('Ingrese el NOMBRE del docente: '); readln(nombre); write('Ingrese el EMAIL del docente: '); readln(email); end; end; procedure leerProyecto(var p: proyecto); begin with p do begin write('Ingrese el CODIGO UNIOCO: '); readln(codigoUnico); write('Ingrese TITULO del proyecto: '); readln(titulo); leerDocente(p.docenteC); write('Ingrese la cantidad de ALUMNOS que participan: '); readln(cantAlumnos); write('Ingres el NOMBRE DE LA ESCUELA: '); readln(nomEsculea); write('Ingrese nombre de LOCALIDAD: '); readln(localidad); writeln('--------------------------------------------'); end; end; procedure escuelaMayorAlumnos(p: proyecto; contAlumnos:Integer; var max1,max2: Integer; var nomMax1,nomMax2: str40); begin if (contAlumnos >= max1) then begin max2:= max1; nomMax2:= nomMax1; max1:= contAlumnos; nomMax1:= p.nomEsculea; end else if (contAlumnos >= max2) then begin max2:= contAlumnos; nomMax2:= p.nomEsculea; end; end; function descomponer(codigo: Integer): Boolean; var dig, contP, contI: Integer; begin contP:= 0; contI:= 0; while (codigo <> 0) do begin dig:= codigo mod 10; if ((dig mod 2)= 0) then begin contP:= contP + 1; end else contI:= contI + 1; codigo:= codigo div 10; end; descomponer:= (contP = contI); end; var d: docente; p: proyecto; max1,max2, contEscuela, contEsculaLocalidad, contAlumnos: Integer; nomMax1, nomMax2: str40; localidadActual, escuelaActual: str40; begin max1:= -1; max2:= -1; nomMax1:= ''; nomMax2:= ''; contEscuela:= 0; leerProyecto(p); while (p.codigoUnico <> -1) do begin contEsculaLocalidad:= 0; localidadActual:= p.localidad; while (localidadActual = p.localidad) and (p.codigoUnico <> -1) do //localidad begin contEscuela:= contEscuela + 1; escuelaActual:= p.nomEsculea; contEsculaLocalidad:= contEsculaLocalidad + 1; contAlumnos:= 0; while (escuelaActual = p.nomEsculea) and (p.codigoUnico <> -1) do //Escuela begin if (p.localidad = 'Daireaux') and (descomponer(p.codigoUnico)) then begin write('Titulo del proyecto: ',p.titulo); end; contAlumnos:= contAlumnos + 1; leerProyecto(p); end; contEsculaLocalidad:= contEsculaLocalidad + 1; escuelaMayorAlumnos(p,contAlumnos,max1,max2,nomMax1,nomMax2); end; writeln('La cantidad de escuelas en la localidad : ', p.localidad, ' es: ',contEsculaLocalidad); end; writeln('La cantidad de escuales que participaron en la convocatoria 2020 son: ', contEscuela ); writeln('Los dos nombres de las dos escuelas con mayor cantidad de alumnos participantes son: ', nomMax1, ' y ', nomMax2); end.
unit DebugDraw; interface uses Box2DTypes, Box2D.Common; //// Not used by FMX TestBed. Declared as some tests refer to 'g_camera' //struct Camera //{ // Camera() // { // m_center.Set(0.0f, 20.0f); // m_extent = 25.0f; // m_zoom = 1.0f; // m_width = 1280; // m_height = 800; // } // // b2Vec2 m_center; // float32 m_extent; // float32 m_zoom; // int32 m_width; // int32 m_height; //}; type TCamera = record // Camera() // { // m_center.Set(0.0f, 20.0f); // m_extent = 25.0f; // m_zoom = 1.0f; // m_width = 1280; // m_height = 800; // } m_center: b2Vec2; m_extent: single; m_zoom: single; m_width: Int32; m_height: Int32; class function Create: TCamera; static; end; (* class TDebugDraw : public b2Draw { TCanvas* FCanvas; /* TODO : Merge Camera and TDebugDraw state */ float FOffsetX, FOffsetY; float FScaleX, FScaleY; float FCanvasHeight; TPathData* GPath; void SetCanvas(TCanvas* canvas); void SetOffsetX(float offset); void SetOffsetY(float offset); void SetScaleX(float scale); void SetScaleY(float scale); void SetCanvasHeight(float height); void b2VerticesToPolygon(const b2Vec2* vertices, int32 vertexCount, TPolygon &polygon); public: TDebugDraw(); ~TDebugDraw(); b2Vec2 ScreenToWorld(float x, float y) const; // b2Draw void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color); void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color); void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color); void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color); void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color); void DrawTransform(const b2Transform& xf); // Used by Tests void DrawPoint(const b2Vec2& p, float32 size, const b2Color& color); void DrawString(int x, int y, const char* string, ...); void DrawString(const b2Vec2& p, const char* string, ...); void DrawAABB(b2AABB* aabb, const b2Color& color); void Flush(); __property TCanvas* Canvas = {read=FCanvas, write=SetCanvas}; __property float OffsetX = {read=FOffsetX, write=SetOffsetX}; __property float OffsetY = {read=FOffsetY, write=SetOffsetY}; __property float ScaleX = {read=FScaleX, write=SetScaleX}; __property float ScaleY = {read=FScaleY, write=SetScaleY}; __property float CanvasHeight = {read=FCanvasHeight, write=SetCanvasHeight}; private: TDebugDraw(const TDebugDraw&); TDebugDraw& operator=(const TDebugDraw&); }; extern TDebugDraw g_debugDraw; extern Camera g_camera; const double DEFAULT_OPACITY = 100; *) implementation (* TDebugDraw g_debugDraw; Camera g_camera; TDebugDraw::TDebugDraw() :FCanvas(0), FOffsetX(0), FOffsetY(0), FScaleX(10), FScaleY(10), FCanvasHeight(0) { GPath = new TPathData(); } TDebugDraw::~TDebugDraw() { delete GPath; } void TDebugDraw::SetCanvas(TCanvas* canvas) { this->FCanvas = canvas; } void TDebugDraw::SetOffsetX(float offset) { this->FOffsetX = offset; } void TDebugDraw::SetOffsetY(float offset) { this->FOffsetY = offset; } void TDebugDraw::SetScaleX(float scale) { this->FScaleX = scale; } void TDebugDraw::SetScaleY(float scale) { this->FScaleY = scale; } void TDebugDraw::SetCanvasHeight(float height) { this->FCanvasHeight = height; } b2Vec2 TDebugDraw::ScreenToWorld(float x, float y) const { return b2Vec2((x - FOffsetX)/FScaleX, ((FCanvasHeight-y)-FOffsetY)/FScaleY); } void TDebugDraw::b2VerticesToPolygon(const b2Vec2* vertices, int32 vertexCount, TPolygon &polygon) { polygon.Length = vertexCount+1; for(int i=0; i<vertexCount; ++i) { polygon[i].X = vertices[i].x*FScaleX + FOffsetX; polygon[i].Y = FCanvasHeight - (vertices[i].y*FScaleY + FOffsetY); } polygon[vertexCount] = polygon[0]; } void TDebugDraw::DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) { TColor clr = b2Color2TColor(color); TPolygon polygon; b2VerticesToPolygon(vertices, vertexCount, polygon); Canvas->Fill->Color = clr; Canvas->Stroke->Color = clr; Canvas->Stroke->Kind = TBrushKind::Solid; Canvas->Stroke->Thickness = 1; Canvas->DrawPolygon(polygon, DEFAULT_OPACITY); } /// Draw a solid closed polygon provided in CCW order. void TDebugDraw::DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) { TColor clr = b2Color2TColor(color); TPolygon polygon; b2VerticesToPolygon(vertices, vertexCount, polygon); Canvas->Fill->Color = clr; Canvas->Stroke->Color = clr; Canvas->Stroke->Kind = TBrushKind::Solid; Canvas->Stroke->Thickness = 1; Canvas->DrawPolygon(polygon, DEFAULT_OPACITY); Canvas->FillPolygon(polygon, 0.1); } /// Draw a circle. void TDebugDraw::DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) { TColor clr = b2Color2TColor(color); TPointF p(center.x*FScaleX + FOffsetX, FCanvasHeight - (center.y*FScaleY + FOffsetY)); TRectF r(p.X - radius*FScaleX, p.Y + radius*FScaleY, p.X + radius*FScaleX, p.Y - radius*FScaleY); Canvas->Fill->Color = clr; Canvas->Stroke->Color = clr; Canvas->Stroke->Kind = TBrushKind::Solid; Canvas->Stroke->Thickness = 1; Canvas->DrawEllipse(r, DEFAULT_OPACITY); } /// Draw a solid circle. void TDebugDraw::DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) { TColor clr = b2Color2TColor(color); b2Vec2 p(axis.x*radius +center.x, axis.y*radius + center.y); p.x = p.x*FScaleX + FOffsetX; p.y = FCanvasHeight - (p.y*FScaleY + FOffsetY); b2Vec2 pcenter(center.x*FScaleX + FOffsetX, FCanvasHeight - (center.y*FScaleY + FOffsetY)); Canvas->DrawLine(TPointF(pcenter.x, pcenter.y), TPointF(p.x, p.y), DEFAULT_OPACITY); DrawCircle(center, radius, color); } /// Draw a line segment. void TDebugDraw::DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) { TColor clr = b2Color2TColor(color); TPointF pt1(p1.x*FScaleX + FOffsetX, FCanvasHeight - (p1.y*FScaleY + FOffsetY)); TPointF pt2(p2.x*FScaleX + FOffsetX, FCanvasHeight - (p2.y*FScaleY + FOffsetY)); Canvas->Fill->Color = clr; Canvas->Stroke->Color = clr; Canvas->Stroke->Kind = TBrushKind::Solid; Canvas->Stroke->Thickness = 1; Canvas->DrawLine(pt1, pt2, DEFAULT_OPACITY); } /// Draw a transform. Choose your own length scale. /// @param xf a transform. void TDebugDraw::DrawTransform(const b2Transform& xf) { const float32 k_axisScale = 0.4f; b2Color red(1.0f, 0.0f, 0.0f); b2Color green(0.0f, 1.0f, 0.0f); b2Vec2 p1 = xf.p; b2Vec2 p2 = p1 + k_axisScale * xf.q.GetXAxis(); DrawSegment(p1, p2, red); p2 = p1 + k_axisScale * xf.q.GetYAxis(); DrawSegment(p1, p2, green); } void TDebugDraw::DrawPoint(const b2Vec2& p, float32 size, const b2Color& color) { TColor clr = b2Color2TColor(color); TPointF pt(p.x*FScaleX + FOffsetX, FCanvasHeight - (p.y*FScaleY + FOffsetY)); TRectF r(pt.X - 1, pt.Y + 1, pt.X + 1, pt.Y -1); Canvas->Stroke->Color = clr; Canvas->Stroke->Kind = TBrushKind::Solid; Canvas->Stroke->Thickness = 1; Canvas->DrawEllipse(r, DEFAULT_OPACITY); } void TDebugDraw::DrawString(int x, int y, const char* string, ...) { char buffer[128]; va_list arg; va_start(arg, string); vsprintf(buffer, string, arg); va_end(arg); String text(buffer); TRectF rect(x, y, x+FCanvas->TextWidth(text), y+b2Min(static_cast<float>(DRAW_STRING_NEW_LINE), Canvas->TextHeight(text))); Canvas->FillText(rect, text, false, DEFAULT_OPACITY, TFillTextFlags(), TTextAlign::Leading, TTextAlign::Leading); } void TDebugDraw::DrawString(const b2Vec2& p, const char* string, ...) { char buffer[128]; va_list arg; va_start(arg, string); vsprintf(buffer, string, arg); va_end(arg); String text(buffer); TPointF pt(p.x*FScaleX + FOffsetX, FCanvasHeight - (p.y*FScaleY + FOffsetY)); TRectF rect(pt.x, pt.y, pt.x+FCanvas->TextWidth(text), pt.y+b2Min(static_cast<float>(DRAW_STRING_NEW_LINE), Canvas->TextHeight(text))); Canvas->FillText(rect, text, false, DEFAULT_OPACITY, TFillTextFlags(), TTextAlign::Leading, TTextAlign::Leading); } void TDebugDraw::DrawAABB(b2AABB* aabb, const b2Color& color) { b2Vec2 v[4]; v[0] = aabb->lowerBound; v[1] = b2Vec2(aabb->upperBound.x, aabb->lowerBound.y); v[2] = aabb->upperBound; v[3] = b2Vec2(aabb->lowerBound.x, aabb->upperBound.y); DrawPolygon(v, 4, color); } void TDebugDraw::Flush() { } *) { TCamera } class function TCamera.Create: TCamera; begin Result.m_center := b2Vec2.Create(0.0, 20.0); Result.m_extent := 25.0; Result.m_zoom := 1.0; Result.m_width := 1280; Result.m_height := 800; end; end.
PROGRAM Stat(INPUT, OUTPUT); { Программа опредеяет минимальное, максимальное и среднеарифмитическое число для файла целых чисел. Реализован контроль переполнения } PROCEDURE ReadDigit(VAR F: TEXT; VAR D: INTEGER); {В D возвращается цифра, соответствующая цифре-символу, прочтённому из F} VAR Ch: CHAR; BEGIN {ReadDigit} D := -1; IF NOT EOLN THEN BEGIN READ(F, Ch); IF Ch = '0' THEN D := 0 ELSE IF Ch = '1' THEN D := 1 ELSE IF Ch = '2' THEN D := 2 ELSE IF Ch = '3' THEN D := 3 ELSE IF Ch = '4' THEN D := 4 ELSE IF Ch = '5' THEN D := 5 ELSE IF Ch = '6' THEN D := 6 ELSE IF Ch = '7' THEN D := 7 ELSE IF Ch = '8' THEN D := 8 ELSE IF Ch = '9' THEN D := 9 END END; {ReadDigit} PROCEDURE ReadNumber(VAR F: TEXT; VAR N: INTEGER); {В N возвращается число, прочитанное из F} VAR Digit, PossibleFrontier: INTEGER; Overflow: BOOLEAN; BEGIN {ReadNumber} N := 0; IF NOT EOLN THEN BEGIN Digit := 0; Overflow := FALSE; PossibleFrontier := MAXINT DIV 10; WHILE NOT Overflow AND (Digit <> -1) DO BEGIN IF (N > PossibleFrontier) OR ((N = PossibleFrontier) AND (Digit > 7)) THEN Overflow := TRUE; IF Overflow THEN N := -1 ELSE N := N * 10 + Digit; ReadDigit(F, Digit) END END END; {ReadNumber} VAR Number, Sum, CountOfNumbers, MaxNumber, MinNumber, MathAverage, Reminder: INTEGER; Overflow: BOOLEAN; BEGIN {Stat} Overflow := FALSE; MaxNumber := 0; MinNumber := MAXINT; MathAverage := 0; CountOfNumbers := 0; Sum := 0; Number := 0; WHILE NOT EOLN AND NOT Overflow AND (Number <> -1) { Складываем числа, счётчик += 1 } DO BEGIN ReadNumber(INPUT, Number); IF Number <> -1 THEN BEGIN Sum := Sum + Number; WRITELN(Number); IF Number < MinNumber { Ищем макс. и миним. значения } THEN MinNumber := Number; IF Number > MaxNumber THEN MaxNumber := Number; CountOfNumbers := CountOfNumbers + 1; END; Overflow := (Sum + Number) > MAXINT; IF Overflow THEN WRITELN('Err, Overflow!') END; IF MinNumber = MAXINT THEN MinNumber := 0; IF CountOfNumbers <> 0 THEN BEGIN MathAverage := Sum DIV CountOfNumbers; Reminder := Sum MOD CountOfNumbers; { целый остаток? } IF ((Reminder * 10) MOD CountOfNumbers) <> 0 THEN Reminder := (Reminder * 100) DIV CountOfNumbers END; IF Overflow THEN WRITE('Err, overflow!') ELSE BEGIN WRITELN('MinNumber :', MinNumber: 10); WRITELN('MaxNumber :', MaxNumber: 10); WRITELN('Sum :', Sum: 10); WRITE('MathAverage:', MathAverage: 10); WRITELN('.', Reminder) END END. {Stat}
unit ExtAIStatesTerrain; interface uses Classes, SysUtils, ExtAIMsgStates, ExtAISharedInterface; // Storage for terrain of the KP type TExtAIStatesTerrain = class private // Method for callbacks from message procedure TerrainSize(aX, aY: Word); procedure TerrainPassability(aPassability: TBoolArr); procedure TerrainFertility(aFertility: TBoolArr); public // Terrain variables MapHeight: Word; MapWidth: Word; Passability: TBoolArr; Fertility: TBoolArr; constructor Create(aMsgStates: TExtAIMsgStates); destructor Destroy; override; end; implementation { TExtAIStatesTerrain } constructor TExtAIStatesTerrain.Create(aMsgStates: TExtAIMsgStates); begin Inherited Create; // Init values MapHeight := 0; MapWidth := 0; SetLength(Passability,0); SetLength(Fertility,0); // Connect callbacks aMsgStates.OnTerrainSize := TerrainSize; aMsgStates.OnTerrainPassability := TerrainPassability; aMsgStates.OnTerrainFertility := TerrainFertility; end; destructor TExtAIStatesTerrain.Destroy(); begin Inherited; end; procedure TExtAIStatesTerrain.TerrainSize(aX, aY: Word); begin MapHeight := aY; MapWidth := aX; end; procedure TExtAIStatesTerrain.TerrainPassability(aPassability: TBoolArr); begin Passability := aPassability; end; procedure TExtAIStatesTerrain.TerrainFertility(aFertility: TBoolArr); begin Fertility := aFertility; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clCertificateKey; interface {$I clVer.inc} type TclCertificateKeyType = (ktKeyExchange, ktSignature); TclCertificateKey = class private FLength: Integer; FName: string; FKeyType: TclCertificateKeyType; FAlgorithm: string; FAlgorithmName: string; protected procedure Load(const AName, ACSP: string; AProviderType: Integer); virtual; public constructor Create(const AName, ACSP: string; AProviderType: Integer); property Name: string read FName; property KeyType: TclCertificateKeyType read FKeyType; property Length: Integer read FLength; property Algorithm: string read FAlgorithm; property AlgorithmName: string read FAlgorithmName; end; function GetKeyTypeInt(AKeyType: TclCertificateKeyType): Integer; implementation uses {$IFNDEF DELPHIXE2} Windows, {$ELSE} Winapi.Windows, {$ENDIF} clCryptAPI, clCryptUtils, clUtils, clWUtils; function GetKeyTypeInt(AKeyType: TclCertificateKeyType): Integer; const types: array[TclCertificateKeyType] of Integer = (1, 2); begin Result := types[AKeyType]; end; { TclCertificateKey } constructor TclCertificateKey.Create(const AName, ACSP: string; AProviderType: Integer); begin inherited Create(); Load(AName, ACSP, AProviderType); end; procedure TclCertificateKey.Load(const AName, ACSP: string; AProviderType: Integer); var context: HCRYPTPROV; hKey: HCRYPTKEY; data: TclCryptData; len: Integer; pOidInfo: PCCRYPT_OID_INFO; s: string; begin FName := AName; context := nil; try if not CryptAcquireContext(@context, PclChar(GetTclString(AName)), PclChar(GetTclString(ACSP)), AProviderType, 0) then begin RaiseCryptError('CryptAcquireContext'); end; hKey := nil; try if CryptGetUserKey(context, AT_KEYEXCHANGE, @hKey) then begin FKeyType := ktKeyExchange; end else if CryptGetUserKey(context, AT_SIGNATURE, @hKey) then begin FKeyType := ktSignature; end; if (hKey <> nil) then begin data := TclCryptData.Create(256); try len := data.DataSize; if CryptGetKeyParam(hKey, KP_ALGID, data.Data, @len, 0) then begin pOidInfo := CryptFindOIDInfo(CRYPT_OID_INFO_ALGID_KEY, data.Data, 0); if (pOidInfo <> nil) then begin s := GetString_(pOidInfo.pszOID); FAlgorithm := system.Copy(s, 1, system.Length(s)); s := string(WideString(pOidInfo.pwszName)); FAlgorithmName := system.Copy(s, 1, system.Length(s)); end; end; len := data.DataSize; if CryptGetKeyParam(hKey, KP_KEYLEN, data.Data, @len, 0) then begin if (len >= 4) then begin FLength := DWORD(Pointer(data.Data)^); end; end; finally data.Free(); end; end; finally if (hKey <> nil) then begin CryptDestroyKey(hKey); end; end; finally if (context <> nil) then begin CryptReleaseContext(context, 0); end; end; end; end.
unit GX_SynMemoUtils; {$I GX_CondDefine.inc} interface uses // If you get errors here, add SynEdit to your library path SynEdit, SynUnicode, GX_GenericUtils, GX_IDEUtils; function GetGXHighlighterForCurrentSourceEditor: TGXSyntaxHighlighter; procedure SetSynEditHighlighter(SynEdit: TCustomSynEdit; Highlighter: TGXSyntaxHighlighter); implementation uses SynEditHighlighter, SynHighlighterPas, SynHighlighterCpp, SynHighlighterHtml, SynHighlighterSql, SynHighlighterCS, SynHighlighterXML, SynHighlighterGeneral, GX_VerDepConst, Classes, SysUtils, ToolsAPI, GX_OtaUtils, Graphics; procedure GxGetIDEHighLigherSettings(Highlighter: TSynCustomHighlighter; const Prefer: string); var Elements: TStrings; PreferIndex: Integer; begin Elements := TStringList.Create; try Highlighter.EnumUserSettings(Elements); PreferIndex := Elements.IndexOf(Prefer); if PreferIndex > -1 then Highlighter.UseUserSettings(PreferIndex) else if Elements.Count > 0 then Highlighter.UseUserSettings(Elements.Count - 1); finally FreeAndNil(Elements); end; end; procedure SetSynEditHighlighter(SynEdit: TCustomSynEdit; Highlighter: TGXSyntaxHighlighter); var i: Integer; begin Assert(SynEdit <> nil); SynEdit.Highlighter.Free; SynEdit.Highlighter := nil; case Highlighter of gxpPAS: SynEdit.Highlighter := TSynPasSyn.Create(SynEdit); gxpCPP: SynEdit.Highlighter := TSynCppSyn.Create(SynEdit); gxpHTML: SynEdit.Highlighter := TSynHtmlSyn.Create(SynEdit); gxpCS: SynEdit.Highlighter := TSynCSSyn.Create(SynEdit); gxpXML: SynEdit.Highlighter := TSynXMLSyn.Create(SynEdit); gxpSQL: begin SynEdit.Highlighter := TSynSqlSyn.Create(SynEdit); for i := 0 to SynEdit.Highlighter.AttrCount - 1 do begin if SynEdit.Highlighter.Attribute[i].Name = 'Number' then SynEdit.Highlighter.Attribute[i].Foreground := clMaroon else if SynEdit.Highlighter.Attribute[i].Name = 'String' then SynEdit.Highlighter.Attribute[i].Foreground := clTeal else if SynEdit.Highlighter.Attribute[i].Name = 'Comment' then begin SynEdit.Highlighter.Attribute[i].Foreground := clBlue; SynEdit.Highlighter.Attribute[i].Style := SynEdit.Highlighter.Attribute[i].Style - [fsItalic]; end; end; end; else SynEdit.Highlighter := TSynGeneralSyn.Create(SynEdit); end; if Highlighter in [gxpPAS, gxpCPP, gxpSQL, gxpCS] then GxGetIDEHighLigherSettings(SynEdit.Highlighter, GetIDEVersionID); end; function GetGXHighlighterForCurrentSourceEditor: TGXSyntaxHighlighter; var SourceEditor: IOTASourceEditor; begin Result := gxpNone; if not GxOtaTryGetCurrentSourceEditor(SourceEditor) then Exit; Result := GxOtaGetCurrentSyntaxHighlighter(SourceEditor); end; end.
unit ControleContainer; interface uses Classes, DateUtils, SysUtils; type TOperacao = (Entrada, Saida); type TStatus = (Digitado, Impresso, Pago, Cancelado); type TFormaPgamento = (AVista, Faturado); type TLocalizacao = class(Tpersistent) private FAndar: integer; FNumero: integer; FApartamento: integer; FRua: string; public property Rua: string read FRua write FRua; property Numero: integer read FNumero write FNumero; property Andar: integer read FAndar write FAndar; property Apartamento: integer read FApartamento write FApartamento; end; type TControleContainer = class(TPersistent) private FFil_Orig: string; FCliente: string; FProduto: string; FDataSaida: TDateTime; FDataEntrada: TDateTime; FOperacao: TOperacao; FStatus: TStatus; FNroTicket: integer; FOperador: string; FObservacao: string; FLocalizacao: TLocalizacao; FDataMovimentacao: TDateTime; FTipoServico: integer; FPeriodo: integer; FVlrPeriodo: real; FVlrCalculado: real; FHorasPermanencia: real; FVlrAPagar: real; FVlrTransbordo: real; FTara: real; FVeiculo: string; FContainer: string; FMotorista: string; FFormaPgamento: TFormaPgamento; FPeriodoEmHoras: integer; FCarenciaPeriodo: integer; iHoraPermanencia: integer; iMinutoPermanencia: integer; FTransbordoEmHoras: integer; FCarenciaTransbordo: integer; function GetVlrAPagar: real; function GetHorasPermanencia: string; function GetCalculado: real; public constructor Create; property Operacao: TOperacao read FOperacao write FOperacao; property Cliente: string read FCliente write FCliente; property Fil_Orig: string read FFil_Orig write FFil_Orig; property Produto: string read FProduto write FProduto; property DataEntrada: TDateTime read FDataEntrada write FDataEntrada; property DataSaida: TDateTime read FDataSaida write FDataSaida; property DataMovimentacao: TDateTime read FDataMovimentacao write FDataMovimentacao; property Status: TStatus read FStatus write FStatus; property NroTicket: integer read FNroTicket write FNroTicket; property Observacao: string read FObservacao write FObservacao; property Localizacao: TLocalizacao read FLocalizacao write FLocalizacao; property Operador: string read FOperador write FOperador; property FormaPgamento: TFormaPgamento read FFormaPgamento write FFormaPgamento; property Veiculo: string read FVeiculo write FVeiculo; property Motorista: string read FMotorista write FMotorista; property Container: string read FContainer write FContainer; property TipoServico: integer read FTipoServico write FTipoServico; property Tara: real read FTara write FTara; property HorasPermanencia: string read GetHorasPermanencia; property Periodo: integer read FPeriodo write FPeriodo; property VlrCalculado: real read GetCalculado; property VlrAPagar: real read GetVlrAPagar write FVlrAPagar; //valores fixo ->vem cadastro property VlrPeriodo: real read FVlrPeriodo write FVlrPeriodo; property VlrTransbordo: real read FVlrTransbordo write FVlrTransbordo; property PeriodoEmHoras: integer read FPeriodoEmHoras write FPeriodoEmHoras; property CarenciaPeriodo: integer read FCarenciaPeriodo write FCarenciaPeriodo; property TransbordoEmHoras: integer read FTransbordoEmHoras write FTransbordoEmHoras; property CarenciaTransbordo: integer read FCarenciaTransbordo write FCarenciaTransbordo; end; implementation { TControleContainer } constructor TControleContainer.Create; begin FLocalizacao := TLocalizacao.Create; end; function TControleContainer.GetCalculado: real; begin FPeriodo := 0; if (iHoraPermanencia < FPeriodoEmHoras) then begin if ((iHoraPermanencia = FTransbordoEmHoras) and (iMinutoPermanencia <= FCarenciaTransbordo)) or (iHoraPermanencia < FTransbordoEmHoras) then Result := FVlrTransbordo else Result := FVlrPeriodo; end; if (iHoraPermanencia = FPeriodoEmHoras) then begin if (iMinutoPermanencia <= FCarenciaPeriodo) then FPeriodo := 1 else FPeriodo := 2; Result := FVlrPeriodo * FPeriodo; end; if (iHoraPermanencia > FPeriodoEmHoras) then begin FPeriodo := iHoraPermanencia div FPeriodoEmHoras; if FPeriodo = 0 then FPeriodo := 1; if (iMinutoPermanencia > FCarenciaPeriodo) then FPeriodo := FPeriodo + 1; Result := FVlrPeriodo * FPeriodo; end; FVlrCalculado := Result; end; function TControleContainer.GetHorasPermanencia: string; begin iHoraPermanencia := MinutesBetween(FDataEntrada, FDataSaida) div 60; iMinutoPermanencia := MinutesBetween(FDataEntrada, FDataSaida) Mod 60; Result := IntToStr(iHoraPermanencia) + ':' + IntToStr(iMinutoPermanencia); //HoursBetween(DateOf(aDataEntrada), DateOf(aDataSaida)); end; function TControleContainer.GetVlrAPagar: real; begin if (FVlrAPagar <> FVlrCalculado) and (FVlrAPagar > 0) then Result := FVlrAPagar else Result := FVlrCalculado; end; end.
{ CSI 1101-X, Winter 1999 } { Assignment 4, Question 1 } { Identification: Mark Sattolo, student# 428500 } { tutorial group DGD-4, t.a. = Manon Sanscartier } program a4q1 (input,output) ; type element_type = real ; pointer = ^node ; node = record value: element_type ; next: pointer end ; list = pointer ; (* variable for the main program - NOT to be referenced anywhere else *) var YESorNO: char ; (*** The following global variable is used for memory management. You might find it useful while debugging your code, but the solutions you hand in must not refer to this variable in any way. ***) memory_count: integer ; (********* MEMORY MANAGEMENT PROCEDURES ************) (* get_node - Returns a pointer to a new node. *) procedure get_node( var P: pointer ); begin memory_count := memory_count + 1 ; new( P ) end ; (* return_node - Make the node pointed at by P "free" (available to get_node). *) procedure return_node(var P: pointer) ; begin memory_count := memory_count - 1 ; P^.value := -7777.77 ; (* "scrub" memory to aid debugging *) P^.next := P ; (* "scrub" memory to aid debugging *) dispose( P ) end ; (******************************************************************) (* create_empty - sets list L to be empty. *) procedure create_empty ( var L: list ) ; begin L := nil end ; procedure write_list ( var L:list ); var p: pointer ; begin if L = nil then writeln('empty list') else begin p := L ; while p <> nil do begin write( ' ',p^.value:4:1 ); p := p^.next end ; writeln end end ; procedure destroy( var L:list ) ; begin if L <> Nil then { General case } begin destroy (L^.next) ; { step 1 } return_node (L) ; { step 2 } end { i.e. Base case = "else, do nothing" } end; { procedure } procedure insert_at_end(var L:list; V: element_type) ; begin if L = nil then begin get_node(L) ; L^.value := V ; L^.next := nil ; end { if } else insert_at_end(L^.next, V) ; end; { procedure } procedure delete_all_occurrences( var L:list; V: element_type) ; var p : pointer ; begin if L = nil then { do nothing } else begin delete_all_occurrences(L^.next, V) ; if (L^.value = V) then begin p := L ; L := L^.next ; return_node(p) ; end { if } end { else } end; { procedure } procedure assignment4q1 ; var L: list ; val: element_type ; begin create_empty( L ); writeln('enter a list of reals, all values on one line'); while (not eoln) do begin read(val) ; insert_at_end(L,val) end ; readln ; (* clear the empty line *) writeln ; writeln('Here is the list you entered'); write_list(L); writeln ; writeln('enter a value to be deleted (empty line to quit)' ); while (not eoln) do begin readln(val) ; delete_all_occurrences(L, val) ; writeln('Here is the list after deleting all occurrences of ',val:6:1); write_list(L); writeln ; writeln('enter a value to be deleted (empty line to quit)' ) end ; readln ; (* clear the empty line *) (* to finish off, return all the nodes in all lists back to the global pool *) destroy( L ) end; (******* YOU MUST CHANGE THIS PROCEDURE TO DESCRIBE YOURSELF *******) procedure identify_myself ; (* Writes who you are to the screen *) begin writeln ; writeln('CSI 1101-X (winter, 1999). Assignment 4, Question 1.') ; writeln('Mark Sattolo, student# 428500.') ; writeln('tutorial section DGD-4, t.a. = Manon Sanscartier') ; writeln end ; begin { main program } memory_count := 0 ; identify_myself ; repeat assignment4q1 ; writeln('Amount of dynamic memory allocated but not returned (should be 0) ', memory_count:0) ; writeln('Do you wish to continue (y or n) ?') ; readln(YESorNO); until (YESorNO <> 'y') end.
unit EdPanel; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TEdPanel = class(TPanel) Ed:TEdit; List:TListBox; Lab:TLabel; private { Private declarations } _Items:TStrings; _Space:integer; _LabSpace:integer; _EdWidth:single; _EdAlign:boolean; _LabCaption:string; _EdOnKeyPress:TKeyPressEvent; _EdOnClick:TNotifyEvent; _ListOnKeyPress:TKeyPressEvent; _ListOnClick:TNotifyEvent; _ListOnDblClick:TNotifyEvent; _ListOnKeyDown:TKeyEvent; _EdOnEnter:TNotifyEvent; _ListOnEnter:TNotifyEvent; procedure wSpace(value:integer); procedure wItems(value:TStrings); procedure wLabSpace(value:integer); procedure wEdWidth(value:single); procedure wEdAlign(value:boolean); procedure wLabCaption(value:string); procedure wListIndex(value:integer); function rListIndex:integer; procedure wEdOnClick(value:TNotifyEvent); procedure wListOnClick(value:TNotifyEvent); procedure wListOnDblClick(value:TNotifyEvent); procedure wEdOnKeyPress(value:TKeyPressEvent); procedure wListOnKeyPress(value:TKeyPressEvent); procedure wListOnKeyDown(value:TKeyEvent); procedure wEdOnEnter(value:TNotifyEvent); procedure wListOnEnter(value:TNotifyEvent); procedure EdResize; protected { Protected declarations } public { Public declarations } constructor Create(AOwner:TComponent);override; destructor Destroy;override; procedure Paint;override; published { Published declarations } property Space:integer read _Space write wSpace; property Items:TStrings read _Items write wItems; property LabSpace:integer read _LabSpace write wLabSpace; property EdWidth:single read _EdWidth write wEdWidth; property EdAlign:boolean read _EdAlign write wEdAlign; property LabCaption:string read _LabCaption write wLabCaption; property ListIndex:integer read rListIndex write wListIndex; property EdOnKeyPress:TKeyPressEvent read _EdOnKeyPress write wEdOnKeyPress; property EdOnClick:TNotifyEvent read _EdOnClick write wEdOnClick; property ListOnKeyPress:TKeyPressEvent read _ListOnKeyPress write wListOnKeyPress; property ListOnClick:TNotifyEvent read _ListOnClick write wListOnClick; property ListOnDblClick:TNotifyEvent read _ListOnDblClick write wListOnDblClick; property ListOnKeyDown:TKeyEvent read _ListOnKeyDown write wListOnKeyDown; property EdOnEnter:TNotifyEvent read _EdOnEnter write wEdOnEnter; property ListOnEnter:TNotifyEvent read _ListOnEnter write wListOnEnter; end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TEdPanel]); end; constructor TEdPanel.Create; begin inherited Create(AOwner); BorderWidth:=2; BevelInner:=bvNone; BevelOuter:=bvNone; Ed:=TEdit.Create(Self); List:=TListBox.Create(Self); Lab:=TLabel.Create(Self); Items:=List.Items; with Lab do begin Parent:=Self; Top:=BorderWidth+BevelWidth; Left:=Top; end; with Ed do begin Parent:=Self; Left:=Lab.Left; end; with List do begin Parent:=Self; Left:=Lab.Left; end; Caption:=''; Space:=5; EdWidth:=1; EdAlign:=True; EdResize; end; destructor TEdPanel.Destroy; begin Lab.Destroy; Ed.Destroy; List.Destroy; inherited Destroy; end; procedure TEdPanel.Paint; begin if List.Height<>Self.Height-(Ed.Top+Ed.Height+Space+BorderWidth) then EdResize; if List.Width<>Self.Width-(2*List.Left) then EdResize; inherited Paint; end; procedure TEdPanel.EdResize; begin if EdAlign then Ed.Width:=Width-(2*Ed.Left); Ed.Top:=Lab.Top+Lab.Height+LabSpace; List.Top:=Ed.Top+Ed.Height+Space; List.Width:=Width-(2*List.Left); List.Height:=Height-(Ed.Top+Ed.Height+Space); end; procedure TEdPanel.wItems; begin _Items:=List.Items; end; procedure TEdPanel.wSpace; begin _Space:=value;EdResize; end; procedure TEdPanel.wLabSpace; begin _LabSpace:=value;EdResize; end; procedure TEdPanel.wEdWidth; begin _EdWidth:=value; if not EdAlign then Ed.Width:=trunc(List.Width*EdWidth); end; procedure TEdPanel.wEdAlign; begin _EdAlign:=value;if EdAlign then EdResize; end; procedure TEdPanel.wLabCaption; begin _LabCaption:=value;Lab.Caption:=LabCaption; end; procedure TEdPanel.wListIndex; begin List.ItemIndex:=value; end; function TEdPanel.rListIndex; begin Result:=List.ItemIndex; end; procedure TEdPanel.wEdOnClick; begin _EdOnClick:=value;Ed.OnClick:=EdOnClick; end; procedure TEdPanel.wListOnClick; begin _ListOnClick:=value;List.OnClick:=ListOnClick; end; procedure TEdPanel.wListOnDblClick; begin _ListOnDblClick:=value;List.OnDblClick:=ListOnDblClick; end; procedure TEdPanel.wEdOnKeyPress; begin _EdOnKeyPress:=value;Ed.OnKeyPress:=EdOnKeyPress; end; procedure TEdPanel.wListOnKeyPress; begin _ListOnKeyPress:=value;List.OnKeyPress:=ListOnKeyPress; end; procedure TEdPanel.wListOnKeyDown; begin _ListOnKeyDown:=value;List.OnKeyDown:=ListOnKeyDown; end; procedure TEdPanel.wEdOnEnter; begin _EdOnEnter:=value;Ed.OnEnter:=EdOnEnter; end; procedure TEdPanel.wListOnEnter; begin _ListOnEnter:=value;List.OnEnter:=ListOnEnter; end; end.
unit UMain; interface uses Winapi.Windows, System.Win.Registry, System.IniFiles, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation, FMX.Layouts; const MIN_BDS_VERSION = 19; MAX_BDS_VERSION = 20; type TMainForm = class(TForm) lblLibraryPath: TLabel; memLibraryPath: TMemo; lblBrowsingPath: TLabel; memBrowsingPath: TMemo; lblDebugPath: TLabel; memDebugPath: TMemo; btnInstall: TButton; StyleBook: TStyleBook; lytBottom: TLayout; Label1: TLabel; procedure btnInstallClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation uses System.IOUtils; {$R *.fmx} procedure TMainForm.btnInstallClick(Sender: TObject); procedure AddPaths(AReg: TRegistry; const AKeyPath, ARegName: string; AStrings: TStrings); const ALL_PLATFORMS: array[0..8] of string = ('Win32', 'Win64', 'iOSDevice32', 'iOSDevice64', 'iOSSimulator', 'OSX32', 'Android32', 'Android64', 'Linux64'); ALL_PLATFORMS_PATH_NAMES: array[0..8] of string = ('Win32', 'Win64', 'iOSDevice32', 'iOSDevice64', 'iOSSimulator', 'OSX32', 'Android', 'Android64', 'Linux64'); var LPlatform: string; LPlatformPath: string; LList: TStringList; LDir: string; LFullDir: string; LListItem: string; I: Integer; J: Integer; K: Integer; begin for K := Low(ALL_PLATFORMS) to High(ALL_PLATFORMS) do begin LPlatform := ALL_PLATFORMS[K]; LPlatformPath := AKeyPath + LPlatform + '\'; if AReg.KeyExists(LPlatformPath) then begin AReg.OpenKey(LPlatformPath, False); try LList := TStringList.Create; try LList.Text := AReg.ReadString(ARegName).Replace(';', #13#10, [rfReplaceAll]).Trim; for I := 0 to AStrings.Count-1 do begin LDir := TPath.GetFullPath(AStrings[I]); LFullDir := LDir.Replace('($Platform)', ALL_PLATFORMS_PATH_NAMES[K], [rfReplaceAll, rfIgnoreCase]); for J := LList.Count-1 downto I do begin LListItem := LList[J].ToLower.Trim; if LListItem.EndsWith('\') then LListItem := LListItem.Substring(0, LListItem.Length-1); if (LDir.ToLower = LListItem) or (LFullDir.ToLower = LListItem) then LList.Delete(J); end; LList.Insert(I, LFullDir); end; AReg.WriteString(ARegName, LList.Text.Replace(#13#10, ';', [rfReplaceAll]).Trim); finally LList.Free; end; finally AReg.CloseKey; end; end; end; end; procedure ClearInvalidStrings(AStrings: TStrings); var I: Integer; J: Integer; LStr: string; begin // Fix the paths for I := AStrings.Count-1 downto 0 do begin AStrings[I] := AStrings[I].Trim; if AStrings[I].IsEmpty then AStrings.Delete(I) else if AStrings[I].EndsWith('\') then AStrings[I] := AStrings[I].Substring(0, AStrings[I].Length-1); end; // Remove invalid paths for I := AStrings.Count-1 downto 0 do begin try LStr := TPath.GetFullPath(AStrings[I]); except showmessage('Invalid path "'+AStrings[I]+'". It will be removed.'); AStrings.Delete(I); Continue; end; end; // Remove duplicates for I := AStrings.Count-1 downto 0 do begin LStr := TPath.GetFullPath(AStrings[I]).ToLower; for J := 0 to I-1 do begin if TPath.GetFullPath(AStrings[J]).ToLower = LStr then begin AStrings.Delete(I); Break; end; end; end; end; procedure WriteIniStrings(AIni: TIniFile; AStrings: TStrings; const ASection: string); var I: Integer; begin for I := 0 to AStrings.Count-1 do AIni.WriteString(ASection, I.ToString, AStrings[I]); end; var LReg: TRegistry; LKeyPath: string; LVersion: Integer; LIni: TIniFile; begin ClearInvalidStrings(memLibraryPath.Lines); ClearInvalidStrings(memBrowsingPath.Lines); ClearInvalidStrings(memDebugPath.Lines); LReg := TRegistry.Create(KEY_ALL_ACCESS); try LReg.RootKey := HKEY_CURRENT_USER; for LVersion := MIN_BDS_VERSION to MAX_BDS_VERSION do begin LKeyPath := Format('Software\Embarcadero\BDS\%d.0\Library\', [LVersion]); if LReg.KeyExists(LKeyPath) then begin AddPaths(LReg, LKeyPath, 'Search Path', memLibraryPath.Lines); AddPaths(LReg, LKeyPath, 'Browsing Path', memBrowsingPath.Lines); AddPaths(LReg, LKeyPath, 'Debug DCU Path', memDebugPath.Lines); end; end; finally LReg.Free; end; if TFile.Exists(TPath.ChangeExtension(ParamStr(0), '.ini')) then TFile.Delete(TPath.ChangeExtension(ParamStr(0), '.ini')); LIni := TIniFile.Create(TPath.ChangeExtension(ParamStr(0), '.ini')); try WriteIniStrings(LIni, memLibraryPath.Lines, 'Library Path'); WriteIniStrings(LIni, memBrowsingPath.Lines, 'Browsing Path'); WriteIniStrings(LIni, memDebugPath.Lines, 'Debug DCU Path'); finally LIni.Free; end; Showmessage('Finished!'); end; procedure TMainForm.FormCreate(Sender: TObject); procedure ReadIniStrings(AIni: TIniFile; AStrings: TStrings; const ASection: string); var I: Integer; begin I := 0; while AIni.ValueExists(ASection, I.ToString) do begin if AIni.ReadString(ASection, I.ToString, '') <> '' then AStrings.Add(AIni.ReadString(ASection, I.ToString, '')); Inc(I); end; end; var LIni: TIniFile; begin if TFile.Exists(TPath.ChangeExtension(ParamStr(0), '.ini')) then begin LIni := TIniFile.Create(TPath.ChangeExtension(ParamStr(0), '.ini')); try ReadIniStrings(LIni, memLibraryPath.Lines, 'Library Path'); ReadIniStrings(LIni, memBrowsingPath.Lines, 'Browsing Path'); ReadIniStrings(LIni, memDebugPath.Lines, 'Debug DCU Path'); finally LIni.Free; end; end; end; end.
unit UPRT_Liner; interface uses UPRT, UTime; const LINER_TXBSIZE = 400; LINER_INBSIZE = 1024; type TPRT_LINER = class(TPRT) private prt:TPRT; InBLen,BufPos:Integer; RxReady,NeedXor:Boolean; // буфер полученных "сырых" данных InB:array[0..LINER_INBSIZE-1] of Byte; // буфер для принятого пакета Buf:array[0..LINER_INBSIZE-1] of Byte; protected procedure ClearInBuf; public constructor Create(prt:TPRT); public // interface function Open:HRESULT;override; procedure Close;override; function RxSize():Integer;override; function Rx(var Data; MaxSize:Integer):Integer;override; procedure Tx(const Data; Cnt:Integer);override; function ProcessIO():Integer;override; end; TLinkStat = object BytesI, PacketsI: Cardinal; BytesO, PacketsO: Cardinal; procedure Add(const Stat:TLinkStat); procedure Clear; function GetMsg:String; end; // return True if nothing to do function StdProcessIO(prt:TPRT_LINER; var Stat:TLinkStat):Boolean; implementation uses SysUtils, UNetW; function StdProcessIO(prt:TPRT_LINER; var Stat:TLinkStat):Boolean; var IO,i:Integer; S:String; begin Result:=True; IO:=Prt.ProcessIO; if IO and IO_RX <> 0 then begin Result:=False; SetLength(S,prt.RxSize); SetLength(S,prt.Rx(S[1],Length(S))); if NetW_receive(prt,S[1],Length(S)) then Inc(Stat.PacketsI); Inc(Stat.BytesI,Length(S)); end; if IO and IO_TX <> 0 then begin SetLength(S,LINER_TXBSIZE); i:=NetW_transmit(prt,S[1],Length(S)); if i>0 then begin Result:=False; SetLength(S,i); prt.Tx(S[1],i); Inc(Stat.PacketsO); Inc(Stat.BytesO,i); end end; end; { TPRT_LINER } constructor TPRT_LINER.Create(prt: TPRT); begin Self.prt:=prt; end; procedure TPRT_LINER.ClearInBuf; begin InBLen:=0; end; //******************** begin of PRT interface function TPRT_LINER.Open:HRESULT; begin Result:=prt.Open(); end; procedure TPRT_LINER.Close; begin prt.Close(); end; function TPRT_LINER.Rx(var Data; MaxSize:Integer): Integer; begin if RxReady then begin RxReady := FALSE; if MaxSize<BufPos then BufPos:=MaxSize; if @Data<>nil then move(Buf[0],Data,BufPos); Result:=BufPos; BufPos:=0; end else Result:=0; end; function TPRT_LINER.RxSize: Integer; begin if RxReady then Result:=BufPos else Result:=0; end; procedure TPRT_LINER.Tx(const Data; Cnt: Integer); var TxEOL:Boolean; TxBuf:array of Byte; Src:^Byte; TxPos:Integer; c:Byte; begin TxEOL := True; SetLength(TxBuf,Cnt*2+1); TxPos := 0; if Cnt>0 then begin Src := @Data; while Cnt>0 do begin c := Src^; if (c=$0D) or (c=$7D) or (c=$0A) then begin TxBuf[TxPos] := $7D; Inc(TxPos); c := c xor $20; end; TxBuf[TxPos] := c; Inc(TxPos); Dec(Cnt); Inc(Src); end; end; if TxEOL then begin TxBuf[TxPos] := $0D; Inc(TxPos); end; if TxPos>0 then prt.Tx(TxBuf[0],TxPos); end; function TPRT_LINER.ProcessIO: Integer; var i:Integer; c:Byte; begin Result:=prt.ProcessIO(); if Result and IO_UP = 0 then exit; //********** RX if (InBLen=0) and (Result and IO_RX<>0) then begin InBLen := prt.Rx(InB,LINER_INBSIZE); end; if not RxReady and (InBLen>0) then begin i:=0; while i<InBLen do begin c:=InB[i]; Inc(i); case c of $0D: // Carriage Return begin RxReady := TRUE; break; end; $7D: // ESC prefix '}' NeedXor:=TRUE; $0A: // Line Feed ; // do nothing else if BufPos<LINER_INBSIZE then begin if NeedXor then begin c := c xor $20; NeedXor := FALSE; end; Buf[BufPos]:=c; Inc(BufPos); end; end; end; InBLen:=InBLen-i; if InBLen>0 then Move(InB[i],InB[0],InBLen); if RxReady then NeedXor:=FALSE; end; if RxReady then Result := Result or IO_RX else Result := Result and not IO_RX; end; //******************** end of PRT interface { TLinkStat } procedure TLinkStat.Add; begin Inc(BytesI,Stat.BytesI); Inc(PacketsI,Stat.PacketsI); Inc(BytesO,Stat.BytesO); Inc(PacketsO,Stat.PacketsO); end; procedure TLinkStat.Clear; begin BytesI:=0; PacketsI:=0; BytesO:=0; PacketsO:=0; end; function TLinkStat.GetMsg: String; begin Result:=Format('Rx: %.9d/%.4d; Tx: %.9d/%.4d',[BytesI,PacketsI,BytesO,PacketsO]); end; end.
unit NavigatorKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы Navigator } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Common\NavigatorKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "NavigatorKeywordsPack" MUID: (3ADD81F1E403) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses , vtPanel {$If Defined(Nemesis)} , nscContextFilter {$IfEnd} // Defined(Nemesis) , nscTreeViewWithAdapterDragDrop ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3ImplUses , Navigator_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_Navigator = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы Navigator ---- *Пример использования*: [code] 'aControl' форма::Navigator TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_Navigator Tkw_Navigator_Control_BackgroundPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола BackgroundPanel ---- *Пример использования*: [code] контрол::BackgroundPanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Navigator_Control_BackgroundPanel Tkw_Navigator_Control_BackgroundPanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола BackgroundPanel ---- *Пример использования*: [code] контрол::BackgroundPanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Navigator_Control_BackgroundPanel_Push Tkw_Navigator_Control_ContextFilter = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ContextFilter ---- *Пример использования*: [code] контрол::ContextFilter TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Navigator_Control_ContextFilter Tkw_Navigator_Control_ContextFilter_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола ContextFilter ---- *Пример использования*: [code] контрол::ContextFilter:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Navigator_Control_ContextFilter_Push Tkw_Navigator_Control_NavigatorTree = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола NavigatorTree ---- *Пример использования*: [code] контрол::NavigatorTree TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Navigator_Control_NavigatorTree Tkw_Navigator_Control_NavigatorTree_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола NavigatorTree ---- *Пример использования*: [code] контрол::NavigatorTree:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Navigator_Control_NavigatorTree_Push TkwEnNavigatorBackgroundPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_Navigator.BackgroundPanel } private function BackgroundPanel(const aCtx: TtfwContext; aen_Navigator: Ten_Navigator): TvtPanel; {* Реализация слова скрипта .Ten_Navigator.BackgroundPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnNavigatorBackgroundPanel TkwEnNavigatorContextFilter = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_Navigator.ContextFilter } private function ContextFilter(const aCtx: TtfwContext; aen_Navigator: Ten_Navigator): TnscContextFilter; {* Реализация слова скрипта .Ten_Navigator.ContextFilter } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnNavigatorContextFilter TkwEnNavigatorNavigatorTree = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_Navigator.NavigatorTree } private function NavigatorTree(const aCtx: TtfwContext; aen_Navigator: Ten_Navigator): TnscTreeViewWithAdapterDragDrop; {* Реализация слова скрипта .Ten_Navigator.NavigatorTree } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnNavigatorNavigatorTree function Tkw_Form_Navigator.GetString: AnsiString; begin Result := 'en_Navigator'; end;//Tkw_Form_Navigator.GetString class function Tkw_Form_Navigator.GetWordNameForRegister: AnsiString; begin Result := 'форма::Navigator'; end;//Tkw_Form_Navigator.GetWordNameForRegister function Tkw_Navigator_Control_BackgroundPanel.GetString: AnsiString; begin Result := 'BackgroundPanel'; end;//Tkw_Navigator_Control_BackgroundPanel.GetString class procedure Tkw_Navigator_Control_BackgroundPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_Navigator_Control_BackgroundPanel.RegisterInEngine class function Tkw_Navigator_Control_BackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel'; end;//Tkw_Navigator_Control_BackgroundPanel.GetWordNameForRegister procedure Tkw_Navigator_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('BackgroundPanel'); inherited; end;//Tkw_Navigator_Control_BackgroundPanel_Push.DoDoIt class function Tkw_Navigator_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel:push'; end;//Tkw_Navigator_Control_BackgroundPanel_Push.GetWordNameForRegister function Tkw_Navigator_Control_ContextFilter.GetString: AnsiString; begin Result := 'ContextFilter'; end;//Tkw_Navigator_Control_ContextFilter.GetString class procedure Tkw_Navigator_Control_ContextFilter.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscContextFilter); end;//Tkw_Navigator_Control_ContextFilter.RegisterInEngine class function Tkw_Navigator_Control_ContextFilter.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ContextFilter'; end;//Tkw_Navigator_Control_ContextFilter.GetWordNameForRegister procedure Tkw_Navigator_Control_ContextFilter_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ContextFilter'); inherited; end;//Tkw_Navigator_Control_ContextFilter_Push.DoDoIt class function Tkw_Navigator_Control_ContextFilter_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ContextFilter:push'; end;//Tkw_Navigator_Control_ContextFilter_Push.GetWordNameForRegister function Tkw_Navigator_Control_NavigatorTree.GetString: AnsiString; begin Result := 'NavigatorTree'; end;//Tkw_Navigator_Control_NavigatorTree.GetString class procedure Tkw_Navigator_Control_NavigatorTree.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscTreeViewWithAdapterDragDrop); end;//Tkw_Navigator_Control_NavigatorTree.RegisterInEngine class function Tkw_Navigator_Control_NavigatorTree.GetWordNameForRegister: AnsiString; begin Result := 'контрол::NavigatorTree'; end;//Tkw_Navigator_Control_NavigatorTree.GetWordNameForRegister procedure Tkw_Navigator_Control_NavigatorTree_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('NavigatorTree'); inherited; end;//Tkw_Navigator_Control_NavigatorTree_Push.DoDoIt class function Tkw_Navigator_Control_NavigatorTree_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::NavigatorTree:push'; end;//Tkw_Navigator_Control_NavigatorTree_Push.GetWordNameForRegister function TkwEnNavigatorBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext; aen_Navigator: Ten_Navigator): TvtPanel; {* Реализация слова скрипта .Ten_Navigator.BackgroundPanel } begin Result := aen_Navigator.BackgroundPanel; end;//TkwEnNavigatorBackgroundPanel.BackgroundPanel class function TkwEnNavigatorBackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := '.Ten_Navigator.BackgroundPanel'; end;//TkwEnNavigatorBackgroundPanel.GetWordNameForRegister function TkwEnNavigatorBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwEnNavigatorBackgroundPanel.GetResultTypeInfo function TkwEnNavigatorBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnNavigatorBackgroundPanel.GetAllParamsCount function TkwEnNavigatorBackgroundPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_Navigator)]); end;//TkwEnNavigatorBackgroundPanel.ParamsTypes procedure TkwEnNavigatorBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx); end;//TkwEnNavigatorBackgroundPanel.SetValuePrim procedure TkwEnNavigatorBackgroundPanel.DoDoIt(const aCtx: TtfwContext); var l_aen_Navigator: Ten_Navigator; begin try l_aen_Navigator := Ten_Navigator(aCtx.rEngine.PopObjAs(Ten_Navigator)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_Navigator: Ten_Navigator : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_aen_Navigator)); end;//TkwEnNavigatorBackgroundPanel.DoDoIt function TkwEnNavigatorContextFilter.ContextFilter(const aCtx: TtfwContext; aen_Navigator: Ten_Navigator): TnscContextFilter; {* Реализация слова скрипта .Ten_Navigator.ContextFilter } begin Result := aen_Navigator.ContextFilter; end;//TkwEnNavigatorContextFilter.ContextFilter class function TkwEnNavigatorContextFilter.GetWordNameForRegister: AnsiString; begin Result := '.Ten_Navigator.ContextFilter'; end;//TkwEnNavigatorContextFilter.GetWordNameForRegister function TkwEnNavigatorContextFilter.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscContextFilter); end;//TkwEnNavigatorContextFilter.GetResultTypeInfo function TkwEnNavigatorContextFilter.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnNavigatorContextFilter.GetAllParamsCount function TkwEnNavigatorContextFilter.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_Navigator)]); end;//TkwEnNavigatorContextFilter.ParamsTypes procedure TkwEnNavigatorContextFilter.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ContextFilter', aCtx); end;//TkwEnNavigatorContextFilter.SetValuePrim procedure TkwEnNavigatorContextFilter.DoDoIt(const aCtx: TtfwContext); var l_aen_Navigator: Ten_Navigator; begin try l_aen_Navigator := Ten_Navigator(aCtx.rEngine.PopObjAs(Ten_Navigator)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_Navigator: Ten_Navigator : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ContextFilter(aCtx, l_aen_Navigator)); end;//TkwEnNavigatorContextFilter.DoDoIt function TkwEnNavigatorNavigatorTree.NavigatorTree(const aCtx: TtfwContext; aen_Navigator: Ten_Navigator): TnscTreeViewWithAdapterDragDrop; {* Реализация слова скрипта .Ten_Navigator.NavigatorTree } begin Result := aen_Navigator.NavigatorTree; end;//TkwEnNavigatorNavigatorTree.NavigatorTree class function TkwEnNavigatorNavigatorTree.GetWordNameForRegister: AnsiString; begin Result := '.Ten_Navigator.NavigatorTree'; end;//TkwEnNavigatorNavigatorTree.GetWordNameForRegister function TkwEnNavigatorNavigatorTree.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscTreeViewWithAdapterDragDrop); end;//TkwEnNavigatorNavigatorTree.GetResultTypeInfo function TkwEnNavigatorNavigatorTree.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnNavigatorNavigatorTree.GetAllParamsCount function TkwEnNavigatorNavigatorTree.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_Navigator)]); end;//TkwEnNavigatorNavigatorTree.ParamsTypes procedure TkwEnNavigatorNavigatorTree.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству NavigatorTree', aCtx); end;//TkwEnNavigatorNavigatorTree.SetValuePrim procedure TkwEnNavigatorNavigatorTree.DoDoIt(const aCtx: TtfwContext); var l_aen_Navigator: Ten_Navigator; begin try l_aen_Navigator := Ten_Navigator(aCtx.rEngine.PopObjAs(Ten_Navigator)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_Navigator: Ten_Navigator : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(NavigatorTree(aCtx, l_aen_Navigator)); end;//TkwEnNavigatorNavigatorTree.DoDoIt initialization Tkw_Form_Navigator.RegisterInEngine; {* Регистрация Tkw_Form_Navigator } Tkw_Navigator_Control_BackgroundPanel.RegisterInEngine; {* Регистрация Tkw_Navigator_Control_BackgroundPanel } Tkw_Navigator_Control_BackgroundPanel_Push.RegisterInEngine; {* Регистрация Tkw_Navigator_Control_BackgroundPanel_Push } Tkw_Navigator_Control_ContextFilter.RegisterInEngine; {* Регистрация Tkw_Navigator_Control_ContextFilter } Tkw_Navigator_Control_ContextFilter_Push.RegisterInEngine; {* Регистрация Tkw_Navigator_Control_ContextFilter_Push } Tkw_Navigator_Control_NavigatorTree.RegisterInEngine; {* Регистрация Tkw_Navigator_Control_NavigatorTree } Tkw_Navigator_Control_NavigatorTree_Push.RegisterInEngine; {* Регистрация Tkw_Navigator_Control_NavigatorTree_Push } TkwEnNavigatorBackgroundPanel.RegisterInEngine; {* Регистрация en_Navigator_BackgroundPanel } TkwEnNavigatorContextFilter.RegisterInEngine; {* Регистрация en_Navigator_ContextFilter } TkwEnNavigatorNavigatorTree.RegisterInEngine; {* Регистрация en_Navigator_NavigatorTree } TtfwTypeRegistrator.RegisterType(TypeInfo(Ten_Navigator)); {* Регистрация типа Ten_Navigator } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TnscContextFilter)); {* Регистрация типа TnscContextFilter } TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTreeViewWithAdapterDragDrop)); {* Регистрация типа TnscTreeViewWithAdapterDragDrop } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clCryptCipher; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Windows, Contnrs, {$ELSE} System.Classes, System.SysUtils, Winapi.Windows, System.Contnrs, {$ENDIF} clCryptAPI, clUtils, clWUtils, clConfig; type TclCryptMethod = (cmEncrypt, cmDecrypt); TclCipher = class(TclConfigObject) public function GetIVSize(): Integer; virtual; abstract; function GetBlockSize(): Integer; virtual; abstract; procedure Init(AMethod: TclCryptMethod; const AKey, AIV: TclByteArray); virtual; abstract; procedure Update(const ABuffer: TclByteArray; AStart, ALen: Integer); virtual; abstract; end; TclCryptApiCipher = class(TclCipher) private FMethod: TclCryptMethod; FContext: HCRYPTPROV; FKey: HCRYPTKEY; FCSPPtr: PclChar; function GetCSPPtr: PclChar; procedure Clear; protected function GetCipherMode: Integer; virtual; abstract; function GetAlgorithm: ALG_ID; virtual; abstract; function GetCSP: string; virtual; abstract; function GetProviderType: Integer; virtual; abstract; public constructor Create; override; destructor Destroy; override; procedure Init(AMethod: TclCryptMethod; const AKey, AIV: TclByteArray); override; procedure Update(const ABuffer: TclByteArray; AStart, ALen: Integer); override; end; TclTripleDesCbc = class(TclCryptApiCipher) protected function GetCipherMode: Integer; override; function GetAlgorithm: ALG_ID; override; function GetCSP: string; override; function GetProviderType: Integer; override; public function GetIVSize(): Integer; override; function GetBlockSize(): Integer; override; end; TclAesCbcBase = class(TclCryptApiCipher) protected function GetCipherMode: Integer; override; function GetCSP: string; override; function GetProviderType: Integer; override; end; TclAes128Cbc = class(TclAesCbcBase) protected function GetAlgorithm: ALG_ID; override; public function GetIVSize(): Integer; override; function GetBlockSize(): Integer; override; end; TclAes192Cbc = class(TclAesCbcBase) protected function GetAlgorithm: ALG_ID; override; public function GetIVSize(): Integer; override; function GetBlockSize(): Integer; override; end; TclAes256Cbc = class(TclAesCbcBase) protected function GetAlgorithm: ALG_ID; override; public function GetIVSize(): Integer; override; function GetBlockSize(): Integer; override; end; TclAesCtrBase = class(TclCipher) private FMethod: TclCryptMethod; FContext: HCRYPTPROV; FKey: HCRYPTKEY; FCSPPtr: PclChar; FCounter: TclByteArray; FXorMask: TQueue; function GetCSPPtr: PclChar; procedure Clear; function NeedMoreXorMaskBytes: Boolean; procedure EncryptCounter; procedure IncrementCounter; protected function GetAlgorithm: ALG_ID; virtual; abstract; function GetCSP: string; virtual; function GetProviderType: Integer; virtual; public constructor Create; override; destructor Destroy; override; procedure Init(AMethod: TclCryptMethod; const AKey, AIV: TclByteArray); override; procedure Update(const ABuffer: TclByteArray; AStart, ALen: Integer); override; end; TclAes128Ctr = class(TclAesCtrBase) protected function GetAlgorithm: ALG_ID; override; public function GetIVSize(): Integer; override; function GetBlockSize(): Integer; override; end; TclAes192Ctr = class(TclAesCtrBase) protected function GetAlgorithm: ALG_ID; override; public function GetIVSize(): Integer; override; function GetBlockSize(): Integer; override; end; TclAes256Ctr = class(TclAesCtrBase) protected function GetAlgorithm: ALG_ID; override; public function GetIVSize(): Integer; override; function GetBlockSize(): Integer; override; end; implementation uses clCryptUtils; { TclTripleDesCbc } function TclTripleDesCbc.GetAlgorithm: ALG_ID; begin Result := CALG_3DES; end; function TclTripleDesCbc.GetBlockSize: Integer; begin Result := 24; end; function TclTripleDesCbc.GetCipherMode: Integer; begin Result := CRYPT_MODE_CBC; end; function TclTripleDesCbc.GetCSP: string; begin Result := MS_ENHANCED_PROV; end; function TclTripleDesCbc.GetIVSize: Integer; begin Result := 8; end; function TclTripleDesCbc.GetProviderType: Integer; begin Result := PROV_RSA_FULL; end; { TclCryptApiCipher } procedure TclCryptApiCipher.Clear; begin if (FKey <> nil) then begin CryptDestroyKey(FKey); FKey := nil; end; if (FContext <> nil) then begin CryptReleaseContext(FContext, 0); FContext := nil; end; FreeMem(FCSPPtr); FCSPPtr := nil; end; constructor TclCryptApiCipher.Create; begin inherited Create(); FContext := nil; FKey := nil; end; destructor TclCryptApiCipher.Destroy; begin Clear(); inherited Destroy(); end; function TclCryptApiCipher.GetCSPPtr: PclChar; var s: TclString; len: Integer; begin Result := FCSPPtr; if (Result <> nil) then Exit; if (Trim(GetCSP()) <> '') then begin s := GetTclString(GetCSP()); len := Length(s); GetMem(FCSPPtr, len + SizeOf(TclChar)); system.Move(PclChar(s)^, FCSPPtr^, len); FCSPPtr[len] := #0; end; Result := FCSPPtr; end; procedure TclCryptApiCipher.Init(AMethod: TclCryptMethod; const AKey, AIV: TclByteArray); var keyBlob: TclCryptData; keyBlobLen, len: Integer; iv, key: TclByteArray; blobHdr: PBLOBHEADER; blobData: PCRYPTOAPI_BLOB; dw: DWORD; begin Clear(); len := Length(AIV); if (len > GetIVSize()) then begin len := GetIVSize(); end; iv := System.Copy(AIV, 0, len); len := Length(AKey); if (len > GetBlockSize()) then begin len := GetBlockSize(); end; key := System.Copy(AKey, 0, len); FMethod := AMethod; if not CryptAcquireContext(@FContext, nil, GetCSPPtr(), GetProviderType(), CRYPT_VERIFYCONTEXT) then begin RaiseCryptError('CryptAcquireContext'); end; keyBlobLen := SizeOf(BLOBHEADER) + SizeOf(DWORD) + GetBlockSize(); keyBlob := TclCryptData.Create(keyBlobLen); try blobHdr := PBLOBHEADER(keyBlob.Data); blobHdr.bType := PLAINTEXTKEYBLOB; blobHdr.bVersion := CUR_BLOB_VERSION; blobHdr.reserved := 0; blobHdr.aiKeyAlg := GetAlgorithm(); blobData := PCRYPTOAPI_BLOB(TclIntPtr(keyBlob.Data) + SizeOf(BLOBHEADER)); blobData.cbData := GetBlockSize(); System.Move(key[0], blobData.pbData, GetBlockSize()); if not CryptImportKey(FContext, keyBlob.Data, keyBlob.DataSize, nil, 0, @FKey) then begin RaiseCryptError('CryptImportKey'); end; dw := GetCipherMode(); if not CryptSetKeyParam(FKey, KP_MODE, @dw, 0) then begin RaiseCryptError('CryptSetKeyParam'); end; if not CryptSetKeyParam(FKey, KP_IV, Pointer(iv), 0) then begin RaiseCryptError('CryptSetKeyParam'); end; finally keyBlob.Free(); end; end; procedure TclCryptApiCipher.Update(const ABuffer: TclByteArray; AStart, ALen: Integer); var dw: DWORD; begin dw := DWORD(ALen); if (FMethod = cmEncrypt) then begin if not CryptEncrypt(FKey, nil, 0, 0, Pointer(TclIntPtr(ABuffer) + AStart), @dw, DWORD(ALen)) then begin RaiseCryptError('CryptEncrypt'); end; end else begin if not CryptDecrypt(FKey, nil, 0, 0, Pointer(TclIntPtr(ABuffer) + AStart), @dw) then begin RaiseCryptError('CryptDecrypt'); end; end; end; { TclAes128Cbc } function TclAes128Cbc.GetAlgorithm: ALG_ID; begin Result := CALG_AES_128; end; function TclAes128Cbc.GetBlockSize: Integer; begin Result := 16; end; function TclAes128Cbc.GetIVSize: Integer; begin Result := 16; end; { TclAes192Cbc } function TclAes192Cbc.GetAlgorithm: ALG_ID; begin Result := CALG_AES_192; end; function TclAes192Cbc.GetBlockSize: Integer; begin Result := 24; end; function TclAes192Cbc.GetIVSize: Integer; begin Result := 16; end; { TclAes256Cbc } function TclAes256Cbc.GetAlgorithm: ALG_ID; begin Result := CALG_AES_256; end; function TclAes256Cbc.GetBlockSize: Integer; begin Result := 32; end; function TclAes256Cbc.GetIVSize: Integer; begin Result := 16; end; { TclAesCbcBase } function TclAesCbcBase.GetCipherMode: Integer; begin Result := CRYPT_MODE_CBC; end; function TclAesCbcBase.GetCSP: string; begin Result := MS_ENH_RSA_AES_PROV; end; function TclAesCbcBase.GetProviderType: Integer; begin Result := PROV_RSA_AES; end; { TclAesCtrBase } procedure TclAesCtrBase.Clear; begin if (FKey <> nil) then begin CryptDestroyKey(FKey); FKey := nil; end; if (FContext <> nil) then begin CryptReleaseContext(FContext, 0); FContext := nil; end; FreeMem(FCSPPtr); FCSPPtr := nil; while FXorMask.Count > 0 do begin FXorMask.Pop(); end; end; constructor TclAesCtrBase.Create; begin inherited Create(); FXorMask := TQueue.Create(); FContext := nil; FKey := nil; end; destructor TclAesCtrBase.Destroy; begin Clear(); FXorMask.Free(); inherited Destroy(); end; function TclAesCtrBase.GetCSP: string; begin Result := MS_ENH_RSA_AES_PROV; end; function TclAesCtrBase.GetCSPPtr: PclChar; var s: TclString; len: Integer; begin Result := FCSPPtr; if (Result <> nil) then Exit; if (Trim(GetCSP()) <> '') then begin s := GetTclString(GetCSP()); len := Length(s); GetMem(FCSPPtr, len + SizeOf(TclChar)); system.Move(PclChar(s)^, FCSPPtr^, len); FCSPPtr[len] := #0; end; Result := FCSPPtr; end; function TclAesCtrBase.GetProviderType: Integer; begin Result := PROV_RSA_AES; end; procedure TclAesCtrBase.Init(AMethod: TclCryptMethod; const AKey, AIV: TclByteArray); var keyBlob: TclCryptData; keyBlobLen, len: Integer; iv, key: TclByteArray; blobHdr: PBLOBHEADER; blobData: PCRYPTOAPI_BLOB; dw: DWORD; begin Clear(); len := Length(AIV); if (len > GetIVSize()) then begin len := GetIVSize(); end; iv := System.Copy(AIV, 0, len); len := Length(AKey); if (len > GetBlockSize()) then begin len := GetBlockSize(); end; key := System.Copy(AKey, 0, len); FMethod := AMethod; FCounter := iv; if not CryptAcquireContext(@FContext, nil, GetCSPPtr(), GetProviderType(), CRYPT_VERIFYCONTEXT) then begin RaiseCryptError('CryptAcquireContext'); end; keyBlobLen := SizeOf(BLOBHEADER) + SizeOf(DWORD) + GetBlockSize(); keyBlob := TclCryptData.Create(keyBlobLen); try blobHdr := PBLOBHEADER(keyBlob.Data); blobHdr.bType := PLAINTEXTKEYBLOB; blobHdr.bVersion := CUR_BLOB_VERSION; blobHdr.reserved := 0; blobHdr.aiKeyAlg := GetAlgorithm(); blobData := PCRYPTOAPI_BLOB(TclIntPtr(keyBlob.Data) + SizeOf(BLOBHEADER)); blobData.cbData := GetBlockSize(); System.Move(key[0], blobData.pbData, GetBlockSize()); if not CryptImportKey(FContext, keyBlob.Data, keyBlob.DataSize, nil, CRYPT_NO_SALT, @FKey) then begin RaiseCryptError('CryptImportKey'); end; dw := CRYPT_MODE_ECB; if not CryptSetKeyParam(FKey, KP_MODE, @dw, 0) then begin RaiseCryptError('CryptSetKeyParam'); end; finally keyBlob.Free(); end; end; procedure TclAesCtrBase.Update(const ABuffer: TclByteArray; AStart, ALen: Integer); var i: Integer; mask: Byte; begin if (ALen > Length(ABuffer)) then begin RaiseCryptError(CryptInvalidArgument, CryptInvalidArgumentCode); end; for i := 0 to ALen - 1 do begin if NeedMoreXorMaskBytes() then begin EncryptCounter(); end; mask := Byte(FXorMask.Pop()); ABuffer[AStart + i] := Byte(ABuffer[AStart + i] xor mask); end; end; function TclAesCtrBase.NeedMoreXorMaskBytes: Boolean; begin Result := (FXorMask.Count = 0); end; procedure TclAesCtrBase.EncryptCounter; var i: Integer; dw: DWORD; counterModeBlock: TclByteArray; begin SetLength(counterModeBlock, Length(FCounter)); System.Move(FCounter[0], counterModeBlock[0], Length(counterModeBlock)); dw := DWORD(Length(counterModeBlock)); if not CryptEncrypt(FKey, nil, 0, 0, Pointer(TclIntPtr(counterModeBlock)), @dw, DWORD(Length(counterModeBlock))) then begin RaiseCryptError('CryptEncrypt'); end; IncrementCounter(); for i := 0 to Length(counterModeBlock) - 1 do begin FXorMask.Push(Pointer(counterModeBlock[i])); end; end; procedure TclAesCtrBase.IncrementCounter; var i: Integer; begin for i := Length(FCounter) - 1 downto 0 do begin if (FCounter[i] < 255) then begin FCounter[i] := FCounter[i] + 1; end else begin FCounter[i] := 0; end; if (FCounter[i] <> 0) then begin Break; end; end; end; { TclAes128Ctr } function TclAes128Ctr.GetAlgorithm: ALG_ID; begin Result := CALG_AES_128; end; function TclAes128Ctr.GetBlockSize: Integer; begin Result := 16; end; function TclAes128Ctr.GetIVSize: Integer; begin Result := 16; end; { TclAes192Ctr } function TclAes192Ctr.GetAlgorithm: ALG_ID; begin Result := CALG_AES_192; end; function TclAes192Ctr.GetBlockSize: Integer; begin Result := 24; end; function TclAes192Ctr.GetIVSize: Integer; begin Result := 16; end; { TclAes256Ctr } function TclAes256Ctr.GetAlgorithm: ALG_ID; begin Result := CALG_AES_256; end; function TclAes256Ctr.GetBlockSize: Integer; begin Result := 32; end; function TclAes256Ctr.GetIVSize: Integer; begin Result := 16; end; end.
unit MoveDestinationToRouteUnit; interface uses SysUtils, BaseExampleUnit; type TMoveDestinationToRoute = class(TBaseExample) public procedure Execute(ToRouteId: String; RouteDestinationId, AfterDestinationId: integer); end; implementation procedure TMoveDestinationToRoute.Execute(ToRouteId: String; RouteDestinationId, AfterDestinationId: integer); var ErrorString: String; Success: boolean; begin Success := Route4MeManager.Route.MoveDestinationToRoute(ToRouteId, RouteDestinationId, AfterDestinationId, ErrorString); WriteLn(''); if (Success) then begin WriteLn('MoveDestinationToRoute executed successfully'); WriteLn(Format( 'Destination %d moved to Route %s after Destination %d', [RouteDestinationId, ToRouteId, AfterDestinationId])); end else WriteLn(Format('MoveDestinationToRoute error: "%s"', [ErrorString])); end; end.
program statistics(input, output); var number, sum, mean, deviation : real; count : integer; begin writeln('Enter a list of numbers (final number must be zero).'); number := 5.0; sum := 0.0; count := 0; while (number <> 0) do begin read(number); sum := sum + number; count := succ(count); end; count := pred(count); writeln('Mean: ', (sum / count):4:6); end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clImap4; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, {$ELSE} System.Classes, System.SysUtils, {$ENDIF} clMC, clTcpCommandClient, clMailMessage, clTcpClient, clImapUtils, clMailUtils, clSocketUtils; type EclImap4Error = class(EclTcpClientError); TclImap4 = class(TclCustomMail) private FCommandTag: Integer; FMailBoxSeparator: Char; FCurrentMailBox: TclImap4MailBoxInfo; FCurrentMessage: Integer; FConnectionState: TclImap4ConnectionState; FAutoReconnect: Boolean; FIsTaggedCommand: Boolean; FTotalBytesToReceive: Integer; FIsFetchCommand: Boolean; class procedure RaiseError(const AMessage: string; AErrorCode: Integer); function GetNextCommandTag: string; function GetLastCommandTag: string; procedure SetAutoReconnect(const Value: Boolean); procedure OpenImapSession; procedure Login; procedure Logout; procedure Authenticate; procedure NtlmAuthenticate; procedure CramMD5Authenticate; procedure OAuthAuthenticate; procedure ParseMailBoxes(AList: TStrings; const ACommand: string); procedure ParseSelectedMailBox(const AName: string); procedure ParseSearchMessages(AList: TStrings); function ParseMessageSize(const AMessageId: string; AIsUid: Boolean): Int64; function ParseMessageUid(AIndex: Integer): string; function ParseMessageFlags(const AMessageId: string; AIsUid: Boolean): TclMailMessageFlags; procedure ParseMessage(const AMessageId: string; AMessage: TclMailMessage; AIsUid, AIsHeader: Boolean); function GetMessageId(const ACommand, AResponseLine: string; AIsUid: Boolean): string; procedure CheckMessageValid(AIndex: Integer); procedure CheckUidValid(const AUid: string); procedure CheckConnection(AStates: array of TclImap4ConnectionState); procedure DoDataProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); function ExtractAppendUID(const AResponse: string): string; procedure CheckFetchCommand(const ACommand: string); protected function GetDefaultPort: Integer; override; function GetResponseCode(const AResponse: string): Integer; override; procedure OpenSession; override; procedure CloseSession; override; procedure SendKeepAlive; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure StartTls; override; procedure WaitResponse(const AOkResponses: array of Integer); override; procedure SendTaggedCommand(const ACommand: string; const AOkResponses: array of Integer); overload; procedure SendTaggedCommand(const ACommand: string; const AOkResponses: array of Integer; const Args: array of const); overload; procedure Noop; procedure GetCapability(AList: TStrings); procedure SelectMailBox(const AName: string); procedure ExamineMailBox(const AName: string); procedure CreateMailBox(const AName: string); procedure DeleteMailBox(const AName: string); procedure RenameMailBox(const ACurrentName, ANewName: string); procedure SubscribeMailBox(const AName: string); procedure UnsubscribeMailBox(const AName: string); procedure GetMailBoxes(AList: TStrings); overload; procedure GetMailBoxes(AList: TStrings; const ACriteria: string); overload; procedure GetMailBoxes(AList: TStrings; const AReferenceName, ACriteria: string); overload; procedure GetSubscribedMailBoxes(AList: TStrings); overload; procedure GetSubscribedMailBoxes(AList: TStrings; const ACriteria: string); overload; procedure GetSubscribedMailBoxes(AList: TStrings; const AReferenceName, ACriteria: string); overload; procedure SearchMessages(const ASearchCriteria: string; AMessageList: TStrings); procedure UidSearchMessages(const ASearchCriteria: string; AMessageList: TStrings); function GetMessageFlags(AIndex: Integer): TclMailMessageFlags; function UidGetMessageFlags(const AUid: string): TclMailMessageFlags; procedure SetMessageFlags(AIndex: Integer; AMethod: TclSetFlagsMethod; AFlags: TclMailMessageFlags); procedure UidSetMessageFlags(const AUid: string; AMethod: TclSetFlagsMethod; AFlags: TclMailMessageFlags); procedure DeleteMessage(AIndex: Integer); procedure UidDeleteMessage(const AUid: string); procedure PurgeMessages; procedure CopyMessage(AIndex: Integer; const ADestMailBox: string); procedure UidCopyMessage(const AUid, ADestMailBox: string); procedure CopyMessages(const AMessageSet, ADestMailBox: string); procedure UidCopyMessages(const AMessageSet, ADestMailBox: string); function GetMessageSize(AIndex: Integer): Int64; function UidGetMessageSize(const AUid: string): Int64; function GetMessageUid(AIndex: Integer): string; function AppendMessage(const AMailBoxName: string; AFlags: TclMailMessageFlags): string; overload; function AppendMessage(const AMailBoxName: string; AMessage: TclMailMessage; AFlags: TclMailMessageFlags): string; overload; function AppendMessage(const AMailBoxName: string; AMessage: TStrings; AFlags: TclMailMessageFlags): string; overload; procedure RetrieveMessage(AIndex: Integer); overload; procedure RetrieveMessage(AIndex: Integer; AMessage: TclMailMessage); overload; procedure UidRetrieveMessage(const AUid: string; AMessage: TclMailMessage); procedure RetrieveHeader(AIndex: Integer); overload; procedure RetrieveHeader(AIndex: Integer; AMessage: TclMailMessage); overload; procedure UidRetrieveHeader(const AUid: string; AMessage: TclMailMessage); property CurrentMailBox: TclImap4MailBoxInfo read FCurrentMailBox; property MailBoxSeparator: Char read FMailBoxSeparator; property CurrentMessage: Integer read FCurrentMessage; property ConnectionState: TclImap4ConnectionState read FConnectionState; property LastCommandTag: string read GetLastCommandTag; published property AutoReconnect: Boolean read FAutoReconnect write SetAutoReconnect default False; property Port default DefaultImapPort; end; resourcestring MailboxNameInvalid = 'Mailbox name is invalid, it must not be empty or begin with mailbox separator'; ArgumentInvalid = 'Function arguments are invalid'; MailMessageNoInvalid = 'Message number is invalid, must be greater than 0'; MailMessageUidInvalid = 'Message UID is invalid, must be numeric and greater than 0'; ConnectionStateInvalid = 'The command is not valid in this state'; const IMAP_OK = 10; IMAP_NO = 20; IMAP_BAD = 30; IMAP_PREAUTH = 40; IMAP_BYE = 50; IMAP_CONTINUE = 60; MailboxNameInvalidCode = -200; ArgumentInvalidCode = -201; MailMessageNoInvalidCode = -202; MailMessageUidInvalidCode = -203; ConnectionStateInvalidCode = -204; implementation uses clUtils, clCryptMac, clSocket, clSspiAuth, clEncoder {$IFNDEF DELPHIXE2} {$IFDEF DEMO}, Forms, Windows, clCertificate{$ENDIF}; {$ELSE} {$IFDEF DEMO}, Vcl.Forms, Winapi.Windows, clCertificate{$ENDIF}; {$ENDIF} const SetMethodLexem: array[TclSetFlagsMethod] of string = ('', '+', '-'); { TclImap4 } constructor TclImap4.Create(AOwner: TComponent); begin inherited Create(AOwner); FCurrentMailBox := TclImap4MailBoxInfo.Create(); FConnectionState := csNonAuthenticated; FAutoReconnect := False; FIsTaggedCommand := False; FIsFetchCommand := False; FMailBoxSeparator := '/'; end; procedure TclImap4.CloseSession; begin Logout(); end; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} procedure TclImap4.OpenSession; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsDemoDisplayed) and (not IsEncoderDemoDisplayed) and (not IsCertDemoDisplayed) and (not IsMailMessageDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsDemoDisplayed := True; IsEncoderDemoDisplayed := True; IsCertDemoDisplayed := True; IsMailMessageDemoDisplayed := True; {$ENDIF} end; {$ENDIF} WaitResponse([IMAP_OK, IMAP_PREAUTH]); FCommandTag := 0; ExplicitStartTls(); OpenImapSession(); end; procedure TclImap4.Login; begin if (Password <> '') then begin SendTaggedCommand('LOGIN "%s" "%s"', [IMAP_OK], [UserName, Password]); end else begin SendTaggedCommand('LOGIN "%s"', [IMAP_OK], [UserName]); end; end; procedure TclImap4.CramMD5Authenticate; var respLine, challenge: string; begin SendTaggedCommand('AUTHENTICATE CRAM-MD5', [IMAP_CONTINUE]); respLine := Copy(Response.Text, 3, MaxInt); challenge := TclEncoder.Decode(respLine, cmBase64); respLine := UserName + ' ' + HMAC_MD5(challenge, Password); respLine := TclEncoder.EncodeToString(respLine, cmBase64); SendCommandSync(respLine, [IMAP_OK]); end; procedure TclImap4.NtlmAuthenticate; var sspi: TclNtAuthClientSspi; encoder: TclEncoder; buf: TStream; authIdentity: TclAuthIdentity; challenge: string; begin SendTaggedCommand('AUTHENTICATE NTLM', [IMAP_CONTINUE]); sspi := nil; encoder := nil; buf := nil; authIdentity := nil; try sspi := TclNtAuthClientSspi.Create(); encoder := TclEncoder.Create(nil); encoder.SuppressCrlf := True; encoder.EncodeMethod := cmBase64; buf := TMemoryStream.Create(); if (UserName <> '') then begin authIdentity := TclAuthIdentity.Create(UserName, Password); end; while not sspi.GenChallenge('NTLM', buf, Server, authIdentity) do begin buf.Position := 0; challenge := encoder.Encode(buf); SendCommandSync(challenge, [IMAP_CONTINUE]); challenge := system.Copy(Response.Text, 3, MaxInt); buf.Size := 0; encoder.Decode(challenge, buf); buf.Position := 0; end; if (buf.Size > 0) then begin buf.Position := 0; challenge := encoder.Encode(buf); SendCommandSync(challenge, [IMAP_OK]); end; finally authIdentity.Free(); buf.Free(); encoder.Free(); sspi.Free(); end; end; procedure TclImap4.GetCapability(AList: TStrings); const lexem = '* CAPABILITY '; var i: Integer; s: string; begin SendTaggedCommand('CAPABILITY', [IMAP_OK]); AList.Clear(); for i := 0 to Response.Count - 1 do begin s := Response[i]; if (System.Pos(lexem, UpperCase(s)) = 1) then begin s := system.Copy(s, Length(lexem) + 1, Length(s)); s := StringReplace(s, ' ', #13#10, [rfReplaceAll]); AddTextStr(AList, s, False); end; end; end; procedure TclImap4.OAuthAuthenticate; begin SendTaggedCommand('AUTHENTICATE XOAUTH2 %s', [IMAP_OK, IMAP_CONTINUE], [GetOAuthChallenge()]); if (LastResponseCode <> IMAP_OK) then begin SendCommandSync('', [0]); end; end; procedure TclImap4.Authenticate; var list: TStrings; begin list := TStringList.Create(); try GetCapability(list); if (Authorization <> '') and (FindInStrings(list, 'AUTH=XOAUTH2') > -1) and (FindInStrings(list, 'SASL-IR') > -1) then begin OAuthAuthenticate(); end else if FindInStrings(list, 'AUTH=NTLM') > -1 then begin NtlmAuthenticate(); end else if FindInStrings(list, 'AUTH=CRAM-MD5') > -1 then begin CramMD5Authenticate(); end else if SaslOnly then begin RaiseError(AuthMethodInvalid, AuthMethodInvalidCode); end else begin Login(); end; finally list.Free(); end; end; procedure TclImap4.OpenImapSession; begin FCommandTag := 0; if (LastResponseCode = IMAP_OK) then begin if UseSasl then begin Authenticate(); end else begin Login(); end; FConnectionState := csAuthenticated; end else if (LastResponseCode = IMAP_PREAUTH) then begin FConnectionState := csAuthenticated; end; end; function TclImap4.GetNextCommandTag: string; begin Inc(FCommandTag); Result := GetLastCommandTag(); end; procedure TclImap4.SelectMailBox(const AName: string); begin CheckConnection([csAuthenticated, csSelected]); try SendTaggedCommand('SELECT "%s"', [IMAP_OK], [AName]); ParseSelectedMailBox(AName); FConnectionState := csSelected; except on E: EclSocketError do begin FCurrentMailBox.Clear(); FConnectionState := csAuthenticated; raise; end; end; end; procedure TclImap4.SendTaggedCommand(const ACommand: string; const AOkResponses: array of Integer); begin CheckFetchCommand(ACommand); FIsTaggedCommand := True; try SendCommandSync(GetNextCommandTag() + #32 + ACommand, AOkResponses); finally FIsFetchCommand := False; FIsTaggedCommand := False; end; end; procedure TclImap4.CreateMailBox(const AName: string); begin if (Trim(AName) = '') or (Trim(AName)[1] = MailBoxSeparator) then begin RaiseError(MailboxNameInvalid, MailboxNameInvalidCode); end; CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('CREATE "%s"', [IMAP_OK], [AName]); end; procedure TclImap4.DeleteMailBox(const AName: string); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('DELETE "%s"', [IMAP_OK], [AName]); end; procedure TclImap4.RenameMailBox(const ACurrentName, ANewName: string); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('RENAME "%s" "%s"', [IMAP_OK], [ACurrentName, ANewName]); end; procedure TclImap4.GetMailBoxes(AList: TStrings); begin GetMailBoxes(AList, '', '*'); end; procedure TclImap4.GetMailBoxes(AList: TStrings; const AReferenceName, ACriteria: string); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('LIST "' + AReferenceName + '" "' + ACriteria + '"', [IMAP_OK]); ParseMailBoxes(AList, 'LIST'); end; function TclImap4.GetMessageFlags(AIndex: Integer): TclMailMessageFlags; begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('FETCH %d (FLAGS)', [IMAP_OK], [AIndex]); Result := ParseMessageFlags(IntToStr(AIndex), False); FCurrentMessage := AIndex; end; function TclImap4.AppendMessage(const AMailBoxName: string; AFlags: TclMailMessageFlags): string; begin Result := AppendMessage(AMailBoxName, MailMessage, AFlags); end; function TclImap4.AppendMessage(const AMailBoxName: string; AMessage: TclMailMessage; AFlags: TclMailMessageFlags): string; begin if (AMessage = nil) then begin RaiseError(ArgumentInvalid, ArgumentInvalidCode); end; Result := AppendMessage(AMailBoxName, AMessage.MessageSource, AFlags); end; procedure TclImap4.CopyMessage(AIndex: Integer; const ADestMailBox: string); begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('COPY %d "%s"', [IMAP_OK], [AIndex, ADestMailBox]); FCurrentMessage := AIndex; end; procedure TclImap4.CopyMessages(const AMessageSet, ADestMailBox: string); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('COPY %s "%s"', [IMAP_OK], [AMessageSet, ADestMailBox]); FCurrentMessage := 0; end; procedure TclImap4.DeleteMessage(AIndex: Integer); begin SetMessageFlags(AIndex, fmAdd, [mfDeleted]); end; procedure TclImap4.ParseMailBoxes(AList: TStrings; const ACommand: string); var i: Integer; s: string; begin AList.Clear(); for i := 0 to Response.Count - 1 do begin if (System.Pos(Format('* %s ', [UpperCase(ACommand)]), UpperCase(Response[i])) = 1) then begin ParseMailboxInfo(Response[i], FMailBoxSeparator, s); if (s <> '') then begin AList.Add(s); end; end; end; end; procedure TclImap4.GetMailBoxes(AList: TStrings; const ACriteria: string); begin GetMailBoxes(AList, '', ACriteria); end; function TclImap4.GetMessageSize(AIndex: Integer): Int64; begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('FETCH %d (RFC822.SIZE)', [IMAP_OK], [AIndex]); Result := ParseMessageSize(IntToStr(AIndex), False); FCurrentMessage := AIndex; end; procedure TclImap4.GetSubscribedMailBoxes(AList: TStrings; const ACriteria: string); begin GetSubscribedMailBoxes(AList, '', ACriteria); end; procedure TclImap4.RetrieveHeader(AIndex: Integer; AMessage: TclMailMessage); begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('FETCH %d (BODY.PEEK[HEADER])', [IMAP_OK], [AIndex]); ParseMessage(IntToStr(AIndex), AMessage, False, True); FCurrentMessage := AIndex; end; procedure TclImap4.RetrieveHeader(AIndex: Integer); begin RetrieveHeader(AIndex, MailMessage); end; procedure TclImap4.RetrieveMessage(AIndex: Integer); begin RetrieveMessage(AIndex, MailMessage); end; procedure TclImap4.RetrieveMessage(AIndex: Integer; AMessage: TclMailMessage); begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); FTotalBytesToReceive := 0; if Assigned(OnProgress) then begin FTotalBytesToReceive := GetMessageSize(AIndex); end; try SendTaggedCommand('FETCH %d (BODY.PEEK[])', [IMAP_OK], [AIndex]); finally FTotalBytesToReceive := 0; end; ParseMessage(IntToStr(AIndex), AMessage, False, False); FCurrentMessage := AIndex; end; procedure TclImap4.WaitResponse(const AOkResponses: array of Integer); begin if (FTotalBytesToReceive > 0) then begin Connection.OnProgress := DoDataProgress; Connection.InitProgress(0, FTotalBytesToReceive); end; try inherited WaitResponse(AOkResponses); DoProgress(FTotalBytesToReceive, FTotalBytesToReceive); finally Connection.OnProgress := nil; end; end; procedure TclImap4.DoDataProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); begin DoProgress(ABytesProceed, ATotalBytes); end; procedure TclImap4.SearchMessages(const ASearchCriteria: string; AMessageList: TStrings); begin CheckConnection([csSelected]); SendTaggedCommand('SEARCH %s', [IMAP_OK], [ASearchCriteria]); ParseSearchMessages(AMessageList); end; procedure TclImap4.SetMessageFlags(AIndex: Integer; AMethod: TclSetFlagsMethod; AFlags: TclMailMessageFlags); var cmd: string; begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); cmd := GetStrByImapMessageFlags(AFlags); SendTaggedCommand('STORE %d %sFLAGS.SILENT (%s)', [IMAP_OK], [AIndex, SetMethodLexem[AMethod], cmd]); FCurrentMessage := AIndex; end; procedure TclImap4.SubscribeMailBox(const AName: string); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('SUBSCRIBE "%s"', [IMAP_OK], [AName]); end; procedure TclImap4.UnsubscribeMailBox(const AName: string); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('UNSUBSCRIBE "%s"', [IMAP_OK], [AName]); end; procedure TclImap4.SetAutoReconnect(const Value: Boolean); begin if (FAutoReconnect <> Value) then begin FAutoReconnect := Value; Changed(); end; end; function TclImap4.GetResponseCode(const AResponse: string): Integer; var s: string; ind: Integer; begin Result := SOCKET_WAIT_RESPONSE; if (AResponse = '') then Exit; if (not FIsFetchCommand) and ((System.Pos('+ ', AResponse) = 1) or ('+' = Trim(AResponse))) then begin Result := IMAP_CONTINUE; Exit; end; ind := System.Pos(' ', AResponse); if (ind < 2) or (ind > Length(AResponse) - 1) then Exit; s := Trim(System.Copy(AResponse, ind + 1, Length(AResponse))); ind := System.Pos(' ', s); if (ind < 1) then begin ind := Length(s); end; if FIsTaggedCommand and (System.Pos(UpperCase(LastCommandTag), UpperCase(AResponse)) <> 1) then Exit; s := Trim(System.Copy(s, 1, ind)); if (s = 'OK') then begin Result := IMAP_OK; end else if (s = 'NO') then begin Result := IMAP_NO; end else if (s = 'BAD') then begin Result := IMAP_BAD; end else if (s = 'PREAUTH') then begin Result := IMAP_PREAUTH; end else if (s = 'BYE') then begin Result := IMAP_BYE; end; end; procedure TclImap4.GetSubscribedMailBoxes(AList: TStrings); begin GetSubscribedMailBoxes(AList, '', '*'); end; procedure TclImap4.GetSubscribedMailBoxes(AList: TStrings; const AReferenceName, ACriteria: string); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('LSUB "' + AReferenceName + '" "' + ACriteria + '"', [IMAP_OK]); ParseMailBoxes(AList, 'LSUB'); end; class procedure TclImap4.RaiseError(const AMessage: string; AErrorCode: Integer); begin raise EclImap4Error.Create(AMessage, AErrorCode); end; procedure TclImap4.Logout; begin if (ConnectionState in [csAuthenticated, csSelected]) then begin try SendTaggedCommand('LOGOUT', [IMAP_OK]); except on EclSocketError do ; end; end; FConnectionState := csNonAuthenticated; end; procedure TclImap4.CheckConnection(AStates: array of TclImap4ConnectionState); begin if not IsInState(ConnectionState, AStates) then begin if AutoReconnect then begin if not Active then begin Open(); end else begin OpenImapSession(); end; end else begin RaiseError(ConnectionStateInvalid, ConnectionStateInvalidCode); end; end; end; destructor TclImap4.Destroy; begin FCurrentMailBox.Free(); inherited Destroy(); end; procedure TclImap4.ParseSelectedMailBox(const AName: string); function GetLexemPos(const ALexem, AText: string; var APos: Integer): Boolean; begin APos := System.Pos(ALexem, AText); Result := APos > 0; end; var i, ind: Integer; responseStr: string; begin CurrentMailBox.Clear(); CurrentMailBox.Name := AName; for i := 0 to Response.Count - 1 do begin responseStr := UpperCase(Response[i]); if GetLexemPos('EXISTS', responseStr, ind) then begin CurrentMailBox.ExistsMessages := StrToIntDef(Trim(System.Copy(responseStr, 3, ind - 3)), 0); end else if not GetLexemPos('FLAGS', responseStr, ind) and GetLexemPos('RECENT', responseStr, ind) then begin CurrentMailBox.RecentMessages := StrToIntDef(Trim(System.Copy(responseStr, 3, ind - 3)), 0); end else if GetLexemPos('[UNSEEN', responseStr, ind) then begin CurrentMailBox.FirstUnseen := StrToIntDef(Trim(System.Copy(responseStr, ind + Length('[UNSEEN'), System.Pos(']', responseStr) - ind - Length('[UNSEEN'))), 0); end else if GetLexemPos('[READ-WRITE]', responseStr, ind) then begin CurrentMailBox.ReadOnly := False; end else if GetLexemPos('[READ-ONLY]', responseStr, ind) then begin CurrentMailBox.ReadOnly := True; end else if not GetLexemPos('[PERMANENTFLAGS', responseStr, ind) and GetLexemPos('FLAGS', responseStr, ind) then begin CurrentMailBox.Flags := GetImapMessageFlagsByStr(System.Copy(responseStr, ind, clUtils.TextPos(')', responseStr, ind) - ind)); end else if GetLexemPos('[PERMANENTFLAGS', responseStr, ind) then begin CurrentMailBox.ChangeableFlags := GetImapMessageFlagsByStr(System.Copy(responseStr, ind, clUtils.TextPos(')', responseStr, ind) - ind)); end; if GetLexemPos('[UIDVALIDITY', responseStr, ind) then begin ind := ind + Length('[UIDVALIDITY'); CurrentMailBox.UIDValidity := Trim(System.Copy(responseStr, ind, clUtils.TextPos(']', responseStr, ind) - ind)); end; end; end; procedure TclImap4.ParseSearchMessages(AList: TStrings); const lexem = '* SEARCH'; var i: Integer; begin AList.Clear(); for i := 0 to Response.Count - 1 do begin if (System.Pos(lexem, UpperCase(Response[i])) = 1) then begin AList.Text := Trim(StringReplace( System.Copy(Response[i], Length(lexem) + 1, MaxInt), ' ', #13#10, [rfReplaceAll])); Break; end; end; end; function TclImap4.ParseMessageSize(const AMessageId: string; AIsUid: Boolean): Int64; var i, ind: Integer; responseStr: string; begin Result := 0; for i := 0 to Response.Count - 1 do begin responseStr := UpperCase(Response[i]); if (GetMessageId('FETCH', responseStr, AIsUid) = AMessageId) then begin ind := System.Pos('RFC822.SIZE ', responseStr); if (ind > 0) then begin Result := StrToInt64Def(Trim(ExtractNumeric(responseStr, ind + Length('RFC822.SIZE '))), 0); end; Break; end; end; end; function TclImap4.ParseMessageFlags(const AMessageId: string; AIsUid: Boolean): TclMailMessageFlags; var i, ind: Integer; responseStr: string; begin Result := []; for i := 0 to Response.Count - 1 do begin responseStr := UpperCase(Response[i]); if (GetMessageId('FETCH', responseStr, AIsUid) = AMessageId) then begin ind := System.Pos('FLAGS', responseStr); if (ind > 0) then begin Result := GetImapMessageFlagsByStr(System.Copy(responseStr, ind, clUtils.TextPos(')', responseStr, ind) - ind)); end; Break; end; end; end; procedure TclImap4.PurgeMessages; begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('CLOSE', [IMAP_OK]); FCurrentMailBox.Clear(); FConnectionState := csAuthenticated; end; procedure TclImap4.ParseMessage(const AMessageId: string; AMessage: TclMailMessage; AIsUid, AIsHeader: Boolean); var i: Integer; msgSize, size: Int64; begin if (Response.Count < 4) then Exit; while (Response.Count > 0) do begin if (GetMessageId('FETCH', Response[0], AIsUid) = AMessageId) then Break; Response.Delete(0); end; msgSize := ExtractMessageSize(Response[0]); if (msgSize = 0) then Exit; Response.Delete(0); i := 0; size := 0; while (i < Response.Count) do begin size := size + Length(Response[i]) + Length(#13#10); if (size <= msgSize) then begin Inc(i); end else if (Length(Response[i]) > 0) and ((size - msgSize) < (Length(Response[i]) + Length(#13#10))) then begin Response[i] := system.Copy(Response[i], 1, Length(Response[i]) + Length(#13#10) - (size - msgSize)); Inc(i); end else begin Response.Delete(i); end; end; if (AMessage <> nil) then begin if (AIsHeader) then begin AMessage.HeaderSource := Response; end else begin AMessage.MessageSource := Response; end; end; end; function TclImap4.GetMessageId(const ACommand, AResponseLine: string; AIsUid: Boolean): string; var ind: Integer; begin ind := System.Pos(#32 + ACommand, UpperCase(AResponseLine)); Result := '0'; if (ind < 4) then Exit; if AIsUid then begin ind := clUtils.TextPos('UID ', AResponseLine, ind); if (ind > 0) then begin Result := ExtractNumeric(AResponseLine, ind + Length('UID ')); end; end else begin Result := IntToStr(StrToIntDef(Trim(System.Copy(AResponseLine, 2, ind - 1)), 0)); end; end; procedure TclImap4.CheckMessageValid(AIndex: Integer); begin if (AIndex < 1) then begin RaiseError(MailMessageNoInvalid, MailMessageNoInvalidCode); end; end; function TclImap4.GetLastCommandTag: string; begin Result := Format('a%.4d', [FCommandTag]); end; procedure TclImap4.SendKeepAlive; begin Noop(); end; procedure TclImap4.CheckFetchCommand(const ACommand: string); begin FIsFetchCommand := (System.Pos('FETCH ', UpperCase(ACommand)) > 0); end; procedure TclImap4.SendTaggedCommand(const ACommand: string; const AOkResponses: array of Integer; const Args: array of const); begin CheckFetchCommand(ACommand); FIsTaggedCommand := True; try SendCommandSync(GetNextCommandTag() + #32 + ACommand, AOkResponses, Args); finally FIsFetchCommand := False; FIsTaggedCommand := False; end; end; procedure TclImap4.UidDeleteMessage(const AUid: string); begin UidSetMessageFlags(AUid, fmAdd, [mfDeleted]); end; procedure TclImap4.UidCopyMessage(const AUid, ADestMailBox: string); begin CheckUidValid(AUid); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('UID COPY %s "%s"', [IMAP_OK], [AUid, ADestMailBox]); FCurrentMessage := 0; end; procedure TclImap4.UidCopyMessages(const AMessageSet, ADestMailBox: string); begin CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('UID COPY %s "%s"', [IMAP_OK], [AMessageSet, ADestMailBox]); FCurrentMessage := 0; end; procedure TclImap4.UidSetMessageFlags(const AUid: string; AMethod: TclSetFlagsMethod; AFlags: TclMailMessageFlags); var cmd: string; begin CheckUidValid(AUid); CheckConnection([csAuthenticated, csSelected]); cmd := GetStrByImapMessageFlags(AFlags); SendTaggedCommand('UID STORE %s %sFLAGS.SILENT (%s)', [IMAP_OK], [AUid, SetMethodLexem[AMethod], cmd]); FCurrentMessage := 0; end; function TclImap4.UidGetMessageFlags(const AUid: string): TclMailMessageFlags; begin CheckUidValid(AUid); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('UID FETCH %s (FLAGS)', [IMAP_OK], [AUid]); Result := ParseMessageFlags(AUid, True); FCurrentMessage := 0; end; function TclImap4.UidGetMessageSize(const AUid: string): Int64; begin CheckUidValid(AUid); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('UID FETCH %s (RFC822.SIZE)', [IMAP_OK], [AUid]); Result := ParseMessageSize(AUid, True); FCurrentMessage := 0; end; procedure TclImap4.UidRetrieveMessage(const AUid: string; AMessage: TclMailMessage); begin CheckUidValid(AUid); CheckConnection([csAuthenticated, csSelected]); FTotalBytesToReceive := 0; if Assigned(OnProgress) then begin FTotalBytesToReceive := UidGetMessageSize(AUid); end; try SendTaggedCommand('UID FETCH %s (BODY.PEEK[])', [IMAP_OK], [AUid]); finally FTotalBytesToReceive := 0; end; ParseMessage(AUid, AMessage, True, False); FCurrentMessage := 0; end; procedure TclImap4.UidRetrieveHeader(const AUid: string; AMessage: TclMailMessage); begin CheckUidValid(AUid); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('UID FETCH %s (BODY.PEEK[HEADER])', [IMAP_OK], [AUid]); ParseMessage(AUid, AMessage, True, True); FCurrentMessage := 0; end; procedure TclImap4.CheckUidValid(const AUid: string); begin if (AUid = '') then begin RaiseError(MailMessageUidInvalid, MailMessageUidInvalidCode); end; if StrToIntDef(AUid, 0) < 1 then begin RaiseError(MailMessageUidInvalid, MailMessageUidInvalidCode); end; end; procedure TclImap4.UidSearchMessages(const ASearchCriteria: string; AMessageList: TStrings); begin CheckConnection([csSelected]); SendTaggedCommand('UID SEARCH %s', [IMAP_OK], [ASearchCriteria]); ParseSearchMessages(AMessageList); end; function TclImap4.GetMessageUid(AIndex: Integer): string; begin CheckMessageValid(AIndex); CheckConnection([csAuthenticated, csSelected]); SendTaggedCommand('FETCH %d (UID)', [IMAP_OK], [AIndex]); Result := ParseMessageUid(AIndex); FCurrentMessage := AIndex; end; function TclImap4.ParseMessageUid(AIndex: Integer): string; begin if (Response.Count > 0) and (GetMessageId('FETCH', Response[0], False) = IntToStr(AIndex)) then begin Result := GetMessageId('FETCH', Response[0], True); end else begin Result := ''; end; end; function TclImap4.AppendMessage(const AMailBoxName: string; AMessage: TStrings; AFlags: TclMailMessageFlags): string; var flags: string; begin if (Trim(AMailBoxName) = '') then begin RaiseError(ArgumentInvalid, ArgumentInvalidCode); end; CheckConnection([csAuthenticated, csSelected]); flags := GetStrByImapMessageFlags(AFlags); if (flags <> '') then begin flags := Format('(%s) ', [flags]); end; SendTaggedCommand('APPEND "%s" %s{%d}', [IMAP_CONTINUE], [AMailBoxName, flags, Length(AMessage.Text)]); SendMultipleLines(AMessage, #13#10); WaitResponse([IMAP_OK]); Result := ExtractAppendUID(Response[0]); end; function TclImap4.ExtractAppendUID(const AResponse: string): string; var ind: Integer; s: string; begin Result := ''; ind := clUtils.TextPos('APPENDUID ', UpperCase(AResponse)); if (ind > 0) then begin s := system.Copy(AResponse, ind + Length('APPENDUID '), 1000); if (WordCount(s, [#32, ']']) > 1) then begin Result := Trim(ExtractWord(2, s, [#32, ']'])); end; end; end; procedure TclImap4.ExamineMailBox(const AName: string); begin CheckConnection([csAuthenticated, csSelected]); try SendTaggedCommand('EXAMINE "%s"', [IMAP_OK], [AName]); ParseSelectedMailBox(AName); FConnectionState := csSelected; except on E: EclSocketError do begin FCurrentMailBox.Clear(); FConnectionState := csAuthenticated; raise; end; end; end; procedure TclImap4.Noop; begin SendTaggedCommand('NOOP', [IMAP_OK]); end; procedure TclImap4.StartTls; begin SendTaggedCommand('STARTTLS', [IMAP_OK]); inherited StartTls(); end; function TclImap4.GetDefaultPort: Integer; begin Result := DefaultImapPort; end; end.
unit bsEditGroupName; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Admin" // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Admin/bsEditGroupName.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Администратор::Admin::Admin::Admin::TbsEditGroupName // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If defined(Admin)} uses l3Interfaces, AdminInterfaces, l3ProtoObject ; {$IfEnd} //Admin {$If defined(Admin)} type TbsEditGroupName = class(Tl3ProtoObject, IbsEditGroupName) private // private fields f_Name : Il3CString; protected // realized methods function Get_Name: Il3CString; procedure Set_Name(const aValue: Il3CString); protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } public // public methods constructor Create(const aName: Il3CString); reintroduce; class function Make(const aName: Il3CString): IbsEditGroupName; reintroduce; end;//TbsEditGroupName {$IfEnd} //Admin implementation {$If defined(Admin)} // start class TbsEditGroupName constructor TbsEditGroupName.Create(const aName: Il3CString); //#UC START# *49EEFC1B007D_49EEFBA6010A_var* //#UC END# *49EEFC1B007D_49EEFBA6010A_var* begin //#UC START# *49EEFC1B007D_49EEFBA6010A_impl* inherited Create; f_Name := aName; //#UC END# *49EEFC1B007D_49EEFBA6010A_impl* end;//TbsEditGroupName.Create class function TbsEditGroupName.Make(const aName: Il3CString): IbsEditGroupName; var l_Inst : TbsEditGroupName; begin l_Inst := Create(aName); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TbsEditGroupName.Get_Name: Il3CString; //#UC START# *49EEFAAB0318_49EEFBA6010Aget_var* //#UC END# *49EEFAAB0318_49EEFBA6010Aget_var* begin //#UC START# *49EEFAAB0318_49EEFBA6010Aget_impl* Result := f_Name; //#UC END# *49EEFAAB0318_49EEFBA6010Aget_impl* end;//TbsEditGroupName.Get_Name procedure TbsEditGroupName.Set_Name(const aValue: Il3CString); //#UC START# *49EEFAAB0318_49EEFBA6010Aset_var* //#UC END# *49EEFAAB0318_49EEFBA6010Aset_var* begin //#UC START# *49EEFAAB0318_49EEFBA6010Aset_impl* f_Name := aValue; //#UC END# *49EEFAAB0318_49EEFBA6010Aset_impl* end;//TbsEditGroupName.Set_Name procedure TbsEditGroupName.Cleanup; //#UC START# *479731C50290_49EEFBA6010A_var* //#UC END# *479731C50290_49EEFBA6010A_var* begin //#UC START# *479731C50290_49EEFBA6010A_impl* f_Name := nil; inherited Cleanup; //#UC END# *479731C50290_49EEFBA6010A_impl* end;//TbsEditGroupName.Cleanup {$IfEnd} //Admin end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { { Rev 1.5 11/27/2004 8:27:14 PM JPMugaas { Fix for compiler errors. } { { Rev 1.4 11/27/04 2:56:40 AM RLebeau { Added support for overloaded version of LoginSASL(). { { Added GetDisplayName() method to TIdSASLListEntry, and FindSASL() method to { TIdSASLEntries. } { { Rev 1.3 10/26/2004 10:55:32 PM JPMugaas { Updated refs. } { Rev 1.2 6/11/2004 9:38:38 AM DSiders Added "Do not Localize" comments. } { { Rev 1.1 2004.02.03 5:45:50 PM czhower { Name changes } { { Rev 1.0 1/25/2004 3:09:54 PM JPMugaas { New collection class for SASL mechanism processing. } unit IdSASLCollection; interface uses IdBaseComponent, IdCoder, IdException, IdSASL, IdSys, IdTCPConnection, IdObjs; type TIdSASLListEntry = class(TIdCollectionItem) protected FSASL : TIdSASL; function GetDisplayName: String; override; public procedure Assign(Source: TIdPersistent); override; published property SASL : TIdSASL read FSASL write FSASL; end; TIdSASLEntries = class ( TIdOwnedCollection ) protected function GetItem ( Index: Integer ) : TIdSASLListEntry; procedure SetItem ( Index: Integer; const Value: TIdSASLListEntry ); public constructor Create ( AOwner : TIdPersistent ); reintroduce; function Add: TIdSASLListEntry; function LoginSASL(const ACmd: String; const AOkReplies, AContinueReplies: array of string; AClient : TIdTCPConnection; ACapaReply : TIdStrings; const AAuthString : String = 'AUTH'): Boolean; overload; {Do not Localize} function LoginSASL(const ACmd: String; const AServiceName: String; const AOkReplies, AContinueReplies: array of string; AClient : TIdTCPConnection; ACapaReply : TIdStrings; const AAuthString : String = 'AUTH'): Boolean; overload; {Do not Localize} function ParseCapaReply(ACapaReply: TIdStrings; const AAuthString: String = 'AUTH') : TIdStrings; {do not localize} function FindSASL(const AServiceName: String): TIdSASL; function Insert(Index: Integer): TIdSASLListEntry; procedure RemoveByComp(AComponent : TIdNativeComponent); function IndexOfComp(AItem : TIdSASL): Integer; property Items [ Index: Integer ] : TIdSASLListEntry read GetItem write SetItem; default; end; EIdSASLException = class(EIdException); EIdEmptySASLList = class(EIdSASLException); EIdSASLNotSupported = class(EIdSASLException); EIdSASLMechNeeded = class(EIdSASLException); // for use in implementing components TAuthenticationType = (atNone, atUserPass, atAPOP, atSASL); TAuthenticationTypes = set of TAuthenticationType; EIdSASLMsg = class(EIdException); EIdSASLNotValidForProtocol = class(EIdSASLMsg); implementation uses IdCoderMIME, IdGlobal, IdGlobalProtocols; { TIdSASLListEntry } procedure TIdSASLListEntry.Assign(Source: TIdPersistent); begin if Source is TIdSASLListEntry then begin FSASL := TIdSASLListEntry(Source).SASL; end else begin inherited Assign(Source); end; end; function TIdSASLListEntry.GetDisplayName: String; begin if FSASL <> nil then begin Result := FSASL.ServiceName; end else begin Result := inherited GetDisplayName; end; end; { TIdSASLEntries } function CheckStrFail(const AStr : String; const AOk, ACont: array of string) : Boolean; begin Result := (PosInStrArray(AStr, AOk) = -1) and (PosInStrArray(AStr, ACont) = -1); end; function PerformSASLLogin(const ACmd: String; ASASL: TIdSASL; AEncoder: TIdEncoder; ADecoder: TIdDecoder; const AOkReplies, AContinueReplies: array of string; AClient : TIdTCPConnection): Boolean; var S: String; begin Result := False; AClient.SendCmd(ACmd+' '+ASASL.ServiceName, []);//[334, 504]); if CheckStrFail(AClient.LastCmdResult.Code, AOkReplies, AContinueReplies) then begin Exit; // this mechanism is not supported end; if (PosInStrArray(AClient.LastCmdResult.Code, AOkReplies) > -1) then begin Result := True; Exit; // we've authenticated successfully :) end; S := ADecoder.DecodeString(Sys.TrimRight(AClient.LastCmdResult.Text.Text)); S := ASASL.StartAuthenticate(S); AClient.SendCmd(AEncoder.Encode(S)); if CheckStrFail(AClient.LastCmdResult.Code, AOkReplies, AContinueReplies) then begin ASASL.FinishAuthenticate; Exit; end; while PosInStrArray(AClient.LastCmdResult.Code, AContinueReplies) > -1 do begin S := ADecoder.DecodeString(Sys.TrimRight(AClient.LastCmdResult.Text.Text)); S := ASASL.ContinueAuthenticate(S); AClient.SendCmd(AEncoder.Encode(S)); if CheckStrFail(AClient.LastCmdResult.Code, AOkReplies, AContinueReplies) then begin ASASL.FinishAuthenticate; Exit; end; end; Result := (PosInStrArray(AClient.LastCmdResult.Code, AOkReplies) > -1); ASASL.FinishAuthenticate; end; function TIdSASLEntries.Add: TIdSASLListEntry; begin Result := TIdSASLListEntry ( inherited Add ); end; constructor TIdSASLEntries.Create(AOwner: TIdPersistent); begin inherited Create ( AOwner, TIdSASLListEntry ); end; function TIdSASLEntries.GetItem(Index: Integer): TIdSASLListEntry; begin Result := TIdSASLListEntry ( inherited Items [ Index ] ); end; function TIdSASLEntries.IndexOfComp(AItem: TIdSASL): Integer; begin for Result := 0 to Count -1 do begin if Items[Result].SASL = AItem then begin Exit; end; end; Result := -1; end; function TIdSASLEntries.Insert(Index: Integer): TIdSASLListEntry; begin Result := TIdSASLListEntry( inherited Insert(Index) ); end; function TIdSASLEntries.LoginSASL(const ACmd: String; const AOkReplies, AContinueReplies: array of string; AClient: TIdTCPConnection; ACapaReply: TIdStrings; const AAuthString: String): Boolean; var i : Integer; LE : TIdEncoderMIME; LD : TIdDecoderMIME; LSupportedSASL : TIdStrings; LSASLList: TIdList; LSASL : TIdSASL; begin Result := False; LSASLList := TIdList.Create; try LSupportedSASL := ParseCapaReply(ACapaReply, AAuthString); try //create a list of supported mechanisms we also support for i := Count-1 downto 0 do begin LSASL := Items[i].SASL; if LSASL <> nil then begin if LSupportedSASL <> nil then begin if not LSASL.IsAuthProtocolAvailable(LSupportedSASL) then begin Continue; end; end; if LSASLList.IndexOf(LSASL) = -1 then begin LSASLList.Add(LSASL); end; end; end; if LSASLList.Count > 0 then begin //now do it LE := TIdEncoderMIME.Create(nil); try LD := TIdDecoderMIME.Create(nil); try for i := 0 to LSASLList.Count-1 do begin Result := PerformSASLLogin(ACmd, TIdSASL(LSASLList.Items[i]), LE, LD, AOkReplies, AContinueReplies, AClient); if Result then begin Exit; end; end; finally Sys.FreeAndNil(LD); end; finally Sys.FreeAndNil(LE); end; end; finally Sys.FreeAndNil(LSupportedSASL); end; finally Sys.FreeAndNil(LSASLList); end; end; function TIdSASLEntries.LoginSASL(const ACmd: String; const AServiceName: String; const AOkReplies, AContinueReplies: array of string; AClient: TIdTCPConnection; ACapaReply: TIdStrings; const AAuthString: String): Boolean; var LE : TIdEncoderMIME; LD : TIdDecoderMIME; LSupportedSASL : TIdStrings; LSASL : TIdSASL; begin // if (AuthenticationType = atSASL) and ((SASLMechanisms=nil) or (SASLMechanisms.Count = 0)) then begin // raise EIdSASLMechNeeded.Create(RSASLRequired); // end; Result := False; LSupportedSASL := ParseCapaReply(ACapaReply, AAuthString); try if LSupportedSASL <> nil then begin if LSupportedSASL.IndexOf(AServiceName) = -1 then begin Exit; end; end; //determine if we also support the mechanism LSASL := FindSASL(AServiceName); if LSASL <> nil then begin //now do it LE := TIdEncoderMIME.Create(nil); try LD := TIdDecoderMIME.Create(nil); try Result := PerformSASLLogin(ACmd, LSASL, LE, LD, AOkReplies, AContinueReplies, AClient); if not Result then begin AClient.RaiseExceptionForLastCmdResult; end; finally Sys.FreeAndNil(LD); end; finally Sys.FreeAndNil(LE); end; end; finally Sys.FreeAndNil(LSupportedSASL); end; end; function TIdSASLEntries.ParseCapaReply(ACapaReply: TIdStrings; const AAuthString: String): TIdStrings; {do not localize} var i: Integer; s, LPrefix: string; LEntry : String; begin if ACapaReply = nil then begin Result := nil; Exit; end; Result := TIdStringList.Create; try for i := 0 to ACapaReply.Count - 1 do begin s := Sys.UpperCase(ACapaReply[i]); LPrefix := Copy(s, 1, Length(AAuthString)+1); if TextIsSame(LPrefix, AAuthString+' ') or TextIsSame(LPrefix, AAuthString+'=') then {Do not Localize} begin s := Copy(s, Length(LPrefix), MaxInt); s := Sys.StringReplace(s, '=', ' '); {Do not Localize} while Length(s) > 0 do begin LEntry := Fetch(s, ' '); {Do not Localize} if LEntry <> '' then begin if Result.IndexOf(LEntry) = -1 then begin Result.Add(LEntry); end; end; end; end; end; except Sys.FreeAndNil(Result); raise; end; end; function TIdSASLEntries.FindSASL(const AServiceName: String): TIdSASL; var i: Integer; LEntry: TIdSASLListEntry; begin Result := nil; For i := 0 to Count-1 do begin LEntry := Items[i]; if LEntry.SASL <> nil then begin if TextIsSame(LEntry.SASL.ServiceName, AServiceName) then begin Result := LEntry.SASL; Exit; end; end; end; end; procedure TIdSASLEntries.RemoveByComp(AComponent: TIdNativeComponent); var i : Integer; begin for i := Count-1 downto 0 do begin if Items[i].SASL = AComponent then begin Delete(i); end; end; end; procedure TIdSASLEntries.SetItem(Index: Integer; const Value: TIdSASLListEntry); begin inherited SetItem ( Index, Value ); end; end.
unit relative_pointer_unstable_v1_protocol; {$mode objfpc} {$H+} {$interfaces corba} interface uses Classes, Sysutils, ctypes, wayland_util, wayland_client_core, wayland_protocol; type Pzwp_relative_pointer_manager_v1 = Pointer; Pzwp_relative_pointer_v1 = Pointer; Pzwp_relative_pointer_manager_v1_listener = ^Tzwp_relative_pointer_manager_v1_listener; Tzwp_relative_pointer_manager_v1_listener = record end; Pzwp_relative_pointer_v1_listener = ^Tzwp_relative_pointer_v1_listener; Tzwp_relative_pointer_v1_listener = record relative_motion : procedure(data: Pointer; AZwpRelativePointerV1: Pzwp_relative_pointer_v1; AUtimeHi: DWord; AUtimeLo: DWord; ADx: Longint{24.8}; ADy: Longint{24.8}; ADxUnaccel: Longint{24.8}; ADyUnaccel: Longint{24.8}); cdecl; end; TZwpRelativePointerManagerV1 = class; TZwpRelativePointerV1 = class; IZwpRelativePointerManagerV1Listener = interface ['IZwpRelativePointerManagerV1Listener'] end; IZwpRelativePointerV1Listener = interface ['IZwpRelativePointerV1Listener'] procedure zwp_relative_pointer_v1_relative_motion(AZwpRelativePointerV1: TZwpRelativePointerV1; AUtimeHi: DWord; AUtimeLo: DWord; ADx: Longint{24.8}; ADy: Longint{24.8}; ADxUnaccel: Longint{24.8}; ADyUnaccel: Longint{24.8}); end; TZwpRelativePointerManagerV1 = class(TWLProxyObject) private const _DESTROY = 0; const _GET_RELATIVE_POINTER = 1; public destructor Destroy; override; function GetRelativePointer(APointer: TWlPointer; AProxyClass: TWLProxyObjectClass = nil {TZwpRelativePointerV1}): TZwpRelativePointerV1; function AddListener(AIntf: IZwpRelativePointerManagerV1Listener): LongInt; end; TZwpRelativePointerV1 = class(TWLProxyObject) private const _DESTROY = 0; public destructor Destroy; override; function AddListener(AIntf: IZwpRelativePointerV1Listener): LongInt; end; var zwp_relative_pointer_manager_v1_interface: Twl_interface; zwp_relative_pointer_v1_interface: Twl_interface; implementation var vIntf_zwp_relative_pointer_manager_v1_Listener: Tzwp_relative_pointer_manager_v1_listener; vIntf_zwp_relative_pointer_v1_Listener: Tzwp_relative_pointer_v1_listener; destructor TZwpRelativePointerManagerV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; function TZwpRelativePointerManagerV1.GetRelativePointer(APointer: TWlPointer; AProxyClass: TWLProxyObjectClass = nil {TZwpRelativePointerV1}): TZwpRelativePointerV1; var id: Pwl_proxy; begin id := wl_proxy_marshal_constructor(FProxy, _GET_RELATIVE_POINTER, @zwp_relative_pointer_v1_interface, nil, APointer.Proxy); if AProxyClass = nil then AProxyClass := TZwpRelativePointerV1; Result := TZwpRelativePointerV1(AProxyClass.Create(id)); if not AProxyClass.InheritsFrom(TZwpRelativePointerV1) then Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TZwpRelativePointerV1]); end; function TZwpRelativePointerManagerV1.AddListener(AIntf: IZwpRelativePointerManagerV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zwp_relative_pointer_manager_v1_Listener, @FUserDataRec); end; destructor TZwpRelativePointerV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; function TZwpRelativePointerV1.AddListener(AIntf: IZwpRelativePointerV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zwp_relative_pointer_v1_Listener, @FUserDataRec); end; procedure zwp_relative_pointer_v1_relative_motion_Intf(AData: PWLUserData; Azwp_relative_pointer_v1: Pzwp_relative_pointer_v1; AUtimeHi: DWord; AUtimeLo: DWord; ADx: Longint{24.8}; ADy: Longint{24.8}; ADxUnaccel: Longint{24.8}; ADyUnaccel: Longint{24.8}); cdecl; var AIntf: IZwpRelativePointerV1Listener; begin if AData = nil then Exit; AIntf := IZwpRelativePointerV1Listener(AData^.ListenerUserData); AIntf.zwp_relative_pointer_v1_relative_motion(TZwpRelativePointerV1(AData^.PascalObject), AUtimeHi, AUtimeLo, ADx, ADy, ADxUnaccel, ADyUnaccel); end; const pInterfaces: array[0..9] of Pwl_interface = ( (nil), (nil), (nil), (nil), (nil), (nil), (nil), (nil), (@zwp_relative_pointer_v1_interface), (@wl_pointer_interface) ); zwp_relative_pointer_manager_v1_requests: array[0..1] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'get_relative_pointer'; signature: 'no'; types: @pInterfaces[8]) ); zwp_relative_pointer_v1_requests: array[0..0] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]) ); zwp_relative_pointer_v1_events: array[0..0] of Twl_message = ( (name: 'relative_motion'; signature: 'uuffff'; types: @pInterfaces[0]) ); initialization Pointer(vIntf_zwp_relative_pointer_v1_Listener.relative_motion) := @zwp_relative_pointer_v1_relative_motion_Intf; zwp_relative_pointer_manager_v1_interface.name := 'zwp_relative_pointer_manager_v1'; zwp_relative_pointer_manager_v1_interface.version := 1; zwp_relative_pointer_manager_v1_interface.method_count := 2; zwp_relative_pointer_manager_v1_interface.methods := @zwp_relative_pointer_manager_v1_requests; zwp_relative_pointer_manager_v1_interface.event_count := 0; zwp_relative_pointer_manager_v1_interface.events := nil; zwp_relative_pointer_v1_interface.name := 'zwp_relative_pointer_v1'; zwp_relative_pointer_v1_interface.version := 1; zwp_relative_pointer_v1_interface.method_count := 1; zwp_relative_pointer_v1_interface.methods := @zwp_relative_pointer_v1_requests; zwp_relative_pointer_v1_interface.event_count := 1; zwp_relative_pointer_v1_interface.events := @zwp_relative_pointer_v1_events; end.
unit l3CacheableBase; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "L3" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/L3/l3CacheableBase.pas" // Начат: 12.04.1998 16:28 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Low Level::L3::l3CoreObjects::Tl3CacheableBase // // Базовый класс для кешируемых объектов // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\L3\l3Define.inc} interface uses l3_Base ; type Tl3CacheableBase = class(Tl3_Base) {* Базовый класс для кешируемых объектов } protected // overridden protected methods {$If not defined(DesignTimeLibrary)} class function IsCacheable: Boolean; override; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } {$IfEnd} //not DesignTimeLibrary end;//Tl3CacheableBase implementation // start class Tl3CacheableBase {$If not defined(DesignTimeLibrary)} class function Tl3CacheableBase.IsCacheable: Boolean; //#UC START# *47A6FEE600FC_46780E690001_var* //#UC END# *47A6FEE600FC_46780E690001_var* begin //#UC START# *47A6FEE600FC_46780E690001_impl* Result := true; //#UC END# *47A6FEE600FC_46780E690001_impl* end;//Tl3CacheableBase.IsCacheable {$IfEnd} //not DesignTimeLibrary end.
unit littleFuncs; interface procedure SwapIntegers(var i1,i2: Integer); procedure SwapFloats(var f1,f2: Real); procedure SwapVariants(var v1,v2: Variant); function ByteSwap(const a: integer): integer; function ByteSwap16(inp:word): word; function DataToHex(aData: Pointer; aSize: Cardinal):String; implementation uses sysUtils, windows; procedure SwapIntegers(var i1,i2: Integer); var t: Integer; begin t:=i1; i1:=i2; i2:=t; end; procedure SwapFloats(var f1,f2: Real); var t: Real; begin t:=f1; f1:=f2; f2:=t; end; procedure SwapVariants(var v1,v2: Variant); var t: TVarData; begin //хитрость некая - если в 8 байтах хранятся указатели на другие области данных, //мы эти данные не перемещаем, пущай лежат где лежали. //если бы мы написали t:=v1; v1:=v2; v2:=t, произошло бы полноценное копирование, //удаление и пр. - гораздо медленнее. t:=TVarData(v1); TVarData(v1):=TVarData(v2); TVarData(v2):=t; end; {Invert bytes using assembly} function ByteSwap(const a: integer): integer; asm bswap eax end; function ByteSwap16(inp:word): word; asm bswap eax shr eax, 16 end; type T2Char = array [0..1] of Char; P2Char = ^T2Char; var DataToHexArray: Array [0..255] of T2Char; function DataToHex(aData: Pointer; aSize: Cardinal): string; var i: Integer; DataArray: PByteArray absolute aData; begin SetLength(Result,aSize*2); for i := 0 to aSize-1 do CopyMemory(@Result[1+i shl 1],@DataToHexArray[DataArray^[i]],SizeOf(T2Char)); end; procedure PrepareDataToHexArray; var i: Integer; str: string; begin for i := 0 to 255 do begin str:=IntToHex(i,2); DataToHexArray[i]:=P2Char(@str[1])^; end; end; initialization PrepareDataToHexArray; end.
unit ADC.Types; interface uses Winapi.Windows, System.Classes, System.Generics.Collections, System.Generics.Defaults, System.SysUtils, System.DateUtils, Winapi.Messages, Vcl.Controls, Vcl.Graphics, System.RegularExpressions, System.StrUtils, System.AnsiStrings, Winapi.ActiveX, MSXML2_TLB, ActiveDs_TLB, ADOX_TLB, ADC.ExcelEnum; const { Название приложения } APP_TITLE = 'AD Commander'; APP_TITLE_JOKE = 'Zhigadlo AD Commander'; ADC_SEARCH_PAGESIZE = 1000; { Имена таблиц для экспорта } EXPORT_TABNAME_USERS = 'Users'; EXPORT_TABNAME_GROUPS = 'Groups'; EXPORT_TABNAME_WORKSTATIONS = 'Workstations'; { Разделы ini файла } INI_SECTION_GENERAL = 'GENERAL'; INI_SECTION_ATTRIBUTES = 'ATTRIBUTES'; INI_SECTION_EVENTS = 'EVENTS'; INI_SECTION_EDITOR = 'EDITOR'; INI_SECTION_FLOATING = 'FLOATING_WINDOW'; INI_SECTION_MOUSE = 'MOUSE'; INI_SECTION_STATE = 'STATE'; INI_SECTION_DMRC = 'DAMEWARE'; INI_SECTION_PSEXEC = 'PSEXEC'; { Тип подключения DameWare } DMRC_CONNECTION_MRC = 0; DMRC_CONNECTION_RDP = 1; { Тип авторизации DameWare } DMRC_AUTH_PROPRIETARY = 0; DMRC_AUTH_WINNT = 1; DMRC_AUTH_WINLOGON = 2; DMRC_AUTH_SMARTCARD = 3; DMRC_AUTH_CURRENTUSER = 4; { Используемый API } ADC_API_LDAP = 0; ADC_API_ADSI = 1; { Опции левой клавиши мыши } MOUSE_LMB_OPTION1 = 1; MOUSE_LMB_OPTION2 = 2; { Опции фильтра записей } FILTER_BY_ANY = 0; FILTER_BY_NAME = 1; { Типы аттрибутов AD } ATTR_TYPE_ANY = '_any_'; ATTR_TYPE_UNDEFINED = 'Undefined'; ATTR_TYPE_DN_STRING = 'DN'; ATTR_TYPE_OID = 'OID'; ATTR_TYPE_CASE_EXACT_STRING = 'CaseExactString'; ATTR_TYPE_CASE_IGNORE_STRING = 'CaseIgnoreString'; ATTR_TYPE_PRINTABLE_STRING = 'PrintableString'; ATTR_TYPE_NUMERIC_STRING = 'NumericString'; ATTR_TYPE_DN_WITH_BINARY = 'DNWithBinary'; ATTR_TYPE_BOOLEAN = 'Boolean'; ATTR_TYPE_INTEGER = 'INTEGER'; ATTR_TYPE_OCTET_STRING = 'OctetString'; ATTR_TYPE_UTC_TIME = 'GeneralizedTime'; ATTR_TYPE_DIRECTORY_STRING = 'DirectoryString'; ATTR_TYPE_PRESENTATION_ADDRESS = 'PresentationAddress'; ATTR_TYPE_DN_WITH_STRING = 'DNWithString'; ATTR_TYPE_NT_SECURITY_DESCRIPTOR = 'ObjectSecurityDescriptor'; ATTR_TYPE_LARGE_INTEGER = 'INTEGER8'; ATTR_TYPE_SID_STRING = 'OctetString'; { Контрольные события } CTRL_EVENT_STORAGE_DISK = 0; CTRL_EVENT_STORAGE_AD = 1; { Режим редактирования } ADC_EDIT_MODE_CREATE = 0; ADC_EDIT_MODE_CHANGE = 1; ADC_EDIT_MODE_DELETE = 2; { Парметры изображения пользователя } USER_IMAGE_EMPTY = 0; USER_IMAGE_ASSIGNED = 1; USER_IMAGE_MAX_WIDTH = 96; USER_IMAGE_MAX_HEIGHT = 96; COLOR_SELBORDER: TColorRef = $00B16300; //RGB(0, 99, 177); COLOR_GRAY_TEXT: TColorRef = $333333; { При запуске нескольких копий приложения } EXEC_NEW_INSTANCE = 1; EXEC_PROMPT_ACTION = 2; { Категория контейнера AD } AD_CONTCAT_CONTAINER = 1; AD_CONTCAT_ORGUNIT = 2; { Объекты фильтра } FILTER_OBJECT_USER = 1; // 1 shl 0 FILTER_OBJECT_GROUP = 2; // 1 shl 1 FILTER_OBJECT_WORKSTATION = 4; // 1 shl 2 FILTER_OBJECT_DC = 8; // 1 shl 3 { Текстовые константы } TEXT_NO_DATA = '<нет данных>'; TEXT_FILE_NOT_FOUND = 'Файл не найден'; {$ALIGN 8} type TFloatingWindowStyle = (fwsLync, fwsSkype); type TAdsValueArray = array[0..ANYSIZE_ARRAY-1] of ADSVALUE; PAdsValueArray = ^TAdsValueArray; type TIPAddr = record FQDN : string; v4 : string; v6 : string; end; PIPAddr = ^TIPAddr; TDHCPInfo = record ServerNetBIOSName: string; ServerName: string; ServerAddress: string; HardwareAddress: string; IPAddress: TIPAddr; SubnetMask: string; LeaseExpires: TDateTime; end; PDHCPInfo = ^TDHCPInfo; type PImgByteArray = ^TImgByteArray; TImgByteArray = array of Byte; TImgByteArrayHelper = record helper for TImgByteArray function AsBinString: string; function AsBinAnsiString: AnsiString; end; type PXMLByteArray = ^TXMLByteArray; TXMLByteArray = array of Byte; TXMLByteArrayHelper = record helper for TXMLByteArray function AsBinString: string; function AsBinAnsiString: AnsiString; end; type PADContainer = ^TADContainer; TADContainer = record name: string; systemFlags: Integer; allowedChildClasses: string; Category: Byte; DistinguishedName: string; CanonicalName: string; Path: string; procedure Clear; end; TOrganizationalUnitHelper = record helper for TADContainer function ExtractName: string; function CanBeDeleted: Boolean; function CanContainClass(AClass: string): Boolean; end; type PADAttribute = ^TADAttribute; TADAttribute = packed record ID: Byte; Name: string[255]; { Имя атрибута Active Directory } ObjProperty: string[255]; { Имя поля объекта TADObject } Title: string[255]; { Текстовое описание атрибута } Comment: string[255]; { Краткий комментарий к атрибуту } Visible: Boolean; { Отображать столбец в списке } Width: Word; { Ширина столбца в списке } Alignment: TAlignment; { Выравнивание при отображении } BgColor: TColor; { Цвет фона } FontColor: TColor; { Цвет шрифта } ReadOnly: Boolean; { Только для чтения } end; TADAttributeHelper = record helper for TADAttribute function IsExportRequired: Boolean; function IsNotExported: Boolean; function FieldName: string; function ADODataType: DWORD; function ExcelColumnWidth: Integer; function ExcelColumnAlignment: Integer; function ExcelCellFormat(AExcel: Variant): string; end; type PADGroupMember = ^TADGroupMember; TADGroupMember = record Selected: Boolean; SortKey: Integer; name: string; sAMAccountName: string; distinguishedName: string; primaryGroupID: Integer; end; TADGroupMemberList = class(TList) private FOwnsObjects: Boolean; function Get(Index: Integer): PADGroupMember; public constructor Create(AOwnsObjects: Boolean = True); reintroduce; destructor Destroy; override; function Add(Value: PADGroupMember): Integer; procedure Clear; override; procedure SetSelected(AIndex: Integer; ASelected: Boolean); function SelCount: Integer; function ContainsGroups: Boolean; function ContainsMember(AMemberDN: string): Boolean; property Items[Index: Integer]: PADGroupMember read Get; default; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; end; type PADGroup = ^TADGroup; TADGroup = record ImageIndex: Integer; Selected: Boolean; IsMember: Boolean; IsPrimary: Boolean; distinguishedName: string; name: string; description: string; primaryGroupToken: Integer; groupType: Integer; end; TADGroupList = class(TList) protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; private FOwnsObjects: Boolean; function Get(Index: Integer): PADGroup; function GetPrimaryGroupName: string; function GetPrimaryGroupIndex: integer; public constructor Create(AOwnsObjects: Boolean = True); reintroduce; destructor Destroy; override; function Add(Value: PADGroup): Integer; procedure Clear; override; function GetPrimaryGroup: PADGroup; procedure SetGroupAsPrimary(AToken: Integer); procedure SetSelected(AIndex: Integer; ASelected: Boolean); function IndexOf(AToken: Integer): Integer; overload; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; property Items[Index: Integer]: PADGroup read Get; default; property PrimaryGroupName: string read GetPrimaryGroupName; property PrimaryGroupIndex: integer read GetPrimaryGroupIndex; end; type PADEvent = ^TADEvent; TADEvent = record ID: Integer; Date: TDate; Description: string; procedure Clear; end; TADEventList = class(TList) private FOwnsObjects: Boolean; procedure Notify(Ptr: Pointer; Action: TListNotification); override; function GenerateItemID: Integer; function Get(Index: Integer): PADEvent; public constructor Create(AOwnsObjects: Boolean = True); reintroduce; destructor Destroy; override; function Add(Value: PADEvent): Integer; procedure Clear; override; function GetNearestEvent: TDate; function GetEventByID(AID: Integer): PADEvent; property Items[Index: Integer]: PADEvent read Get; default; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; end; type TProgressProc = procedure (AItem: TObject; AProgress: Integer) of object; TExceptionProc = procedure (AMsg: string; ACode: ULONG) of object; TSelectContainerProc = procedure (Sender: TObject; ACont: TADContainer) of object; TCreateUserProc = procedure (Sender: TObject; AOpenEditor: Boolean) of object; TChangeComputerProc = procedure (Sender: TObject) of object; TChangeUserProc = procedure (Sender: TObject) of object; TPwdChangeProc = procedure (Sender: TObject; AChangeOnLogon: Boolean) of object; TSelectGroupProc = procedure (Sender: TObject; AGroupList: TADGroupList) of object; TSelectGroupMemberProc = procedure (Sender: TObject; AMemberList: TADGroupMemberList) of object; TApplyWorkstationsProc = procedure (Sender: TObject; AWorkstations: string) of object; TChangeEventProc = procedure (Sender: TObject; AMode: Byte; AEvent: TADEvent) of object; TCreateOrganizationalUnitProc = procedure (ANewDN: string) of object; TCreateGroupProc = procedure (ANewDN: string) of object; TQueryFullProcessImageName = function (Process: THandle; Flags: DWORD; Buffer: LPTSTR; Size: PDWORD): DWORD; stdcall; function GetUserNameEx(NameFormat: DWORD; lpNameBuffer: LPSTR; var nSize: DWORD): Boolean; stdcall; implementation function GetUserNameEx; external 'secur32.dll' name 'GetUserNameExA'; { TADGroupMemberList } function TADGroupMemberList.Add(Value: PADGroupMember): Integer; begin Result := inherited Add(Value); end; procedure TADGroupMemberList.Clear; var i: Integer; begin if FOwnsObjects then for i := Self.Count - 1 downto 0 do Dispose(Self.Items[i]); inherited Clear; end; function TADGroupMemberList.ContainsGroups: Boolean; var i: Integer; begin Result := False; for i := 0 to Self.Count - 1 do if Self.Items[i]^.SortKey = 1 then begin Result := True; Break; end; end; function TADGroupMemberList.ContainsMember(AMemberDN: string): Boolean; var i: Integer; begin Result := False; for i := 0 to Self.Count - 1 do if CompareText(Self.Items[i]^.distinguishedName, AMemberDN) = 0 then begin Result := True; Break; end; end; constructor TADGroupMemberList.Create(AOwnsObjects: Boolean); begin inherited Create; FOwnsObjects := AOwnsObjects; end; destructor TADGroupMemberList.Destroy; begin Clear; inherited; end; function TADGroupMemberList.Get(Index: Integer): PADGroupMember; begin Result := PADGroupMember(inherited Get(Index)); end; function TADGroupMemberList.SelCount: Integer; var i: Integer; res: Integer; begin res := 0; for i := 0 to Self.Count - 1 do if Self.Items[i]^.Selected then Inc(res); Result := res; end; procedure TADGroupMemberList.SetSelected(AIndex: Integer; ASelected: Boolean); begin try Self.Items[AIndex]^.Selected := ASelected; except end; end; { TOrganizationalUnit } procedure TADContainer.Clear; begin Category := 0; name := ''; systemFlags := 0; DistinguishedName := ''; CanonicalName := ''; Path := ''; end; { TImgByteArrayHelper } function TImgByteArrayHelper.AsBinAnsiString: AnsiString; begin SetString(Result, PAnsiChar(@Self[0]), Length(Self)); end; function TImgByteArrayHelper.AsBinString: string; begin SetString(Result, PWideChar(@Self[0]), Length(Self) div 2); end; { TXMLByteArrayHelper } function TXMLByteArrayHelper.AsBinAnsiString: AnsiString; begin SetString(Result, PAnsiChar(@Self[0]), Length(Self)); end; function TXMLByteArrayHelper.AsBinString: string; begin SetString(Result, PWideChar(@Self[0]), Length(Self) div 2); end; { TADGroupList } function TADGroupList.Add(Value: PADGroup): Integer; begin Result := inherited Add(Value); end; procedure TADGroupList.Clear; var i: Integer; begin if FOwnsObjects then for i := Self.Count - 1 downto 0 do Dispose(Self.Items[i]); inherited Clear; end; constructor TADGroupList.Create(AOwnsObjects: Boolean = True); begin inherited Create; FOwnsObjects := AOwnsObjects; end; destructor TADGroupList.Destroy; begin inherited Destroy; end; function TADGroupList.Get(Index: Integer): PADGroup; begin Result := PADGroup(inherited Get(Index)); end; function TADGroupList.GetPrimaryGroup: PADGroup; var i: Integer; begin i := Self.PrimaryGroupIndex; if i > -1 then Result := Self[i] else Result := nil; end; function TADGroupList.GetPrimaryGroupIndex: integer; var g: PADGroup; begin Result := -1; for g in Self do if g^.IsPrimary then begin Result := Self.IndexOf(g); Break; end; end; function TADGroupList.GetPrimaryGroupName: string; var g: PADGroup; begin Result := ''; for g in Self do if g^.IsPrimary then begin Result := g^.name; Break; end; end; function TADGroupList.IndexOf(AToken: Integer): Integer; var g: PADGroup; begin Result := -1; for g in Self do if g^.primaryGroupToken = AToken then begin Result := IndexOf(g); Break; end; end; procedure TADGroupList.Notify(Ptr: Pointer; Action: TListNotification); begin case Action of lnAdded: ; lnExtracted: ; lnDeleted: ; end; inherited; end; procedure TADGroupList.SetGroupAsPrimary(AToken: Integer); var g: PADGroup; begin for g in Self do g^.IsPrimary := g^.primaryGroupToken = AToken; end; procedure TADGroupList.SetSelected(AIndex: Integer; ASelected: Boolean); begin try Self.Items[AIndex]^.Selected := ASelected; except end; end; { TADEventList } function TADEventList.Add(Value: PADEvent): Integer; begin Result := inherited Add(Value); end; procedure TADEventList.Clear; var i: Integer; begin for i := Self.Count - 1 downto 0 do Self.Delete(i); inherited Clear; end; constructor TADEventList.Create(AOwnsObjects: Boolean); begin inherited Create; FOwnsObjects := AOwnsObjects; end; destructor TADEventList.Destroy; begin inherited; end; function TADEventList.GenerateItemID: Integer; var id: Integer; begin id := 0; repeat id := id + 1; until (Self.GetEventByID(id) = nil) or (id > Self.Count); Result := id; end; function TADEventList.Get(Index: Integer): PADEvent; begin Result := PADEvent(inherited Get(Index)); end; function TADEventList.GetEventByID(AID: Integer): PADEvent; var e: PADEvent; begin Result := nil; for e in Self do begin if e^.ID = AID then begin Result := e; Break; end; end; end; function TADEventList.GetNearestEvent: TDate; var e: PADEvent; res: TDate; begin if Self.Count > 0 then res := Self[0]^.Date else res := 0; for e in Self do if CompareDate(e^.Date, res) < 0 then res := e^.Date; Result := res; end; procedure TADEventList.Notify(Ptr: Pointer; Action: TListNotification); begin inherited; case Action of lnAdded: begin PADEvent(Ptr)^.ID := Self.GenerateItemID; end; lnExtracted: begin PADEvent(Ptr)^.ID := 0; end; lnDeleted: begin if FOwnsObjects then Dispose(PADEvent(Ptr)) end; end; end; { TADEvent } procedure TADEvent.Clear; begin ID := 0; Date := 0; Description := ''; end; { TOrganizationalUnitHelper } function TOrganizationalUnitHelper.CanBeDeleted: Boolean; const FLAG_DISALLOW_DELETE = $80000000; begin Result := Self.systemFlags and FLAG_DISALLOW_DELETE = 0; end; function TOrganizationalUnitHelper.CanContainClass(AClass: string): Boolean; var valList: TStringList; begin valList := TStringList.Create; valList.CaseSensitive := False; valList.Delimiter := ','; valList.DelimitedText := Self.allowedChildClasses; Result := valList.IndexOf(AClass) > -1; valList.Free; end; function TOrganizationalUnitHelper.ExtractName: string; var RegEx: TRegEx; begin RegEx := TRegEx.Create('(?<=[\\\/])[^\\\/]+$', [roIgnoreCase]); Result := RegEx.Match(Self.CanonicalName).Value end; { TADAttributeHelper } function TADAttributeHelper.ADODataType: DWORD; begin case IndexText(Self.Name, [ 'lastLogon', { 0 } 'pwdLastSet', { 1 } 'badPwdCount', { 2 } 'groupType', { 3 } 'userAccountControl', { 4 } 'primaryGroupToken', { 5 } 'thumbnailPhoto', { 6 } 'description', { 7 } 'distinguishedName', { 8 } 'canonicalName' { 9 } ] ) of 0..1: Result := adDate; 2..5: Result := adInteger; 6: Result := adLongVarBinary; 7..9: Result := adLongVarWChar; else if CompareText('nearestEvent', Self.ObjProperty) = 0 then Result := adDate else Result := adVarWChar; end; end; function TADAttributeHelper.ExcelColumnAlignment: Integer; begin case IndexText(Self.Name, [ 'lastLogon', { 0 } 'pwdLastSet', { 1 } 'badPwdCount' { 2 } ] ) of 0..2: Result := xlCenter; else if CompareText('nearestEvent', Self.ObjProperty) = 0 then Result := xlCenter else Result := xlLeft; end; end; function TADAttributeHelper.ExcelCellFormat(AExcel: Variant): string; begin case IndexText(Self.Name, [ 'lastLogon', { 0 } 'pwdLastSet', { 1 } 'badPwdCount', { 2 } 'groupType', { 3 } 'userAccountControl', { 4 } 'primaryGroupToken' { 5 } ] ) of 0: Result := xlGetDateTimeFormat(AExcel); 1: Result := xlGetDateTimeFormat(AExcel); 2: Result := xlGetNumberFormat(AExcel, 0); else if CompareText('nearestEvent', Self.ObjProperty) = 0 then Result := xlGetDateFormat(AExcel) else Result := '@'; end; end; function TADAttributeHelper.ExcelColumnWidth: Integer; begin case IndexText(Self.Name, [ 'name', { 0 } 'sAMAccountName', { 1 } 'employeeID', { 2 } 'title', { 3 } 'telephoneNumber', { 4 } 'lastLogonComputer', { 5 } 'description', { 6 } 'userWorkstations', { 7 } 'physicalDeliveryOfficeName', { 8 } 'department', { 9 } 'mail', { 10 } 'canonicalName', { 11 } 'distinguishedName', { 12 } 'lastLogon', { 13 } 'pwdLastSet', { 14 } 'badPwdCount', { 15 } 'userAccountControl', { 16 } 'objectSid' { 17 } ] ) of 0: Result := 25; 1: Result := 25; 2: Result := 11; 3: Result := 25; 4: Result := 17; 5: Result := 17; 6: Result := 45; 7: Result := 20; 8: Result := 45; 9: Result := 45; 10: Result := 25; 11: Result := 45; 12: Result := 45; 13: Result := 19; 14: Result := 19; 15: Result := 5; 16: Result := 10; 17: Result := 45; else if CompareText('nearestEvent', Self.ObjProperty) = 0 then Result := 11 else Result := 25; end; end; function TADAttributeHelper.FieldName: string; var s: string; begin if CompareText('nearestEvent', Self.ObjProperty) = 0 then s := 'NearestEvent' else if CompareText('passwordExpiration', Self.ObjProperty) = 0 then s := 'PasswordExpiration' else s := IfThen(Self.Name = '', Self.Title, Self.Name); Result := IfThen(s.IsEmpty, 'UntitledField', s); end; function TADAttributeHelper.IsExportRequired: Boolean; begin Result := (CompareText('distinguishedName', Self.Name) = 0); end; function TADAttributeHelper.IsNotExported: Boolean; begin Result := ( not Self.IsExportRequired ) and ( CompareText(Self.Name, 'thumbnailPhoto') = 0 ) end; end.
{$REGION 'Copyright (C) CMC Development Team'} { ************************************************************************** Copyright (C) 2015 CMC Development Team CMC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. CMC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CMC. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** } { ************************************************************************** Additional Copyright (C) for this modul: Chromaprint: Audio fingerprinting toolkit Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com> Lomont FFT: Fast Fourier Transformation Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/ ************************************************************************** } {$ENDREGION} {$REGION 'Notes'} { ************************************************************************** See CP.Chromaprint.pas for more information ************************************************************************** } unit CP.FFT; {$IFDEF FPC} {$MODE delphi} {$DEFINE USE_FFT_LOMONT} // ffmpeg not ready in FPC now :( {$ENDIF} interface uses Classes, SysUtils, CP.Def, CP.AudioConsumer; type { TFFTFrame } TFFTFrame = class(TObject) private FSize: integer; public property Size: integer read FSize; public Data: TDoubleArray; constructor Create(Size: integer); destructor Destroy; override; function Magnitude(i: integer): double; function Energy(i: integer): double; end; TFFTFrameConsumer = class(TObject) public procedure Consume(frame: TFFTFrame); virtual; abstract; end; TFFTLib = class(TObject) protected FWindow: TDoubleArray; FFrameSize: integer; FFrameSizeH: integer; public constructor Create(frame_size: integer; window: TDoubleArray); destructor Destroy; override; procedure ComputeFrame(input: TSmallintArray; var frame: TFFTFrame); virtual; abstract; end; { TFFT } TFFT = class(TAudioConsumer) private FBufferOffset: integer; FWindow: TDoubleArray; FFFTBuffer: TSmallintArray; FFrame: TFFTFrame; FFrameSize: integer; FIncrement: integer; FLib: TFFTLib; FConsumer: TFFTFrameConsumer; public property FrameSize: integer read FFrameSize; public constructor Create(frame_size: integer; overlap: integer; consumer: TFFTFrameConsumer); destructor Destroy; override; procedure Reset; procedure Consume(input: TSmallintArray; AOffset: integer; lLength: integer); override; function overlap: integer; end; implementation uses Windows, CP.Utils, CP.CombinedBuffer, {$IFNDEF FPC} CP.AVFFT, {$ENDIF} CP.LomontFFT; { TFFTFrame } constructor TFFTFrame.Create(Size: integer); begin FSize := Size; SetLength(Data, FSize); end; destructor TFFTFrame.Destroy; begin SetLength(Data, 0); inherited Destroy; end; function TFFTFrame.Magnitude(i: integer): double; begin Result := sqrt(Data[i]); end; function TFFTFrame.Energy(i: integer): double; begin Result := Data[i]; end; { TFFT } constructor TFFT.Create(frame_size: integer; overlap: integer; consumer: TFFTFrameConsumer); var i: integer; j: integer; begin SetLength(FWindow, frame_size); FBufferOffset := 0; SetLength(FFFTBuffer, frame_size); FFrame := TFFTFrame.Create(frame_size); FFrameSize := frame_size; FIncrement := frame_size - overlap; FConsumer := consumer; PrepareHammingWindow(FWindow); for i := 0 to frame_size - 1 do begin FWindow[i] := FWindow[i] / $7FFF; end; {$IFDEF USE_FFT_LOMONT} FLib := TFFTLomont.Create(frame_size, FWindow); {$ELSE} FLib := TFFTAV.Create(frame_size, FWindow); {$ENDIF} end; destructor TFFT.Destroy; begin FFrame.Free; FLib.Free; SetLength(FFFTBuffer, 0); SetLength(FWindow, 0); inherited; end; function TFFT.overlap: integer; begin Result := FFrameSize - FIncrement; end; procedure TFFT.Reset; begin FBufferOffset := 0; end; procedure TFFT.Consume(input: TSmallintArray; AOffset: integer; lLength: integer); var lCombinedBuffer: TCombinedBuffer; lBuffer: TSmallintArray; begin // Special case, just pre-filling the buffer if (FBufferOffset + lLength < FFrameSize) then begin Move(input[0], FFFTBuffer[FBufferOffset], lLength * SizeOf(smallint)); FBufferOffset := FBufferOffset + lLength; Exit; end; // Apply FFT on the available data lCombinedBuffer := TCombinedBuffer.Create(FFFTBuffer, FBufferOffset, input, lLength); while (lCombinedBuffer.Size >= FFrameSize) do begin SetLength(lBuffer, FFrameSize); lCombinedBuffer.Read(lBuffer, 0, FFrameSize); FLib.ComputeFrame(lBuffer, FFrame); FConsumer.Consume(FFrame); lCombinedBuffer.Shift(FIncrement); SetLength(lBuffer, 0); end; // Copy the remaining input data to the internal buffer lCombinedBuffer.Flush(FFFTBuffer); FBufferOffset := lCombinedBuffer.Size(); lCombinedBuffer.Free; end; { TFFTLib } constructor TFFTLib.Create; begin end; destructor TFFTLib.Destroy; begin inherited; end; end.
unit Cloud.Utils; interface uses System.SysUtils, System.Generics.Collections, Cloud.Consts; function StrToAmount(const S: string): Extended; function StrToAmountDef(const S: string; Default: Extended): Extended; function AmountToStr(Amount: Extended): string; function AmountToStrI(Amount: Extended): string; function SymbolToPort(const Symbol: string; const Default: string=''): string; function PortToSymbol(const Port: string; const Default: string=''): string; function SymbolID(const Symbol: string; const Default: Integer=0): Integer; function SymbolBy(SymbolID: Integer; const Default: string=''): string; function Skip(const S: string; const SkipChars: array of Char; Count: Integer): string; function Map(const Value: string; const A,B: TArray<string>; const Default: string=''): string; function ArrayToString(const A: TArray<Int64>; const Separator: string): string; implementation var Invariant: TFormatSettings; function StrToAmount(const S: string): Extended; begin Result:=StrToFloat(S.Replace(',',Invariant.DecimalSeparator),Invariant); end; function StrToAmountDef(const S: string; Default: Extended): Extended; begin Result:=StrToFloatDef(S.Replace(',',Invariant.DecimalSeparator), Default,Invariant); end; function AmountToStr(Amount: Extended): string; begin Result:=FormatFloat('0.00######',Amount); end; function AmountToStrI(Amount: Extended): string; begin Result:=FormatFloat('0.00######',Amount,Invariant); end; function IndexOf(const Value: string; const A: TArray<string>): Integer; begin for Result:=0 to High(A) do if SameText(A[Result],Value) then Exit; Result:=-1; end; function Map(const Value: string; const A,B: TArray<string>; const Default: string=''): string; var I: Integer; begin Result:=Default; I:=IndexOf(Value,A); if I<>-1 then Result:=B[I]; end; function SymbolToPort(const Symbol: string; const Default: string=''): string; begin Result:=Map(Symbol,['BTC','LTC','ETH'],[PORT_BITCOIN,PORT_LIGHTCOIN,PORT_ETHEREUM],Default); end; function PortToSymbol(const Port: string; const Default: string=''): string; begin Result:=Map(Port,[PORT_BITCOIN,PORT_LIGHTCOIN,PORT_ETHEREUM],['BTC','LTC','ETH'],Default); end; function SymbolID(const Symbol: string; const Default: Integer=0): Integer; begin Result:=Map(Symbol,['BTC','LTC','ETH','RLC','GTN'],['1','2','3','4','5'],Default.ToString).ToInteger; end; function SymbolBy(SymbolID: Integer; const Default: string=''): string; begin Result:=Map(SymbolID.ToString,['1','2','3','4','5'],['BTC','LTC','ETH','RLC','GTN'],Default); end; function Skip(const S: string; const SkipChars: array of Char; Count: Integer): string; var P: Integer; begin P:=0; while Count>0 do begin P:=S.IndexOfAny(SkipChars,P); if P=-1 then Exit(''); Dec(Count); Inc(P); end; Result:=S.Substring(P); end; function ArrayToString(const A: TArray<Int64>; const Separator: string): string; begin Result:=''; for var V in A do if Result='' then Result:=string.Join('',[Result,V]) else Result:=string.Join(Separator,[Result,V]); end; initialization Invariant:=TFormatSettings.Invariant; end.
unit CachedObjectAuto; interface uses Windows, ActiveX, ComObj, FIVECacheServer_TLB, CacheObjects, CachedObjectWrap; type TCachedObject = class(TAutoObject, ICachedObject) public function ContainsFolder(const Name: WideString): WordBool; safecall; function GetFolderIterator(const Folder: WideString): OleVariant; safecall; function GetPath: WideString; safecall; function SetClass(const Name: WideString): WordBool; safecall; function SetObject(X, Y: Integer): WordBool; safecall; function SetObjectOfWorld(X, Y: Integer; const World: WideString): WordBool; safecall; function SetPath(const aPath: WideString): WordBool; safecall; function SetWorld(const Name: WideString): WordBool; safecall; procedure CreateFolder(const Name: WideString); safecall; procedure CreateObject(const aPath: WideString); safecall; procedure Flush; safecall; function Get_Recache: WordBool; safecall; procedure Set_Recache(Value: WordBool); safecall; function Properties(const Name: WideString): WideString; safecall; procedure KeepAlive; safecall; private fPropertyName : string; fCachedObject : TCachedObjectWrap; private function GetIDsOfNames(const IID : TGUID; Names : Pointer; NameCount, LocaleID : Integer; DispIDs : Pointer) : HResult; override; stdcall; function Invoke(DispID : Integer; const IID : TGUID; LocaleID : Integer; Flags : Word; var Params; VarResult, ExcepInfo, ArgErr : Pointer) : HResult; override; stdcall; public procedure Initialize; override; destructor Destroy; override; protected end; implementation uses Classes, SysUtils, ComServ, CacheCommon, CacheRegistryData, SpecialChars, CacheNameUtils; var Logs : boolean = false; const NormalDispId = $100; // TCachedObject function TCachedObject.GetIDsOfNames(const IID : TGUID; Names : Pointer; NameCount, LocaleID : Integer; DispIDs : Pointer) : HResult; begin if inherited GetIDsOfNames(IID, Names, NameCount, LocaleID, DispIDs) = S_OK then result := S_OK else if fCachedObject <> nil then begin fPropertyName := POLEStrList(Names)^[0]; PInteger(DispIds)^ := NormalDispId; result := S_OK; end else result := DISP_E_UNKNOWNNAME; end; function TCachedObject.Invoke(DispID : Integer; const IID : TGUID; LocaleID : Integer; Flags : Word; var Params; VarResult, ExcepInfo, ArgErr : Pointer) : HResult; var Parameters : TDispParams; ParamValue : OleVariant; PropValue : WideString; IndexValue : OleVariant; begin if DispId = NormalDispId then try Parameters := TDispParams(Params); if (Flags and DISPATCH_PROPERTYGET <> 0) or (Flags and DISPATCH_METHOD <> 0) then if VarResult <> nil then case Parameters.cArgs of 0 : begin PropValue := fCachedObject.CachedObject.Properties[fPropertyName]; PVariant(VarResult)^ := PropValue; result := S_OK; end; 1 : begin VariantInit(ParamValue); VariantChangeType(ParamValue, OleVariant(Parameters.rgvarg[0]), 0, VT_BSTR); PropValue := fCachedObject.CachedObject.Properties[fPropertyName + ParamValue]; PVariant(VarResult)^ := PropValue; result := S_OK; end; else result := DISP_E_BADPARAMCOUNT; end else result := DISP_E_MEMBERNOTFOUND else if (Parameters.cNamedArgs = 1) and (Parameters.rgdispidNamedArgs[0] = DISPID_PROPERTYPUT) then case Parameters.cArgs of 1 : begin VariantInit(ParamValue); VariantChangeType(ParamValue, OleVariant(Parameters.rgvarg[0]), 0, VT_BSTR); fCachedObject.CachedObject.Properties[fPropertyName] := ParamValue; result := S_OK; end; 2 : begin VariantInit(ParamValue); VariantChangeType(ParamValue, OleVariant(Parameters.rgvarg[0]), 0, VT_BSTR); VariantInit(IndexValue); VariantChangeType(IndexValue, OleVariant(Parameters.rgvarg[1]), 0, VT_BSTR); fCachedObject.CachedObject.Properties[fPropertyName + IndexValue] := ParamValue; result := S_OK; end; else result := DISP_E_BADPARAMCOUNT end else Result := DISP_E_PARAMNOTOPTIONAL except result := E_FAIL; end else result := inherited Invoke(DispID, IID, LocaleID, Flags, Params, VarResult, ExcepInfo, ArgErr); end; function TCachedObject.GetFolderIterator(const Folder: WideString): OleVariant; begin try if fCachedObject.CachedObject.IsFolder then try result := CreateOleObject('FolderIterator.DirectoryIterator'); result.SetFolder(fCachedObject.CachedObject.RelPath + Folder, AllFiveObjects, onBoth); except result := NULL; end else result := NULL; except result := NULL; end; end; function TCachedObject.GetPath : WideString; begin result := fCachedObject.CachedObject.Path; end; function TCachedObject.SetPath(const aPath: WideString): WordBool; begin result := fCachedObject.SetPath(aPath); end; function TCachedObject.ContainsFolder(const Name: WideString): WordBool; begin try result := fCachedObject. ContainsFolder(Name); except result := false; end; end; procedure TCachedObject.Flush; begin // >> end; procedure TCachedObject.CreateFolder(const Name: WideString); begin // >> end; procedure TCachedObject.CreateObject(const aPath: WideString); begin // >> end; function TCachedObject.SetClass(const Name: WideString) : WordBool; begin result := fCachedObject.SetClass(Name); end; function TCachedObject.SetObject(X, Y: Integer) : WordBool; begin result := fCachedObject.SetObject(X, Y); end; function TCachedObject.SetWorld(const Name : WideString) : WordBool; begin result := fCachedObject.SetWorld(Name); end; function TCachedObject.SetObjectOfWorld(X, Y: Integer; const World: WideString) : WordBool; begin result := fCachedObject.SetObjectOfWorld(X, Y, World); end; procedure TCachedObject.Initialize; begin fCachedObject := TCachedObjectWrap.Create; end; destructor TCachedObject.Destroy; begin fCachedObject.Free; inherited; end; function TCachedObject.Get_Recache: WordBool; begin result := fCachedObject.Recache; end; procedure TCachedObject.Set_Recache(Value: WordBool); begin fCachedObject.Recache := Value; end; function TCachedObject.Properties(const Name: WideString): WideString; begin try if fCachedObject.CachedObject <> nil then result := fCachedObject.CachedObject.Properties[Name] else result := ''; except result := ''; end; end; procedure TCachedObject.KeepAlive; begin fCachedObject.KeepAlive; end; initialization TAutoObjectFactory.Create(ComServer, TCachedObject, Class_CachedObject, ciMultiInstance); end.
program newtonRaphson(output); { Equation: x * sin(x) = 1} { Recurrence: (1 + xn^2cos(xn)) / (sin(xn) + xn(cos(xn)))} const EPSILON = 1E-10; var i : integer; numerator : real; denominator : real; root : real; begin i := 0; root := 1.0; numerator := 1.0; denominator := 1.0; while i < 200 do begin numerator := 1 + sqr(root) * cos(root); denominator := sin(root) + root * cos(root); root := numerator / denominator; i := succ(i); end; writeln('The root of [x * sin(x) - 1], is: ', root:3:8, ' found in ', i, ' iterations.'); end.
unit ay_8910; interface uses {$IFDEF WINDOWS}windows,{$else}main_engine,{$ENDIF}sound_engine,cpu_misc; type ay8910_chip=class(snd_chip_class) constructor create(clock:integer;type_:byte;amp:single=1;internal:boolean=false); destructor free; public procedure Write(v:byte); procedure Control(v:byte); function Read:byte; procedure reset; procedure update; function update_internal:pinteger; function get_control:byte; function get_reg(reg:byte):byte; procedure set_reg(reg,valor:byte); procedure change_io_calls(porta_read,portb_read:cpu_inport_call;porta_write,portb_write:cpu_outport_call); function save_snapshot(data:pbyte):word; procedure load_snapshot(data:pbyte); procedure change_clock(clock:dword); procedure change_gain(gain0,gain1,gain2:single); private Regs:array[0..15] of byte; PeriodA,PeriodB,PeriodC,PeriodN,PeriodE:integer; CountA,CountB,CountC,CountN,CountE:integer; VolA,VolB,VolC,VolE:integer; EnvelopeA,EnvelopeB,EnvelopeC:integer; OutputA,OutputB,OutputC,OutputN:integer; latch,type_:byte; CountEnv:shortint; Hold,Alternate,Attack,Holding,RNG,UpdateStep:integer; lastenable:smallint; porta_read,portb_read:cpu_inport_call; porta_write,portb_write:cpu_outport_call; gain0,gain1,gain2:single; procedure AYWriteReg(r,v:byte); function AYReadReg(r:byte):byte; end; var ay8910_0,ay8910_1,ay8910_2,ay8910_3,ay8910_4:ay8910_chip; const AY8910=0; AY8912=1; implementation const AY_AFINE = 0; AY_ACOARSE = 1; AY_BFINE = 2; AY_BCOARSE = 3; AY_CFINE = 4; AY_CCOARSE = 5; AY_NOISEPER = 6; AY_ENABLE = 7; AY_AVOL = 8; AY_BVOL = 9; AY_CVOL = 10; AY_EFINE = 11; AY_ECOARSE = 12; AY_ESHAPE = 13; AY_PORTA = 14; AY_PORTB = 15; STEP=$1000; MAX_OUTPUT=$7FFF; var salida_ay:array[0..3] of integer; vol_table:array[0..31] of single; procedure init_table; var i:integer; l_out:single; begin l_out:=MAX_OUTPUT/4; for i:=31 downto 1 do begin Vol_Table[i]:=trunc(l_out+0.5); // roun to nearest */ l_out:=l_out/1.188502227; // = 10 ^ (1.5/20) = 1.5dB */ end; Vol_Table[0]:=0; end; procedure ay8910_chip.change_gain(gain0,gain1,gain2:single); begin self.gain0:=gain0; self.gain1:=gain1; self.gain2:=gain2; end; procedure ay8910_chip.change_clock(clock:dword); begin self.clock:=clock; self.UpdateStep:=trunc((STEP*FREQ_BASE_AUDIO*8)/self.clock); end; constructor ay8910_chip.create(clock:integer;type_:byte;amp:single=1;internal:boolean=false); begin init_table; self.clock:=clock; self.UpdateStep:=trunc((STEP*FREQ_BASE_AUDIO*8)/self.clock); self.porta_read:=nil; self.portb_read:=nil; self.porta_write:=nil; self.portb_write:=nil; self.PeriodA:=self.UpdateStep; self.PeriodB:=self.UpdateStep; self.PeriodC:=self.UpdateStep; self.PeriodE:=self.UpdateStep; self.PeriodN:=self.UpdateStep; if not(internal) then self.tsample_num:=init_channel; self.amp:=amp; self.reset; self.type_:=type_; self.gain0:=1; self.gain1:=1; self.gain2:=1; end; procedure ay8910_chip.reset; var i:byte; begin self.latch:=0; self.OutputA:= 0; self.OutputB:= 0; self.OutputC:= 0; self.OutputN:= $FF; self.RNG:=1; self.lastenable:=-1; For i := 0 To 13 do self.AYWriteReg(i,0); end; destructor ay8910_chip.free; begin end; function ay8910_chip.save_snapshot(data:pbyte):word; var temp:pbyte; size:word; begin temp:=data; copymemory(temp,@self.regs[0],16);inc(temp,16);size:=16; copymemory(temp,@self.PeriodA,4);inc(temp,4);size:=size+4; copymemory(temp,@self.PeriodB,4);inc(temp,4);size:=size+4; copymemory(temp,@self.PeriodC,4);inc(temp,4);size:=size+4; copymemory(temp,@self.PeriodN,4);inc(temp,4);size:=size+4; copymemory(temp,@self.PeriodE,4);inc(temp,4);size:=size+4; copymemory(temp,@self.CountA,4);inc(temp,4);size:=size+4; copymemory(temp,@self.CountB,4);inc(temp,4);size:=size+4; copymemory(temp,@self.CountC,4);inc(temp,4);size:=size+4; copymemory(temp,@self.CountN,4);inc(temp,4);size:=size+4; copymemory(temp,@self.CountE,4);inc(temp,4);size:=size+4; copymemory(temp,@self.VolA,4);inc(temp,4);size:=size+4; copymemory(temp,@self.VolB,4);inc(temp,4);size:=size+4; copymemory(temp,@self.VolC,4);inc(temp,4);size:=size+4; copymemory(temp,@self.VolE,4);inc(temp,4);size:=size+4; copymemory(temp,@self.EnvelopeA,4);inc(temp,4);size:=size+4; copymemory(temp,@self.EnvelopeB,4);inc(temp,4);size:=size+4; copymemory(temp,@self.EnvelopeC,4);inc(temp,4);size:=size+4; copymemory(temp,@self.OutputA,4);inc(temp,4);size:=size+4; copymemory(temp,@self.OutputB,4);inc(temp,4);size:=size+4; copymemory(temp,@self.OutputC,4);inc(temp,4);size:=size+4; copymemory(temp,@self.OutputN,4);inc(temp,4);size:=size+4; temp^:=self.latch;inc(temp);size:=size+1; temp^:=self.type_;inc(temp);size:=size+1; copymemory(temp,@self.CountEnv,sizeof(shortint));inc(temp,sizeof(shortint));size:=size+sizeof(shortint); copymemory(temp,@self.Hold,4);inc(temp,4);size:=size+4; copymemory(temp,@self.Alternate,4);inc(temp,4);size:=size+4; copymemory(temp,@self.Attack,4);inc(temp,4);size:=size+4; copymemory(temp,@self.Holding,4);inc(temp,4);size:=size+4; copymemory(temp,@self.RNG,4);inc(temp,4);size:=size+4; copymemory(temp,@self.UpdateStep,4);inc(temp,4);size:=size+4; copymemory(temp,@self.lastenable,sizeof(smallint));size:=size+sizeof(smallint); save_snapshot:=size; end; procedure ay8910_chip.load_snapshot(data:pbyte); var temp:pbyte; begin temp:=data; copymemory(@self.regs[0],temp,16);inc(temp,16); copymemory(@self.PeriodA,temp,4);inc(temp,4); copymemory(@self.PeriodB,temp,4);inc(temp,4); copymemory(@self.PeriodC,temp,4);inc(temp,4); copymemory(@self.PeriodN,temp,4);inc(temp,4); copymemory(@self.PeriodE,temp,4);inc(temp,4); copymemory(@self.CountA,temp,4);inc(temp,4); copymemory(@self.CountB,temp,4);inc(temp,4); copymemory(@self.CountC,temp,4);inc(temp,4); copymemory(@self.CountN,temp,4);inc(temp,4); copymemory(@self.CountE,temp,4);inc(temp,4); copymemory(@self.VolA,temp,4);inc(temp,4); copymemory(@self.VolB,temp,4);inc(temp,4); copymemory(@self.VolC,temp,4);inc(temp,4); copymemory(@self.VolE,temp,4);inc(temp,4); copymemory(@self.EnvelopeA,temp,4);inc(temp,4); copymemory(@self.EnvelopeB,temp,4);inc(temp,4); copymemory(@self.EnvelopeC,temp,4);inc(temp,4); copymemory(@self.OutputA,temp,4);inc(temp,4); copymemory(@self.OutputB,temp,4);inc(temp,4); copymemory(@self.OutputC,temp,4);inc(temp,4); copymemory(@self.OutputN,temp,4);inc(temp,4); self.latch:=temp^;inc(temp); self.type_:=temp^;inc(temp); copymemory(@self.CountEnv,temp,sizeof(shortint));inc(temp,sizeof(shortint)); copymemory(@self.Hold,temp,4);inc(temp,4); copymemory(@self.Alternate,temp,4);inc(temp,4); copymemory(@self.Attack,temp,4);inc(temp,4); copymemory(@self.Holding,temp,4);inc(temp,4); copymemory(@self.RNG,temp,4);inc(temp,4); copymemory(@self.UpdateStep,temp,4);inc(temp,4); copymemory(@self.lastenable,temp,sizeof(smallint)); end; procedure ay8910_chip.change_io_calls(porta_read,portb_read:cpu_inport_call;porta_write,portb_write:cpu_outport_call); begin self.porta_read:=porta_read; if self.type_=AY8912 then self.portb_read:=porta_read else self.portb_read:=portb_read; self.porta_write:=porta_write; if self.type_=AY8912 then self.portb_write:=porta_write else self.portb_write:=portb_write; end; procedure ay8910_chip.AYWriteReg(r,v:byte); var old:integer; begin self.Regs[r]:=v; case r of AY_AFINE, AY_ACOARSE:begin self.Regs[AY_ACOARSE] := self.Regs[AY_ACOARSE] and $F; old := self.PeriodA; self.PeriodA:=cardinal((self.Regs[AY_AFINE] + (256 * self.Regs[AY_ACOARSE]))*self.UpdateStep); if (self.PeriodA = 0) then self.PeriodA:=cardinal(self.UpdateStep); self.CountA := self.CountA + (self.PeriodA - old); if (self.CountA <= 0) then self.CountA := 1; end; AY_BFINE, AY_BCOARSE:begin self.Regs[AY_BCOARSE] := self.Regs[AY_BCOARSE] and $F; old := self.PeriodB; self.PeriodB := trunc((self.Regs[AY_BFINE] + (256 * self.Regs[AY_BCOARSE]))* self.UpdateStep); if (self.PeriodB = 0) then self.PeriodB := trunc(self.UpdateStep); self.CountB := self.CountB + self.PeriodB - old; if (self.CountB <= 0) then self.CountB := 1 end; AY_CFINE, AY_CCOARSE:begin self.Regs[AY_CCOARSE] := self.Regs[AY_CCOARSE] and $F; old := self.PeriodC; self.PeriodC := trunc((self.Regs[AY_CFINE] + (256 * self.Regs[AY_CCOARSE]))*self.UpdateStep); if (self.PeriodC = 0) then self.PeriodC := trunc(self.UpdateStep); self.CountC := self.CountC + (self.PeriodC - old); if (self.CountC <= 0) then self.CountC := 1; end; AY_NOISEPER:begin self.Regs[AY_NOISEPER] := self.Regs[AY_NOISEPER] and $1F; old := self.PeriodN; self.PeriodN := trunc(self.Regs[AY_NOISEPER] * self.UpdateStep); if (self.PeriodN = 0) then self.PeriodN := trunc(self.UpdateStep); self.CountN := self.CountN + (self.PeriodN - old); if (self.CountN <= 0) then self.CountN := 1; end; AY_ENABLE:begin if ((self.lastEnable = -1) or ((self.lastEnable and $40)<>(self.Regs[AY_ENABLE] and $40))) then begin // write out 0xff if port set to input */ if (@self.PortA_write<>nil) then begin if (self.Regs[AY_ENABLE] and $40)<>0 then self.porta_write(self.Regs[AY_PORTA]) else self.porta_write($ff); end; end; if ((self.lastEnable=-1) or ((self.lastEnable and $80)<>(self.Regs[AY_ENABLE] and $80))) then begin // write out 0xff if port set to input */ if (@self.portb_write<>nil) then begin if (self.Regs[AY_ENABLE] and $80)<>0 then self.portb_write(self.Regs[AY_PORTB]) else self.portb_write($ff); end; end; self.lastEnable:= self.Regs[AY_ENABLE]; end; AY_AVOL:begin self.Regs[AY_AVOL] := self.Regs[AY_AVOL] and $1F; self.EnvelopeA := self.Regs[AY_AVOL] and $10; if self.Regs[AY_AVOL]<>0 then old:=self.Regs[AY_AVOL]*2+1 else old:=0; if self.EnvelopeA <> 0 then self.VolA := self.VolE else self.VolA:=trunc(Vol_Table[old]); end; AY_BVOL:begin self.Regs[AY_BVOL] := self.Regs[AY_BVOL] and $1F; self.EnvelopeB := self.Regs[AY_BVOL] and $10; if self.Regs[AY_BVOL]<>0 then old:=self.Regs[AY_BVOL]*2+1 else old:=0; if self.EnvelopeB <> 0 then self.VolB := self.VolE else self.VolB :=trunc(Vol_Table[old]); end; AY_CVOL:begin self.Regs[AY_CVOL] := self.Regs[AY_CVOL] and $1F; self.EnvelopeC := self.Regs[AY_CVOL] and $10; if self.Regs[AY_CVOL]<>0 then old:=self.Regs[AY_CVOL]*2+1 else old:=0; if self.EnvelopeC <> 0 then self.VolC := self.VolE else self.VolC :=trunc(Vol_Table[old]); end; AY_EFINE, AY_ECOARSE:begin old := self.PeriodE; self.PeriodE := trunc((self.Regs[AY_EFINE] + (256 * self.Regs[AY_ECOARSE]))* self.UpdateStep); if (self.PeriodE = 0) then self.PeriodE := trunc(self.UpdateStep/2); self.CountE := self.CountE + (self.PeriodE - old); if (self.CountE <= 0) then self.CountE := 1 end; AY_ESHAPE:begin self.Regs[AY_ESHAPE] := self.Regs[AY_ESHAPE] and $F; if ((self.Regs[AY_ESHAPE] and $4)<>0) then self.Attack := $1f else self.Attack := $0; if ((self.Regs[AY_ESHAPE] and $8) = 0) then begin self.Hold:= 1; self.Alternate:= self.Attack; end else begin self.Hold:= self.Regs[AY_ESHAPE] and $1; self.Alternate:= self.Regs[AY_ESHAPE] and $2; end; self.CountE := self.PeriodE; self.CountEnv := $1F; self.Holding := 0; self.VolE :=trunc(Vol_Table[self.CountEnv xor self.Attack]); if (self.EnvelopeA <> 0) then self.VolA := self.VolE; if (self.EnvelopeB <> 0) then self.VolB := self.VolE; if (self.EnvelopeC <> 0) then self.VolC := self.VolE; end; AY_PORTA:if @self.porta_write<>nil then self.porta_write(v) else self.Regs[AY_PORTA]:=v; AY_PORTB:if @self.portb_write<>nil then self.portb_write(v) else self.Regs[AY_PORTB]:=v; end; //case end; function ay8910_chip.AYReadReg(r:byte):byte; begin case r of AY_PORTA:if (@self.porta_read<>nil) then self.Regs[AY_PORTA]:=self.porta_read; AY_PORTB:if (@self.portb_read<>nil) then self.Regs[AY_PORTB]:=self.portb_read; end; AYReadReg:=self.Regs[r]; end; function ay8910_chip.Read:byte; begin read:=self.AYReadReg(self.latch); end; function ay8910_chip.get_reg(reg:byte):byte; begin get_reg:=self.Regs[reg]; end; procedure ay8910_chip.set_reg(reg,valor:byte); begin self.Regs[reg]:=valor; end; procedure ay8910_chip.write(v:byte); begin self.AYWriteReg(self.latch,v); end; procedure ay8910_chip.control(v:byte); begin self.latch:=v and $f; end; function ay8910_chip.get_control:byte; begin get_control:=self.latch; end; function ay8910_chip.update_internal:pinteger; var AY_OutNoise: integer; VolA,VolB,VolC: integer; lOut1,lOut2,lOut3: integer; AY_Left: integer; AY_NextEvent: integer; temp2:integer; begin if (self.Regs[AY_ENABLE] and $1)<>0 then begin if self.CountA <=STEP then self.CountA :=self.CountA +STEP; self.OutputA := 1; end else if (self.Regs[AY_AVOL] = 0) then begin if self.CountA <=STEP then self.CountA :=self.CountA +STEP; end; if (self.Regs[AY_ENABLE] and $2)<>0 then begin if self.CountB <=STEP then self.CountB :=self.CountB + STEP; self.OutputB := 1; end else if self.Regs[AY_BVOL] = 0 then begin if self.CountB <=STEP then self.CountB :=self.CountB + STEP; end; if (self.Regs[AY_ENABLE] and $4)<>0 then begin if self.CountC <=STEP then self.CountC :=self.CountC + STEP; self.OutputC := 1; end else if (self.Regs[AY_CVOL] = 0) then begin if self.CountC <=STEP then self.CountC :=self.CountC +STEP; end; if ((self.Regs[AY_ENABLE] and $38) = $38) then if (self.CountN <=STEP) then self.CountN:=self.CountN +STEP; AY_OutNoise := (self.OutputN Or self.Regs[AY_ENABLE]); VolA := 0; VolB := 0; VolC := 0; AY_Left :=STEP; repeat If (self.CountN < AY_Left) Then AY_NextEvent := self.CountN else AY_NextEvent := AY_Left; If (AY_OutNoise And $8)<>0 Then begin If self.OutputA<>0 Then VolA := VolA + self.CountA; self.CountA := self.CountA - AY_NextEvent; While (self.CountA <= 0) do begin self.CountA := self.CountA + self.PeriodA; If (self.CountA > 0) Then begin self.OutputA := self.OutputA Xor 1; If (self.OutputA<>0) Then VolA := VolA + self.PeriodA; break; end; self.CountA := self.CountA + self.PeriodA; VolA := VolA + self.PeriodA; end; If (self.OutputA<>0) Then VolA := VolA - self.CountA; end Else begin self.CountA := self.CountA - AY_NextEvent; While (self.CountA <= 0) do begin self.CountA := self.CountA + self.PeriodA; If (self.CountA > 0) Then begin self.OutputA := self.OutputA Xor 1; break; end; self.CountA := self.CountA + self.PeriodA; end; end; If (AY_OutNoise And $10)<>0 Then begin If self.OutputB<>0 Then VolB := VolB + self.CountB; self.CountB := self.CountB - AY_NextEvent; While (self.CountB <= 0) do begin self.CountB := self.CountB + self.PeriodB; If (self.CountB > 0) Then begin self.OutputB := self.OutputB Xor 1; If (self.OutputB<>0) Then VolB := VolB + self.PeriodB; break; end; self.CountB := self.CountB + self.PeriodB; VolB := VolB + self.PeriodB; end; If (self.OutputB<>0) Then VolB := VolB - self.CountB; end Else begin self.CountB := self.CountB - AY_NextEvent; While (self.CountB <= 0) do begin self.CountB := self.CountB + self.PeriodB; If (self.CountB > 0) Then begin self.OutputB := self.OutputB Xor 1; break; end; self.CountB := self.CountB + self.PeriodB; end; end; If (AY_OutNoise And $20)<>0 Then begin If (self.OutputC<>0) Then VolC := VolC + self.CountC; self.CountC := self.CountC - AY_NextEvent; While (self.CountC <= 0) do begin self.CountC := self.CountC + self.PeriodC; If (self.CountC > 0) Then begin self.OutputC := self.OutputC Xor 1; If (self.OutputC<>0) Then VolC := VolC + self.PeriodC; break; end; self.CountC := self.CountC + self.PeriodC; VolC := VolC + self.PeriodC; end; If (self.OutputC<>0) Then VolC := VolC - self.CountC; end Else begin self.CountC := self.CountC - AY_NextEvent; While (self.CountC <= 0) do begin self.CountC := self.CountC + self.PeriodC; If (self.CountC > 0) Then begin self.OutputC := self.OutputC Xor 1; break; end; self.CountC := self.CountC + self.PeriodC; end; end; self.CountN := self.CountN - AY_NextEvent; If (self.CountN <= 0) Then begin if ((self.RNG + 1) and 2)<>0 then begin //* (bit0^bit1)? */ self.OutputN:=not(self.OutputN); AY_Outnoise:=(self.OutputN or self.Regs[AY_ENABLE]); end; if (self.RNG and 1)<>0 then self.RNG:=self.RNG xor $28000; //* This version is called the "Galois configuration". */ self.RNG:=self.RNG shr 1; self.CountN:=self.CountN+self.PeriodN; end; AY_Left := AY_Left - AY_NextEvent; until (AY_Left <= 0); if (self.Holding = 0) then begin self.CountE :=self.CountE -STEP; If (self.CountE <= 0) then begin repeat self.CountEnv := self.CountEnv - 1; self.CountE := self.CountE + self.PeriodE; until (self.CountE > 0); if (self.CountEnv < 0) then begin if (self.Hold<>0) then begin if (self.Alternate<>0) then self.Attack:=self.Attack xor $1f; self.Holding:=1; self.CountEnv:=0; end else begin If (self.Alternate<>0) and ((self.CountEnv and $20)<>0) then self.Attack := self.Attack xor $1f; self.CountEnv:=self.CountEnv and $1f; //1f end; end; self.VolE :=trunc(Vol_Table[self.CountEnv xor self.Attack]); If (self.EnvelopeA<>0) then self.VolA:=self.VolE; If (self.EnvelopeB<>0) then self.VolB:=self.VolE; If (self.EnvelopeC<>0) then self.VolC:=self.VolE; end; end; lOut1:=trunc(((VolA*self.VolA)/STEP)*self.gain0*self.amp); lOut2:=trunc(((VolB*self.VolB)/STEP)*self.gain1*self.amp); lOut3:=trunc(((VolC*self.VolC)/STEP)*self.gain2*self.amp); temp2:=trunc(((((VolA*self.VolA)/STEP)*self.gain0)+(((VolB*self.VolB)/STEP)*self.gain1)+(((VolC*self.VolC)/STEP))*self.gain2)*self.amp); if lout1>32767 then salida_ay[1]:=32767 else if lout1<-32767 then salida_ay[1]:=-32767 else salida_ay[1]:=lout1; if lout2>32767 then salida_ay[2]:=32767 else if lout2<-32767 then salida_ay[2]:=-32767 else salida_ay[2]:=lout2; if lout3>32767 then salida_ay[3]:=32767 else if lout3<-32767 then salida_ay[3]:=-32767 else salida_ay[3]:=lout3; if temp2>32767 then salida_ay[0]:=32767 else if temp2<-32767 then salida_ay[0]:=-32767 else salida_ay[0]:=temp2; update_internal:=@salida_ay[0]; end; procedure ay8910_chip.update; begin self.update_internal; tsample[self.tsample_num,sound_status.posicion_sonido]:=salida_ay[0]; if sound_status.stereo then tsample[self.tsample_num,sound_status.posicion_sonido+1]:=salida_ay[0]; end; end.
unit nsLogManager; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Logging\nsLogManager.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnsLogManager" MUID: (55B761180244) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , l3SimpleObject , LoggingWrapperInterfaces , LoggingUnit ; type TnsLogManager = class(Tl3SimpleObject, InsLogManager) private f_LoggingTestService: InsLoggingTestService; f_LogManager: ILogManager; protected function pm_GetLogManager: ILogManager; procedure AddEvent(aLogEvent: TLogEvent; const aData: InsLogEventData); procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; procedure ClearFields; override; public class function Instance: TnsLogManager; {* Метод получения экземпляра синглетона TnsLogManager } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } protected property LogManager: ILogManager read pm_GetLogManager; end;//TnsLogManager implementation uses l3ImplUses , DataAdapter , nsLoggingTestService , TypInfo , SysUtils , l3Base //#UC START# *55B761180244impl_uses* //#UC END# *55B761180244impl_uses* ; var g_TnsLogManager: TnsLogManager = nil; {* Экземпляр синглетона TnsLogManager } procedure TnsLogManagerFree; {* Метод освобождения экземпляра синглетона TnsLogManager } begin l3Free(g_TnsLogManager); end;//TnsLogManagerFree function TnsLogManager.pm_GetLogManager: ILogManager; //#UC START# *55B761D70223_55B761180244get_var* //#UC END# *55B761D70223_55B761180244get_var* begin //#UC START# *55B761D70223_55B761180244get_impl* if not Assigned(f_LogManager) and Assigned(DefDataAdapter) then f_LogManager := DefDataAdapter.LogManager; Result := f_LogManager; //#UC END# *55B761D70223_55B761180244get_impl* end;//TnsLogManager.pm_GetLogManager procedure TnsLogManager.AddEvent(aLogEvent: TLogEvent; const aData: InsLogEventData); //#UC START# *55B760550256_55B761180244_var* var l_LogString: String; //#UC END# *55B760550256_55B761180244_var* begin //#UC START# *55B760550256_55B761180244_impl* l_LogString := GetEnumName(TypeInfo(TLogEvent), Ord(aLogEvent)) + aData.AsString; f_LoggingTestService.AddLogString(l_LogString); LogManager.AddEvent(aLogEvent, aData.AsLogEventData); //#UC END# *55B760550256_55B761180244_impl* end;//TnsLogManager.AddEvent class function TnsLogManager.Instance: TnsLogManager; {* Метод получения экземпляра синглетона TnsLogManager } begin if (g_TnsLogManager = nil) then begin l3System.AddExitProc(TnsLogManagerFree); g_TnsLogManager := Create; end; Result := g_TnsLogManager; end;//TnsLogManager.Instance class function TnsLogManager.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TnsLogManager <> nil; end;//TnsLogManager.Exists procedure TnsLogManager.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_55B761180244_var* //#UC END# *479731C50290_55B761180244_var* begin //#UC START# *479731C50290_55B761180244_impl* f_LogManager := nil; f_LoggingTestService := nil; inherited; //#UC END# *479731C50290_55B761180244_impl* end;//TnsLogManager.Cleanup procedure TnsLogManager.InitFields; //#UC START# *47A042E100E2_55B761180244_var* //#UC END# *47A042E100E2_55B761180244_var* begin //#UC START# *47A042E100E2_55B761180244_impl* inherited; f_LogManager := nil; f_LoggingTestService := TnsLoggingTestService.Instance; //#UC END# *47A042E100E2_55B761180244_impl* end;//TnsLogManager.InitFields procedure TnsLogManager.ClearFields; begin f_LogManager := nil; inherited; end;//TnsLogManager.ClearFields end.
unit uJanelaProgressMutilThreading; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.LogEvents.Progress, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm43 = class(TForm) Memo1: TMemo; Button1: TButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } procedure LogProgressEvent(Sender: TObject; ATipo: TLogEventType; msg: string; APosition: double); public { Public declarations } end; var Form43: TForm43; implementation {$R *.dfm} Uses System.LogEvents, System.Threading; procedure TForm43.Button1Click(Sender: TObject); var n: integer; i: integer; j:integer; begin j := 0; for i := 0 to 1000 do begin TTask.create( procedure begin n := random(1000); LogEvents.DoProgress(self, 0, etPreparing, 'Iniciado'); TThread.Sleep(n); inc(j); LogEvents.DoProgress(self, 0, etFinished, 'Terminei '+j.ToString + 'I: '+i.ToString ); end).start; end; end; procedure TForm43.FormCreate(Sender: TObject); begin LogEvents.register(self, LogProgressEvent, 0); LogEvents.DoProgress(self, 0, etCreating, 'Iniciado'); end; procedure TForm43.LogProgressEvent(Sender: TObject; ATipo: TLogEventType; msg: string; APosition: double); //var n:double; begin try // n := 9999 / 0; raise Exception.Create('Error Message'); Memo1.lines.Add(msg); except on e:exception do memo1.Lines.Add(e.message); end; end; end.
program retrieve; {-----------------------------------------------------------------------} {Author: Travis Keep Modifications: 3-1-97 Added drive letter to command line} {-----------------------------------------------------------------------} uses dos; type retrievetype=record f:file; disknum:integer; drivenum:integer; control:word; isopened:boolean end; var r:retrievetype; g_buffer:pointer; Function ischecksumvalid(var r:retrievetype;cs:longint):boolean; var temp:boolean; hipart:word; lopart:word; p:^word; segment,offset:word; begin segment := seg(cs); offset := ofs(cs); p := ptr(segment,offset); lopart := p^; p := ptr(segment,offset+sizeof(word)); hipart := p^; if r.disknum = 1 then r.control := hipart; if (r.control = hipart) and (r.disknum = lopart) then temp := true else temp := false; ischecksumvalid := temp end; Procedure retrieveinit(var r:retrievetype;drive:char); begin r.disknum := 0; r.drivenum := (ord(drive) and 95) - 64; r.isopened := false end; Function retrievedriveletter(var r:retrievetype):char; begin retrievedriveletter := chr(r.drivenum + 64) end; Procedure retrieveprompt(var r:retrievetype); var error:integer; done:boolean; cs:longint; result:word; fname:string[20]; begin r.disknum := r.disknum + 1; write('Insert disk ',r.disknum,' and press ENTER to resume.'); readln; done := false; fname := '?:\tar.dat'; fname[1] := retrievedriveletter(r); repeat assign(r.f,fname); {$I-} reset(r.f,1); {$I+} error := IOresult; if error <> 0 then begin write('Error reading drive ',retrievedriveletter(r),'. Press ENTER to retry.'); readln end else begin blockread(r.f,cs,sizeof(cs),result); if (result < sizeof(cs)) then begin write('Error reading drive ',retrievedriveletter(r),'. Press ENTER to retry.'); readln; close(r.f) end else if not ischecksumvalid(r,cs) then begin write('Wrong disk! '); write('Insert disk ',r.disknum,' and press ENTER.'); readln; close(r.f) end else begin r.isopened := true; done := true end end until done end; Procedure retrieveread(var r:retrievetype;var buffer;count:word); var lefttoread,result:word; segment,offset:word; p:pointer; begin lefttoread := count; segment := Seg(buffer); offset := Ofs(buffer); while lefttoread > 0 do begin if not r.isopened then retrieveprompt(r); p := ptr(segment,offset); blockread(r.f,p^,lefttoread,result); if result < lefttoread then begin close(r.f); r.isopened := false; lefttoread := lefttoread - result; offset := offset + result end else lefttoread := 0 end end; Procedure retrieveclose(var r:retrievetype); begin if r.isopened then close(r.f) end; Procedure curattrread(var r:retrievetype;var srec:SearchRec); begin retrieveread(r,srec,sizeof(SearchRec)) end; Procedure curfileread(var r:retrievetype;var srec:SearchRec); var f:file; numwritten:word; blocksize:word; lefttoread:longint; error:integer; begin assign(f,srec.Name); {$I-} rewrite(f,1); {$I+} error := IOresult; if (error <> 0) then writeln('Could not create '+fexpand(srec.Name)); lefttoread := srec.size; while (lefttoread > 0) do begin if (lefttoread < 65520) then blocksize := lefttoread else blocksize := 65520; retrieveread(r,g_buffer^,blocksize); if error = 0 then blockwrite(f,g_buffer^,blocksize,numwritten) else numwritten := blocksize; if (numwritten < blocksize) then begin writeln('Out of disk space'); halt(1) end; lefttoread := lefttoread - blocksize end; if error = 0 then begin setftime(f,srec.time); close(f); setfattr(f,srec.attr) end end; Procedure curdirsetattr(var srec:searchrec); var f:file; begin assign(f,srec.name); setfattr(f,(srec.attr and 239)) end; Function isenddir(var srec:searchrec):boolean; begin isenddir := (srec.size = -1) end; Function isendall(var srec:searchrec):boolean; begin isendall := (srec.size = -2) end; Procedure retrievefiles; var r:retrievetype; srec:searchrec; done:boolean; error:integer; thedrive:string[2]; begin thedrive := paramstr(1); if thedrive = '' then retrieveinit(r,'a') else begin if not (thedrive[1] in ['A'..'Z','a'..'z']) then begin writeln('Invalid drive letter on command line'); halt(1) end; retrieveinit(r,thedrive[1]) end; done := false; repeat curattrread(r,srec); if isendall(srec) then done := true else if isenddir(srec) then chdir('..') else if (srec.Attr and 16) > 0 then begin {$I-} mkdir(srec.Name); {$I+} error := IOresult; chdir(srec.Name) end else curfileread(r,srec) until done; retrieveclose(r) end; begin FileMode := 0; getmem(g_buffer,65520); retrievefiles end.
{************************************************************************} { TRTFLabel component } { for Delphi & C++Builder } { } { written by } { TMS Software } { copyright © 1999-2013 } { Email : info@tmssoftware.com } { Website : http://www.tmssoftware.com } { } { The source code is given as is. The author is not responsible } { for any possible damage done due to the use of this code. } { The component can be freely used in any application. The complete } { source code remains property of the author and may not be distributed, } { published, given or sold in any form as such. No parts of the source } { code can be included in any other component or application without } { written authorization of the author. } {************************************************************************} unit RTFLDE; interface {$I TMSDEFS.INC} uses Classes, Forms, Dialogs, RTFLabel, FRTFBox, Messages, Windows, Controls, DesignIntf, DesignEditors; type TRichTextProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; function GetValue:string; override; procedure Edit; override; end; implementation { TRichTextProperty } function TRichTextProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog,paReadOnly]; end; function TRichTextProperty.GetValue: string; begin Result := '(TRichText)'; end; procedure TRichTextProperty.Edit; var rtfbox: TRTFBox; ms: TStringStream; s: string; begin rtfbox := TRTFBox.Create(application); try s := (GetComponent(0) as TRTFLabel).RichText; ms := TStringStream.Create(''); try ms.WriteString(s); ms.position := 0; rtfbox.RTFControl.lines.LoadFromStream(ms); finally ms.free; end; if rtfbox.Showmodal = mrOk then begin ms := TStringStream.Create(''); try rtfbox.RTFControl.Lines.SaveToStream(ms); s := ms.DataString; finally ms.Free; end; (GetComponent(0) as TRTFLabel).RichText := s; (GetComponent(0) as TRTFLabel).Repaint; Modified; end; finally rtfbox.Free; end; end; end.
unit fDistribution; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,cMegaROM,cConfiguration; type TfrmDistribution = class(TForm) lblOriginalFile: TLabel; lblOutputPatch: TLabel; txtOriginalROM: TEdit; txtOutputPatch: TEdit; lblPatchFormat: TLabel; cbPatchFormat: TComboBox; cmdOK: TButton; cmdCancel: TButton; OpenDialog: TOpenDialog; cmdOriginal: TButton; cmdOutput: TButton; SaveDialog: TSaveDialog; procedure cmdOriginalClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure cmdOutputClick(Sender: TObject); procedure cmdOKClick(Sender: TObject); private _ROMData : TMegamanROM; _EditorConfig : TRRConfig; { Private declarations } public property ROMData : TMegamanROM read _ROMData write _ROMData; property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig; { Public declarations } end; var frmDistribution: TfrmDistribution; implementation uses uglobal, ulunarcompress; {$R *.dfm} procedure TfrmDistribution.cmdOriginalClick(Sender: TObject); begin if (txtOriginalROM.Text <> '') and (DirectoryExists(ExtractFileDir(txtOriginalROM.Text))) then OpenDialog.InitialDir := ExtractFileDir(txtOriginalROM.Text) else OpenDialog.InitialDir := ExtractFileDir(Application.ExeName); if OpenDialog.Execute then begin if (OpenDialog.FileName <> '') and (FileExists(OpenDialog.Filename)) then begin txtOriginalROM.Text := OpenDialog.FileName; txtOriginalROM.SelStart := Length(txtOriginalROM.Text); end; end; end; procedure TfrmDistribution.FormShow(Sender: TObject); begin txtOriginalROM.Text := _EditorConfig.OriginalROMFile; txtOutputPatch.Text := _EditorConfig.IPSOutput; end; procedure TfrmDistribution.cmdOutputClick(Sender: TObject); begin if (txtOutputPatch.Text <> '') and (DirectoryExists(ExtractFileDir(txtOutputPatch.Text))) then SaveDialog.InitialDir := ExtractFileDir(txtOutputPatch.Text) else SaveDialog.InitialDir := ExtractFileDir(Application.ExeName); if SaveDialog.Execute then begin txtOutputPatch.Text := SaveDialog.FileName; txtOutputPatch.SelStart := Length(txtOutputPatch.Text); end; end; procedure TfrmDistribution.cmdOKClick(Sender: TObject); var output : String; begin if Assigned(_ROMData) then begin if (FileExists(txtOriginalROM.Text) = true) then begin if cbPatchFormat.ItemIndex = 0 then begin if txtOutputPatch.Text = '' then Output := ChangeFileExt(_ROMData.Filename,'.ips') else Output := _EditorConfig.IPSOutput; _ROMData.Save; LunarIPSCreate(handle,PChar(Output),PChar(txtOriginalROM.Text),PChar(_ROMData.Filename),0); end; end else begin ModalResult := mrNone; showmessage('Please enter the original ROM filename to base the patch off.'); end; end; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_Queue * Implements a generic thread safe stack *********************************************************************************************************************** } Unit TERRA_Stack; {$I terra.inc} Interface Uses TERRA_String, TERRA_Utils, TERRA_Collections, TERRA_Queue; Type Stack = Class(Queue) Public Function Push(Item:CollectionObject):Boolean; Override; Function Pop():CollectionObject; Override; End; Implementation { Stack } Function Stack.Pop:CollectionObject; Begin Result := _First; If (_First <> Nil) Then _First := _First.Next; End; Function Stack.Push(Item: CollectionObject): Boolean; Begin Item.Next := _First; _First := Item; Result := True; End; End.
unit InfoBLTRTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoBLTRRecord = record PLender: String[4]; PLoanNumber: String[18]; POccur: String[4]; PLetterDate: String[8]; PLetterTime: String[6]; PUserId: String[10]; PModCount: Integer; PLetterCode: String[6]; End; TInfoBLTRClass2 = class public PLender: String[4]; PLoanNumber: String[18]; POccur: String[4]; PLetterDate: String[8]; PLetterTime: String[6]; PUserId: String[10]; PModCount: Integer; PLetterCode: String[6]; End; // function CtoRInfoBLTR(AClass:TInfoBLTRClass):TInfoBLTRRecord; // procedure RtoCInfoBLTR(ARecord:TInfoBLTRRecord;AClass:TInfoBLTRClass); TInfoBLTRBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoBLTRRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoBLTR = (InfoBLTRPrimaryKey, InfoBLTRbldat, InfoBLTRbydate); TInfoBLTRTable = class( TDBISAMTableAU ) private FDFLender: TStringField; FDFLoanNumber: TStringField; FDFOccur: TStringField; FDFLetterDate: TStringField; FDFLetterTime: TStringField; FDFUserId: TStringField; FDFModCount: TIntegerField; FDFLetterCode: TStringField; FDFLetter: TBlobField; procedure SetPLender(const Value: String); function GetPLender:String; procedure SetPLoanNumber(const Value: String); function GetPLoanNumber:String; procedure SetPOccur(const Value: String); function GetPOccur:String; procedure SetPLetterDate(const Value: String); function GetPLetterDate:String; procedure SetPLetterTime(const Value: String); function GetPLetterTime:String; procedure SetPUserId(const Value: String); function GetPUserId:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetPLetterCode(const Value: String); function GetPLetterCode:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoBLTR); function GetEnumIndex: TEIInfoBLTR; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoBLTRRecord; procedure StoreDataBuffer(ABuffer:TInfoBLTRRecord); property DFLender: TStringField read FDFLender; property DFLoanNumber: TStringField read FDFLoanNumber; property DFOccur: TStringField read FDFOccur; property DFLetterDate: TStringField read FDFLetterDate; property DFLetterTime: TStringField read FDFLetterTime; property DFUserId: TStringField read FDFUserId; property DFModCount: TIntegerField read FDFModCount; property DFLetterCode: TStringField read FDFLetterCode; property DFLetter: TBlobField read FDFLetter; property PLender: String read GetPLender write SetPLender; property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber; property POccur: String read GetPOccur write SetPOccur; property PLetterDate: String read GetPLetterDate write SetPLetterDate; property PLetterTime: String read GetPLetterTime write SetPLetterTime; property PUserId: String read GetPUserId write SetPUserId; property PModCount: Integer read GetPModCount write SetPModCount; property PLetterCode: String read GetPLetterCode write SetPLetterCode; published property Active write SetActive; property EnumIndex: TEIInfoBLTR read GetEnumIndex write SetEnumIndex; end; { TInfoBLTRTable } TInfoBLTRQuery = class( TDBISAMQueryAU ) private FDFLender: TStringField; FDFLoanNumber: TStringField; FDFOccur: TStringField; FDFLetterDate: TStringField; FDFLetterTime: TStringField; FDFUserId: TStringField; FDFModCount: TIntegerField; FDFLetterCode: TStringField; FDFLetter: TBlobField; procedure SetPLender(const Value: String); function GetPLender:String; procedure SetPLoanNumber(const Value: String); function GetPLoanNumber:String; procedure SetPOccur(const Value: String); function GetPOccur:String; procedure SetPLetterDate(const Value: String); function GetPLetterDate:String; procedure SetPLetterTime(const Value: String); function GetPLetterTime:String; procedure SetPUserId(const Value: String); function GetPUserId:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetPLetterCode(const Value: String); function GetPLetterCode:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; public function GetDataBuffer:TInfoBLTRRecord; procedure StoreDataBuffer(ABuffer:TInfoBLTRRecord); property DFLender: TStringField read FDFLender; property DFLoanNumber: TStringField read FDFLoanNumber; property DFOccur: TStringField read FDFOccur; property DFLetterDate: TStringField read FDFLetterDate; property DFLetterTime: TStringField read FDFLetterTime; property DFUserId: TStringField read FDFUserId; property DFModCount: TIntegerField read FDFModCount; property DFLetterCode: TStringField read FDFLetterCode; property DFLetter: TBlobField read FDFLetter; property PLender: String read GetPLender write SetPLender; property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber; property POccur: String read GetPOccur write SetPOccur; property PLetterDate: String read GetPLetterDate write SetPLetterDate; property PLetterTime: String read GetPLetterTime write SetPLetterTime; property PUserId: String read GetPUserId write SetPUserId; property PModCount: Integer read GetPModCount write SetPModCount; property PLetterCode: String read GetPLetterCode write SetPLetterCode; published property Active write SetActive; end; { TInfoBLTRTable } procedure Register; implementation function TInfoBLTRTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoBLTRTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoBLTRTable.GenerateNewFieldName } function TInfoBLTRTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoBLTRTable.CreateField } procedure TInfoBLTRTable.CreateFields; begin FDFLender := CreateField( 'Lender' ) as TStringField; FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField; FDFOccur := CreateField( 'Occur' ) as TStringField; FDFLetterDate := CreateField( 'LetterDate' ) as TStringField; FDFLetterTime := CreateField( 'LetterTime' ) as TStringField; FDFUserId := CreateField( 'UserId' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFLetterCode := CreateField( 'LetterCode' ) as TStringField; FDFLetter := CreateField( 'Letter' ) as TBlobField; end; { TInfoBLTRTable.CreateFields } procedure TInfoBLTRTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoBLTRTable.SetActive } procedure TInfoBLTRTable.SetPLender(const Value: String); begin DFLender.Value := Value; end; function TInfoBLTRTable.GetPLender:String; begin result := DFLender.Value; end; procedure TInfoBLTRTable.SetPLoanNumber(const Value: String); begin DFLoanNumber.Value := Value; end; function TInfoBLTRTable.GetPLoanNumber:String; begin result := DFLoanNumber.Value; end; procedure TInfoBLTRTable.SetPOccur(const Value: String); begin DFOccur.Value := Value; end; function TInfoBLTRTable.GetPOccur:String; begin result := DFOccur.Value; end; procedure TInfoBLTRTable.SetPLetterDate(const Value: String); begin DFLetterDate.Value := Value; end; function TInfoBLTRTable.GetPLetterDate:String; begin result := DFLetterDate.Value; end; procedure TInfoBLTRTable.SetPLetterTime(const Value: String); begin DFLetterTime.Value := Value; end; function TInfoBLTRTable.GetPLetterTime:String; begin result := DFLetterTime.Value; end; procedure TInfoBLTRTable.SetPUserId(const Value: String); begin DFUserId.Value := Value; end; function TInfoBLTRTable.GetPUserId:String; begin result := DFUserId.Value; end; procedure TInfoBLTRTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TInfoBLTRTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TInfoBLTRTable.SetPLetterCode(const Value: String); begin DFLetterCode.Value := Value; end; function TInfoBLTRTable.GetPLetterCode:String; begin result := DFLetterCode.Value; end; procedure TInfoBLTRTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Lender, String, 4, N'); Add('LoanNumber, String, 18, N'); Add('Occur, String, 4, N'); Add('LetterDate, String, 8, N'); Add('LetterTime, String, 6, N'); Add('UserId, String, 10, N'); Add('ModCount, Integer, 0, N'); Add('LetterCode, String, 6, N'); Add('Letter, Memo, 0, N'); end; end; procedure TInfoBLTRTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Lender;LoanNumber;Occur;LetterDate;LetterTime, Y, Y, N, N'); Add('bldat, Lender;LoanNumber;Occur;LetterDate;LetterTime, N, N, N, N'); Add('bydate, Lender;LetterDate;LoanNumber, N, N, N, N'); end; end; procedure TInfoBLTRTable.SetEnumIndex(Value: TEIInfoBLTR); begin case Value of InfoBLTRPrimaryKey : IndexName := ''; InfoBLTRbldat : IndexName := 'bldat'; InfoBLTRbydate : IndexName := 'bydate'; end; end; function TInfoBLTRTable.GetDataBuffer:TInfoBLTRRecord; var buf: TInfoBLTRRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLender := DFLender.Value; buf.PLoanNumber := DFLoanNumber.Value; buf.POccur := DFOccur.Value; buf.PLetterDate := DFLetterDate.Value; buf.PLetterTime := DFLetterTime.Value; buf.PUserId := DFUserId.Value; buf.PModCount := DFModCount.Value; buf.PLetterCode := DFLetterCode.Value; result := buf; end; procedure TInfoBLTRTable.StoreDataBuffer(ABuffer:TInfoBLTRRecord); begin DFLender.Value := ABuffer.PLender; DFLoanNumber.Value := ABuffer.PLoanNumber; DFOccur.Value := ABuffer.POccur; DFLetterDate.Value := ABuffer.PLetterDate; DFLetterTime.Value := ABuffer.PLetterTime; DFUserId.Value := ABuffer.PUserId; DFModCount.Value := ABuffer.PModCount; DFLetterCode.Value := ABuffer.PLetterCode; end; function TInfoBLTRTable.GetEnumIndex: TEIInfoBLTR; var iname : string; begin result := InfoBLTRPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoBLTRPrimaryKey; if iname = 'BLDAT' then result := InfoBLTRbldat; if iname = 'BYDATE' then result := InfoBLTRbydate; end; function TInfoBLTRQuery.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoBLTRQuery.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoBLTRQuery.GenerateNewFieldName } function TInfoBLTRQuery.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoBLTRQuery.CreateField } procedure TInfoBLTRQuery.CreateFields; begin FDFLender := CreateField( 'Lender' ) as TStringField; FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField; FDFOccur := CreateField( 'Occur' ) as TStringField; FDFLetterDate := CreateField( 'LetterDate' ) as TStringField; FDFLetterTime := CreateField( 'LetterTime' ) as TStringField; FDFUserId := CreateField( 'UserId' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFLetterCode := CreateField( 'LetterCode' ) as TStringField; FDFLetter := CreateField( 'Letter' ) as TBlobField; end; { TInfoBLTRQuery.CreateFields } procedure TInfoBLTRQuery.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoBLTRQuery.SetActive } procedure TInfoBLTRQuery.SetPLender(const Value: String); begin DFLender.Value := Value; end; function TInfoBLTRQuery.GetPLender:String; begin result := DFLender.Value; end; procedure TInfoBLTRQuery.SetPLoanNumber(const Value: String); begin DFLoanNumber.Value := Value; end; function TInfoBLTRQuery.GetPLoanNumber:String; begin result := DFLoanNumber.Value; end; procedure TInfoBLTRQuery.SetPOccur(const Value: String); begin DFOccur.Value := Value; end; function TInfoBLTRQuery.GetPOccur:String; begin result := DFOccur.Value; end; procedure TInfoBLTRQuery.SetPLetterDate(const Value: String); begin DFLetterDate.Value := Value; end; function TInfoBLTRQuery.GetPLetterDate:String; begin result := DFLetterDate.Value; end; procedure TInfoBLTRQuery.SetPLetterTime(const Value: String); begin DFLetterTime.Value := Value; end; function TInfoBLTRQuery.GetPLetterTime:String; begin result := DFLetterTime.Value; end; procedure TInfoBLTRQuery.SetPUserId(const Value: String); begin DFUserId.Value := Value; end; function TInfoBLTRQuery.GetPUserId:String; begin result := DFUserId.Value; end; procedure TInfoBLTRQuery.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TInfoBLTRQuery.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TInfoBLTRQuery.SetPLetterCode(const Value: String); begin DFLetterCode.Value := Value; end; function TInfoBLTRQuery.GetPLetterCode:String; begin result := DFLetterCode.Value; end; function TInfoBLTRQuery.GetDataBuffer:TInfoBLTRRecord; var buf: TInfoBLTRRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLender := DFLender.Value; buf.PLoanNumber := DFLoanNumber.Value; buf.POccur := DFOccur.Value; buf.PLetterDate := DFLetterDate.Value; buf.PLetterTime := DFLetterTime.Value; buf.PUserId := DFUserId.Value; buf.PModCount := DFModCount.Value; buf.PLetterCode := DFLetterCode.Value; result := buf; end; procedure TInfoBLTRQuery.StoreDataBuffer(ABuffer:TInfoBLTRRecord); begin DFLender.Value := ABuffer.PLender; DFLoanNumber.Value := ABuffer.PLoanNumber; DFOccur.Value := ABuffer.POccur; DFLetterDate.Value := ABuffer.PLetterDate; DFLetterTime.Value := ABuffer.PLetterTime; DFUserId.Value := ABuffer.PUserId; DFModCount.Value := ABuffer.PModCount; DFLetterCode.Value := ABuffer.PLetterCode; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoBLTRTable, TInfoBLTRQuery, TInfoBLTRBuffer ] ); end; { Register } function TInfoBLTRBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..8] of string = ('LENDER','LOANNUMBER','OCCUR','LETTERDATE','LETTERTIME','USERID' ,'MODCOUNT','LETTERCODE' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 8) and (flist[x] <> s) do inc(x); if x <= 8 then result := x else result := 0; end; function TInfoBLTRBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftInteger; 8 : result := ftString; end; end; function TInfoBLTRBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLender; 2 : result := @Data.PLoanNumber; 3 : result := @Data.POccur; 4 : result := @Data.PLetterDate; 5 : result := @Data.PLetterTime; 6 : result := @Data.PUserId; 7 : result := @Data.PModCount; 8 : result := @Data.PLetterCode; end; end; end.
unit uDmDados; interface uses System.SysUtils, System.Variants, System.Classes, Data.DB, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, uDWConstsData, uRESTDWPoolerDB, uRESTDWBase, uDWAbout, uDWConsts, uRESTDWServerEvents, uDWJSONObject, IPPeerClient, REST.Client, REST.Authenticator.Basic, Data.Bind.Components, Data.Bind.ObjectScope, REST.Response.Adapter, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.FMXUI.Wait, FireDAC.DApt, FireDAC.Stan.StorageBin, System.DateUtils, FireDAC.Phys.SQLiteVDataSet, System.ImageList, FMX.ImgList; type TSinc = (tP, tC, tF, tU, tV, tVI); type TDmDados = class(TDataModule) ConexaoInterna: TFDConnection; RESTDWDataBase1: TRESTDWDataBase; RESTClientPooler1: TRESTClientPooler; FDTransaction1: TFDTransaction; rdwSQL: TRESTDWClientSQL; procedure DataModuleCreate(Sender: TObject); private { Private declarations } public { Public declarations } // procedure getfotos; end; var DmDados: TDmDados; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} uses System.IOUtils, uFrmProdutos, System.IniFiles, FMX.Dialogs, uFrmUtilFormate, uDataBase; procedure TDmDados.DataModuleCreate(Sender: TObject); var LDataBasePath, ip, porta: string; ArquivoINI : TIniFile; begin ConexaoInterna.Params.Values['DriverID'] := 'SQLite'; ConexaoInterna.LoginPrompt := false; {$IF DEFINED (ANDROID)} ConexaoInterna.Params.Values['Database'] := TPath.Combine(TPath.GetDocumentsPath, 'g2mobile.db'); ConexaoInterna.Params.Add('SharedCache=False'); ConexaoInterna.Params.Add('LockingMode=Normal'); {$ENDIF} {$IF DEFINED (MSWINDOWS)} ConexaoInterna.Params.Values['Database'] := 'E:\G2Sistemas\G2Mobile\Mobile\BD\g2mobile.db'; {$ENDIF} LDataBasePath := ConexaoInterna.Params.Values['Database']; if not(FileExists(LDataBasePath)) then StrToInt('1'); ConexaoInterna.Connected := True; end; end.
unit aeSceneObject; interface (* Base scene object. Can keep track of its orientation and translation in space. Used for a base class for other scene graph things. *) uses types, math, aeConst, aeTransform, System.Generics.Collections, aeMaths, sysutils; type TaeSetDirtyCallback = procedure of object; type TaeSceneObject = class constructor Create; // set callback to signal to node that it has to put children dirty. procedure SetDirtyCallback(callback: TaeSetDirtyCallback); /// <summary> /// Rotate around axis. Angle in degrees. /// </summary> procedure Rotate(axis: TPoint3D; degrees: single); procedure SetRotation(rotationmatrix: TaeMatrix44); /// <summary> /// Set translation. /// </summary> procedure Move(p: TPoint3D); function getPosition: TPoint3D; function GetPositionString: string; function GetForwardVector: TPoint3D; procedure SetMinimumHeight(mh: single); /// <summary> /// Set scale. /// </summary> procedure Scale(Scale: single); overload; procedure Scale(x, y, z: single); overload; /// <summary> /// Orientate this object towards some point. /// </summary> procedure LookAt(own_pos, target_pos: TPoint3D); overload; procedure LookAt(own_pos, target_pos, up_vector: TPoint3D); overload; procedure LookAt(own_pos: TPoint3D; obj: TaeSceneObject); overload; function GetLocalTransformMatrix: TaeMatrix44; function GetLocalTransform: TaeTransform; procedure resetOrientation; function IsLocalTransformDirty: boolean; procedure SetLocalTransformDirty(dirty: boolean); private // this transform contains stuff done to only this object! _localTransform: TaeTransform; // this matrix contains the sum of all transformations _localTransformMatrix: TaeMatrix44; // pointer to a procedure which is called after a transform is applied. _dirtyCallback: TaeSetDirtyCallback; // minimum height that this object can go! _minHeight: single; protected // transform dirty flag. _localTransformDirty: boolean; end; implementation { TaeSceneObject } constructor TaeSceneObject.Create; begin self._localTransform := TaeTransform.Create; self.resetOrientation; self._minHeight := 0.0; self.SetLocalTransformDirty(false); self._dirtyCallback := nil; self._localTransformMatrix.loadIdentity; // self._transformStack := TList<TaeTransform>.Create; end; // function TaeSceneObject.GetLocalTransformMatrix: TaeMatrix44; // begin // result := self._localTransform.getTransformMatrix(); // end; procedure TaeSceneObject.LookAt(own_pos, target_pos: TPoint3D); begin self._localTransform.LookAt(own_pos, target_pos, Point3D(0, 1, 0)); self.SetLocalTransformDirty(true); end; procedure TaeSceneObject.LookAt(own_pos: TPoint3D; obj: TaeSceneObject); begin self.LookAt(own_pos, obj.getPosition); end; procedure TaeSceneObject.LookAt(own_pos, target_pos, up_vector: TPoint3D); begin self._localTransform.LookAt(own_pos, target_pos, up_vector); self.SetLocalTransformDirty(true); end; procedure TaeSceneObject.resetOrientation; begin self._localTransform.Reset; self.SetLocalTransformDirty(true); end; procedure TaeSceneObject.Rotate(axis: TPoint3D; degrees: single); begin self._localTransform.RotateDegrees(axis, degrees); self.SetLocalTransformDirty(true); end; function TaeSceneObject.getPosition: TPoint3D; begin result := self._localTransform.getPosition; end; function TaeSceneObject.GetPositionString: string; var p: TPoint3D; begin p := self.getPosition; result := 'X=' + FloatToStr(RoundTo(p.x, -2)) + ' Y=' + FloatToStr(RoundTo(p.y, -2)) + 'Z=' + FloatToStr(RoundTo(p.z, -2)); end; function TaeSceneObject.IsLocalTransformDirty: boolean; begin result := self._localTransformDirty; end; function TaeSceneObject.GetForwardVector: TPoint3D; begin // result := (Point3D(0, 0, 1) * self._localTransform).Normalize; end; function TaeSceneObject.GetLocalTransform: TaeTransform; begin result := self._localTransform; end; function TaeSceneObject.GetLocalTransformMatrix: TaeMatrix44; var Translate, Scale, Rotation: TaeMatrix44; begin // 1. rotate 2. scale 3. translate // opengl uses left multiplication // we need to apply the transformations in reverse order if (self.IsLocalTransformDirty) then begin Translate.loadIdentity; Translate.SetTranslation(self._localTransform.getPosition); Scale.loadIdentity; Scale.SetScale(self._localTransform.GetScale); Rotation.loadIdentity; Rotation := self._localTransform.GetRotation; self._localTransformMatrix.loadIdentity; self._localTransformMatrix := self._localTransformMatrix * Scale; self._localTransformMatrix := self._localTransformMatrix * Rotation; self._localTransformMatrix := self._localTransformMatrix * Translate; self._localTransformDirty := false; end; result := _localTransformMatrix; end; procedure TaeSceneObject.Move(p: TPoint3D); begin if (p <> self._localTransform.getPosition) then begin self._localTransform.SetPosition(p); self.SetLocalTransformDirty(true); end; end; procedure TaeSceneObject.Scale(Scale: single); begin self._localTransform.SetScale(Scale); self.SetLocalTransformDirty(true); end; procedure TaeSceneObject.SetLocalTransformDirty(dirty: boolean); begin self._localTransformDirty := dirty; // notify callback if it's set that all children are to be flagged as dirty! // this only applies if this class is inherited by a Node. if (Assigned(self._dirtyCallback)) then self._dirtyCallback; end; procedure TaeSceneObject.Scale(x, y, z: single); begin self._localTransform.SetScale(x, y, z); self.SetLocalTransformDirty(true); end; procedure TaeSceneObject.SetDirtyCallback(callback: TaeSetDirtyCallback); begin self._dirtyCallback := callback; end; procedure TaeSceneObject.SetMinimumHeight(mh: single); begin self._minHeight := mh; end; procedure TaeSceneObject.SetRotation(rotationmatrix: TaeMatrix44); begin self._localTransform.SetRotationMatrix(rotationmatrix); self.SetLocalTransformDirty(true); end; end.