text
stringlengths
14
6.51M
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, DateUtils, MMSystem, StdCtrls, ComCtrls; type TForm1 = class(TForm) Timer1: TTimer; Button1: TButton; DateTimePicker1: TDateTimePicker; Button2: TButton; Label1: TLabel; DateTimePicker2: TDateTimePicker; Label2: TLabel; Label3: TLabel; Button3: TButton; Label4: TLabel; Label5: TLabel; procedure Timer1Timer(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button3Click(Sender: TObject); private myTime: TDateTime; // Holds a value for date and time of alarm public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin if Timer1.Enabled = true then // If timer is active begin Timer1.Enabled := false; // Disable it sndPlaySound(nil, 0); // Stop playing the sound Label3.Caption := 'Alarm stopped at: ' + DateTimeToStr(Now); // Update status end; end; procedure TForm1.Button2Click(Sender: TObject); begin // My time combines date and time values from two DateTimePicker myTime := EncodeDateTime(YearOf(DateTimePicker1.DateTime), MonthOf(DateTimePicker1.DateTime), DayOf(DateTimePicker1.DateTime), HourOf(DateTimePicker2.DateTime), MinuteOf(DateTimePicker2.DateTime), SecondOf(DateTimePicker2.DateTime), MilliSecondOf(DateTimePicker2.DateTime)); Label3.Caption := 'Alarm set to: ' + DateTimeToStr(myTime); // Update status Timer1.Enabled := true; // Enable alarm / timer end; procedure TForm1.Button3Click(Sender: TObject); begin Close; // Close the application end; procedure TForm1.FormCreate(Sender: TObject); begin // Set both DateTimePickers to current datetime when application starts DateTimePicker1.DateTime := Now; DateTimePicker2.DateTime := Now; end; procedure TForm1.Timer1Timer(Sender: TObject); begin if Now > myTime then // if our set datetime value is in the past begin Label3.Caption := 'Alarm started at: ' + DateTimeToStr(myTime) + ', current time: ' + DateTimeToStr(Now); // Update status sndPlaySound('C:\Windows\Media\chimes.wav', SND_NODEFAULT Or SND_ASYNC Or SND_LOOP); // Play sound end; end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Data.DBXMetadataCommon; interface uses System.JSON; type /// <summary> Class to delegate the setting of the Invocation Metadata. /// </summary> /// <remarks> This is done so that the logic /// can be completely removed from the DBXJSonConnectionHandler instance, as this will not /// compile for dotnet, due to the fact that dotnet does not include DBXJSONReflect. /// </remarks> TInvocationMetadataDelegate = class public /// <summary> Sets the metaData into threadvar field indirectly /// </summary> /// <remarks> Note that this will take possession of (and immediately free) the passed in JSONObject) /// </remarks> /// <param name="metaData">The metadata to set</param> class procedure StoreMetadata(var MetaData: TJSONObject); static; /// <summary> If the passed in connection handler is an instance of DBXJSonConnectionHandler then /// this method will write out the metadata from this instance. /// </summary> /// <remarks> This will be done, for example, /// when not running in in-process mode, and needing to pass the metadata from the server back /// to the DataSnap service. /// </remarks> /// <param name="connectionHandler">The connection handler to use</param> class procedure WriteMetadata(const ConnectionHandler: TObject); static; /// <summary> Clears the metadata if not running in-process /// </summary> /// <param name="connectionHandler">the connection handler to use to determine if this is running in-process</param> class procedure ClearMetadata(const ConnectionHandler: TObject); static; end; implementation uses Data.DBXMessageHandlerJSonCommon, Data.DBXPlatform, Data.DBXJSONReflect; const // Must match field name in TDSInvocationMetadata cQueryParamsFieldName = 'FQueryParams'; class procedure TInvocationMetadataDelegate.StoreMetadata(var MetaData: TJSONObject); var UnMarshal: TJSONUnMarshal; MarshalObj: TObject; LReverter: TReverterEvent; begin if MetaData <> nil then begin UnMarshal := TJSONUnMarshal.Create; // Register reverter to unmarshal TStringList. LReverter := TReverterEvent.Create; LReverter.TypeObjectReverter := StringListReverter; UnMarshal.RegisterReverter(TDSInvocationMetadata, cQueryParamsFieldName, LReverter); try MarshalObj := UnMarshal.Unmarshal(MetaData); if MarshalObj is TDSInvocationMetadata then SetInvocationMetadata(TDSInvocationMetadata(MarshalObj)); finally UnMarshal.Free; MetaData.Free; end; end; end; class procedure TInvocationMetadataDelegate.WriteMetadata(const ConnectionHandler: TObject); var MetaDataObj: TDSInvocationMetadata; Marshal: TJSONMarshal; MetaData: TJSONValue; LConverter: TConverterEvent; begin if ConnectionHandler is TDBXJSonConnectionHandler then begin MetaDataObj := GetInvocationMetadata(False); if MetaDataObj <> nil then begin Marshal := TJSONMarshal.Create; // Register converter to marshal TStringList. LConverter := TConverterEvent.Create; LConverter.TypeObjectConverter := StringListConverter; Marshal.RegisterConverter(TDSInvocationMetadata, cQueryParamsFieldName, LConverter); MetaData := nil; try MetaData := Marshal.Marshal(MetaDataObj); (TDBXJSonConnectionHandler(ConnectionHandler)).WriteMetadataData(TJSONObject(MetaData), False); finally MetaData.Free; Marshal.Free; end; end; end; end; class procedure TInvocationMetadataDelegate.ClearMetadata(const ConnectionHandler: TObject); begin if ConnectionHandler is TDBXJSonConnectionHandler then ClearInvocationMetadata(); end; end.
UNIT PLAYHSC; (* HSC Player Unit V1.0 -------------------- Written in 1994 by GLAMOROUS RAY^RADiCAL RHYTHMS Original code and .OBJ by CHiCKEN and ZWERG ZWACK^ELECTRONiC RATS This code is FREE WARE. This means that you can copy and distribute it as you like, but you may not charge any money for its distribution. If you intend to use this code in a commercial product than you have to get written permission from NEO Software Produktions GmbH Austria. Introduction: ------------- What is PLAYHSC? This unit is intended for use with the HSC tracker written by Zwerg Zwack and Chicken on low level support from NEO Software <g>. This unit supports an easy and fast to use way to play sound, so not all general functions of the player are included. It is not possible to do the polling - this is done by the player automatically, it links into the timer interrupt. General overview: ----------------- Below follows a description how to play sound files from your program, calling this unit. There are two ways: 1st: Play a sound file, loading from disk 2nd: Play a sound file, directly from included data. The first method is very easy and simple, the second one more cool ;). The player is build up as an object, so it is initialized on your heap when starting and deinstalled when finishing. Please note that the player does _no_ check for memory. So it's up to you to check if there's enough memory (heap) free to load the music - the player won't just do anything in that case. To get the object to work, you have to declare it as a variable. This is normally done this way: VAR Music : HSC_obj; Now the object is declared and has to be used and called by _you_. An object's variables and procedures a called like a record so you can do the following: Music.Init(0); Music.Done; Software implementation: ------------------------ CONSTRUCTOR HSC_obj.Init (AdlibAddress : WORD); -> Init the player and the object. You must supply a base address for the adlib card. If you want to use the player's autodetection routines, simply use 0 as the base. PROCEDURE HSC_Obj.Start; -> Start music file, located at HSC_Obj.Address. The address is set by either HSC_Obj.LoadMem or HSC_Obj.LoadFile; FUNCTION HSC_Obj.LoadFile (FileName):BOOLEAN; -> Load a file from disk into memory. If the file you tend to load is invalid or simply not there, the player won't play a single voice. The function returns if it has loaded the music or not. If not, there maybe was not enough memory or the file could not be loaded (due to non-existence etc.). PROCEDURE HSC_Obj.LoadMem (Music_Address : Pointer); -> "Load" music from disk. This has to be done to tell the player that the music is _not_ loaded from disk so the memory is not freed up when playing the next file. PROCEDURE HSC_Obj.Stop; -> Stop music (if playing). This has to be done if you want to stop the music. If you want to unload the music, simplay call HSC_Obj.Done as this (of course) stops the music, too! PROCEDURE HSC_Obj.Fade; -> Fade out music. This takes up to 4 seconds, so be sure to wait in you program for fade-out, otherwise you will "kill" the sound when calling HSC_Obj.Done (this will do a very nasty "pop"). DESTRUCTOR HSC_Obj.Done; -> Deinit object <g>. This frees up all memory allocated and stops the music. Hints & Tips section: --------------------- Make sure your program does not exit without calling the destructor or at least stopping the music. If you don't stop the music, your system will hang on loading a new program (This is because of the memory usage - the player still plays while the memory is already freed up and used by another program - "Zack!"). It is a wise idea to put the command into the @Exitproc. If you want to play more than one music file - okay - do it! ;) Examples: --------- Please see the enclosed file TSTHSC.PAS for more information. Including music into .EXE files: -------------------------------- All you need for doing this, is your sound file (*.HSC) and the program BINOBJ.EXE which came with your pascal package. Run the program like this: BINOBJ.EXE MUSIC.HSC MUSIC.OBJ MUSIC_DATA This converts the file MUSIC.HSC into MUSIC.OBJ with the public name set to MUSIC_DATA. Now all you have to do is to declare this object file within you program. This has to be done like this: {$F+} {$L MUSIC.OBJ} PROCEDURE MUSIC_DATA; EXTERNAL; {$F-} To play this file, try: HSC_Obj.LoadMem (@MUSIC_DATA); That's it! Last words: ----------- First, I'd like to comment on my code. I hope, you're able to under- stand this mess <g>. Second, don't bother me for the way it was written. I just know: it works. And it will work on other machines because it is written _cleanly_. If you think, you can do better: please do! (And send me a copy! :)) ) Greetings go to all RADiCAL RHYTHMS members for being an amazing posse. Last, but not least, thanks to Chicken and Zwerg Zwack for their rellay neat program. If you find any bugs, or have ideas for add-ons, please contact me: via modem : The UnderCover BBS - +49 2323 450 850 (9600+, 8N1) via fido : Christian Bartsch@2:2445/321.49 (classic) via phone : +49 2323 460 525 May, 23rd 1994 - GLAMOROUS RAY! C U in cyberspace... *) INTERFACE TYPE HSC_obj = OBJECT (* The following variables are _internal_ variables and should not be changed from outside! *) Address : Pointer; Music_Load : BOOLEAN; Music_Size : LONGINT; Music_Run : BOOLEAN; Music_Fade : BOOLEAN; (* The following procedures/cuntions are for your use. Please read the information above on how to use them! *) CONSTRUCTOR Init (AdlibAddress : WORD); PROCEDURE Start; PROCEDURE Stop; PROCEDURE Fade; PROCEDURE LoadMem (Music_Address : Pointer); FUNCTION LoadFile (FileName : STRING):BOOLEAN; DESTRUCTOR Done; END; IMPLEMENTATION USES CRT; (*-------------------------------------------------------------------------*) (* SECTION: Sub-routines used for by HSC_obj *) (*-------------------------------------------------------------------------*) {$F+} (* Include *) {$L HSCOBJ.OBJ} (* external *) PROCEDURE _HscPlayer; EXTERNAL; (* player *) {$F-} (* object *) FUNCTION DetectAdlib (SuggestedPort : WORD) : WORD; ASSEMBLER; ASM MOV AH,4 MOV BX,SuggestedPort CALL _HscPlayer JNC @GoOn MOV AX,0FFh @GoOn: END; PROCEDURE GetPlayerState (VAR Destination); ASSEMBLER; ASM MOV AH,7 LES SI,DWORD PTR Destination CALL _HscPlayer END; PROCEDURE StartMusic (Song : POINTER; Polling, OldIRQ : BOOLEAN); ASSEMBLER; ASM MOV AH,0 MOV BL,Polling MOV BH,OldIRQ CMP BH,1 JE @Invert MOV BH,1 JMP @GoOn @Invert: XOR BH,BH @GoOn: LES SI,DWORD PTR Song CALL _HscPlayer END; PROCEDURE StopMusic; ASSEMBLER; ASM MOV AH,2 CALL _HscPlayer END; (*-------------------------------------------------------------------------*) (* SECTION: HSC_obj implementation *) (*-------------------------------------------------------------------------*) CONSTRUCTOR HSC_obj.Init (AdlibAddress : WORD); VAR Dummy : WORD; BEGIN Music_Load := FALSE; Music_Run := FALSE; Music_Fade := FALSE; Address := NIL; Dummy := DetectAdlib (0); Delay (30); END; PROCEDURE HSC_obj.Start; BEGIN IF NOT Music_Run THEN BEGIN IF Address <> NIL THEN BEGIN StartMusic (Address,FALSE,TRUE); Music_Run := TRUE; END; END; END; PROCEDURE HSC_obj.Stop; BEGIN IF Music_Run THEN BEGIN StopMusic; Music_Run := FALSE; END; END; PROCEDURE HSC_obj.Fade; BEGIN IF Music_Run THEN BEGIN ASM MOV AH,3 CALL _HscPlayer END; Music_Fade := TRUE; Music_Run := FALSE; END; END; PROCEDURE HSC_Obj.LoadMem (Music_Address : Pointer); BEGIN IF Music_Fade or Music_Run THEN BEGIN StopMusic; Music_Run := FALSE; Music_Fade := FALSE; IF Music_Load THEN FreeMem (Address,Music_Size); END; Music_Load := FALSE; Address := Music_Address; END; FUNCTION HSC_Obj.LoadFile (Filename : STRING):BOOLEAN; VAR f : FILE; BEGIN IF FileName <> '' THEN BEGIN Assign (F,FileName); {$I-} RESET (F,1); {$I+} END; IF (IORESULT <> 0) OR (FileName = '') THEN BEGIN Music_Load := FALSE; LoadFile := FALSE; END ELSE BEGIN IF Music_Fade or Music_Run THEN BEGIN StopMusic; Music_Run := FALSE; Music_Fade := FALSE; IF Music_Load THEN FreeMem (Address,Music_Size); END; Music_Size := FileSize (F); IF MaxAvail < Music_Size THEN BEGIN LoadFile := FALSE; Music_Load := FALSE; END ELSE BEGIN GetMem (Address,Music_Size); BlockRead (f,Address^,Music_Size); LoadFile := TRUE; Music_Load := TRUE; END; Close (f); END; END; DESTRUCTOR HSC_obj.Done; BEGIN IF Music_Run OR Music_Fade THEN StopMusic; IF Music_Load THEN FREEMEM (Address,Music_Size); END; END. (*-------------------------------------------------------------------------*) (* SECTION: END OF FILE ;) *) (*-------------------------------------------------------------------------*)
unit fmxProgress; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls, StdCtrls, Buttons, PlayerThreads; type { TfmProgress } TfmProgress = class(TForm) btStop: TBitBtn; lbInfo: TLabel; ProgressBar: TProgressBar; procedure btStopClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); private FManager: TPlayerThreadManager; FTrackCount: Integer; FFinished: Boolean; procedure SetTrackCount(AValue: Integer); public constructor Create(AOwner: TComponent); override; procedure Processed(Sender: TObject; const AProcessedCount: Integer); procedure ProcessFinished(Sender: TObject); property Manager: TPlayerThreadManager read FManager write FManager; property TrackCount: Integer read FTrackCount write SetTrackCount; end; implementation {$R *.lfm} { TfmProgress } procedure TfmProgress.btStopClick(Sender: TObject); begin FManager.Interrupt(True); end; procedure TfmProgress.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin if not FFinished then CloseAction:=caNone else CloseAction:=caFree; end; procedure TfmProgress.SetTrackCount(AValue: Integer); begin if FTrackCount = AValue then Exit; FTrackCount:=AValue; lbInfo.Caption:=Format('files: 0/%d', [TrackCount]); end; constructor TfmProgress.Create(AOwner: TComponent); begin inherited; FFinished:=False; end; procedure TfmProgress.Processed(Sender: TObject; const AProcessedCount: Integer ); begin ProgressBar.Position:=Round(100 * AProcessedCount / TrackCount); lbInfo.Caption:=Format('files: %d/%d', [AProcessedCount, TrackCount]); end; procedure TfmProgress.ProcessFinished(Sender: TObject); begin FFinished:=True; Close; end; end.
{*******************************************************} { } { Threaded Class Factory Demo } { } {*******************************************************} unit ThrddCF; { This unit provides some custom class factories that implement threading for out of process servers. The TThreadedAutoObjectFactory is for any TAutoObject and the TThreadedClassFactory is for and TComponentFactory. To use them, replace the line in the initialization section of your automation object to use the appropriate threaded class factory instead of the non-threaded version. } interface uses ComObj, ActiveX, Classes, Windows, VCLCom, Forms; type TCreateInstanceProc = function(const UnkOuter: IUnknown; const IID: TGUID; out Obj): HResult of object; stdcall; { TThreadedAutoObjectFactory } TThreadedAutoObjectFactory = class(TAutoObjectFactory, IClassFactory) protected function CreateInstance(const UnkOuter: IUnknown; const IID: TGUID; out Obj): HResult; stdcall; function DoCreateInstance(const UnkOuter: IUnknown; const IID: TGUID; out Obj): HResult; stdcall; end; { TThreadedClassFactory } TThreadedClassFactory = class(TComponentFactory, IClassFactory) protected function CreateInstance(const UnkOuter: IUnknown; const IID: TGUID; out Obj): HResult; stdcall; function DoCreateInstance(const UnkOuter: IUnknown; const IID: TGUID; out Obj): HResult; stdcall; end; { TApartmentThread } TApartmentThread = class(TThread) private FCreateInstanceProc: TCreateInstanceProc; FUnkOuter: IUnknown; FIID: TGuid; FSemaphore: THandle; FStream: Pointer; FCreateResult: HResult; protected procedure Execute; override; public constructor Create(CreateInstanceProc: TCreateInstanceProc; UnkOuter: IUnknown; IID: TGuid); destructor Destroy; override; property Semaphore: THandle read FSemaphore; property CreateResult: HResult read FCreateResult; property ObjStream: Pointer read FStream; end; implementation { TThreadedAutoObjectFactory } function TThreadedAutoObjectFactory.DoCreateInstance(const UnkOuter: IUnknown; const IID: TGUID; out Obj): HResult; stdcall; begin Result := inherited CreateInstance(UnkOuter, IID, Obj); end; function TThreadedAutoObjectFactory.CreateInstance(const UnkOuter: IUnknown; const IID: TGUID; out Obj): HResult; stdcall; begin with TApartmentThread.Create(DoCreateInstance, UnkOuter, IID) do begin if WaitForSingleObject(Semaphore, INFINITE) = WAIT_OBJECT_0 then begin Result := CreateResult; if Result <> S_OK then Exit; Result := CoGetInterfaceAndReleaseStream(IStream(ObjStream), IID, Obj); end else Result := E_FAIL end; end; { TThreadedClassFactory } function TThreadedClassFactory.DoCreateInstance(const UnkOuter: IUnknown; const IID: TGUID; out Obj): HResult; stdcall; begin Result := inherited CreateInstance(UnkOuter, IID, Obj); end; function TThreadedClassFactory.CreateInstance(const UnkOuter: IUnknown; const IID: TGUID; out Obj): HResult; stdcall; begin with TApartmentThread.Create(DoCreateInstance, UnkOuter, IID) do begin if WaitForSingleObject(Semaphore, INFINITE) = WAIT_OBJECT_0 then begin Result := CreateResult; if Result <> S_OK then Exit; Result := CoGetInterfaceAndReleaseStream(IStream(ObjStream), IID, Obj); end else Result := E_FAIL end; end; { TApartmentThread } constructor TApartmentThread.Create(CreateInstanceProc: TCreateInstanceProc; UnkOuter: IUnknown; IID: TGuid); begin FCreateInstanceProc := CreateInstanceProc; FUnkOuter := UnkOuter; FIID := IID; FSemaphore := CreateSemaphore(nil, 0, 1, nil); FreeOnTerminate := True; inherited Create(False); end; destructor TApartmentThread.Destroy; begin FUnkOuter := nil; CloseHandle(FSemaphore); inherited Destroy; Application.ProcessMessages; end; procedure TApartmentThread.Execute; var msg: TMsg; Unk: IUnknown; begin CoInitialize(nil); FCreateResult := FCreateInstanceProc(FUnkOuter, FIID, Unk); if FCreateResult = S_OK then CoMarshalInterThreadInterfaceInStream(FIID, Unk, IStream(FStream)); ReleaseSemaphore(FSemaphore, 1, nil); if FCreateResult = S_OK then while GetMessage(msg, 0, 0, 0) do begin DispatchMessage(msg); Unk._AddRef; if Unk._Release = 1 then break; end; Unk := nil; CoUninitialize; end; end.
unit ClientLoan; interface type TClientLoan = class(TObject) private FLoanId: string; FLoanClassId: integer; FBalance: real; public property LoanId: string read FLoanId write FLoanId; property LoanClassId: integer read FLoanClassId write FLoanClassId; property Balance: real read FBalance write FBalance; constructor Create; overload; constructor Create(const lnId: string; const lncId: integer; const bal: real); overload; end; implementation constructor TClientLoan.Create; begin inherited Create; end; constructor TClientLoan.Create(const lnId: string; const lncId: Integer; const bal: Real); begin FLoanId := lnId; FLoanClassId := lncId; FBalance := bal; end; end.
(***********************************************************) (* xPLRFX *) (* part of Digital Home Server project *) (* http://www.digitalhomeserver.net *) (* info@digitalhomeserver.net *) (***********************************************************) unit uxPLRFX_0x54; interface Uses uxPLRFXConst, u_xPL_Message, u_xpl_common, uxPLRFXMessages; procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages); implementation Uses SysUtils; (* Type $54 - Temperature/Humidity/Barometric sensors Buffer[0] = packetlength = $0D; Buffer[1] = packettype Buffer[2] = subtype Buffer[3] = seqnbr Buffer[4] = id1 Buffer[5] = id2 Buffer[6] = temperaturehigh:7/temperaturesign:1 Buffer[7] = temperaturelow Buffer[8] = humidity Buffer[9] = humidity_status Buffer[10] = baro1 Buffer[11] = baro2 Buffer[12] = forecast Buffer[13] = battery_level:4/rssi:4 Test strings : 0D54020EE90000C9270203E70439 xPL Schema sensor.basic { device=(thb1-thb2) 0x<hex sensor id> type=temp current=<degrees celsius> units=c } sensor.basic { device=(thb1-thb2) 0x<hex sensor id> type=humidity current=(0-100) description=normal|comfort|dry|wet } sensor.basic { device=(thb1-thb2) 0x<hex sensor id> type=pressure current=<hPa> units=hpa forecast=sunny|partly cloudy|cloudy|rain } sensor.basic { device=(thb1-thb2) 0x<hex sensor id> type=battery current=0-100 } *) const // Type TEMPHUMBARO = $54; // Subtype THB1 = $01; THB2 = $02; // Humidity status HUM_NORMAL = $00; HUM_COMFORT = $01; HUM_DRY = $02; HUM_WET = $03; // Humidity status strings HUM_NORMAL_STR = 'normal'; HUM_COMFORT_STR = 'comfort'; HUM_DRY_STR = 'dry'; HUM_WET_STR = 'wet'; // Forecast FC_NOT_AVAILABLE = $00; FC_SUNNY = $01; FC_PARTLY_CLOUDY = $02; FC_CLOUDY = $03; FC_RAIN = $04; // Forecast strings FC_NOT_AVAILABLE_STR = ''; FC_SUNNY_STR = 'sunny'; FC_PARTLY_CLOUDY_STR = 'partly cloudy'; FC_CLOUDY_STR = 'cloudy'; FC_RAIN_STR = 'rain'; var SubTypeArray : array[1..2] of TRFXSubTypeRec = ((SubType : THB1; SubTypeString : 'thb1'), (SubType : THB2; SubTypeString : 'thb2')); procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages); var DeviceID : String; SubType : String; Temperature : Extended; TemperatureSign : String; Humidity : Integer; Status : String; Pressure : Integer; Forecast : String; BatteryLevel : Integer; xPLMessage : TxPLMessage; begin DeviceID := GetSubTypeString(Buffer[2],SubTypeArray)+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2); if Buffer[6] and $80 > 0 then TemperatureSign := '-'; // negative value Buffer[6] := Buffer[6] and $7F; // zero out the temperature sign Temperature := ((Buffer[6] shl 8) + Buffer[7]) / 10; Humidity := Buffer[8]; case Buffer[9] of HUM_NORMAL : Status := HUM_NORMAL_STR; HUM_COMFORT : Status := HUM_COMFORT_STR; HUM_DRY : Status := HUM_DRY_STR; HUM_WET : Status := HUM_WET_STR; end; Pressure := (Buffer[10] shl 8) + Buffer[11]; case Buffer[12] of FC_NOT_AVAILABLE : Forecast := FC_NOT_AVAILABLE_STR; FC_SUNNY : Forecast := FC_SUNNY_STR; FC_PARTLY_CLOUDY : Forecast := FC_PARTLY_CLOUDY_STR; FC_CLOUDY : Forecast := FC_CLOUDY_STR; FC_RAIN : Forecast := FC_RAIN_STR; end; if (Buffer[13] and $0F) = 0 then // zero out rssi BatteryLevel := 0 else BatteryLevel := 100; // Create sensor.basic messages xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID); xPLMessage.Body.AddKeyValue('current='+TemperatureSign+FloatToStr(Temperature)); xPLMessage.Body.AddKeyValue('units=c'); xPLMessage.Body.AddKeyValue('type=temperature'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID); xPLMessage.Body.AddKeyValue('current='+IntToStr(Humidity)); xPLMessage.Body.AddKeyValue('description='+Status); xPLMessage.Body.AddKeyValue('type=humidity'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID); xPLMessage.Body.AddKeyValue('pressure='+IntToStr(Pressure)); xPLMessage.Body.AddKeyValue('forecast='+Forecast); xPLMessage.Body.AddKeyValue('type=pressure'); xPLMEssage.Body.AddKeyValue('units=hpa'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID); xPLMessage.Body.AddKeyValue('current='+IntToStr(BatteryLevel)); xPLMessage.Body.AddKeyValue('type=battery'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; end; end.
unit caVersionInfo; {$H+} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type ppchar = ^Pchar; TVersionResources = (vrCompanyName, vrFileDescription, vrFileVersion, vrInternalName, vrLegalCopyright, vrOriginalFilename, vrProductName, vrProductVersion, vrComments, vrFlags, vrShortFileVersion, vrDateTime, vrFileSize); TcaVersionLabel = class(TCustomLabel) private { Private declarations } FVersionResource: TVersionResources; FInfoPrefix: string; FShowInfoPrefix: boolean; FVersionResourceKey: string; FLangCharset: string; FInfoString: string; // read only caption - current version info FFilename: string; // '' = current exe, DLL whatever. FDateTimeFormat: String; FFileSizeFormat: String; function CalcLangCharset(Buffer: pointer; Buflen: UINT): String; function Slice(var S: string; Delimiter: string): string; procedure SetupInfoPrefix; procedure SetupResourceKey; function GetStringFileInfo(Buffer: Pchar; size: integer): string; function GetFixedFileInfo(Buffer: PChar; size: integer): string; function GetDateTimeInfo: String; function GetFileSizeInfo: String; function GetInfo: string; procedure SetupCaption; protected { Protected declarations } procedure SetFileSizeFormat(Value: String); procedure SetDateTimeFormat(Value: String); procedure SetFilename(Value: string); procedure SetInfoPrefix(Value: String); function GetInfoPrefix: string; procedure SetVersionResource(Value: TVersionResources); procedure SetShowInfoPrefix(Value: boolean); procedure SetVersionResourceKey(Value: string); procedure SetLangCharset(Value: string); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } property VersionResource: TVersionResources read FVersionResource write SetVersionResource; property VersionResourceKey: string read FVersionResourceKey write SetVersionResourceKey; property InfoPrefix: String read GetInfoPrefix write SetInfoPrefix; property ShowInfoPrefix: boolean read FShowInfoPrefix write SetShowInfoPrefix; property LangCharset: string read FLangCharset write SetLangCharset; property WordWrap; property Align; property Color; property Font; property AutoSize; property Alignment; property ParentFont; property Visible; property Transparent; property InfoString: string read FInfoString; // Read only copy of caption property Filename: string read FFilename write SetFilename; property DateTimeFormat: String read FDateTimeFormat write SetDateTimeFormat; property FileSizeFormat: String read FFileSizeFormat write SetFileSizeFormat; end; const // The order of this array must be the same as the VersionResources // enum type as that is used for the index lookup VersionLookup: array[TVersionResources, 0..1] of string = ( ('CompanyName', 'Company Name:'), ('FileDescription', 'File Description:'), ('FileVersion', 'File Version:'), ('InternalName', 'Internal Name:'), ('LegalCopyright', 'Legal Copyright:'), ('OriginalFilename', 'Original Filename:'), ('ProductName', 'Product Name:'), ('ProductVersion', 'Product Version:'), ('Comments', 'Comments:'), ('Flags', 'Flags:'), ('FileVersion', 'v'), ('DateTime', 'File Date/Time:'), ('Filesize', 'File Size:')); implementation procedure Register; begin RegisterComponents('Leviathan', [TcaVersionLabel]); end; constructor TcaVersionLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); FInfoString := ''; FFilename := ''; FDateTimeFormat := ShortDateFormat; FFileSizeFormat := '#,#0" Bytes"'; WordWrap := false; Autosize := true; ShowInfoPrefix := true; LangCharset :='-1'; {-1 = auto detect} VersionResource := vrFileVersion; end; destructor TcaVersionLabel.Destroy; begin inherited Destroy; end; procedure TcaVersionLabel.SetVersionResource(Value: TVersionResources); begin FVersionResource := Value; SetupResourceKey; SetupInfoPrefix; end; procedure TcaVersionLabel.SetFilename(Value: string); begin FFilename := Value; SetupCaption; end; procedure TcaVersionLabel.SetDateTimeFormat(Value: String); begin if Value = '' then exit; FDateTimeFormat := Value; SetupCaption; end; procedure TcaVersionLabel.SetFileSizeFormat(Value: String); begin if Value = '' then exit; FFileSizeFormat := Value; SetupCaption; end; procedure TcaVersionLabel.SetupInfoPrefix; var s: string; begin s := VersionLookup[FVersionResource, 1]; InfoPrefix := s; end; procedure TcaVersionLabel.SetupResourceKey; var s: string; begin s := VersionLookup[FVersionResource, 0]; VersionResourceKey := s; end; function TcaVersionLabel.GetFixedFileInfo(Buffer: PChar; size: integer): string; var // ValLen: integer; ValLen: UINT; FixedFileInfo: PVSFixedFileInfo; begin if VerQueryValue(buffer, '\', Pointer(FixedFileInfo), ValLen) then begin Result := ''; if (ValLen > 1) then begin if FixedFileInfo.dwFileFlags and VS_FF_DEBUG <> 0 then Result := Result+', Debug Build'; if FixedFileInfo.dwFileFlags and VS_FF_PRERELEASE <> 0 then Result := Result+', Pre-Release Build'; if FixedFileInfo.dwFileFlags and VS_FF_PATCHED <> 0 then Result := Result+', Patched Build'; if FixedFileInfo.dwFileFlags and VS_FF_PRIVATEBUILD <> 0 then Result := Result+', Private Build'; if FixedFileInfo.dwFileFlags and VS_FF_INFOINFERRED <> 0 then Result := Result+', InfoInferred'; if FixedFileInfo.dwFileFlags and VS_FF_SPECIALBUILD <> 0 then Result := Result+', Special Build'; if result <> '' then if Result[1] = ',' then Delete(Result, 1, 2); end; end else Result := '< Error retrieving fixed version info >'; end; function TcaVersionLabel.GetStringFileInfo(Buffer: Pchar; size: integer): string; //var vallen, Translen: integer; var vallen, Translen: UINT; VersionPointer: pointer; TransBuffer: pointer; Major, Minor: integer; begin if FLangCharSet = '-1' then begin VerQueryValue(buffer, '\VarFileInfo\Translation', TransBuffer, TransLen); if TransLen >= 4 then begin FLangCharSet := CalcLangCharSet(TransBuffer, TransLen); end else begin Result := '< Error retrieving translation info >'; exit; end; end; if VerQueryValue(buffer, pchar('\StringFileInfo\'+FLangCharSet+'\'+ VersionResourceKey), VersionPointer, vallen) then begin if (Vallen > 1) then begin SetLength(Result, vallen); StrLCopy(Pchar(Result), VersionPointer, vallen); // special case for 'short' file versions if FVersionResource = vrShortFileVersion then begin try Major := StrtoInt(Slice(Result, '.')); except Major := 0; end; try Minor := StrtoInt(Slice(Result, '.')); except Minor := 0; end; Result := Format('%d.%.2d', [Major, Minor]); end; end else Result := '< No Version Info >'; end else result := '< Error retrieving string version info >'; end; function TcaVersionLabel.GetDateTimeInfo: String; var DT: TDateTime; FileHandle: Longint; Filecheck: Array[0..255] of char; begin Filecheck := ''; if FFilename = '' then GetModuleFileName(HInstance, Filecheck, 255) else StrPCopy(Filecheck, FFilename); FileHandle := CreateFile(Filecheck, GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0); if FileHandle = -1 then begin result := '<Error getting file handle>'; exit; end; DT := FileDateToDateTime(FileGetDate(FileHandle)); CloseHandle(FileHandle); result := FOrmatDateTime(FDateTimeFormat, DT); end; function TcaVersionLabel.GetFileSizeInfo: String; var fs: Longint; FileHandle: Longint; Filecheck: Array[0..255] of char; begin Filecheck := ''; if FFilename = '' then GetModuleFileName(HInstance, Filecheck, 255) else StrPCopy(Filecheck, FFilename); FileHandle := CreateFile(Filecheck, GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0); if FileHandle = -1 then begin result := '<Error getting file handle>'; exit; end; fs := GetFileSize(FileHandle, nil); CloseHandle(FileHandle); result := FormatFloat(FFileSizeFormat, fs); end; // Looks at the translation structure and returns the hex formatted string // containing the language and code page identifier function TcaVersionLabel.CalcLangCharset(Buffer: pointer; Buflen: UINT): String; begin (* Buffer points to the following structure? Not as far as I can tell it doesn't! Oh well, go with what works... WORD=16 bit value WCHAR=WideChar Var { WORD wLength; WORD wValueLength; WORD wType; WCHAR szKey[]; WORD Padding[]; DWORD Value[]; }; *) Result := Format('%4.4x%4.4x', [LoWord(UInt(Buffer^)), HiWord(UInt(Buffer^))]); end; {Called at run time to get version information} function TcaVersionLabel.GetInfo: string; //var dump, size: integer; var dump : DWORD; size: integer; buffer: pchar; FileCheck: array[0..255] of char; begin if csDesigning in Self.ComponentState then result := '< No design info >' else begin Filecheck := ''; if FFilename = '' then GetModuleFileName(HInstance, Filecheck, 255) else StrPCopy(Filecheck, FFilename); size := GetFileVersionInfoSize(Filecheck, dump); if size = 0 then begin Result := '< No Data Available >'; end else begin buffer := StrAlloc(size+1); try if not GetFileVersionInfo(FileCheck, 0, size, buffer) then result := '< Error retrieving version info >' else begin case FVersionResource of vrFlags: Result := GetFixedFileInfo(buffer, size); vrDateTime: result := GetDateTimeInfo; vrFileSize: result := GetFileSizeInfo; else Result := GetStringFileInfo(buffer, size); end; end; finally StrDispose(Buffer); end; end; end; if ShowInfoPrefix then Result := InfoPrefix+' '+Result; end; procedure TcaVersionLabel.SetInfoPrefix(Value: String); begin if FInfoPrefix = Value then exit; FInfoPrefix := Value; {The caption needs to be recalculated everytime the prefix is changed, otherwise the detaults override the user specified one} SetupCaption; end; procedure TcaVersionLabel.SetVersionResourceKey(Value: string); begin if FVersionResourceKey = Value then exit; FVersionResourceKey := Value; InfoPrefix := Value; end; function TcaVersionLabel.GetInfoPrefix: string; begin result := FInfoPrefix; end; procedure TcaVersionLabel.SetShowInfoPrefix(Value: boolean); begin if FShowInfoPrefix = value then exit; FShowInfoPrefix := Value; SetupCaption; end; procedure TcaVersionLabel.SetLangCharset(Value: string); begin if FLangCharSet = Value then exit; FLangCharSet := Value; SetupCaption; end; procedure TcaVersionLabel.SetupCaption; begin Caption := GetInfo; FInfoString := Caption; end; // Find first section of string - remove from front of string and return it function TcaVersionLabel.Slice(var S: string; Delimiter: string): string; var p : Integer; begin p := pos(Delimiter, S); if p = 0 then begin Result := S; S:=''; end else begin Result := Copy(S,1,p-1); Delete(S,1,p+Length(Delimiter)-1); end; end; end.
unit Main; interface uses Winapi.Messages, Winapi.Windows, System.Classes, System.SysUtils, System.Variants, Vcl.Controls, Vcl.Dialogs, Vcl.ExtDlgs, Vcl.Forms, Vcl.Graphics, Vcl.Menus, Vcl.StdCtrls, mmSystem, WaveIO, WaveOut, WavePlayers, WaveStorage, WaveUtils, Generics.Collections, AsyncSoundSynthesizer, SettingsManager, SoundRepository, SoundSynthesizer, TextTokenizer, ShellApi; type TFormMain = class(TForm) MainMenu: TMainMenu; MemoFairytale: TMemo; ButtonPlay: TButton; MenuFile: TMenuItem; MenuHelp: TMenuItem; MenuExit: TMenuItem; MenuAboutFairyteller: TMenuItem; MenuOpenFile: TMenuItem; Separator0: TMenuItem; OpenTextFileDialog: TOpenTextFileDialog; MenuPreferences: TMenuItem; MenuSettings: TMenuItem; AudioPlayer: TAudioPlayer; procedure ButtonPlayClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure PlayNext(Sender: TObject); procedure MenuOpenFileClick(Sender: TObject); procedure MenuSettingsClick(Sender: TObject); procedure MenuAboutFairytellerClick(Sender: TObject); procedure MenuExitClick(Sender: TObject); private FSettingsManager: TSettingsManager; FSoundRepository: TSoundRepository; FTextTokenizer: TTextTokenizer; FSoundSynthesizer: TSoundSynthesizer; FAsyncSoundSynthesizer: TAsyncSoundSynthesizer; FVocalizedSentences: TList<TWave>; FAvailableSentencesCount: Integer; FCurrentSentenceIndex: Integer; FThreadIsRunning: Boolean; FIsPlaying: Boolean; private procedure OnSentenceSynthesized(var AMessage: TMessage); message WM_USER; procedure SelectMemoAtLine(const AMemo: TCustomMemo; const ALineNumber: Integer); end; var FormMain: TFormMain; implementation {$R *.dfm} procedure TFormMain.PlayNext(Sender: TObject); begin FIsPlaying := False; if (not FIsPlaying and not FThreadIsRunning and not AudioPlayer.Active) then begin ButtonPlay.Caption := 'Play'; end; if (FAvailableSentencesCount > 0) then begin Dec(FAvailableSentencesCount); Inc(FCurrentSentenceIndex); AudioPlayer.Wave := FVocalizedSentences.Items[FCurrentSentenceIndex]; FIsPlaying := True; AudioPlayer.Active := True; SelectMemoAtLine(MemoFairytale, FCurrentSentenceIndex); end; end; procedure TFormMain.SelectMemoAtLine(const AMemo: TCustomMemo; const ALineNumber: Integer); begin AMemo.SetFocus; AMemo.SelStart := SendMessage(AMemo.Handle, EM_LINEINDEX, ALineNumber, 0); AMemo.SelLength := Length(AMemo.Lines[ALineNumber]); end; procedure TFormMain.ButtonPlayClick(Sender: TObject); begin if (FIsPlaying and not AudioPlayer.Paused) then begin FIsPlaying := False; AudioPlayer.Paused := True; (Sender as TButton).Caption := 'Play'; Exit; end; if (not FIsPlaying and AudioPlayer.Paused) then begin FIsPlaying := True; AudioPlayer.Paused := False; (Sender as TButton).Caption := 'Pause'; Exit; end; if ((FAsyncSoundSynthesizer = nil) and (not FIsPlaying)) then begin FIsPlaying := True; FThreadIsRunning := True; FAsyncSoundSynthesizer := TAsyncSoundSynthesizer.Create(Handle, FSoundSynthesizer, MemoFairytale.Text); (Sender as TButton).Caption := 'Pause'; end; end; procedure TFormMain.FormClose(Sender: TObject; var Action: TCloseAction); var i: Integer; begin inherited; AudioPlayer.Active := False; AudioPlayer.OnDeactivate := nil; if (FAsyncSoundSynthesizer <> nil) then begin FAsyncSoundSynthesizer.Terminated := True; while (FThreadIsRunning) do Application.ProcessMessages; end; FreeAndNil(FSettingsManager); FreeAndNil(FSoundRepository); FreeAndNil(FTextTokenizer); FreeAndNil(FSoundSynthesizer); for i := 0 to FVocalizedSentences.Count - 1 do begin FVocalizedSentences.Items[i].Free; end; FreeAndNil(FVocalizedSentences); end; procedure TFormMain.FormCreate(Sender: TObject); begin FSettingsManager := TSettingsManager.Create; FSoundRepository := TSoundRepository.Create; FSoundRepository.SetVoice('voices/zahar'); FTextTokenizer := TTextTokenizer.Create; FSoundSynthesizer := TSoundSynthesizer.Create(FSoundRepository, FSettingsManager, FTextTokenizer); FAsyncSoundSynthesizer := nil; FVocalizedSentences := TList<TWave>.Create; FAvailableSentencesCount := 0; FCurrentSentenceIndex := -1; FThreadIsRunning := False; FIsPlaying := False; end; procedure TFormMain.MenuAboutFairytellerClick(Sender: TObject); begin MessageDlg(Format('Program: Faityteller' + #13#10 + 'Version: 1.0' + #13#10 + 'Authot: Alexey (icetear)', []), mtInformation, [mbOk], -1); end; procedure TFormMain.MenuExitClick(Sender: TObject); begin Close; end; procedure TFormMain.MenuOpenFileClick(Sender: TObject); var Sentences: TArray<String>; begin try if (OpenTextFileDialog.Execute(Handle)) then begin MemoFairytale.Lines.LoadFromFile(OpenTextFileDialog.FileName, TEncoding.UTF8); Sentences := FTextTokenizer.GetCleanSentences(MemoFairytale.Text); MemoFairytale.Clear; MemoFairytale.Lines.AddStrings(Sentences); end; except on E: Exception do MessageDlg(Format('File "%s" should be in UTF-8', [ExtractFileName(OpenTextFileDialog.FileName)]), mtError, [mbOk], -1); end; end; procedure TFormMain.MenuSettingsClick(Sender: TObject); begin ShellExecute(Handle, nil, PChar(ExtractFilePath(Application.ExeName) + FSettingsManager.SettingsFilename), nil, nil, SW_SHOWNORMAL); end; procedure TFormMain.OnSentenceSynthesized(var AMessage: TMessage); begin case TMessageType(AMessage.LParam) of mtSentenceSynthesized: begin FVocalizedSentences.Add(TWave(AMessage.WParam)); Inc(FAvailableSentencesCount); if (not AudioPlayer.Active) then begin AudioPlayer.OnDeactivate(nil); end; end; mtThreadEnded: begin FAsyncSoundSynthesizer := nil; FThreadIsRunning := False; end; end; end; end.
unit LoansAuxData; interface uses System.SysUtils, System.Classes, Data.DB, Data.Win.ADODB, System.ImageList, Vcl.Controls, Vcl.ImgList; type TdmLoansAux = class(TDataModule) dscLoanClass: TDataSource; dstLoanClass: TADODataSet; dscClassCharges: TDataSource; dstClassCharges: TADODataSet; dscChargeType: TDataSource; dstChargeType: TADODataSet; dscCompetitors: TDataSource; dstCompetitors: TADODataSet; dscExpType: TDataSource; dstExpType: TADODataSet; dstAppvMethod: TADODataSet; dscAppvMethod: TDataSource; dstCancelReason: TADODataSet; dscCancelReason: TDataSource; dstRejectReason: TADODataSet; dscRejectReason: TDataSource; dstReleaseMethod: TADODataSet; dscReleaseMethod: TDataSource; dstPurpose: TADODataSet; dscPurpose: TDataSource; dstBranches: TADODataSet; dscBranches: TDataSource; dstLoanTypes: TADODataSet; dscLoanTypes: TDataSource; dstAcctTypes: TADODataSet; dscAcctTypes: TDataSource; dstRecommendation: TADODataSet; dscRecommendation: TDataSource; dstClassChargesclass_id: TIntegerField; dstClassChargescharge_type: TStringField; dstClassChargescharge_value: TBCDField; dstClassChargesvalue_type: TWordField; dstClassChargesratio_amt: TBCDField; dstClassChargesfor_new: TWordField; dstClassChargesfor_renew: TWordField; dstClassChargescharge_name: TStringField; dstClassChargescharge_value_f: TStringField; dstClassChargesratio_amt_f: TStringField; dstClassChargesfor_new_f: TStringField; dstClassChargesfor_renew_f: TStringField; dstClassChargesvalue_type_desc: TStringField; dstClassChargesfor_reloan: TWordField; dstClassChargesfor_restructure: TWordField; dstClassChargesfor_restructure_f: TStringField; dstClassChargesfor_reloan_f: TStringField; dstClassChargesmax_value: TBCDField; dstClassChargesmax_value_type: TWordField; dstClassChargesmax_value_f: TStringField; dstChargeTypes: TADODataSet; dscChargeTypes: TDataSource; dstCloseReason: TADODataSet; dscCloseReason: TDataSource; dstAdvancePayment: TADODataSet; dscAdvancePayment: TDataSource; procedure dstLoanClassBeforePost(DataSet: TDataSet); procedure dstLoanClassAfterOpen(DataSet: TDataSet); procedure DataModuleDestroy(Sender: TObject); procedure dstLoanClassAfterPost(DataSet: TDataSet); procedure dstClassChargesNewRecord(DataSet: TDataSet); procedure dstLoanClassAfterScroll(DataSet: TDataSet); procedure dstClassChargesBeforePost(DataSet: TDataSet); procedure dstClassChargesAfterPost(DataSet: TDataSet); procedure dstClassChargesAfterOpen(DataSet: TDataSet); procedure dstClassChargesBeforeOpen(DataSet: TDataSet); procedure dstLoanTypesBeforePost(DataSet: TDataSet); procedure dstAcctTypesBeforePost(DataSet: TDataSet); procedure dstAcctTypesAfterPost(DataSet: TDataSet); procedure dstLoanTypesAfterPost(DataSet: TDataSet); procedure dstRecommendationAfterScroll(DataSet: TDataSet); procedure dstClassChargesCalcFields(DataSet: TDataSet); procedure dstAdvancePaymentBeforeOpen(DataSet: TDataSet); procedure dstAdvancePaymentAfterOpen(DataSet: TDataSet); procedure dstAdvancePaymentBeforePost(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; var dmLoansAux: TdmLoansAux; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} uses AppData, DBUtil, LoanClassification, LoanClassCharge, LoanType, Loan, Assessment, Group, LoanClassAdvance; procedure TdmLoansAux.DataModuleDestroy(Sender: TObject); var i: integer; begin // close all datasets for i := 0 to ComponentCount - 1 do if Components[i] is TADODataSet then (Components[i] as TADODataSet).Close; end; procedure TdmLoansAux.dstAcctTypesAfterPost(DataSet: TDataSet); var id: integer; begin with DataSet do begin id := FieldbyName('acct_type').AsInteger; RefreshDataSet(id,'acct_type',DataSet); end; end; procedure TdmLoansAux.dstAcctTypesBeforePost(DataSet: TDataSet); begin with DataSet do if State = dsInsert then FieldByName('acct_type').AsInteger := GetAccountTypeId; end; procedure TdmLoansAux.dstAdvancePaymentAfterOpen(DataSet: TDataSet); var LAdvancePayment: TLoanClassAdvance; begin with DataSet do begin LAdvancePayment := TLoanClassAdvance.Create; if RecordCount > 0 then begin Edit; LAdvancePayment.Interest := FieldByName('int').AsInteger; LAdvancePayment.Principal := FieldByName('principal').AsInteger; LAdvancePayment.AdvanceMethod := TAdvanceMethod(FieldByName('advance_method').AsInteger); LAdvancePayment.IncludePrincipal := FieldByName('include_principal').AsBoolean; end else Append; lnc.AdvancePayment := LAdvancePayment; end; end; procedure TdmLoansAux.dstAdvancePaymentBeforeOpen(DataSet: TDataSet); begin if Assigned(lnc) then (DataSet as TADODataSet).Parameters.ParamByName('@class_id').Value := lnc.ClassificationId; end; procedure TdmLoansAux.dstAdvancePaymentBeforePost(DataSet: TDataSet); begin if DataSet.State = dsInsert then DataSet.FieldByName('class_id').AsInteger := lnc.ClassificationId; end; procedure TdmLoansAux.dstClassChargesAfterOpen(DataSet: TDataSet); var ct,cn: string; cv, ratio, max: real; vt: TValueType; maxType: TMaxValueType; forNew, forRenewal, forRestructure, forReloan: boolean; begin (DataSet as TADODataSet).Properties['Unique Table'].Value := 'LoanClassCharge'; with DataSet do begin DisableControls; while not Eof do begin ct := FieldByName('charge_type').AsString; cn := FieldByName('charge_name').AsString; cv := FieldByName('charge_value').AsCurrency; vt := TValueType(FieldByName('value_type').AsInteger); ratio := FieldByName('ratio_amt').AsCurrency; max := FieldByName('max_value').AsCurrency; maxType := TMaxValueType(FieldByName('max_value_type').AsInteger); forNew := FieldByName('for_new').AsInteger = 1; forRenewal := FieldByName('for_renew').AsInteger = 1; forRestructure := FieldByName('for_restructure').AsInteger = 1; forReloan := FieldByName('for_reloan').AsInteger = 1; lnc.AddClassCharge(TLoanClassCharge.Create(ct,cn,cv,vt,ratio,max,maxType, forNew,forRenewal,forRestructure,forReloan)); Next; end; First; EnableControls; end; end; procedure TdmLoansAux.dstClassChargesAfterPost(DataSet: TDataSet); var ct: string; cv: real; vt: TValueType; begin with DataSet do begin ct := FieldByName('charge_type').AsString; cv := FieldByName('charge_value').AsCurrency; vt := TValueType(FieldByName('value_type').AsInteger); lnc.AddClassCharge(TLoanClassCharge.Create(ct,cv,vt)); RefreshDataSet(ct,'charge_type',DataSet); end; end; procedure TdmLoansAux.dstClassChargesBeforeOpen(DataSet: TDataSet); begin if Assigned(lnc) then (DataSet as TADODataSet).Parameters.ParamByName('@class_id').Value := lnc.ClassificationId; end; procedure TdmLoansAux.dstClassChargesBeforePost(DataSet: TDataSet); begin if DataSet.State = dsInsert then DataSet.FieldByName('class_id').AsInteger := lnc.ClassificationId; end; procedure TdmLoansAux.dstClassChargesCalcFields(DataSet: TDataSet); var desc: string; begin with DataSet do begin if TValueType(FieldByName('value_type').AsInteger) = vtFixed then desc := 'Fixed amount' else if TValueType(FieldByName('value_type').AsInteger) = vtPercentage then desc := 'Percentage' else if TValueType(FieldByName('value_type').AsInteger) = vtRatio then desc := 'Ratio'; FieldByName('value_type_desc').AsString := desc; end; end; procedure TdmLoansAux.dstClassChargesNewRecord(DataSet: TDataSet); begin DataSet.FieldByName('value_type').Value := LoanClassCharge.vtFixed; end; procedure TdmLoansAux.dstLoanClassAfterOpen(DataSet: TDataSet); begin (DataSet as TADODataSet).Properties['Unique Table'].Value := 'LoanClass'; end; procedure TdmLoansAux.dstLoanClassAfterPost(DataSet: TDataSet); var classId: integer; begin classId := DataSet.FieldByName('class_id').AsInteger; RefreshDataSet(classId,'class_id',DataSet); end; procedure TdmLoansAux.dstLoanClassAfterScroll(DataSet: TDataSet); var clId, term, comakersMin, comakersMax, age: integer; clName, groupId, intCompMethod: string; interest, maxLoan: currency; validFrom, validUntil: TDate; lt: TLoanType; gp: TGroup; dimType: TDiminishingType; begin with DataSet do begin if State = dsInsert then Exit; clId := FieldByName('class_id').AsInteger; groupId := FieldByName('grp_id').AsString; clName := FieldByName('class_name').AsString; interest := FieldByName('int_rate').AsCurrency; term := FieldByName('term').AsInteger; maxLoan := FieldByName('max_loan').AsCurrency; comakersMin := FieldByName('comakers_min').AsInteger; comakersMax := FieldByName('comakers_max').AsInteger; validFrom := FieldByName('valid_from').AsDateTime; validUntil := FieldByName('valid_until').AsDateTime; age := FieldByName('max_age').AsInteger; intCompMethod := FieldByName('int_comp_method').AsString; dimType := TDiminishingType(FieldByName('dim_type').AsInteger); lt := TLoanType.Create(FieldByName('loan_type').AsInteger, FieldByName('loan_type_name').AsString); gp := TGroup.Create; gp.GroupId := FieldByName('grp_id').AsString; gp.GroupName := FieldByName('grp_name').AsString; end; if not Assigned(lnc) then lnc := TLoanClassification.Create(clId, clName, interest, term, maxLoan, comakersMin, comakersMax, validFrom, validUntil, age,lt, gp, intCompMethod, dimType) else begin lnc.ClassificationId := clId; lnc.ClassificationName := clName; lnc.Interest := interest; lnc.Term := term; lnc.MaxLoan := maxLoan; lnc.ComakersMin := comakersMin; lnc.ComakersMax := comakersMax; lnc.ValidFrom := validFrom; lnc.ValidUntil := validUntil; lnc.MaxAge := age; lnc.LoanType := lt; lnc.Group := gp; lnc.InterestComputationMethod := intCompMethod; lnc.DiminishingType := dimType; lnc.EmptyClassCharges; end; // refresh charges dataset // TODO: find a better solution dstClassCharges.Close; dstClassCharges.Open; // refresh advance payment dataset // TODO: find a better solution dstAdvancePayment.Close; dstAdvancePayment.Open; end; procedure TdmLoansAux.dstLoanClassBeforePost(DataSet: TDataSet); begin if DataSet.State = dsInsert then DataSet.FieldByName('class_id').AsInteger := GetLoanClassId; end; procedure TdmLoansAux.dstLoanTypesAfterPost(DataSet: TDataSet); var loanType: integer; begin loanType := DataSet.FieldByName('loan_type').AsInteger; RefreshDataSet(loanType,'loan_type',DataSet); end; procedure TdmLoansAux.dstLoanTypesBeforePost(DataSet: TDataSet); begin with DataSet do if State = dsInsert then FieldByName('loan_type').AsInteger := GetLoanTypeId; end; procedure TdmLoansAux.dstRecommendationAfterScroll(DataSet: TDataSet); var rec: integer; begin rec := DataSet.FieldbyName('value').AsInteger; if not Assigned(ln.Assessment) then ln.Assessment := TAssessment.Create(rec,0) else ln.Assessment.Recommendation := TRecommendation(rec); end; end.
program _demo; Array[0] var X : TReal1DArray; Y : TReal1DArray; D : TReal1DArray; N : AlglibInteger; I : AlglibInteger; T : Double; S : Spline1DInterpolant; Err : Double; MaxErr : Double; begin // // Interpolation by natural Cubic spline. // Write(Format('INTERPOLATION BY HERMITE SPLINE'#13#10''#13#10'',[])); Write(Format('F(x)=sin(x), [0, pi], 3 nodes'#13#10''#13#10'',[])); Write(Format(' x F(x) S(x) Error'#13#10'',[])); // // Create spline // N := 3; SetLength(X, N); SetLength(Y, N); SetLength(D, N); I:=0; while I<=N-1 do begin X[I] := Pi*I/(N-1); Y[I] := Sin(X[I]); D[I] := Cos(X[I]); Inc(I); end; Spline1DBuildHermite(X, Y, D, N, S); // // Output results // T := 0; MaxErr := 0; while AP_FP_Less(T,0.999999*Pi) do begin Err := AbsReal(Spline1DCalc(S, T)-Sin(T)); MaxErr := Max(Err, MaxErr); Write(Format('%6.3f %6.3f %6.3f %6.3f'#13#10'',[ T, Sin(T), Spline1DCalc(S, T), Err])); T := Min(Pi, T+0.25); end; Err := AbsReal(Spline1DCalc(S, Pi)-Sin(Pi)); MaxErr := Max(Err, MaxErr); Write(Format('%6.3f %6.3f %6.3f %6.3f'#13#10''#13#10'',[ Pi, Sin(Pi), Spline1DCalc(S, Pi), Err])); Write(Format('max|error| = %0.3f'#13#10'',[ MaxErr])); Write(Format('Try other demos (spline1d_linear, spline1d_cubic) and compare errors...'#13#10''#13#10''#13#10'',[])); end.
unit Intersection; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ParseMath, Dialogs, Func; type TMethIntersection = class private public MParse: TParseMath; constructor Create(); destructor Destroy(); override; function Func(x: real; f: string): real; function MBisIni(a,b,e: real; fn: string): real; function MBisect(a,b,e: real; fn: string): TBox; function MFalPos(a,b,e: real; fn: string): TBox; function MNewton(a,e: real; fn,fp: string): TBox; function MSecant(a,e: real; fn: string): TBox; end; implementation constructor TMethIntersection.Create(); begin MParse:= TParseMath.create(); MParse.AddVariable('x',0); end; destructor TMethIntersection.Destroy(); begin end; function TMethIntersection.Func(x: real; f: string): real; begin MParse.NewValue('x',x); MParse.Expression:= f; Result:= MParse.Evaluate(); end; function TMethIntersection.MBisect(a,b,e: real; fn: string): TBox; var et,vt,v,s: real; MT: TList; begin et:= e+1; v:= 0; MT:= TList.Create; while(e<et) do begin vt:= v; v:= (a+b)/2; et:= abs(vt-v); s:= Func(a,fn)*Func(v,fn); MT.Add(Pointer(a)); MT.Add(Pointer(b)); MT.Add(Pointer(v)); MT.Add(Pointer(et)); if(s<0) then b:= v else a:= v; end; Result:= TBox.Create(MT,4); MT.Clear; end; function TMethIntersection.MBisIni(a,b,e: real; fn: string): real; var et,vt,v,s: real; begin et:= e+1; v:= 0; while(e<et) do begin vt:= v; v:= (a+b)/2; et:= abs(vt-v); s:= Func(a,fn)*Func(v,fn); if(s<0) then b:= v else a:= v; end; Result:= v; end; function TMethIntersection.MFalPos(a,b,e: real; fn: string): TBox; var et,vt,v,s: real; MT: TList; begin et:= e+1; v:= 0; MT:= TList.Create; while(e<et) do begin vt:= v; v:= b-((Func(b,fn)*(a-b))/(Func(a,fn)-Func(b,fn))); et:= abs(vt-v); s:= Func(a,fn)*Func(v,fn); MT.Add(Pointer(a)); MT.Add(Pointer(b)); MT.Add(Pointer(v)); MT.Add(Pointer(et)); if(s<0) then b:= v else a:= v; end; Result:= TBox.Create(MT,4); MT.Clear; end; function TMethIntersection.MNewton(a,e: real; fn,fp: string): TBox; var v,vt,et: real; MT: TList; begin v:= a; et:= e+1; MT:= TList.Create; while(e<et) do begin vt:= v; if(Func(v,fp) = 0.0) then v:= v-(Func(v,fn)/(Func(v,fp)+0.0001)) else v:= v-(Func(v,fn)/Func(v,fp)); et:= abs(vt-v); MT.Add(Pointer(v)); MT.Add(Pointer(et)); end; Result:= TBox.Create(MT,2); MT.Clear; end; function TMethIntersection.MSecant(a,e: real; fn: string): TBox; var v,vt,et,h: real; MT: TList; begin h:= e/10; v:= a; et:= e+1; MT:= TList.Create; while(e<et) do begin vt:= v; if((Func(v+h,fn)-Func(v-h,fn)) = 0.0) then v:= v-((2*h*Func(v,fn))/(Func(v+h,fn)-Func(v-h,fn)+0.0001)) else v:= v-((2*h*Func(v,fn))/(Func(v+h,fn)-Func(v-h,fn))); et:= abs(vt-v); MT.Add(Pointer(v)); MT.Add(Pointer(et)); end; Result:= TBox.Create(MT,2); MT.Clear; end; end.
unit ServerConst1; (* Projet : POC Notes de frais URL du projet : https://www.developpeur-pascal.fr/p/_6006-poc-notes-de-frais-une-application-multiplateforme-de-saisie-de-notes-de-frais-en-itinerance.html Auteur : Patrick Prémartin https://patrick.premartin.fr Editeur : Olf Software https://www.olfsoftware.fr Site web : https://www.developpeur-pascal.fr/ Ce fichier et ceux qui l'accompagnent sont fournis en l'état, sans garantie, à titre d'exemple d'utilisation de fonctionnalités de Delphi dans sa version Tokyo 10.2 Vous pouvez vous en inspirer dans vos projets mais n'êtes pas autorisé à rediffuser tout ou partie des fichiers de ce projet sans accord écrit préalable. *) interface resourcestring sPortInUse = '- Erreur : Le port %s est déjà utilisé'; sPortSet = '- Port défini sur %s'; sServerRunning = '- Le serveur est déjà exécuté'; sStartingServer = '- Démarrage du serveur HTTP sur le port %d'; sStoppingServer = '- Arrêt du serveur'; sServerStopped = '- Serveur arrêté'; sServerNotRunning = '- Le serveur n'#39'est pas exécuté'; sInvalidCommand = '- Erreur : Commande non valide'; sIndyVersion = '- Version Indy : '; sActive = '- Actif : '; sPort = '- Port : '; sSessionID = '- Nom de cookie de l'#39'ID de session : '; sCommands = 'Entrez une commande : '#13#10' - "start" pour démarrer le serveur'#13#10' - "stop" pour arrêter le serveur'#13#10' - "set port" pour changer le port par défaut'#13#10' - "status" pour obtenir l'#39'état du serveur'#13#10' - "help" pour afficher les commandes'#13#10' - "exit" pour fe'+ 'rmer l'#39'application'; const cArrow = '->'; cCommandStart = 'start'; cCommandStop = 'stop'; cCommandStatus = 'status'; cCommandHelp = 'help'; cCommandSetPort = 'set port'; cCommandExit = 'exit'; implementation end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.Helpers; interface uses FMX.Forms, FMX.Types; type { TfgScreen } TfgScreenHelper = class helper for TScreen private const SCALE_UNDEFINED = -1; class var FScreenScale: Single; public class constructor Create; class function Scale: Single; class function Orientation: TScreenOrientation; end; { TfgGeneratorUniquiID } TfgGeneratorUniqueID = class sealed private class var FLastID: Int64; public class constructor Create; class function GenerateID: Integer; end; implementation uses System.Math, FMX.Platform, FGX.Consts; { TfgScreen } class constructor TfgScreenHelper.Create; begin FScreenScale := SCALE_UNDEFINED; end; class function TfgScreenHelper.Orientation: TScreenOrientation; var ScreenService: IFMXScreenService; begin if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, ScreenService) then Result := ScreenService.GetScreenOrientation else Result := TScreenOrientation.Portrait; end; class function TfgScreenHelper.Scale: Single; var ScreenService: IFMXScreenService; begin if SameValue(FScreenScale, SCALE_UNDEFINED, EPSILON_SINGLE) then begin if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, ScreenService) then FScreenScale := ScreenService.GetScreenScale else FScreenScale := 1; end; Result := FScreenScale; Assert(Result > 0); end; { TfgGeneratorUniquiID } class constructor TfgGeneratorUniqueID.Create; begin FLastID := 0; end; class function TfgGeneratorUniqueID.GenerateID: Integer; begin Inc(FLastID); Result := FLastID end; end.
unit hardsid; {------------------------------------------------------------------------- unit hardsid.pas * HardSID library headers for FPC https://github.com/tednilsen/HardSID-FPC * Supports SIDBlaster https://github.com/Galfodo/SIDBlasterUSB_HardSID-emulation-driver * Unit supports static and dynamic loading of the library, see hardsid.inc for settings. -------------------------------------------------------------------------} {$MODE objfpc}{$H+} {$I hardsid.inc} // <- edit for settings interface {$IFDEF HS_STATIC_LIB} // static hardsid library //.......................... hardsid.dll v1.x ..........................\\ procedure InitHardSID_Mapper; EXTDECL 'InitHardSID_Mapper'; function GetDLLVersion: Word; EXTDECL 'GetDLLVersion'; function GetHardSIDCount: Byte; EXTDECL 'GetHardSIDCount'; // Tells you the number of HardSID's in the machine (depends on the HardSIDConfig.exe !). if 0, no HardSID is configured. procedure MuteHardSID(deviceID, channel: Byte; mute: Boolean); EXTDECL 'MuteHardSID'; procedure MuteHardSID_Line(mute: Boolean); EXTDECL 'MuteHardSID_Line'; // If you selected a HardSID line in HardSIDConfig.exe, you can mute/demute it TRUE/FALSE. USE IT WHILE NOT PLAYING!!! procedure MuteHardSIDAll(deviceID: Byte; mute: Boolean); EXTDECL 'MuteHardSIDAll'; function ReadFromHardSID(deviceID, sidReg: Byte): Byte; EXTDECL 'ReadFromHardSID'; // Reads data from the HardSID's specified register 0-28 ($00 - $1C), the last two regs are read-only. $1B = Waveform generator, $1C = ADSR generator (for voice #3). procedure WriteToHardSID(deviceID, sidReg, data: Byte); EXTDECL 'WriteToHardSID'; // Writes data to the HardSID's specified register 0-28 ($00 - $1C), the last two regs are read-only. Valid DeviceID = 0 to (GetHardSIDCount - 1). procedure SetDebug(enabled: Boolean); EXTDECL 'SetDebug'; // You can display a SID debug window which will show you the states of the SID registers //.......................... hardsid.dll v2.x ..........................\\ function HardSID_Read(deviceID: Byte; cycles: Word; sidReg: Byte): Byte; EXTDECL 'HardSID_Read'; procedure HardSID_Write(deviceID: Byte; cycles: Word; sidReg, data: Byte); EXTDECL 'HardSID_Write'; procedure HardSID_Delay(deviceID: Byte; cycles: Word); EXTDECL 'HardSID_Delay'; procedure HardSID_Sync(deviceID: Byte); EXTDECL 'HardSID_Sync'; procedure HardSID_Filter(deviceID: Byte; Filter: Boolean); EXTDECL 'HardSID_Filter'; procedure HardSID_Flush(deviceID: Byte); EXTDECL 'HardSID_Flush'; procedure HardSID_Mute(deviceID, channel: Byte; mute: Boolean); EXTDECL 'HardSID_Mute'; procedure HardSID_MuteAll(deviceID: Byte; mute: Boolean); EXTDECL 'HardSID_MuteAll'; procedure HardSID_Reset(deviceID: Byte); EXTDECL 'HardSID_Reset'; function HardSID_Devices: Byte; EXTDECL 'HardSID_Devices'; function HardSID_Version: Word; EXTDECL 'HardSID_Version'; //.......................... hardsid.dll v2.0.3 ........................\\ procedure HardSID_Reset2(deviceID, volume : Byte); EXTDECL 'HardSID_Reset2'; // Click reduction function HardSID_Lock(deviceID : Byte): Boolean; EXTDECL 'HardSID_Lock'; // Lock SID to application procedure HardSID_Unlock(deviceID : Byte); EXTDECL 'HardSID_Unlock'; function HardSID_Group(deviceID: Byte; Enable: Boolean; groupID: Byte): Boolean; EXTDECL 'HardSID_Group'; // Add SID to group when enable is true. SID can only be added or moved to an existing group. If deviceID = groupID then a new group is created with the SID device becoming group master. Only writes to the master are played on the other grouped SIDs. //.......................... hardsid.dll v2.0.6 ........................\\ procedure HardSID_Mute2(deviceID, channel: Byte; mute, manual: Boolean); EXTDECL 'HardSID_Mute2'; // Support whether the channel change was a request from the user or the program (auto or manual respectively). External mixers can use this to prioritise requests //.......................... hardsid.dll v2.0.7 ........................\\ procedure HardSID_OtherHardware; EXTDECL 'HardSID_OtherHardware'; // Enable support for non hardsid hardware (e.g. Catweasel MK3/4) //.......................... hardsid.dll v3.x ..........................\\ procedure HardSID_SoftFlush(deviceID: Byte); EXTDECL 'HardSID_SoftFlush'; procedure HardSID_AbortPlay(deviceID: Byte); EXTDECL 'HardSID_AbortPlay'; procedure HardSID_Try_Write(deviceID: Byte; cycles: Word; sidReg, data: Byte); EXTDECL 'HardSID_Try_Write'; //.......................... hardsid.dll v3.0.2 ........................\\ {$IFDEF HS_SIDBLASTER} procedure HardSID_ExternalTiming(deviceID: Byte); EXTDECL 'HardSID_ExternalTiming'; {$ENDIF HS_SIDBLASTER} implementation {$ELSE HS_STATIC_LIB} // else, dynamic loading of hardsid library uses dynlibs; function HS_InitializeLib: Boolean; procedure HS_FinalizeLib; function HS_Initialized: Boolean; inline; function HS_GetLibHandle: TLibHandle; inline; procedure HS_SetLibHandle(libHandle: TLibHandle); function HS_GetLibName: string; inline; procedure HS_SetLibName(const name: string); inline; var //.......................... hardsid.dll v1.x ..........................\\ InitHardSID_Mapper: procedure; EXTDECL; GetDLLVersion: function: Word; EXTDECL; GetHardSIDCount: function: Byte; EXTDECL; // Tells you the number of HardSID's in the machine (depends on the HardSIDConfig.exe !). if 0, no HardSID is configured. MuteHardSID: procedure(deviceID, channel: byte; mute: Boolean); EXTDECL; MuteHardSID_Line: procedure(mute: Boolean); EXTDECL; // If you selected a HardSID line in HardSIDConfig.exe, you can mute/demute it TRUE/FALSE. USE IT WHILE NOT PLAYING!!! MuteHardSIDAll: procedure(deviceID: byte; mute: Boolean); EXTDECL; ReadFromHardSID: function(deviceID, sidReg: Byte): Byte; EXTDECL; // Reads data from the HardSID's specified register 0-28 ($00 - $1C), the last two regs are read-only. $1B = Waveform generator, $1C = ADSR generator (for voice #3). WriteToHardSID: procedure(deviceID, sidReg, data: Byte); EXTDECL; // Writes data to the HardSID's specified register 0-28 ($00 - $1C), the last two regs are read-only. Valid DeviceID = 0 to (GetHardSIDCount - 1). SetDebug: procedure(Enabled: Boolean); EXTDECL; // You can display a SID debug window which will show you the states of the SID registers //.......................... hardsid.dll v2.x ..........................\\ HardSID_Read: function(deviceID: Byte; cycles: Word; sidReg: Byte): Byte; EXTDECL; HardSID_Write: procedure(deviceID: Byte; cycles: Word; sidReg, data: Byte); EXTDECL; HardSID_Delay: procedure(deviceID: Byte; cycles: Word); EXTDECL; HardSID_Sync: procedure(deviceID: Byte); EXTDECL; HardSID_Filter: procedure(deviceID: Byte; Filter: Boolean); EXTDECL; HardSID_Flush: procedure(deviceID: Byte); EXTDECL; HardSID_Mute: procedure(deviceID, channel: Byte; mute: Boolean); EXTDECL; HardSID_MuteAll: procedure(deviceID: Byte; mute: Boolean); EXTDECL; HardSID_Reset: procedure(deviceID: Byte); EXTDECL; HardSID_Devices: function: Byte; EXTDECL; HardSID_Version: function: Word; EXTDECL; //.......................... hardsid.dll v2.0.3 ........................\\ HardSID_Reset2: procedure(deviceID, volume : Byte); EXTDECL; // Click reduction HardSID_Lock: function(deviceID : Byte): Boolean; EXTDECL; // Lock SID to application HardSID_Unlock: procedure(deviceID : Byte); EXTDECL; HardSID_Group: function(deviceID: Byte; Enable: Boolean; groupID: Byte): Boolean; EXTDECL; // Add SID to group when enable is true. SID can only be added or moved to an existing group. If deviceID = groupID then a new group is created with the SID device becoming group master. Only writes to the master are played on the other grouped SIDs. //.......................... hardsid.dll v2.0.6 ........................\\ HardSID_Mute2: procedure(deviceID, channel: byte; mute, Manual: Boolean); EXTDECL; // Support whether the channel change was a request from the user or the program (auto or manual respectively). External mixers can use this to prioritise requests //.......................... hardsid.dll v2.0.7 ........................\\ HardSID_OtherHardware: procedure; EXTDECL; // Enable support for non hardsid hardware (e.g. Catweasel MK3/4) //.......................... hardsid.dll v3.x ..........................\\ HardSID_SoftFlush: procedure(deviceID: Byte); EXTDECL; HardSID_AbortPlay: procedure(deviceID: Byte); EXTDECL; HardSID_Try_Write: procedure(deviceID: Byte; cycles: Word; sidReg, data: Byte); EXTDECL; //.......................... hardsid.dll v3.0.2 ........................\\ {$IFDEF HS_SIDBLASTER} HardSID_ExternalTiming: procedure(deviceID: Byte); EXTDECL; {$ENDIF HS_SIDBLASTER} implementation const LIB_HARDSID = 'hardsid'; var libHS: TLibHandle = NilHandle; // library handle libName: string = LIB_HARDSID; // name of the library //------------------------------------------------------------------------- // _initProc //------------------------------------------------------------------------- procedure _initProc(var procPointer; procName: PChar); begin pointer(procPointer) := dynlibs.GetProcAddress(libHS, procName); end; //------------------------------------------------------------------------- // HS_Initialized // * Returns True if hardsid library is loaded and present //------------------------------------------------------------------------- function HS_Initialized: boolean; begin Result := libHS <> NilHandle; end; //------------------------------------------------------------------------- // HS_GetLibHandle // * Returns the handle of EGL library. //------------------------------------------------------------------------- function HS_GetLibHandle: TLibHandle; begin Result := libHS; end; //------------------------------------------------------------------------- // HS_GetLibName // - Returns the library's name (without suffix). //------------------------------------------------------------------------- function HS_GetLibName: string; begin Result := libName; end; //------------------------------------------------------------------------- // HS_SetLibName // - Set the name for the library (without suffix). //------------------------------------------------------------------------- procedure HS_SetLibName(const name: string); begin libName := name; end; //------------------------------------------------------------------------- // HS_SetLibHandle // - Set the handle of hardsid library. //------------------------------------------------------------------------- procedure HS_SetLibHandle(libHandle: TLibHandle); begin libHS := libHandle; end; //------------------------------------------------------------------------- // HS_NilLib // - Nil all the function variables //------------------------------------------------------------------------- procedure HS_NilLib; begin //.......................... hardsid.dll v1.x ..........................\\ InitHardSID_Mapper := nil; GetDLLVersion := nil; GetHardSIDCount := nil; MuteHardSID := nil; MuteHardSID_Line := nil; MuteHardSIDAll := nil; ReadFromHardSID := nil; WriteToHardSID := nil; SetDebug := nil; //.......................... hardsid.dll v2.x ..........................\\ HardSID_Read := nil; HardSID_Write := nil; HardSID_Delay := nil; HardSID_Sync := nil; HardSID_Filter := nil; HardSID_Flush := nil; HardSID_Mute := nil; HardSID_Mute2 := nil; HardSID_MuteAll := nil; HardSID_Reset := nil; HardSID_Reset2 := nil; HardSID_Group := nil; HardSID_Devices := nil; HardSID_Lock := nil; HardSID_Unlock := nil; HardSID_Version := nil; HardSID_OtherHardware := nil; //.......................... hardsid.dll v3.x ..........................\\ HardSID_SoftFlush := nil; HardSID_AbortPlay := nil; HardSID_Try_Write := nil; //.......................... hardsid.dll v3.0.2 ........................\\ {$IFDEF HS_SIDBLASTER} HardSID_ExternalTiming := nil; {$ENDIF HS_SIDBLASTER} end; //------------------------------------------------------------------------- // HS_LoadLib // - Set the function variables (if available) //------------------------------------------------------------------------- procedure HS_LoadLib; var version: word = $0000; begin //.......................... hardsid.dll v1.x ..........................\\ _initProc(GetDLLVersion, 'GetDLLVersion'); if Assigned(GetDLLVersion) then version := GetDLLVersion() else exit; if version >= $0100 then begin _initProc(InitHardSID_Mapper, 'InitHardSID_Mapper'); _initProc(GetHardSIDCount, 'GetHardSIDCount'); _initProc(MuteHardSID, 'MuteHardSID'); _initProc(MuteHardSID_Line, 'MuteHardSID_Line'); _initProc(MuteHardSIDAll, 'MuteHardSIDAll'); _initProc(ReadFromHardSID, 'ReadFromHardSID'); _initProc(WriteToHardSID, 'WriteToHardSID'); _initProc(SetDebug, 'SetDebug'); end; //.......................... hardsid.dll v2.x ..........................\\ if version >= $0200 then begin _initProc(HardSID_Read, 'HardSID_Read'); _initProc(HardSID_Write, 'HardSID_Write'); _initProc(HardSID_Delay, 'HardSID_Delay'); _initProc(HardSID_Sync, 'HardSID_Sync'); _initProc(HardSID_Filter, 'HardSID_Filter'); _initProc(HardSID_Flush, 'HardSID_Flush'); _initProc(HardSID_Mute, 'HardSID_Mute'); _initProc(HardSID_MuteAll, 'HardSID_MuteAll'); _initProc(HardSID_Reset, 'HardSID_Reset'); _initProc(HardSID_Devices, 'HardSID_Devices'); _initProc(HardSID_Version, 'HardSID_Version'); end; //.......................... hardsid.dll v2.0.3 ........................\\ if version >= $0203 then begin _initProc(HardSID_Reset2, 'HardSID_Reset2'); _initProc(HardSID_Lock, 'HardSID_Lock'); _initProc(HardSID_Unlock, 'HardSID_Unlock'); _initProc(HardSID_Group, 'HardSID_Group'); end; //.......................... hardsid.dll v2.0.6 ........................\\ if version >= $0206 then begin _initProc(HardSID_Mute2, 'HardSID_Mute2'); end; //.......................... hardsid.dll v2.0.7 ........................\\ if version >= $0207 then begin _initProc(HardSID_OtherHardware, 'HardSID_OtherHardware'); end; //.......................... hardsid.dll v3.x ..........................\\ if version >= $0300 then begin _initProc(HardSID_SoftFlush, 'HardSID_SoftFlush'); _initProc(HardSID_AbortPlay, 'HardSID_AbortPlay'); _initProc(HardSID_Try_Write, 'HardSID_Try_Write'); end; //.......................... hardsid.dll v3.0.2 ........................\\ {$IFDEF HS_SIDBLASTER} if version >= $0302 then begin _initProc(HardSID_ExternalTiming, 'HardSID_ExternalTiming'); end; {$ENDIF HS_SIDBLASTER} end; //------------------------------------------------------------------------- // HS_InitializeLib // - Load and Initialize the hardsid library. //------------------------------------------------------------------------- function HS_InitializeLib: boolean; begin try HS_NilLib; if libHS = NilHandle then libHS:= dynlibs.LoadLibrary(libName + '.' + dynlibs.SharedSuffix); if libHS <> NilHandle then HS_LoadLib; finally Result := libHS <> NilHandle; end; end; //------------------------------------------------------------------------- // HS_FinalizeLib // - Unloads the hardsid library (if loaded and not shared) //------------------------------------------------------------------------- procedure HS_FinalizeLib; begin if libHS <> NilHandle then begin dynlibs.FreeLibrary(libHS); libHS := NilHandle; HS_NilLib; end; end; {$IFDEF HS_AutoInitialize} // <--- define to automatic initialize the unit //========================================================= // initialization //========================================================= initialization begin HS_InitializeLib; end; //========================================================= // finalization //========================================================= finalization begin HS_FinalizeLib; end; {$ENDIF HS_AutoInitialize} {$ENDIF HS_STATIC_LIB} end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Tether.BluetoothAdapter; interface {$IFNDEF IOS} {$DEFINE BT_PLATFORM} {$ENDIF} {$IFDEF BT_PLATFORM} {$SCOPEDENUMS ON} uses System.SyncObjs, System.Tether.Manager, System.Tether.Comm; type TTetheringBluetoothAdapter = class; TTetheringBluetoothManagerCommunicationThread = class(TTetheringManagerCommunicationThread) private const TTetheringBTBaseUUID: TGUID = '{00000000-62CC-0000-BBBF-BF3E3BBB1374}'; MAXCONNECTIONS = 10; private FServerComm: TTetheringBTServerComm; FClientComm: TTetheringBTComm; FLastConnection: string; procedure DoOnExecute(const AConnection: TTetheringCustomComm); procedure DoOnConnect(const AConnection: TTetheringCustomComm); procedure DoOnDisconnect(const AConnection: TTetheringCustomComm); protected function ProcessResponse(const AData: string; var RemoteConnectionString: string): string; override; procedure DoSendCommand(const AConnection, AData: string); override; function IsListening: Boolean; override; public constructor Create(const AnAdapter: TTetheringAdapter); override; destructor Destroy; override; procedure Execute; override; end; TTetheringBluetoothAdapter = class(TTetheringAdapter) public const MaxBluetoothConnections = 6; AdapterID = 'Bluetooth'; // do not localize private [Weak] FCommunicationThread: TTetheringBluetoothManagerCommunicationThread; protected function GetAutomaticTimeout: Cardinal; override; procedure DoDiscoverManagers(Timeout: Cardinal; const ATargetList: TTetheringTargetHosts; const AProfileGroups, AProfileTexts: TArray<string>); override; function GetAdapterType: TTetheringAdapterType; override; function DoCreateCommunicationThread(const AnAdapter: TTetheringAdapter): TTetheringManagerCommunicationThread; override; procedure DoStopListening; override; public constructor Create; override; destructor Destroy; override; class function CreateInstance: TTetheringAdapter; override; function GetClientPeer(const ProtocolId: TTetheringProtocolType): TTetheringCustomComm; override; function GetServerPeer(const ProtocolId: TTetheringProtocolType): TTetheringCustomServerComm; override; function MaxConnections: Integer; override; function GetTargetConnection(const Port, Offset: Integer): string; override; end; {$ENDIF BT_PLATFORM} implementation {$IFDEF BT_PLATFORM} uses System.SysUtils, System.Tether.Consts, System.Tether.TCPProtocol, System.Bluetooth; { TTetheringBluetoothManagerCommunicationThread } constructor TTetheringBluetoothManagerCommunicationThread.Create(const AnAdapter: TTetheringAdapter); begin inherited Create(AnAdapter); FServerComm := TTetheringBTServerComm.Create; FClientComm := TTetheringBTComm.Create; end; destructor TTetheringBluetoothManagerCommunicationThread.Destroy; begin FClientComm.Free; FServerComm.Free; inherited; end; procedure TTetheringBluetoothManagerCommunicationThread.DoOnConnect(const AConnection: TTetheringCustomComm); begin end; procedure TTetheringBluetoothManagerCommunicationThread.DoOnDisconnect(const AConnection: TTetheringCustomComm); begin end; procedure TTetheringBluetoothManagerCommunicationThread.DoOnExecute(const AConnection: TTetheringCustomComm); var RespOk: TBytes; LCommand: TBytes; LStrCommand: string; LCommands: TArray<string>; begin LCommand := AConnection.ReadData; RespOk := [Ord('O'), Ord('k')]; AConnection.WriteData(RespOk); LStrCommand := TEncoding.UTF8.GetString(LCommand); LCommands := TTetheringManagerCommand.Split(LStrCommand, TetheringCommandSeparator); for LStrCommand in LCommands do begin if LStrCommand <> '' then FCommandQueue.Enqueue(LStrCommand); end; end; procedure TTetheringBluetoothManagerCommunicationThread.Execute; const Retries = 3; var I: Integer; LGUID: TGUID; Resp: string; RemoteConnectionString: string; begin inherited; FServerComm.OnExecute := DoOnExecute; FServerComm.OnConnect := DoOnConnect; FServerComm.OnDisconnect := DoOnDisconnect; for I := 1 to Retries do begin LGUID := TTetheringBTBaseUUID; LGUID.D1 := Cardinal(Pointer(FAdapter)); LGUID.D3 := Random(65535); FServerComm.Target := LGUID.ToString; if FServerComm.StartServer then Break; end; TTetheringBluetoothAdapter(FAdapter).SetLocalConnectionString(TBluetoothManager.Current.CurrentAdapter.Address + TetheringConnectionSeparator + FServerComm.Target); CommunicationThreadInitialized; if not FServerComm.Active then raise ETetheringException.Create(SManagerBluetoothCreation); while not Terminated do begin FCommandQueue.WaitCommand; while not Terminated and (FCommandQueue.Count > 0) do begin try Resp := ProcessResponse(FCommandQueue.Dequeue, RemoteConnectionString); if (not Terminated) and (Resp <> TetheringEmpty) then SendCommand(RemoteConnectionString, Resp); except end; end; end; end; function TTetheringBluetoothManagerCommunicationThread.IsListening: Boolean; begin Result := FServerComm.Active; end; function TTetheringBluetoothManagerCommunicationThread.ProcessResponse(const AData: string; var RemoteConnectionString: string): string; begin Result := inherited ProcessResponse(AData, RemoteConnectionString); end; procedure TTetheringBluetoothManagerCommunicationThread.DoSendCommand(const AConnection, AData: string); const Retries = 3; var I: Integer; begin inherited; if AData <> TetheringEmpty then begin TMonitor.Enter(FClientComm); try for I := 1 to Retries do begin if FLastConnection <> AConnection then begin if FClientComm.Connected then FClientComm.Disconnect; FClientComm.Connect(AConnection); if FClientComm.Connected then FLastConnection := AConnection else FLastConnection := ''; end; if FClientComm.Connected then begin try FClientComm.WriteData(TEncoding.UTF8.GetBytes(AData)); FClientComm.ReadData; except FLastConnection := ''; end; Break; end else FLastConnection := ''; end; finally TMonitor.Exit(FClientComm); end; end; end; { TTetheringBluetoothAdapter } constructor TTetheringBluetoothAdapter.Create; begin inherited; end; class function TTetheringBluetoothAdapter.CreateInstance: TTetheringAdapter; var LBTManager: TBluetoothManager; LBTAdapter: TBluetoothAdapter; begin Result := nil; // Before creating an instance we need to ensure that BT is present LBTManager := TBluetoothManager.Current; if LBTManager <> nil then if LBTManager.ConnectionState = TBluetoothConnectionState.Connected then begin LBTAdapter := LBTManager.CurrentAdapter; if LBTAdapter <> nil then Result := TTetheringBluetoothAdapter.Create; end; end; destructor TTetheringBluetoothAdapter.Destroy; begin inherited; end; procedure TTetheringBluetoothAdapter.DoDiscoverManagers(Timeout: Cardinal; const ATargetList: TTetheringTargetHosts; const AProfileGroups, AProfileTexts: TArray<string>); function DeviceInTarget(const ADevice: TBluetoothDevice; const ATargetArray: TArray<string>): Boolean; var LTarget: string; begin Result := False; for LTarget in ATargetArray do if SameText(ADevice.Address, LTarget) or SameText(ADevice.DeviceName, LTarget) then begin Result := True; Break; end; end; function IsTTetheringManager(const AGUIDString: string): Boolean; var LGUID: TGUID; begin LGUID := TGUID.Create(AGUIDString); LGUID.D1 := 0; LGUID.D3 := 0; Result := LGUID = TTetheringBluetoothManagerCommunicationThread.TTetheringBTBaseUUID; end; procedure SendDiscoverCommand(const ADevice: TBluetoothDevice; const AService: TBluetoothService); var LUUID: TGUID; LClientComm: TTetheringBTComm; I: Integer; LBuff: TBytes; LServers: TArray<string>; begin LUUID := AService.UUID; LUUID.D1 := 0; LUUID.D3 := 0; // Try to find BT Server to get registered servers if LUUID = TTetheringBTServerComm.BTServerBaseUUID then begin LClientComm := TTetheringBTComm.Create; try try if not LClientComm.Connect(ADevice.DeviceName + TetheringConnectionSeparator + AService.UUID.ToString) then Exit; except Exit; end; try LBuff := LClientComm.ReadData; except end; if Length(LBuff) > 0 then begin LClientComm.WriteData(TEncoding.UTF8.GetBytes('ok')); LServers := TEncoding.UTF8.GetString(LBuff).Split([TetheringConnectionSeparator]); end else LClientComm.WriteData(TEncoding.UTF8.GetBytes('error')); finally LClientComm.Free; end; for I := 0 to High(LServers) do begin if IsTTetheringManager(LServers[I]) then begin FCommunicationThread.SendCommand(ADevice.Address + TetheringConnectionSeparator + LServers[I], FCommunicationThread.CommandStr(TTetheringBluetoothManagerCommunicationThread.TetheringDiscoverManagers, Manager.Version, [LServers[I]])); end; end; end; end; var LDevice: TBluetoothDevice; LService: TBluetoothService; LDeviceList: TBluetoothDeviceList; begin LDeviceList := TBluetoothManager.Current.GetPairedDevices; if Length(ATargetList) = 0 then begin for LDevice in LDeviceList do begin for LService in LDevice.GetServices do SendDiscoverCommand(LDevice, LService); end; end else begin for LDevice in LDeviceList do begin if DeviceInTarget(LDevice, ATargetList) then begin for LService in LDevice.GetServices do SendDiscoverCommand(LDevice, LService); end; end; end; end; function TTetheringBluetoothAdapter.DoCreateCommunicationThread(const AnAdapter: TTetheringAdapter): TTetheringManagerCommunicationThread; begin inherited; Result := TTetheringBluetoothManagerCommunicationThread.Create(Self); FCommunicationThread := TTetheringBluetoothManagerCommunicationThread(Result); // The Adapter is responsible of releasing it end; procedure TTetheringBluetoothAdapter.DoStopListening; begin inherited; end; function TTetheringBluetoothAdapter.GetAdapterType: TTetheringAdapterType; begin Result := AdapterID; end; function TTetheringBluetoothAdapter.GetAutomaticTimeout: Cardinal; begin Result := 2000 + TBluetoothManager.Current.GetPairedDevices.Count * 8500; end; function TTetheringBluetoothAdapter.GetClientPeer(const ProtocolId: TTetheringProtocolType): TTetheringCustomComm; begin Result := TTetheringBTComm.Create; end; function TTetheringBluetoothAdapter.GetServerPeer(const ProtocolId: TTetheringProtocolType): TTetheringCustomServerComm; begin Result := TTetheringBTServerComm.Create; end; function TTetheringBluetoothAdapter.GetTargetConnection(const Port, Offset: Integer): string; var LGUID: TGUID; begin LGUID := TTetheringBluetoothManagerCommunicationThread.TTetheringBTBaseUUID; LGUID.D1 := Cardinal(Pointer(Self)); LGUID.D2 := LGUID.D2 + $11 + Offset; LGUID.D3 := $FFFF and (Random(65535) + Port); Result := LGUID.ToString; end; function TTetheringBluetoothAdapter.MaxConnections: Integer; begin Result := MaxBluetoothConnections; end; initialization TTetheringAdapters.RegisterAdapter(TTetheringBluetoothAdapter, TTetheringBluetoothAdapter.AdapterID); finalization TTetheringAdapters.UnRegisterAdapter(TTetheringBluetoothAdapter.AdapterID); {$ENDIF BT_PLATFORM} end.
unit RTEH; {run-time error handler} interface implementation uses support; var OldExit:pointer; Procedure RunTimeExitProc; Far; var Message:string; begin if ErrorAddr<>Nil then begin case ExitCode of 1:message:='Invalid function number'; 2:message:='File not found'; 3:message:='Path not found'; 4:message:='Too many open files'; 5:message:='File access denied'; 6:message:='Invalid file handle'; 12:message:='Invalid file access code'; 15:message:='Invalid drive number'; 16:message:='Cannot remove current directory'; 17:message:='Cannot rename across drives'; 18:message:='No more files'; 100:message:='Disk read error'; 101:message:='Disk write error'; 102:message:='File not assigned'; 103:message:='File not open'; 104:message:='File not open for input'; 105:message:='File not open for output'; 106:message:='Invalid numeric format'; 150:message:='Disk is write-protected'; 151:message:='Bad drive request struct length'; 152:message:='Drive not ready'; 154:message:='CRC error in data'; 156:message:='Disk seek error'; 157:message:='Unknown media type'; 158:message:='Sector Not Found'; 159:message:='Printer out of paper'; 160:message:='Device write fault'; 161:message:='Device read fault'; 162:message:='Hardware failure'; 200:message:='Division by zero'; 201:message:='Range check error'; 202:message:='Stack overflow error'; 203:message:='Heap overflow error'; 204:message:='Invalid pointer operation'; 205:message:='Floating point overflow'; 206:message:='Floating point underflow'; 207:message:='Invalid floating point operation'; 208:message:='Overlay manager not installed'; 209:message:='Overlay file read error'; 210:message:='Object not initialized'; 211:message:='Call to abstract method'; 212:message:='Stream registration error'; 213:message:='Collection index out of range'; 214:message:='Collection overflow error'; 215:message:='Arithmetic overflow error'; 216:message:='General Protection fault'; else message:='Unknown'; end; {force text mode so we can see the error!} asm mov ax,0003 int 10h end; writeln('Fatal runtime error ',ExitCode, ' at ',hexword(seg(ErrorAddr^)), ':',hexword(ofs(ErrorAddr^)), ': ',Message); ErrorAddr:=nil; ExitCode:=1; end; ExitProc:=OldExit; end; {====================================================================} begin OldExit:=ExitProc; ExitProc:=@RunTimeExitProc; end.
unit PUSHMessage; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinsDefaultPainters, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxMemo; type TPUSHMessageForm = class(TForm) bbCancel: TcxButton; bbOk: TcxButton; Memo: TcxMemo; pn2: TPanel; pn1: TPanel; procedure FormCreate(Sender: TObject); procedure MemoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; function ShowPUSHMessage(AMessage : string; DlgType: TMsgDlgType = mtInformation) : boolean; implementation {$R *.dfm} procedure TPUSHMessageForm.FormCreate(Sender: TObject); begin Memo.Style.Font.Size := Memo.Style.Font.Size + 4; end; procedure TPUSHMessageForm.MemoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_Return then ModalResult := mrOk; end; function ShowPUSHMessage(AMessage : string; DlgType: TMsgDlgType = mtInformation) : boolean; var PUSHMessageForm : TPUSHMessageForm; begin PUSHMessageForm := TPUSHMessageForm.Create(Screen.ActiveControl); try PUSHMessageForm.Memo.Lines.Text := AMessage; case DlgType of mtWarning : PUSHMessageForm.Caption := 'Предупреждение'; mtError : begin PUSHMessageForm.Caption := 'Ошибка'; PUSHMessageForm.Memo.Style.TextColor := clRed; end; mtInformation : PUSHMessageForm.Caption := 'Сообщение'; mtConfirmation : PUSHMessageForm.Caption := 'Подтверждение'; end; Result := PUSHMessageForm.ShowModal = mrOk; finally PUSHMessageForm.Free; end; end; end.
unit DirUtil; // 説 明:汎用ディレクトリ処理ユニット。PerlのGlobライクに使える // 作 者:クジラ飛行机(web@kujirahand.com) https://sakuramml.com // 公開日:2001/10/21 {------------------------------------------------ フォルダ内のファイルを列挙したり、サブディレクトリ以下の全ファイルを列挙。 PerlのGlobを目指して作ったユニット。 使い方: var g: TGlob; begin g := TGlob.Create( path ); ShowMessage( g.FileList.Text ); //ファイル一覧 ShowMessage( g.DirList.Text ); //フォルダ一覧 g.Free; end; サブディレクトリ以下の全ファイルを列挙 var s: TStringList; begin s := getAllFiles(path + filter); ShowMessage( s.Text ); //全ファイルを表示 s.Free; end; } interface uses SysUtils, Classes, Windows, FileCtrl,Forms, comctrls, stdctrls, Dialogs; type TGlob = class private rec: TSearchRec; CurPath: string; public DirList: TStringList; FileList: TStringList; constructor Create(path: string); destructor Destroy; override; procedure ChangePath(path: string); function GetPath : string; function DeleteAllFile: Boolean; function DeleteForceDir: Boolean; function CopyDirectory(toPath: string):Boolean; function CopyDirectory2(path: String; proBar:TProgressBar; lbl:TLabel): Boolean; end; {ファイルの拡張子を問わず、その名前ファイルがあるかどうかチェック あれば、そのファイル名を、なければ、''を返す} function ExistsFileNameWE(path: string): string; {ワイルドカードで似たファイルを適当に特定する。} function FindLikeFile(path: string): string; {ディレクトリ以下の完全コピー} function DirCopy(const FromPath, ToPath: string):Boolean; function DirCopy2(const FromPath, ToPath: string; proBar: TProgressBar; lbl:TLabel):Boolean; {ディレクトリ以下の完全消去} function DirDelete(path: string):Boolean; {階層以下の全てのファイルを得る} function getAllFiles(const path: string): TStringList; {ファイルサイズの小さい順に並べる} procedure SortFileSize(sl:TStringList); function GetFileSizeEasy(fname: string): Integer; {ファイルの更新履歴順に並べる} procedure SortFileDate(sl:TStringList); implementation {ファイルの更新履歴順に並べる} procedure SortFileDate(sl:TStringList); var i,j,szi,szj:Integer; s: string; begin if sl=nil then Exit; for i:=0 to sl.Count -1 do begin for j:=0 to sl.Count - 1 do begin if i=j then Continue; try szi := FileAge(sl.Strings[i]); szj := FileAge(sl.Strings[j]); if szi < szj then begin //swap s := sl.Strings[i]; sl.Strings[i] := sl.Strings[j]; sl.Strings[j] := s; end; except Continue; end; end; end; end; {ファイルサイズの小さい順に並べる} function GetFileSizeEasy(fname: string): Integer; var f:File; begin Result := 0; if FileExists(fname) then begin AssignFile(f, fname); Reset(f); Result := FileSize(f); closeFile(f); end; end; procedure SortFileSize(sl:TStringList); var i,j,szi,szj:Integer; s: string; f:File; begin if sl=nil then Exit; for i:=0 to sl.Count -1 do begin for j:=0 to sl.Count - 1 do begin if i=j then Continue; try AssignFile(f, sl.Strings[i]); Reset(f); szi := FileSize(f); closeFile(f); AssignFile(f, sl.Strings[j]); Reset(f); szj := FileSize(f); closeFile(f); if szi < szj then begin //swap s := sl.Strings[i]; sl.Strings[i] := sl.Strings[j]; sl.Strings[j] := s; end; except Continue; end; end; end; end; {階層以下の全てのファイルを得る} function getAllFiles(const path: string): TStringList; var sl: TStringList; filter, ps: string; procedure checkDir(path:string); var i:Integer; g:TGlob; begin g := TGlob.Create(path+Filter); try for i:=0 to g.FileList.Count - 1 do begin sl.Add(g.GetPath + g.FileList.Strings[i]); end; finally g.Free; end; g := TGlob.Create(path); try for i:=0 to g.DirList.Count - 1 do begin if Copy(g.DirList.Strings[i],1,1)='.' then Continue; checkDir(g.GetPath + g.DirList.Strings[i]+'\'); end; finally g.Free; end; end; begin filter := ExtractFileName(path); ps := ExtractFilePath(path); sl := TStringList.Create; try checkDir(ps); except sl.Free; sl := nil; end; Result := sl; end; {ディレクトリ以下の完全消去} function DirDelete(path: string):Boolean; var g:TGlob; begin g := TGlob.Create(path); try Result := g.DeleteForceDir; finally g.Free; end; end; {ディレクトリ以下の完全コピー} function DirCopy(const FromPath, ToPath: string):Boolean; var glob:TGlob; begin glob := TGlob.Create(FromPath); try Result := glob.CopyDirectory(ToPath); finally glob.Free ; end; end; function DirCopy2(const FromPath, ToPath: string; proBar: TProgressBar; lbl:TLabel):Boolean; var glob:TGlob; begin Result := False; glob := TGlob.Create(FromPath); try try Result := glob.CopyDirectory2(ToPath, proBar, lbl); except raise EFilerError.Create(''); end; finally glob.Free ; end; end; {ワイルドカードで似たファイルを適当に特定する。} function FindLikeFile(path: string): string; var glob: TGlob; begin glob := TGlob.Create(path); try if glob.FileList.Count > 0 then Result := glob.GetPath + glob.FileList.Strings[0] else Result := ''; finally glob.Free ; end; end; {ファイルの拡張子を問わず、そのファイルがあるかどうかチェック あれば、そのファイル名を、なければ、''を返す} function ExistsFileNameWE(path: string): string; var p, fname, d: string; glob: TGlob; begin p := ExtractFilePath(path); fname := ExtractFileName(path); d := ExtractFileExt(path); path := p + Copy(fname, 1, Length(fname)-Length(d)); path := path + '.*'; glob := TGlob.Create(path); try if glob.FileList.Count > 0 then Result := p + glob.FileList.Strings[0] else Result := ''; finally glob.Free ; end; end; { TGlob } procedure TGlob.ChangePath(path: string); procedure chkType; var s: string; begin s := rec.Name ; if (rec.Attr and faDirectory) = faDirectory then begin if Copy(rec.Name,1,1) = '.' then begin //カレントディレクトリは、加えない。 end else begin DirList.Add( s ); end; end else begin FileList.Add( s ); end; end; begin CurPath := ExtractFilePath(path); DirList.Clear; FileList.Clear; if FindFirst(path, faAnyFile, rec) = 0 then begin chkType; while FindNext(rec) = 0 do begin chkType; end; SysUtils.FindClose(rec); end; end; function TGlob.CopyDirectory(toPath: string): Boolean; var nowPath, s: string; i: Integer; procedure copyAllFile(glob:TGlob; des:string); var i:integer; s,s1,s2:string; begin des := ExtractFilePath(des); if false=DirectoryExists(des) then begin ForceDirectories(des); end; for i:=0 to glob.FileList.Count - 1 do begin s := glob.FileList.Strings[i]; s1 := glob.GetPath + s; s2 := des + s; if CopyFile(PChar(s1), PChar(s2), False)=False then Result := False else begin FileSetAttr(s2, 0); end; end; end; procedure subCopy(src,des:string); var glob: TGlob; i:Integer; s:string; begin glob := TGlob.Create(src); try for i:=0 to glob.DirList.Count - 1 do begin s := glob.DirList.Strings[i]; subCopy(glob.GetPath+s+'\', des+s+'\'); end; copyAllFile(glob, des); finally glob.Free; end; end; begin Result := True; nowPath := GetPath ; for i:=0 to DirList.Count - 1 do begin s := DirList.Strings[i]; subCopy(nowPath+s+'\', ExtractFilePath(toPath)+s+'\'); Application.ProcessMessages; end; copyAllFile(self, toPath); end; function TGlob.CopyDirectory2(path: String; proBar: TProgressBar; lbl: TLabel): Boolean; var nowPath, s: string; i, cnt: Integer; sl: TStringList; procedure copyAllFile(glob:TGlob; des:string); var i:integer; msg,s,s1,s2:string; begin des := ExtractFilePath(des); if false=DirectoryExists(des) then begin ForceDirectories(des); end; for i:=0 to glob.FileList.Count - 1 do begin s := glob.FileList.Strings[i]; s1 := glob.GetPath + s; s2 := des + s; if FileExists(s2) then begin FileSetAttr(s2, 0); DeleteFile(PChar(s2)); end; FileSetAttr(s2, 0); if CopyFile(PChar(s1), PChar(s2), False)=False then begin Result := False; msg := ('"'+s1+'"から、'#13#10'"'+ s2+'" へのコピーに失敗しました。'); ShowMessage(msg); raise EFilerError.Create(msg); end else begin FileSetAttr(s2, 0); end; proBar.Position := cnt; Inc(cnt); lbl.Caption := ExtractFileName(s1); Application.ProcessMessages ; end; end; procedure subCopy(src,des:string); var glob: TGlob; i:Integer; s:string; begin glob := TGlob.Create(src); try for i:=0 to glob.DirList.Count - 1 do begin s := glob.DirList.Strings[i]; subCopy(glob.GetPath+s+'\', des+s+'\'); end; copyAllFile(glob, des); finally glob.Free; end; end; begin Result := True; sl := GetAllFiles(nowPath+'*'); try try nowPath := GetPath ; proBar.Max := sl.Count; cnt := 0; for i:=0 to DirList.Count - 1 do begin s := DirList.Strings[i]; subCopy(nowPath+s+'\', ExtractFilePath(Path)+s+'\'); Application.ProcessMessages; end; copyAllFile(self, Path); proBar.Position := proBar.Max ; except ShowMessage('"'+nowPath+s+'\"のコピーでエラー'); ShowMessage('インストールに失敗しました。再試行してください。'); raise EFilerError.Create('"'+nowPath+s+'\"のコピーでエラー'); end; finally sl.Free; end; end; constructor TGlob.Create(path: string); begin DirList := TStringList.Create ; FileList := TStringList.Create; if Copy(path,Length(path),1)='\' then path := path + '*'; ChangePath(path); end; function TGlob.DeleteAllFile: Boolean; var i: Integer; s: string; begin Result := True; for i:=0 to FileList.Count - 1 do begin s := CurPath + FileList.Strings[i]; if SysUtils.DeleteFile(s) = False then Result := False; end; end; function TGlob.DeleteForceDir: Boolean; var i: Integer; path: string; function DelDir(path: string): Boolean; var g:TGlob; begin path := ExtractFilePath(path)+'*.*'; g := TGlob.Create(path); try Result := g.DeleteForceDir; finally g.Free; end; end; begin Result := True; for i:=0 to DirList.Count - 1 do begin path := CurPath + DirList.Strings[i] + '\'; if DelDir(path)=False then Result := False; end; if DeleteAllFile=False then Result := False; if RemoveDir(CurPath)=False then Result := False; end; destructor TGlob.Destroy; begin inherited; DirList.Free; FileList.Free; end; function TGlob.GetPath: string; begin Result := ExtractFilePath(CurPath); end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Edit, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Objects, FMX.Layouts; type TForm1 = class(TForm) Layout1: TLayout; Rectangle1: TRectangle; Label1: TLabel; Button1: TButton; Button2: TButton; Button3: TButton; Edit1: TEdit; Edit2: TEdit; Edit3: TEdit; Edit4: TEdit; procedure FormCreate(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure EsconderPopup(Sender: TObject); procedure MostrarPopup; end; var Form1: TForm1; implementation uses TDevRopcks.Util.Background; {$R *.fmx} procedure TForm1.Button1Click(Sender: TObject); begin TBackground.Hide; EsconderPopup(Sender); end; procedure TForm1.Button2Click(Sender: TObject); begin TBackground.Show(Application.MainForm, EsconderPopup); MostrarPopup; end; procedure TForm1.Button3Click(Sender: TObject); begin TBackground.Show(Application.MainForm); MostrarPopup; end; procedure TForm1.EsconderPopup(Sender: TObject); begin // Layout1.Visible := False; end; procedure TForm1.FormCreate(Sender: TObject); begin Layout1.Visible := False; end; procedure TForm1.MostrarPopup; begin Layout1.Visible := True; Layout1.Align := TAlignLayout.Center; Layout1.BringToFront; end; end.
{ *********************************************************************************************************************** * Dev.Halil Han Badem * * 24/07/2019 * Instagram: halilhanbademm * * Github, Twitter, Facebook: halilhanbadem * * Instagram: halilhanbademm * * halilhanbadem@protonmail.com * *********************************************************************************************************************** } unit AESDemo1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, AESEncDec, System.NetEncoding; type TfrmAESDemo = class(TForm) aesMemo: TMemo; Encryption: TButton; procedure EncryptionClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmAESDemo: TfrmAESDemo; implementation {$R *.dfm} procedure TfrmAESDemo.EncryptionClick(Sender: TObject); var Cha: TChainingMode; Pad: TPaddingMode; size: Integer; Enc: TEncoding; Password, Data, IV, Crypto: TBytes; begin size := 256; Enc := TEncoding.ANSI; Cha := cmCBC; Pad := pmPKCS7; Data := Enc.GetBytes('halilhanbadem testi türkçe karakter'); Password := Enc.GetBytes('pstestpstestpstestpstestpstest12'); IV := Enc.GetBytes('ivtest_ivtest123'); aesMemo.Lines.Text := TNetEncoding.Base64.EncodeBytesToString (TAESEncDec.Create.EncryptAES(Data, Password, Size, IV, cha, pad)); end; end.
unit MainUnit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, mysql56conn, mysql57conn, SQLDB, DB, Forms, Controls, Graphics, Dialogs, DBGrids, StdCtrls, ActnList; type { TMainForm } TMainForm = class(TForm) TablesList: TComboBox; SaveButton: TButton; DataSource: TDataSource; DBGrid: TDBGrid; MySQL57Connection: TMySQL57Connection; SQLQuery: TSQLQuery; SQLTransaction: TSQLTransaction; procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure SaveButtonClick(Sender: TObject); procedure TablesListChange(Sender: TObject); procedure TablesListClick(Sender: TObject); procedure TablesListKeyPress(Sender: TObject; var Key: char); private public end; var MainForm: TMainForm; implementation {$R *.lfm} procedure SetComponentCorrectPos(); begin MainForm.SaveButton.width:=round(MainForm.width / 10); MainForm.SaveButton.top:=0; MainForm.SaveButton.left:=MainForm.Width - MainForm.SaveButton.Width; MainForm.DBGrid.top:=MainForm.TablesList.height; MainForm.DBGrid.Left:=1; MainForm.DBGrid.width:=MainForm.width; MainForm.DBGrid.height:=MainForm.height - MainForm.TablesList.Height; MainForm.TablesList.Top:=1; MainForm.TablesList.left:=1; MainForm.TablesList.width:=MainForm.width - MainForm.SaveButton.width; end; { TMainForm } procedure TMainForm.FormCreate(Sender: TObject); begin self.Width:=round(screen.Width / 2); self.height:=round(screen.Height / 2); SetComponentCorrectPos(); end; procedure TMainForm.FormResize(Sender: TObject); begin SetComponentCorrectPos(); end; procedure TMainForm.SaveButtonClick(Sender: TObject); begin SQLQuery.ApplyUpdates; SQLTransaction.Commit; SQLQuery.open; end; procedure TMainForm.TablesListChange(Sender: TObject); begin SQLQuery.close; case TablesList.ItemIndex of 0:SQLQuery.SQL.Text:='select * from raspisanie'; 1:SQLQuery.SQL.Text:='select * from zakaz'; end; SQLQuery.Open; end; procedure TMainForm.TablesListClick(Sender: TObject); begin end; procedure TMainForm.TablesListKeyPress(Sender: TObject; var Key: char); begin Key:=#0; end; end.
unit IdQOTDUDP; interface uses classes, IdAssignedNumbers, IdUDPBase, IdUDPClient; type TIdQOTDUDP = class(TIdUDPClient) protected Function GetQuote : String; public constructor Create(AOwner: TComponent); override; { This is the quote from the server } Property Quote: String read GetQuote; published Property Port default IdPORT_QOTD; end; implementation { TIdQOTDUDP } constructor TIdQOTDUDP.Create(AOwner: TComponent); begin inherited Create(AOwner); Port := IdPORT_QOTD; end; function TIdQOTDUDP.GetQuote: String; begin //The string can be anything - The RFC says the server should discard packets Send(' '); {Do not Localize} Result := ReceiveString; end; end.
unit TimeEntry; {$mode objfpc}{$H+} interface uses Classes, SysUtils, sqldb, db, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, EditBtn; type { TTimeForm } TTimeForm = class(TForm) SaveButton: TButton; CancelButton: TButton; DateEdit1: TDateEdit; SQLQuery1: TSQLQuery; SQLTransaction1: TSQLTransaction; StartTime: TEdit; EndTime: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Memo1: TMemo; ProjName: TMemo; Hours: TEdit; procedure CancelButtonClick(Sender: TObject); procedure DateEdit1KeyPress(Sender: TObject; var Key: char); procedure FormActivate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure HoursExit(Sender: TObject); procedure ConvertToHHHH(var min: integer); procedure HoursKeyPress(Sender: TObject; var Key: char); procedure TimeInsert(); Function CloseForm():Boolean; procedure Memo1Enter(Sender: TObject); procedure SaveButtonClick(Sender: TObject); private { private declarations } public { public declarations } var RecordID: integer; ActivateForm: boolean; ProjectID: integer; ProjectName: string; NewTime: boolean; end; var TimeForm: TTimeForm; implementation var closeNoQuestion: Boolean; projectName: string; {$R *.lfm} { TTimeForm } procedure TTimeForm.HoursExit(Sender: TObject); var s: String; iValue, iCode, r: Integer; begin s := Hours.Text; val(s, iValue, iCode); if (icode <> 0) or (ivalue <> 0) then Begin ShowMessage(FloatToStr(StrToFloat(Hours.Text) * 60)); EndTime.Text := FloatToStr(StrToInt(StartTime.Text) + (StrToFloat(Hours.Text) * 60)); ConvertToHHHH(iCode); end else ShowMessage('You entered '+Hours.Text); end; procedure TTimeForm.FormActivate(Sender: TObject); begin ShortDateFormat := 'mm/dd/yy'; if ActivateForm = True then begin if NewTime = True then begin SQLQuery1.SQL.text:='Select * from time'; SQLQuery1.Open; DateEdit1.Date := Now; Hours.Text := '0'; StartTime.Text := '-'; EndTime.Text := '-'; Memo1.Text := 'Memo1'; end else begin SQLQuery1.Close; SQLQuery1.SQL.text:='Select Time_PK as ID, Cast(Time_Date as Text) as Time_Date, Cast(Time_Hours as Text) as Hours, Cast(Time_Start as Text) as Time_Start, Cast(Time_End as Text) as Time_End, cast(Time_Memo as Text) as Memo from time where ID='+chr(39)+IntToStr(RecordID)+chr(39); SQLQuery1.Open; DateEdit1.Date := StrToDateTime(SQLQuery1.Fields[1].AsString); Hours.Text := SQLQuery1.Fields[2].AsString; StartTime.Text := SQLQuery1.Fields[3].AsString; EndTime.Text := SQLQuery1.Fields[4].AsString; Memo1.Text := SQLQuery1.Fields[5].AsString; end; Label1.Caption := 'Project # '+IntToStr(ProjectID); ProjName.Caption := ProjectName; closeNoQuestion := False; SQLQuery1.close; end; ActivateForm := False; TimeForm.ActiveControl := TimeForm.Hours; // Has to be the last thing that happesn Hours.SelectAll; end; procedure TTimeForm.CancelButtonClick(Sender: TObject); begin TimeForm.Close; end; procedure TTimeForm.DateEdit1KeyPress(Sender: TObject; var Key: char); begin end; Function TTimeForm.CloseForm():Boolean ; Begin {This asks the question whether you want to save or not. If you want to quit it closes the dialog. Otherwise it returns you to the dialog.} case QuestionDlg ('Confirm Cancel.','Are you sure that you want to close without saving?',mtConfirmation,[mrYes, mrNo],'') of mrYes: CloseForm := True; mrNo : CloseForm := False; end; end; procedure TTimeForm.Memo1Enter(Sender: TObject); begin Memo1.SelectAll; end; procedure TTimeForm.SaveButtonClick(Sender: TObject); begin TimeInsert(); end; procedure TTimeForm.TimeInsert; var emptydate : boolean; begin emptydate := false; if DateEdit1.text='' then Begin ShowMessage('Date field cannot be empty.'); emptydate := true; end Else Begin if NewTime = True then Begin SQLQuery1.Open; SQLQuery1.SQL.text:='INSERT INTO time VALUES (:Time_PK, :Time_ProjectFK, :Time_Date, :Time_Hours, :Time_Start, :Time_End, :Time_Memo)'; SQLQuery1.Params.ParamByName('Time_ProjectFK').AsString := IntToStr(ProjectID); SQLQuery1.Params.ParamByName('Time_Date').AsString := DateEdit1.text; SQLQuery1.Params.ParamByName('Time_Hours').AsString := Hours.text; SQLQuery1.Params.ParamByName('Time_Start').AsString := StartTime.text; SQLQuery1.Params.ParamByName('Time_End').AsString := EndTime.text; SQLQuery1.Params.ParamByName('Time_Memo').AsString := Memo1.text; SQLQuery1.ExecSQL; //SQLTransaction1.commit; end Else Begin //SQLQuery1.Close; //SQLQuery1.Open; SQLQuery1.SQL.text:='UPDATE TIME SET Time_Date = :Time_Date, Time_Hours = :Time_Hours, Time_Start = :Time_Start, Time_End = :Time_End, Time_Memo =:Time_Memo WHERE Time_PK='+chr(39)+IntToStr(RecordID)+chr(39); SQLQuery1.Params.ParamByName('Time_Date').AsString := DateEdit1.text; SQLQuery1.Params.ParamByName('Time_Hours').AsString := Hours.text; SQLQuery1.Params.ParamByName('Time_Start').AsString := StartTime.text; SQLQuery1.Params.ParamByName('Time_End').AsString := EndTime.text; SQLQuery1.Params.ParamByName('Time_Memo').AsString := Memo1.text; SQLQuery1.ExecSQL; SQLTransaction1.commit; //SQLQuery1.Close; end; closeNoQuestion := True; // Set it so that no question is asked. TimeForm.Close; end; end; procedure TTimeForm.FormCloseQuery(Sender: TObject; var CanClose: boolean); begin if closeNoQuestion = False then if CloseForm() = False then CanClose := False else TimeForm.Close else TimeForm.Close; closeNoQuestion := False; // Has to be set to false, or else the next // time you open the form, it remembers the previous // value. //Proj_Name_Edit.Text := projectName; end; procedure TTimeForm.ConvertToHHHH(var min: integer); var remainingMinutes: integer; hours_calc: double; begin min := 1235; remainingMinutes := min mod 60; ShowMessage(IntToStr(remainingMinutes)); hours_calc := ((min - remainingMinutes) / 60); ShowMessage(FloatToStr(hours_calc)); end; procedure TTimeForm.HoursKeyPress(Sender: TObject; var Key: char); begin {* http://www.festra.com/eng/snip05.htm *} if not (Key in [#8, '0'..'9', DecimalSeparator]) then begin ShowMessage('Invalid key: ' + Key); Key := #0; end else if (Key = DecimalSeparator) and (Pos(Key, Hours.Text) > 0) then begin ShowMessage('Invalid Key: twice ' + Key); Key := #0; end; end; end.
unit GlenKleidon.CSVUtils; interface uses System.Classes, System.SysUtils; Function IsEvenDefTrue(AInteger: integer): boolean; function nextRow(AStream: TStream; ALineBreak: String; AQuoteChars: string; ABufferSize: integer = 500): string; function CountChars(AText: String; AChars: string; AStart: integer = 0; AEnd: integer = MaxInt):Integer; implementation uses strUtils; function CountChars(AText: String; AChars: string; AStart:integer; AEnd:Integer):Integer; var p: integer; begin result := 0; p:=posEx(AChars, AText,AStart); while (p>0) and (p<=AEnd) do begin Result := Result +1; p:=posEx(AChars, AText,p+1); end; end; Function IsEvenDefTrue(AInteger: integer): boolean; begin Result := True; if AInteger=0 then exit; Result := ( (Ainteger mod 2) = 0); end; function nextRow(AStream: TStream; ALineBreak: String; AQuoteChars: string; ABufferSize: integer):string ; var lBuffer : TStringStream; p: integer; StartPosition, lCharsRemaining : int64; lBytesToRead : integer; LineText : AnsiString; lBufferSize : integer; lCopybufferFromStream : boolean; begin Result := ''; if AStream=nil then exit; // Dont Duplicate the data if using a Memory Stream StartPosition := AStream.Position; lCharsRemaining := AStream.size-AStream.Position; if (AStream.InheritsFrom(TMemoryStream)) then begin lCopybufferFromStream := false; lBufferSize := MaxInt; lBuffer := AStream as TStringStream; p := AStream.Position+1; AStream.Position := AStream.Size; end else begin lBuffer := TStringStream.create; lCopybufferFromStream := true; lBufferSize := ABufferSize; p := 1; if (lBufferSize>lCharsRemaining) then lBufferSize := lCharsRemaining end; try LineText := ''; while lCharsRemaining>0 do Begin if lCopybufferFromStream then lBuffer.copyfrom(AStream,lBufferSize); lCharsRemaining := lBuffer.size - StartPosition - lBuffer.Position; SetString(LineText, pAnsiChar(lBuffer.Memory), lBuffer.size); p :=Pos(ALineBreak, LineText,p); while (p>0) do begin if IsEvenDefTrue(CountChars(LineText,AQuoteChars,1,p)) then begin result := copy(LineText,1,p-1); AStream.Position := StartPosition+ALineBreak.Length-1; exit; end; p := PosEx(ALineBreak, LineText, p+1); end; End; // Not found, must be the remaining text Result := copy(lineText,(StartPosition and MaxInt)+1,MaxInt); finally if lCopybufferFromStream then freeandNil(lBuffer); end; end; end.
unit WHookInt; interface uses Windows, Messages, SysUtils, uHookCommon; function SetHook: Boolean; stdcall; export; function FreeHook: Boolean; stdcall; export; function MsgFilterFuncKbd(Code: Integer; wParam, lParam: Longint): Longint stdcall; export; function MsgFilterFuncMou(Code: Integer; wParam, lParam: Longint): Longint stdcall; export; implementation uses MemMap; const WH_KEYBOARD_LL = 13; WH_MOUSE_LL = 14; type { Structure used by WH_KEYBOARD_LL } PKBDLLHookStruct = ^TKBDLLHookStruct; {$EXTERNALSYM tagKBDLLHOOKSTRUCT} tagKBDLLHOOKSTRUCT = packed record vkCode: DWORD; scanCode: DWORD; flags: DWORD; time: DWORD; dwExtraInfo: PULONG; end; TKBDLLHookStruct = tagKBDLLHOOKSTRUCT; {$EXTERNALSYM KBDLLHOOKSTRUCT} KBDLLHOOKSTRUCT = tagKBDLLHOOKSTRUCT; ULONG_PTR = ^DWORD; POINT = packed record x,y: longint; end; // Low Level Mouse Hook Info Struct // http://msdn.microsoft.com/en-us/ms644970.aspx MSLLHOOKSTRUCT = packed record pt: POINT; mouseData: DWORD; flags: DWORD; time: DWORD; dwExtraInfo: ULONG_PTR; end; PMSLLHOOKSTRUCT = ^MSLLHOOKSTRUCT; // Actual hook stuff type TPMsg = ^TMsg; const VK_D = $44; VK_E = $45; VK_F = $46; VK_M = $4D; VK_R = $52; // global variables, only valid in the process which installs the hook. var lMemMap: TMemMap; lSharedPtr: PMMFData; lPid: DWORD; lHookKbd: HHOOK; lHookMou: HHOOK; { The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain. WH_GETMESSAGE Installs a hook procedure that monitors messages posted to a message queue. For more information, see the GetMsgProc hook procedure. } function SetHook: Boolean; stdcall; begin Result := False; if lSharedPtr = nil then exit; lHookKbd := SetWindowsHookEx(WH_KEYBOARD, MsgFilterFuncKbd, HInstance, 0); lHookMou := SetWindowsHookEx(WH_MOUSE, MsgFilterFuncMou, HInstance, 0); if (lHookKbd = 0) or (lHookMou = 0) then FreeHook // free is something was ok else Result := True; end; { The UnhookWindowsHookEx function removes the hook procedure installed in a hook chain by the SetWindowsHookEx function. } function FreeHook: Boolean; stdcall; var b1, b2: Boolean; begin Result := False; b1 := True; b2 := True; if (lHookKbd <> 0) then b1 := UnHookWindowsHookEx(lHookKbd); if (lHookMou <> 0) then b2 := UnHookWindowsHookEx(lHookMou); Result := b1 and b2; end; (* GetMsgProc( nCode: Integer; {the hook code} wParam: WPARAM; {message removal flag} lParam: LPARAM {a pointer to a TMsg structure} ): LRESULT; {this function should always return zero} { See help on ==> GetMsgProc} *) function MsgFilterFuncKbd(Code: Integer; wParam, lParam: Longint): Longint; var Kill: boolean; what2do : Integer; MessageId: Word; // ext_code: Cardinal; begin if (Code < 0) or (Code <> HC_ACTION) or (lSharedPtr = nil) then begin Result := CallNextHookEx(lHookKbd {ignored in API}, Code, wParam, lParam); exit; end; Result := 0; Kill := False; // ask HDM form only when we're not inside. If we are in HDM, pass all without // any interaction //if (lSharedPtr^.HdmPID <> lPID) then - can't ignore, we need to synchronzie list of events begin //OutputDebugString('DLL: Would ask HIDmacros what to do for KEYBOARD.'); if (lParam and $80000000 > 0) then MessageId := WM_KEYUP else MessageId := WM_KEYDOWN; what2do := SendMessage(lSharedPtr^.MainWinHandle, WM_ASKHDMFORM, MessageId , wParam); if (what2do = -1) then Kill := True; end; if Kill then Result := 1 else Result := CallNextHookEx(lHookKbd {ignored in API}, Code, wParam, lParam); end; function MsgFilterFuncMou(Code: Integer; wParam, lParam: Longint): Longint; var Kill: boolean; locData: TMMFData; what2do: Integer; begin Result := 0; if (Code < 0) or (Code <> HC_ACTION) or (lSharedPtr = nil) then begin Result := CallNextHookEx(lHookMou {ignored in API}, Code, wParam, lParam); exit; end; Kill := False; // ask HDM form only when we're not inside. If we are in HDM, pass all without // any interaction if //(lSharedPtr^.HdmPID <> lPID) and ( (wParam = WM_LBUTTONDOWN) or (wParam = WM_LBUTTONUP) or (wParam = WM_MBUTTONDOWN) or (wParam = WM_MBUTTONUP) or (wParam = WM_RBUTTONDOWN) or (wParam = WM_RBUTTONUP) or (wParam = WM_MOUSEWHEEL) or (wParam = WM_NCLBUTTONDOWN) or (wParam = WM_NCLBUTTONUP) or (wParam = WM_NCMBUTTONDOWN) or (wParam = WM_NCMBUTTONUP) or (wParam = WM_NCRBUTTONDOWN) or (wParam = WM_NCRBUTTONUP) ) then begin //if GetAncestor(PMSLLHOOKSTRUCT(lParam)^.hwnd, GA_ROOT) = locData.WinHandle then // this would be for LL to have Wheel direction, but I wouldn't have // target window handle then. Would have to calculate it from mouse pos // so rather ignore direction if (lSharedPtr^.HdmPID = lPID) then begin //OutputDebugString('DLL: Just info message to HIDMacros window.'); SendMessage(lSharedPtr^.MainWinHandle, WM_ASKHDMFORM, wParam , 1); end else begin //OutputDebugString('DLL: Would ask HIDmacros what to do for MOUSE.'); what2do := SendMessage(lSharedPtr^.MainWinHandle, WM_ASKHDMFORM, wParam , 0); if (what2do = -1) then Kill := True; end; end; if Kill then Result := 1 else Result := CallNextHookEx(lHookMou {ignored in API}, Code, wParam, lParam); end; procedure DebugLog(Value: String); var tmp: PChar; lVal: String; begin lVal := 'DLL:'+ Value; GetMem(tmp, Length(lVal) + 1); try StrPCopy(tmp, lVal); OutputDebugString(tmp); finally FreeMem(tmp); end; end; initialization begin lPID := GetCurrentProcessId; lSharedPtr := nil; //DebugLog('Attached to PID ' + IntToStr(lPID)); try lMemMap := TMemMap.Create(MMFName, SizeOf(TMMFData)); lSharedPtr := lMemMap.Memory; except on EMemMapException do begin DebugLog(IntToStr(lPID)+': Can''t create MMF.'); lMemMap := nil; end; end; end; finalization FreeHook; if lMemMap <> nil then try lMemMap.Free; except on EMemMapException do DebugLog(IntToStr(lPID)+': Can''t release MMF.'); end; end.
{********************************************************************} { } { MediaServer Runtime Component Library } { TMediaServer } { } { Implements interaction with media services, based on } { UpnP\DLNA protocols: } { - AVTransport v.1 } { } { Copyright (c) 2014 Setin Sergey A } { } { v0.5 31.10.2014 } { } {********************************************************************} unit MediaServer; interface uses IdHTTP,Generics.Collections,Classes,Sysutils,XmlDoc,XMLIntf,IdURI,IdLogEvent,IoUtils,Variants,IdExceptionCore, IdUDPClient,IdUDPBase,IdStack {$IF DEFINED(ANDROID)}, Androidapi.JNIBridge, Androidapi.Jni,Androidapi.NativeActivity,Androidapi.JNI.Net.Wifi,androidapi.JNI.JavaTypes{$ENDIF} {$IF DEFINED(MSWINDOWS)},System.Win.ComObj{$ENDIF}; type TTransportState = (STOPPED,PLAYING,TRANSITIONING,PAUSED_PLAYBACK,PAUSED_RECORDING,RECORDING,NO_MEDIA_PRESENT); TCurrentPlayMode = (NORMAL,SHUFFLE,REPEAT_ONE,REPEAT_ALL,RANDOM,DIRECT_1,INTRO); TTransportStatus = (OK,ERROR_OCCURRED); { TActionResult - response from service } TActionResult = class public XMLDoc: IXMLDocument; constructor Create(var xml:TStringStream); destructor Destroy; override; end; { TActionError - error response } TActionError = class(TActionResult) public ErrorText:string; ErrorCode:string; constructor Create(var xml:TStringStream); end; { TMediaService - base MediaService class } TMediaService = class LogEvent:TIDLogEvent; LogList:TStringList; procedure IdLogEventReceived(ASender: TComponent; const AText, AData: string); procedure IdLogEventSent(ASender: TComponent; const AText, AData: string); function SendRequest(method:string;var cmd:tstringlist;var response:TStringStream):boolean; public serviceType:string; servicekind:string; serviceId:string; SCPDURL:string; controlURL:string; baseURL:string; eventSubURL:string; actionresult:string; z_host:string; z_port:integer; constructor Create(islogged:boolean); destructor Destroy; override; end; { TMediaAVService - implements urn:schemas-upnp-org:service:AVTransport } TMediaAVService = class(TMediaService) //states TransportState:TTransportState; TransportStatus:string; TransportPlaySpeed:string; CurrentPlayMode:TCurrentPlayMode; CurrentTrackMetaData:string; CurrentTrackURI:string; AVTransportURI:string; AbsoluteTimePosition:string; RelativeTimePosition:string; public constructor Create(islogged:boolean); //functions function SetAVTransportURI(url:string):TActionResult; function Stop:TActionResult; function Play:TActionResult; function GetMediaInfo:TActionResult; end; { TMediaContentDirectoryService - implements urn:schemas-upnp-org:service:ContentDirectory } TMediaContentDirectoryService = class(TMediaService) //states public constructor Create(islogged:boolean); //functions function Browse(ObjectID:string;BrowseFlag:string;Filter:string;StartingIndex:string;RequestedCount:string; SortCriteria:string;var NumberReturned:UINT64;var TotalMatches:UINT64;var UpdateID:UINT64):TActionResult; end; { TMediaConnectionManagerService - implements urn:schemas-upnp-org:service:ConnectionManager } TMediaConnectionManagerService = class(TMediaService) //states public constructor Create(islogged:boolean); //functions function GetProtocolInfo:TActionResult; end; { TMediaServer - "link" to server (actually client) } TMediaServer = class public IP:string; PORT:string; Modelname:string; Location:string; BaseLocation:string; Logo:string; DeviceType:string; Manufacturer:string; FriendlyName:string; LogoType:string; ModelDescription:string; HomePath:string; LogService:boolean; ServiceList:TObjectList<TMediaService>; constructor Create(cIP: String; cPORT:string; cLocation:string; cHomePath:string); destructor Destroy; override; procedure LoadDescription; function FindService(st:string):TMediaService; function GetServiceCount:integer; end; type TMediaServersList = TObjectList<TMediaServer>; type TOnSearchResult = procedure(serverslist:TMediaServersList) of object; type TOnSearchError = procedure(errortxt:string) of object; { TMediaSearch - searcher of the available media services } type TMediaSearch = class protected type TSThread = class(TThread) IPMASK,PORT,upnpmask:string; {$IF DEFINED(ANDROID)} wifi_manager:JWifiManager; multiCastLock:JWifiManagerMulticastLock; {$ENDIF} lasterror:string; ResultList:TMediaServersList; FOnSearchResult: TOnSearchResult; FOnSearchError: TOnSearchError; procedure SendResult; procedure SendError; function InitMulticast:boolean; function UnInitMulticast:boolean; procedure DettachCurrentThreadFromJVM; protected procedure SetErrorText(msg:string); public constructor Create(ipm:string;portm:string); destructor Destroy; override; procedure Execute; override; procedure SetSearchMask(upnp_mask:string); procedure SetResultEvent(ResultEvent:TOnSearchResult); procedure SetErrorEvent(ErrorEvent:TOnSearchError); end; protected SearchThread: TSThread; public Constructor Create(ipm:string;portm:string); destructor Destroy;override; procedure Search(upnpmask:string); procedure SetResultEvent(ResultEvent:TOnSearchResult); procedure SetErrorEvent(ErrorEvent:TOnSearchError); end; { Helpers } function DownloadFile(url:string;saveto:string):boolean; function ReadParam(str: string; tagb: string; tage: string; tp: string): string; implementation function ReadParam(str: string; tagb: string; tage: string; tp: string): string; var buf,tmp: String; a, b: integer; begin Result := ''; if tp = 'xml' then begin a := str.IndexOf(tagb) + length(tagb); tmp:= str.Substring(a , length(str) - a); b := tmp.IndexOf(tage); if (a > High(tagb)) and (b > 1) then begin Result := trim(str.Substring(a, b)); end; end else begin buf:=str.UpperCase(str); a := buf.IndexOf(tagb) + length(tagb); tmp:=buf.Substring(a , length(buf) - a); b := tmp.IndexOf(tage); if (a > High(tagb)) and (b > 1) then begin Result := trim(str.Substring(a, b)); end; end; end; { TMediaSearch.TSThread } constructor TMediaSearch.TSThread.Create(ipm:string;portm:string); begin inherited Create(true); FreeOnTerminate:=true; IPMASK := ipm; PORT := portm; lasterror:=''; {$IF DEFINED(ANDROID)} wifi_manager:=nil; multiCastLock:=nil; {$ENDIF} end; destructor TMediaSearch.TSThread.Destroy; begin inherited; end; procedure TMediaSearch.TSThread.SetSearchMask(upnp_mask:string); begin upnpmask:=upnp_mask; end; procedure TMediaSearch.TSThread.SetErrorText(msg:string); begin lasterror:=msg; end; procedure TMediaSearch.TSThread.SetResultEvent(ResultEvent:TOnSearchResult); begin FOnSearchResult:=ResultEvent; end; procedure TMediaSearch.TSThread.SetErrorEvent(ErrorEvent:TOnSearchError); begin FOnSearchError:=ErrorEvent; end; procedure TMediaSearch.SetResultEvent(ResultEvent:TOnSearchResult); begin SearchThread.SetResultEvent(ResultEvent); end; procedure TMediaSearch.SetErrorEvent(ErrorEvent:TOnSearchError); begin SearchThread.SetErrorEvent(ErrorEvent); end; procedure TMediaSearch.TSThread.SendResult; begin FOnSearchResult(ResultList); end; procedure TMediaSearch.TSThread.SendError; begin FOnSearchError(lasterror); end; function TMediaSearch.TSThread.InitMulticast:boolean; begin Result:=true; {$IF DEFINED(ANDROID)} try wifi_manager:=GetWiFiManager; if assigned(wifi_manager) then begin multiCastLock := wifi_manager.createMulticastLock(StringToJString('mservlock')); multiCastLock.setReferenceCounted(true); multiCastLock.acquire; end; except on E:Exception do begin Result:=false; lasterror:=E.Message; if assigned(FOnSearchError) then Synchronize(SendError); end; end; {$ENDIF} end; function TMediaSearch.TSThread.UnInitMulticast:boolean; begin {$IF DEFINED(ANDROID)} if assigned(multiCastLock)then multiCastLock.release; multiCastLock:=nil; wifi_manager:=nil; {$ENDIF} end; procedure TMediaSearch.TSThread.DettachCurrentThreadFromJVM; {$IF DEFINED(ANDROID)} var PActivity: PANativeActivity; JNIEnvRes: PJNIEnv; {$ENDIF} begin {$IF DEFINED(ANDROID)} JNIEnvRes := TJNIResolver.JNIEnvRes; if JNIEnvRes <> nil then begin PActivity := PANativeActivity(System.DelphiActivity); PActivity^.vm^.DetachCurrentThread(PActivity^.vm); TJNIResolver.JNIEnvRes := nil; end; {$ENDIF} end; procedure TMediaSearch.TSThread.Execute; var S: TStringList; U: TIdUDPClient; iPeerPort: Word; sPeerIP, sResponse, url: string; str:TStringList; ms:TMediaServer; tmppath:string; begin inherited; if terminated then exit; sPeerIP:=''; sResponse:=''; url:=''; {$IF DEFINED(MSWINDOWS)} CoInitializeEx(nil, 0); {$ENDIF} if not InitMulticast then exit; ResultList:=TMediaServersList.Create(true); tmppath:=TPath.GetTempPath; str:=tstringlist.Create; U := TIdUDPClient.Create; S := TStringList.Create; S.LineBreak:=#13#10; str.LineBreak:=#13; try S.Add('M-SEARCH * HTTP/1.1'); S.Add('HOST: '+IPMASK+':'+PORT); S.Add('MAN: "ssdp:discover"'); S.Add('MX: 4'); S.Add('ST: '+upnpmask); S.Add('USER-AGENT: OS/1 UPnP/1.1 TMediaServer/1.0'); S.Add(''); U.ReceiveTimeout:=5000; U.Send(IPMASK, StrToInt(PORT), S.Text); repeat sResponse := U.ReceiveString(sPeerIP, iPeerPort); if iPeerPort <> 0 then begin str.Clear; str.Text:=sResponse; url:=ReadParam(str.Text,'LOCATION:',#13,'http'); if url>'-' then begin ms:=TMediaServer.Create(sPeerIP,inttostr(iPeerPort),url,tmppath); ms.LoadDescription; ResultList.Add(ms); end; end; until iPeerPort = 0; S.Free; U.Free; except on et:EIdConnectTimeout do begin S.Free; U.Free; lasterror:='Connection error'; if assigned(FOnSearchError) then Synchronize(SendError); end; on E:Exception do begin S.Free; U.Free; lasterror:=E.Message; if assigned(FOnSearchError) then Synchronize(SendError); end; end; str.Free; //CoUninitialize; UnInitMulticast; if assigned(FOnSearchResult) then Synchronize(SendResult); {$IF DEFINED(ANDROID)} DettachCurrentThreadFromJVM; {$ENDIF} end; { TMediaSearch } Constructor TMediaSearch.Create(ipm:string;portm:string); begin SearchThread:=TSThread.Create(ipm,portm); end; destructor TMediaSearch.Destroy; begin if assigned(SearchThread) then begin SearchThread.Terminate; end; inherited; end; procedure TMediaSearch.Search(upnpmask:string); begin if not SearchThread.Started then begin SearchThread.SetSearchMask(upnpmask); SearchThread.Start; end else begin //SearchThread.Synchronize(SearchThread.SendError); end; end; { TActionResult } constructor TActionResult.Create(var xml:TstringStream); begin XMLDoc:=TXMLDocument.Create(nil); XMLDoc.LoadFromStream(xml); end; destructor TActionResult.Destroy; begin // if assigned(XMLDoc) then // XMLDoc.Free; end; { TActionError } constructor TActionError.Create(var xml:TstringStream); var Node:IXMLNode; got:boolean; begin inherited Create(xml); got:=false; try Node:=XMLDoc.DocumentElement.ChildNodes['Body'].ChildNodes['Fault']; Node:=Node.ChildNodes.FindNode('detail',''); if Node.HasChildNodes then begin Node:=Node.ChildNodes['UPnPError']; if Node.HasChildNodes then begin Self.ErrorText:=Node.ChildNodes['errorDescription'].Text; Self.ErrorCode:=Node.ChildNodes['errorCode'].Text; got:=true; end; end; except Self.ErrorText:='Unknown error, sorry'; Self.ErrorCode:='-1'; got:=true; end; if not got then begin Self.ErrorText:=XmlDoc.XML.Text; Self.ErrorCode:='-1'; end; end; { TMediaContentDirectoryService } constructor TMediaService.Create(islogged:boolean); begin servicekind:='not implemented'; //create log if (islogged) then begin LogEvent:=TIDLogEvent.Create; LogList:=TStringList.Create; LogEvent.ReplaceCRLF:=false; LogEvent.OnReceived:=IdLogEventReceived; LogEvent.OnSent:=IdLogEventSent; end; end; procedure TMediaService.IdLogEventReceived(ASender: TComponent; const AText, AData: string); begin if assigned(LogList)then begin LogList.Add('Received:'); LogList.Add(AData); LogList.Add(''); end; end; procedure TMediaService.IdLogEventSent(ASender: TComponent; const AText, AData: string); begin if assigned(LogList)then begin LogList.Add('Sent:'); LogList.Add(AData); LogList.Add(''); end; end; function TMediaService.SendRequest(method:string;var cmd:tstringlist;var response:TStringStream):boolean; var http:TIDHttp; noterr:boolean; begin http:=TIDHttp.Create; noterr:=true; if Assigned(LogEvent) then begin http.Intercept:=LogEvent; LogEvent.Active:=true; end; try http.Request.Clear; http.HTTPOptions:=[hoKeepOrigProtocol]; http.Request.URL:=controlURL; http.Request.ContentType := 'text/xml; charset=utf-8'; http.ProtocolVersion := pv1_1; http.Request.UserAgent:='TMediaServer v1.0'; http.Request.CustomHeaders.Clear; http.Request.CustomHeaders.AddValue('SOAPAction','"'+method+'"'); http.Post(baseUrl+controlURL,cmd,response); except on e:EIdHTTPProtocolException do begin response.Free; response:=TstringStream.Create(E.ErrorMessage); noterr:=false; end; on e:Exception do begin noterr:=false; response:=tstringstream.Create('<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" '+ 's:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'+ '<s:Body>'+ '<s:Fault>'+ '<faultcode>s:Client</faultcode>'+ '<faultstring>UPnPError</faultstring>'+ '<detail>'+ '<UPnPError xmlns="urn:schemas-upnp-org:control-1-0">'+ '<errorCode>General Error</errorCode>'+ '<errorDescription>'+e.Message+'</errorDescription>'+ '</UPnPError>'+ '</detail>'+ '</s:Fault>'+ '</s:Body>'+ '</s:Envelope>'); end; end; Result:=noterr; if Assigned(LogEvent) then begin LogEvent.Active:=false; end; http.Free; end; destructor TMediaService.Destroy; begin if assigned(LogEvent) then begin LogEvent.Free; end; if assigned(LogList) then begin LogList.SaveToFile(Tpath.Combine(TPath.GetTempPath,servicekind+'.log')); LogList.Free; end; inherited; end; { TMediaConnectionManagerService } constructor TMediaConnectionManagerService.Create(islogged:boolean); begin inherited Create(islogged); servicekind:='ConnectionManager'; end; function TMediaConnectionManagerService.GetProtocolInfo:TActionResult; var cmd:TstringList; response: TStringStream; begin cmd:=tstringlist.Create; response:=TstringStream.Create(''); cmd.LineBreak:=#13; cmd.Text:='<?xml version="1.0" encoding="utf-8"?>'; cmd.Add('<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'); cmd.Add(' <s:Body>'); cmd.Add(' <u:GetProtocolInfo xmlns:u="urn:schemas-upnp-org:service:ConnectionManager:1">'); cmd.Add(' </u:GetProtocolInfo>'); cmd.Add(' </s:Body>'); cmd.Add('</s:Envelope>'); if(not SendRequest('urn:schemas-upnp-org:service:ConnectionManager:1#GetProtocolInfo',cmd,response))then Result:=TActionError.Create(response) else Result:=TActionResult.Create(response); cmd.Free; response.Free; end; { TMediaContentDirectoryService } constructor TMediaContentDirectoryService.Create(islogged:boolean); begin inherited Create(islogged); servicekind:='ContentDirectory'; end; function TMediaContentDirectoryService.Browse(ObjectID:string;BrowseFlag:string;Filter:string;StartingIndex:string;RequestedCount:string; SortCriteria:string;var NumberReturned:UINT64;var TotalMatches:UINT64;var UpdateID:UINT64):TActionResult; var http:TIDHttp; cmd:TstringList; err:boolean; response: TStringStream; ares:TActionResult; begin cmd:=tstringlist.Create; http:=TIDHttp.Create; response:=TstringStream.Create(''); if Assigned(LogEvent) then begin http.Intercept:=LogEvent; LogEvent.Active:=true; LogEvent.Open; end; cmd.LineBreak:=#13; cmd.Text:='<?xml version="1.0" encoding="utf-8"?>'; cmd.Add('<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'); cmd.Add(' <s:Body>'); cmd.Add(' <u:Browse xmlns:u="urn:schemas-upnp-org:service:ContentDirectory:1">'); cmd.Add(' <ObjectID>'+ObjectID+'</ObjectID>'); cmd.Add(' <BrowseFlag>'+BrowseFlag+'</BrowseFlag>'); cmd.Add(' <Filter>'+Filter+'</Filter>'); cmd.Add(' <StartingIndex>'+StartingIndex+'</StartingIndex>'); cmd.Add(' <RequestedCount>'+RequestedCount+'</RequestedCount>'); cmd.Add(' <SortCriteria>'+SortCriteria+'</SortCriteria>'); cmd.Add(' </u:Browse>'); cmd.Add(' </s:Body>'); cmd.Add('</s:Envelope>'); try http.Request.Clear; http.HTTPOptions:=[hoKeepOrigProtocol]; http.Request.URL:=controlURL; http.Request.ContentType := 'text/xml; charset=utf-8'; http.ProtocolVersion := pv1_1; http.Request.UserAgent:='TMediaServer v1.0'; http.Request.CustomHeaders.Clear; http.Request.CustomHeaders.AddValue('SOAPAction','"urn:schemas-upnp-org:service:ContentDirectory:1#Browse"'); http.Post(baseUrl+controlURL,cmd,response); except on e:EIdHTTPProtocolException do begin response.Free; response:=TstringStream.Create(E.ErrorMessage); end; on e:Exception do begin response:=tstringstream.Create('<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" '+ 's:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'+ '<s:Body>'+ '<s:Fault>'+ '<faultcode>s:Client</faultcode>'+ '<faultstring>UPnPError</faultstring>'+ '<detail>'+ '<UPnPError xmlns="urn:schemas-upnp-org:control-1-0">'+ '<errorCode>General Error</errorCode>'+ '<errorDescription>'+e.Message+'</errorDescription>'+ '</UPnPError>'+ '</detail>'+ '</s:Fault>'+ '</s:Body>'+ '</s:Envelope>'); end; end; ares:=TActionError.Create(response); if Assigned(LogEvent) then begin LogEvent.Close; LogEvent.Active:=false; end; Result:=ares; cmd.Free; http.Free; response.Free; end; { TMediaAVService } constructor TMediaAVService.Create(islogged:boolean); begin inherited Create(islogged); servicekind:='AVTransport'; end; { SetAVTransportURI - set url to play by service } function TMediaAVService.SetAVTransportURI(url:string):TActionResult; var cmd:TstringList; response: TStringStream; begin cmd:=tstringlist.Create; response:=TstringStream.Create(''); cmd.LineBreak:=#13; cmd.Text:='<?xml version="1.0" encoding="utf-8"?>'; cmd.Add('<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'); cmd.Add(' <s:Body>'); cmd.Add(' <u:SetAVTransportURI xmlns:u="urn:schemas-upnp-org:service:AVTransport:1">'); cmd.Add(' <InstanceID>0</InstanceID>'); cmd.Add(' <CurrentURI>'+url+'</CurrentURI>'); cmd.Add(' <CurrentURIMetaData />'); cmd.Add(' </u:SetAVTransportURI>'); cmd.Add(' </s:Body>'); cmd.Add('</s:Envelope>'); if(not SendRequest('urn:schemas-upnp-org:service:AVTransport:1#SetAVTransportURI',cmd,response))then Result:=TActionError.Create(response) else Result:=TActionResult.Create(response); cmd.Free; response.Free; end; { Stop - stop playing } function TMediaAVService.Stop:TActionResult; var cmd:TstringList; response: TStringStream; begin cmd:=tstringlist.Create; response:=TstringStream.Create(''); cmd.LineBreak:=#13; cmd.Text:='<?xml version="1.0" encoding="utf-8"?>'; cmd.Add('<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'); cmd.Add(' <s:Body>'); cmd.Add(' <u:Stop xmlns:u="urn:schemas-upnp-org:service:AVTransport:1">'); cmd.Add(' <InstanceID>0</InstanceID>'); cmd.Add(' </u:Stop>'); cmd.Add(' </s:Body>'); cmd.Add('</s:Envelope>'); if(not SendRequest('urn:schemas-upnp-org:service:AVTransport:1#Stop',cmd,response))then Result:=TActionError.Create(response) else Result:=TActionResult.Create(response); cmd.Free; response.Free; end; { GetMediaInfo - returns information associated with the current media } function TMediaAVService.GetMediaInfo:TActionResult; var cmd:TstringList; response: TStringStream; begin cmd:=tstringlist.Create; response:=TstringStream.Create(''); cmd.LineBreak:=#13; cmd.Text:='<?xml version="1.0" encoding="utf-8"?>'; cmd.Add('<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'); cmd.Add(' <s:Body>'); cmd.Add(' <u:GetMediaInfo xmlns:u="urn:schemas-upnp-org:service:AVTransport:1">'); cmd.Add(' <InstanceID>0</InstanceID>'); cmd.Add(' </u:GetMediaInfo>'); cmd.Add(' </s:Body>'); cmd.Add('</s:Envelope>'); if(not SendRequest('urn:schemas-upnp-org:service:AVTransport:1#GetMediaInfo',cmd,response))then Result:=TActionError.Create(response) else Result:=TActionResult.Create(response); cmd.Free; response.Free; end; { Play - play url, that was set by SetAVTransportURI } function TMediaAVService.Play:TActionResult; var cmd:TstringList; response: TStringStream; begin cmd:=tstringlist.Create; response:=TstringStream.Create(''); cmd.LineBreak:=#13; cmd.Text:='<?xml version="1.0" encoding="utf-8"?>'; cmd.Add('<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'); cmd.Add(' <s:Body>'); cmd.Add(' <u:Play xmlns:u="urn:schemas-upnp-org:service:AVTransport:1">'); cmd.Add(' <InstanceID>0</InstanceID>'); cmd.Add(' <Speed>1</Speed>'); cmd.Add(' </u:Play>'); cmd.Add(' </s:Body>'); cmd.Add('</s:Envelope>'); if(not SendRequest('urn:schemas-upnp-org:service:AVTransport:1#Play',cmd,response))then Result:=TActionError.Create(response) else Result:=TActionResult.Create(response); cmd.Free; response.Free; end; function DownloadFile(url:string;saveto:string):boolean; var http:TIDHttp; Stream:TMemoryStream; begin Result:=true; try Stream:=TMemoryStream.Create; http:=TIDHttp.Create; http.ConnectTimeout:=3000; http.ReadTimeout:=4000; http.Get(url,Stream); Stream.SaveToFile(saveto); Stream.Free; http.Free; except on e:EIdConnectTimeout do begin Result:=false; http.Free; Stream.Free; end; on e:Exception do begin Result:=false; http.Free; Stream.Free; end; end; end; { TMediaServer } constructor TMediaServer.Create(cIP: String; cPORT:string; cLocation:string; cHomePath:string); var uri:TIdURI; begin LogService:=false; Logo:=''; LogoType:=''; IP:=cIP; PORT:=cPORT; Location:=cLocation; HomePath:=cHomePath; uri:=TIduri.Create(cLocation); BaseLocation:=uri.Protocol+'://'+uri.Host+':'+uri.Port; uri.Free; end; function TMediaServer.GetServiceCount:integer; begin Result:=0; if assigned(ServiceList) then Result:=ServiceList.Count; end; function TMediaServer.FindService(st:string):TMediaService; var i:integer; begin Result:=nil; if Assigned(ServiceList) then for i := 0 to ServiceList.Count - 1 do if TMediaService(ServiceList.Items[i]).servicekind=st then Result:=ServiceList.Items[i]; end; procedure TMediaServer.LoadDescription; var XMLDoc: IXMLDocument; Node:IXMLNode; i,size:integer; tmp:TMediaService; begin if(Length(Location)>4)then begin DeleteFile(TPath.Combine(HomePath, 'descrtmp.xml')); if not DownloadFile(Location,TPath.Combine(HomePath, 'descrtmp.xml')) then begin raise Exception.Create('Cant load server description'); end; XMLDoc:=TXMLDocument.Create(nil); XMLDoc.LoadFromFile(TPath.Combine(HomePath, 'descrtmp.xml')); if Assigned(XMLDoc) then if XMLDoc.DocumentElement<>nil then begin Node:= XMLDoc.DocumentElement.ChildNodes['device']; Modelname:=Node.ChildNodes['modelName'].Text; DeviceType:=Node.ChildNodes['deviceType'].Text; Manufacturer:=Node.ChildNodes['manufacturer'].Text; FriendlyName:=Node.ChildNodes['friendlyName'].Text; ModelDescription:=Node.ChildNodes['modelDescription'].Text; Node:=Node.ChildNodes['iconList']; size:=500; for i := 0 to Node.ChildNodes.Count-1 do begin if(Node.ChildNodes[i].ChildNodes['mimetype'].text='image/png')then begin if(size>strtoint(Node.ChildNodes[i].ChildNodes['width'].text))then begin size:=strtoint(Node.ChildNodes[i].ChildNodes['width'].text); LogoType:='image/png'; Logo:=Node.ChildNodes[i].ChildNodes['url'].text; end; end; end; if Logo='' then begin size:=500; for i := 0 to Node.ChildNodes.Count-1 do begin if(Node.ChildNodes[i].ChildNodes['mimetype'].text='image/jpeg')then begin if(size>strtoint(Node.ChildNodes[i].ChildNodes['width'].text))then begin size:=strtoint(Node.ChildNodes[i].ChildNodes['width'].text); LogoType:='image/jpeg'; Logo:=Node.ChildNodes[i].ChildNodes['url'].text; end; end; end; end; if Logo>'-' then begin if Logo[Low(Logo)]<>'/' then Logo:='/'+Logo; if LogoType='image/png' then begin DownLoadFile(BaseLocation+Logo,TPath.Combine(HomePath, Modelname+'.png')); end; end; //getting services list Node:= XMLDoc.DocumentElement.ChildNodes['device'].ChildNodes['serviceList']; if Node.HasChildNodes then ServiceList:=TObjectList<TMediaService>.Create(true); for i := 0 to Node.ChildNodes.Count-1 do begin //creating services if Node.ChildNodes[i].ChildNodes['serviceType'].Text.Substring(0,41)='urn:schemas-upnp-org:service:AVTransport:' then tmp:=TMediaAVService.Create(LogService) else if Node.ChildNodes[i].ChildNodes['serviceType'].Text.Substring(0,46)='urn:schemas-upnp-org:service:ContentDirectory:' then tmp:=TMediaContentDirectoryService.Create(LogService) else if Node.ChildNodes[i].ChildNodes['serviceType'].Text.Substring(0,47)='urn:schemas-upnp-org:service:ConnectionManager:' then tmp:=TMediaConnectionManagerService.Create(LogService) else tmp:=TMediaService.Create(LogService); tmp.serviceType:=Node.ChildNodes[i].ChildNodes['serviceType'].Text; tmp.serviceId:=Node.ChildNodes[i].ChildNodes['serviceId'].Text; tmp.SCPDURL:=Node.ChildNodes[i].ChildNodes['SCPDURL'].Text; tmp.controlURL:=Node.ChildNodes[i].ChildNodes['controlURL'].Text; tmp.baseURL:=Self.BaseLocation; tmp.eventSubURL:=Node.ChildNodes[i].ChildNodes['eventSubURL'].Text; if tmp.controlURL>'-' then if tmp.controlURL[Low(tmp.controlURL)]<>'/' then tmp.controlURL:='/'+tmp.controlURL; ServiceList.Add(tmp); end; end; end; end; destructor TMediaServer.Destroy; begin if Assigned(ServiceList) then begin ServiceList.Clear; ServiceList.Free; end; inherited; end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.MSAccDef; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf; type // TFDPhysMSAccConnectionDefParams // Generated for: FireDAC MSAcc driver TFDMSAccStringFormat = (sfChoose, sfUnicode, sfANSI); /// <summary> TFDPhysMSAccConnectionDefParams class implements FireDAC MSAcc driver specific connection definition class. </summary> TFDPhysMSAccConnectionDefParams = class(TFDConnectionDefParams) private function GetDriverID: String; procedure SetDriverID(const AValue: String); function GetODBCAdvanced: String; procedure SetODBCAdvanced(const AValue: String); function GetLoginTimeout: Integer; procedure SetLoginTimeout(const AValue: Integer); function GetSystemDB: String; procedure SetSystemDB(const AValue: String); function GetReadOnly: Boolean; procedure SetReadOnly(const AValue: Boolean); function GetStringFormat: TFDMSAccStringFormat; procedure SetStringFormat(const AValue: TFDMSAccStringFormat); published property DriverID: String read GetDriverID write SetDriverID stored False; property ODBCAdvanced: String read GetODBCAdvanced write SetODBCAdvanced stored False; property LoginTimeout: Integer read GetLoginTimeout write SetLoginTimeout stored False; property SystemDB: String read GetSystemDB write SetSystemDB stored False; property ReadOnly: Boolean read GetReadOnly write SetReadOnly stored False; property StringFormat: TFDMSAccStringFormat read GetStringFormat write SetStringFormat stored False default sfChoose; end; implementation uses FireDAC.Stan.Consts; // TFDPhysMSAccConnectionDefParams // Generated for: FireDAC MSAcc driver {-------------------------------------------------------------------------------} function TFDPhysMSAccConnectionDefParams.GetDriverID: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_DriverID]; end; {-------------------------------------------------------------------------------} procedure TFDPhysMSAccConnectionDefParams.SetDriverID(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysMSAccConnectionDefParams.GetODBCAdvanced: String; begin Result := FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced]; end; {-------------------------------------------------------------------------------} procedure TFDPhysMSAccConnectionDefParams.SetODBCAdvanced(const AValue: String); begin FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysMSAccConnectionDefParams.GetLoginTimeout: Integer; begin Result := FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout]; end; {-------------------------------------------------------------------------------} procedure TFDPhysMSAccConnectionDefParams.SetLoginTimeout(const AValue: Integer); begin FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysMSAccConnectionDefParams.GetSystemDB: String; begin Result := FDef.AsString[S_FD_ConnParam_MSAcc_SystemDB]; end; {-------------------------------------------------------------------------------} procedure TFDPhysMSAccConnectionDefParams.SetSystemDB(const AValue: String); begin FDef.AsString[S_FD_ConnParam_MSAcc_SystemDB] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysMSAccConnectionDefParams.GetReadOnly: Boolean; begin Result := FDef.AsBoolean[S_FD_ConnParam_MSAcc_ReadOnly]; end; {-------------------------------------------------------------------------------} procedure TFDPhysMSAccConnectionDefParams.SetReadOnly(const AValue: Boolean); begin FDef.AsBoolean[S_FD_ConnParam_MSAcc_ReadOnly] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysMSAccConnectionDefParams.GetStringFormat: TFDMSAccStringFormat; var s: String; begin s := FDef.AsString[S_FD_ConnParam_MSAcc_StringFormat]; if CompareText(s, 'Choose') = 0 then Result := sfChoose else if CompareText(s, 'Unicode') = 0 then Result := sfUnicode else if CompareText(s, 'ANSI') = 0 then Result := sfANSI else Result := sfChoose; end; {-------------------------------------------------------------------------------} procedure TFDPhysMSAccConnectionDefParams.SetStringFormat(const AValue: TFDMSAccStringFormat); const C_StringFormat: array[TFDMSAccStringFormat] of String = ('Choose', 'Unicode', 'ANSI'); begin FDef.AsString[S_FD_ConnParam_MSAcc_StringFormat] := C_StringFormat[AValue]; end; end.
unit BanksList; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseDocked, Data.DB, RzTabs, Vcl.Grids, Vcl.DBGrids, RzDBGrid, Vcl.StdCtrls, RzLabel, Vcl.ExtCtrls, RzPanel, RzButton, Vcl.DBCtrls, RzDBEdit, Vcl.Mask, RzEdit, SaveIntf, NewIntf, RzCmboBx; type TfrmBanksList = class(TfrmBaseDocked, ISave, INew) mmBranch: TRzDBMemo; pnlDetail: TRzPanel; pnlAdd: TRzPanel; sbtnNew: TRzShapeButton; pnlList: TRzPanel; grBranches: TRzDBGrid; Label1: TLabel; cmbBanks: TRzComboBox; edBankName: TRzEdit; Label2: TLabel; Label3: TLabel; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure sbtnNewClick(Sender: TObject); procedure cmbBanksClick(Sender: TObject); private { Private declarations } function EntryIsValid: boolean; procedure FilterBranchList; public { Public declarations } function Save: boolean; procedure Cancel; procedure New; end; implementation {$R *.dfm} uses AuxData, FormsUtil, IFinanceDialogs; procedure TfrmBanksList.FilterBranchList; begin grBranches.DataSource.DataSet.Filter := 'bank_code = ' + QuotedStr(cmbBanks.Value); edBankName.Text := cmbBanks.Text; end; procedure TfrmBanksList.FormClose(Sender: TObject; var Action: TCloseAction); begin OpenDropdownDataSources(pnlDetail,false); OpenGridDataSources(pnlList,false); dmAux.Free; inherited; end; procedure TfrmBanksList.FormShow(Sender: TObject); begin inherited; dmAux := TdmAux.Create(self); PopulateComboBox(dmAux.dstBanks,cmbBanks,'bank_code','bank_name',true); OpenDropdownDataSources(pnlDetail); OpenGridDataSources(pnlList); cmbBanks.ItemIndex := 0; FilterBranchList; end; function TfrmBanksList.Save: boolean; begin Result := false; with grBranches.DataSource.DataSet do begin if EntryIsValid then begin if State in [dsInsert,dsEdit] then begin Post; Result := true; end; end end; end; procedure TfrmBanksList.sbtnNewClick(Sender: TObject); begin New; end; procedure TfrmBanksList.Cancel; begin with grBranches.DataSource.DataSet do begin if State in [dsInsert,dsEdit] then Cancel; end; end; procedure TfrmBanksList.New; begin with grBranches.DataSource.DataSet do begin Append; FieldByName('bank_code').AsString := cmbBanks.Value; end; mmBranch.SetFocus; end; procedure TfrmBanksList.cmbBanksClick(Sender: TObject); begin inherited; FilterBranchList; end; function TfrmBanksList.EntryIsValid: boolean; var error: string; begin if Trim(mmBranch.Text) = '' then error := 'Please enter branch.'; if error <> '' then ShowErrorBox(error); Result := error = ''; end; end.
unit IssuesClientUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DBXpress, DB, SqlExpr, FMTBcd, SoapLinked, InvokeRegistry, IssuesServerUnit, StdCtrls, DBClient, Grids, DBGrids, DBCtrls, XSBuiltIns; type TErrorIDs = array of Integer; TClientForm = class(TForm) Edit1: TEdit; ClientDataSet1: TClientDataSet; ClientDataSet1Owner: TStringField; ClientDataSet1Date_Opened: TDateField; ClientDataSet1Issue: TMemoField; ClientDataSet1ISSUE_ID: TIntegerField; DataSource1: TDataSource; DBGrid1: TDBGrid; DBMemo1: TDBMemo; Button3: TButton; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ClientDataSet1AfterPost(DataSet: TDataSet); procedure ClientDataSet1AfterInsert(DataSet: TDataSet); procedure ClientDataSet1AfterEdit(DataSet: TDataSet); procedure ClientDataSet1AfterDelete(DataSet: TDataSet); procedure Edit1KeyPress(Sender: TObject; var Key: Char); procedure Button3Click(Sender: TObject); private Delta: TIssueArray; NoEvents: Boolean; Rows: Integer; FUpdateType: TIssueUpdateType; IssuesData: TIssueArray; RIO: TLinkedRIO; GetIssues: IIssues; procedure ClearDelta(ErrorIDS: TErrorIDs); procedure CreateDataset; procedure UpdateChanges; procedure GetIssuesData; function IdFound(ID: Integer; ErrorArray: TErrorIds): Boolean; procedure SetDlgReadOnly; function ShowUpdateErrors(Error: TIssueError): Boolean; procedure UpdateDelta(NewIssue: Tissue; OldID: Integer); procedure UpdateDataset(DataSet: TDataSet; NewIssue: Tissue; OldID: Integer); procedure UpdateDatasets(NewIssue: Tissue; OldID: Integer); { Private declarations } public { Public declarations } end; var ClientForm: TClientForm; implementation {$R *.dfm} uses DSIntf, IssueErrors; procedure TClientForm.FormCreate(Sender: TObject); begin SetLength(Delta,0); RIO := TLinkedRIO.Create(Nil); GetIssues := Rio As IIssues; end; procedure TClientForm.FormDestroy(Sender: TObject); begin ClearDelta(Nil); end; procedure TClientForm.CreateDataSet; begin NoEvents := True; ClientDataSet1.Close; ClientDataSet1.Data := NULL; ClientDataSet1.CreateDataSet; IssueArrayToDataSet(ClientDataSet1, IssuesData, Rows); NoEvents := False; end; procedure TClientForm.GetIssuesData; begin Rows := GetIssues.RetrieveIssues(Edit1.Text, IssuesData); CreateDataSet; ClearDelta(Nil); end; procedure TClientForm.SetDlgReadOnly; begin UpdateErrorDlg.Edit1.ReadOnly := False; UpdateErrorDlg.Edit2.ReadOnly := False; UpdateErrorDlg.Edit3.ReadOnly := False; end; procedure TClientForm.UpdateDelta(NewIssue: Tissue; OldID: Integer); var I: Integer; begin for I := 0 to Length(Delta) -1 do begin if Delta[I].ID = OldID then begin Delta[I].DateOpened := NewIssue.DateOpened; Delta[I].Owner := NewIssue.Owner; Delta[I].ID := NewIssue.ID; break end; end; end; procedure TClientForm.UpdateDataset(DataSet: TDataSet; NewIssue: Tissue; OldID: Integer); begin DataSet.First; while not DataSet.eof do begin if DataSet.Fields[0].Value = OldID then begin DataSet.Edit; DataSet.Fields[2].Value := NewIssue.DateOpened.AsDateTime; DataSet.Fields[1].Value := NewIssue.Owner; DataSet.Fields[0].Value := NewIssue.ID; DataSet.Post; break; end; DataSet.Next; end; DataSet.First; end; procedure TClientForm.UpdateDatasets(NewIssue: Tissue; OldID: Integer); begin NoEvents := True; UpdateDelta(NewIssue, OldId); UpdateDataSet(ClientDataSet1, NewIssue, OldId); NoEvents := False; end; function TClientForm.ShowUpdateErrors(Error: TIssueError): Boolean; var DlgRslt, OldId: Integer; begin OldId := Error.FailedRecord.ID; UpdateErrorDlg.issue := Error.FailedRecord; UpdateErrorDlg.Edit1.Text := IntToStr(Error.FailedRecord.ID); UpdateErrorDlg.Edit2.Text := Error.FailedRecord.Owner; UpdateErrorDlg.Edit3.Text := DateToStr(Error.FailedRecord.DateOpened.AsDateTime); UpdateErrorDlg.DataSet := ClientDataSet1; // UpdateErrorDlg.Delta := Delta; UpdateErrorDlg.Memo1.Lines.Clear; UpdateErrorDlg.Memo1.Lines.Add(Error.ErrorMsg); DlgRslt := UpdateErrorDlg.ShowModal; SetDlgReadOnly; if DlgRslt <> mrCancel then UpdateDataSets(UpdateErrorDlg.Issue, OldId); if DlgRslt = mrRetry then UpdateChanges; Result := DlgRslt <> mrCancel; end; function TClientForm.IdFound(ID: Integer; ErrorArray: TErrorIds): Boolean; var I: Integer; begin Result := True; for I := 0 to Length(ErrorArray) -1 do if ID = ErrorArray[I] then exit; Result := False; end; procedure TClientForm.ClearDelta(ErrorIDS: TErrorIDs); var I, J: Integer; begin if Length(ErrorIDS) = 0 then begin for I := 0 to Length(Delta) -1 do Delta[I].Free; SetLength(Delta, 0); end else begin for I := 0 to Length(Delta) -1 do begin if not IdFound(Delta[I].ID, ErrorIDS) then begin for J := Length(Delta) -2 to I do Delta[J] := Delta[J+1]; SetLength(Delta, Length(Delta)-1); end; end; end; end; procedure TClientForm.UpdateChanges; var I, Errors: Integer; IssueErrors: TErrorArray; MoreErrors: Boolean; IDArray: TErrorIDs; begin if Length(Delta) > 0 then begin Errors := GetIssues.PutIssues(Delta, Length(Delta), IssueErrors); SetLength(IDArray, Errors); for I := 0 to Errors - 1 do begin MoreErrors := ShowUpdateErrors(IssueErrors[I]); IDArray[I] := IssueErrors[I].FailedRecord.ID; IssueErrors[I].Free; if not MoreErrors then begin IDArray := Nil; break; end end; ClearDelta(IDArray); end; end; procedure TClientForm.ClientDataSet1AfterPost(DataSet: TDataSet); var I, Current: Integer; begin if NoEvents then exit; Current := 0; for I := 0 to Length(Delta) -1 do begin if Delta[I].ID = ClientDataSet1.Fields[0].Value then begin Current := I; break; end; end; if Current = 0 then begin SetLength(Delta, Length(Delta) + 1); Current := Length(Delta)-1; Delta[Current] := TIssue.Create; Delta[Current].DateOpened := TXSDateTime.Create; end; Delta[Current].ID := ClientDataSet1.Fields[0].Value; Delta[Current].Owner := ClientDataSet1.Fields[1].Value; Delta[Current].DateOpened.AsDateTime := ClientDataSet1.Fields[2].Value; Delta[Current].Issue := ClientDataSet1.Fields[3].Value; Delta[Current].UpdateKind := FUpdateType; end; procedure TClientForm.ClientDataSet1AfterInsert(DataSet: TDataSet); begin if not NoEvents then FUpdateType := utUpdateInsert; end; procedure TClientForm.ClientDataSet1AfterEdit(DataSet: TDataSet); begin if not NoEvents then FUpdateType := utUpdateUpdate; end; procedure TClientForm.ClientDataSet1AfterDelete(DataSet: TDataSet); begin if not NoEvents then FUpdateType := utUpdateDelete; end; procedure TClientForm.Edit1KeyPress(Sender: TObject; var Key: Char); begin if Key in [#13, #9] then begin GetIssuesData; DBGrid1.SetFocus; end; end; procedure TClientForm.Button3Click(Sender: TObject); begin UpdateChanges; end; end.
unit rtti_1; interface uses System, sys.rtti; var P: TObject; ti: TRTTIOrdinal; Signed: Boolean; MinI8, MaxI8: Int64; implementation procedure Test; begin P := TypeInfo(Int8); ti := P as TRTTIOrdinal; Signed := ti.Signed; MinI8 := ti.LoBound; MaxI8 := ti.HiBound; end; initialization Test(); finalization Assert(Signed); Assert(MinI8 = Low(Int8)); Assert(MaxI8 = High(Int8)); end.
unit LinkFlds; interface uses Classes, HTTPApp, Db, DbClient, Midas, XMLBrokr, WebComp, MidComp, PagItems, MidItems; type TWebLink = class(TWebDataDisplay, IScriptComponent, IValidateField) private FText: string; FAction: string; FOpenWindow: Boolean; FKeyFieldName: string; protected function ControlContent(Options: TWebContentOptions): string; override; function GetText: string; procedure SetKeyFieldName(const Value: string); { IScriptComponent } procedure AddElements(AddIntf: IAddScriptElements); virtual; function GetSubComponents: TObject; { IValidateField } function ValidateField(DataSet: IMidasWebDataSet; AddIntf: IAddScriptElements): Boolean; public constructor Create(AOwner: TComponent); override; property Action: string read FAction write FAction; property Caption; property CaptionAttributes; property CaptionPosition; property Text: string read GetText write FText; property KeyFieldName: string read FKeyFieldName write SetKeyFieldName; property OpenWindow: Boolean read FOpenWindow write FOpenWindow default True; end; TLinkColumn = class(TWebLink) public class function IsColumn: Boolean; override; published property Text; property Caption; property CaptionAttributes; property Action; property OpenWindow; property KeyFieldName; end; TFieldLink = class(TWebLink) published property Caption; property CaptionAttributes; property CaptionPosition; property Text; property Action; property OpenWindow; end; implementation uses sysutils, MidProd; const sLinkFunctionName = 'GoLink'; // TODO: This function does not set the current row of the rowset. Clicking // on a link in a grid will use values from the focus row which may not be the // focus row. sLinkFunction = 'function %0:s(rs,fname,action,open)' + #13#10 + '{' + #13#10 + ' var s;' + #13#10 + ' var i;' + #13#10 + ' if (rs==null) exit;' + #13#10 + ' if (action.indexOf("?") == -1)' + #13#10 + ' s = action + "?";' + #13#10 + ' else' + #13#10 + ' s = action + "&";' + #13#10 + ' for (i=0; i<rs.FieldCnt; i++)' + #13#10 + ' {' + #13#10 + ' var f;' + #13#10 + ' f = rs.Fields.Fieldx[i];' + #13#10 + ' if (f.name == fname)' + #13#10 + ' {' + #13#10 + ' s = s + f.name + "=" + f.Value();' + #13#10 + ' break;' + #13#10 + ' }' + #13#10 + ' }' + #13#10 + ' s = s.replace(/ /g, "+");' + #13#10 + ' if (open)' + #13#10 + ' window.open(s);' + #13#10 + ' else' + #13#10 + ' location = s;' + #13#10 + '}' + #13#10; { TWebLink } resourcestring sLinkCaption = 'Link'; function TWebLink.ControlContent(Options: TWebContentOptions): string; const truefalse: array[Boolean] of string =('false', 'true'); var Attrs: string; Events: string; begin AddQuotedAttrib(Attrs, 'STYLE', Style); AddQuotedAttrib(Attrs, 'CLASS', StyleRule); AddCustomAttrib(Attrs, Custom); if (not (coNoScript in Options.Flags)) then Events := Format(' onclick="%s;return false;"', [Format('if(%s)%s(%s,''%s'',''%s'',%s)', [sXMLReadyVar, sLinkFunctionName, GetXMLRowSetName, KeyFieldName, Action, truefalse[OpenWindow]])]) else Events := ' onclick="return false;"'; // Note that HREF is ignored because onclick always returns false. Result := Format('<A HREF="%0:s"%1:s%2:s>%3:s</A>', [Action, Attrs, Events, Text]); end; constructor TWebLink.Create(AOwner: TComponent); begin inherited; Caption := sLinkCaption; OpenWindow := True; end; function TWebLink.GetText: string; begin if FText = '' then Result := ClassName else Result := FText; end; procedure TWebLink.AddElements(AddIntf: IAddScriptElements); begin inherited; AddIntf.AddFunction(sLinkFunctionName, Format(sLinkFunction, [sLinkFunctionName])); end; function TWebLink.GetSubComponents: TObject; begin Result := nil; end; procedure TWebLink.SetKeyFieldName(const Value: string); var Intf: IValidateFields; Component: TComponent; begin if (AnsiCompareText(Value, FKeyFieldName) <> 0) then begin FKeyFieldName := Value; if [csLoading, csDesigning] * ComponentState <> [] then begin Component := GetParentComponent; while Assigned(Component) and (not Component.GetInterface(IValidateFields, Intf)) do Component := Component.GetParentComponent; if Assigned(Component) then Intf.EnableValidateFields := True; end; end; end; resourcestring sKeyFieldNameBlank = '%s.KeyFieldName = '''''; sKeyFieldNotFound = '%0:s: KeyField "%1:s" not found'; function TWebLink.ValidateField(DataSet: IMidasWebDataSet; AddIntf: IAddScriptElements): Boolean; procedure AddError(Value: string); begin AddIntf.AddError(Value); Result := False; end; begin Result := True; if KeyFieldName = '' then AddError(Format(sKeyFieldNameBlank, [Name])) else if Assigned(DataSet) then if DataSet.Fields.FindField(KeyFieldName) = nil then AddError(Format(sKeyFieldNotFound, [Name, KeyFieldName])); end; { TLinkColumn } class function TLinkColumn.IsColumn: Boolean; begin Result := True; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} { Author: Ondrej Pokorny, http://www.kluug.net All Rights Reserved. License: MPL 1.1 / GPLv2 / LGPLv2 / FPC modified LGPLv2 } { OBufferedStreams.pas TOBufferedReadStream -> read streams with buffer. Can be used e.g. for reading data from a file stream. Supports seeking within the temp buffer range and also outside the temp buffer. TOBufferedWriteStream -> write data to a destination stream with buffer. E.g. to a file stream. } unit Xml.Internal.OBufferedStreams; {$IF SizeOf(LongInt) = 8} {$DEFINE LONGINT64} {$ENDIF} interface uses System.SysUtils, System.Classes; const OBUFFEREDSTREAMS_DEFBUFFERSIZE = 16*1024;//16 KB OBUFFEREDSTREAMS_DEFCHARBUFFERSIZE = OBUFFEREDSTREAMS_DEFBUFFERSIZE div SizeOf(Char);//16 KB type TOBufferedWriteStream = class(TStream) private fStream: TStream; fStreamPosition: NativeInt; fStreamSize: NativeInt; fTempBuffer: TBytes; fTempBufferUsedLength: NativeInt; fBufferSize: NativeInt; protected function GetSize: Int64; override; public constructor Create(const aStream: TStream; const aBufferSize: NativeInt = OBUFFEREDSTREAMS_DEFBUFFERSIZE); destructor Destroy; override; function Write(const Buffer; Count: LongInt): LongInt; override; function Write(const Buffer: TBytes; Offset, Count: LongInt): LongInt; override; function Read(var {%H-}Buffer; {%H-}Count: LongInt): LongInt; override; function Read(Buffer: TBytes; Offset, Count: LongInt): LongInt; override; {$IFDEF LONGINT64} function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; {$ELSE !LONGINT64} function Seek(Offset: LongInt; Origin: Word): LongInt; override; {$ENDIF !LONGINT64} public //write the whole temporary buffer to the destination stream procedure EnsureTempBufferWritten; end; TOBufferedReadStream = class(TStream) private fStream: TStream; fStreamPosition: NativeInt; fStreamSize: NativeInt; fTempBuffer: TBytes; fTempBufferPosition: NativeInt; fTempBufferUsedLength: NativeInt; fBlockFlushTempBuffer: Integer; fBufferSize: NativeInt; procedure CheckTempBuffer; protected function GetSize: Int64; override; public constructor Create(const aStream: TStream; const aBufferSize: NativeInt = OBUFFEREDSTREAMS_DEFBUFFERSIZE); function Write(const {%H-}Buffer; {%H-}Count: LongInt): LongInt; override; function Write(const Buffer: TBytes; Offset, Count: LongInt): LongInt; override; function Read(var Buffer; Count: LongInt): LongInt; override; function Read(Buffer: TBytes; Offset, Count: LongInt): LongInt; override; {$IFDEF LONGINT64} function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; {$ELSE !LONGINT64} function Seek(Offset: LongInt; Origin: Word): LongInt; override; {$ENDIF !LONGINT64} public //disallow clearing temporary buffer -> use if you need to seek back within the temp buffer. //use if you read from original streams that do not support seeking (e.g. a zip stream). procedure BlockFlushTempBuffer; procedure UnblockFlushTempBuffer; end; EOBufferedWriteStream = class(Exception); EOBufferedReadStream = class(Exception); implementation {$ZEROBASEDSTRINGS OFF} resourcestring OBufferedStreams_NilStream = 'The aStream parameter must be assigned when creating a buffered stream.'; OBufferedStreams_ReadingNotPossible = 'You can''t read from TOBufferedWriteStream'; OBufferedStreams_SeekingNotPossible = 'You can''t use seek in TOBufferedWriteStream'; OBufferedStreams_WritingNotPossible = 'You can''t write to TOBufferedReadStream'; { TOBufferedWriteStream } constructor TOBufferedWriteStream.Create(const aStream: TStream; const aBufferSize: NativeInt); begin inherited Create; if aStream = nil then raise EOBufferedWriteStream.Create(OBufferedStreams_NilStream); fStream := aStream; fStreamPosition := fStream.Position; fStreamSize := fStream.Size; fBufferSize := aBufferSize; SetLength(fTempBuffer, fBufferSize); end; destructor TOBufferedWriteStream.Destroy; begin EnsureTempBufferWritten; inherited; end; procedure TOBufferedWriteStream.EnsureTempBufferWritten; begin if fTempBufferUsedLength > 0 then begin fStream.WriteBuffer(fTempBuffer[0], fTempBufferUsedLength); fStreamSize := fStreamSize + fTempBufferUsedLength; fStreamPosition := fStreamPosition + fTempBufferUsedLength; fTempBufferUsedLength := 0; end; end; function TOBufferedWriteStream.GetSize: Int64; begin Result {%H-}:= fStreamSize + fTempBufferUsedLength; end; function TOBufferedWriteStream.Read(var Buffer; Count: LongInt): LongInt; begin raise EOBufferedWriteStream.Create(OBufferedStreams_ReadingNotPossible); end; function TOBufferedWriteStream.Read(Buffer: TBytes; Offset, Count: LongInt): LongInt; begin Result := Self.Read(Buffer[Offset], Count); end; {$IFDEF LONGINT64} function TOBufferedWriteStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; {$ELSE !LONGINT64} function TOBufferedWriteStream.Seek(Offset: Integer; Origin: Word): LongInt; {$ENDIF !LONGINT64} begin {$IFDEF LONGINT64} if (Origin = soCurrent) and (Offset = 0) then {$ELSE} if (Origin = soFromCurrent) and (Offset = 0) then {$ENDIF} begin Result := fStreamPosition + fTempBufferUsedLength; end else begin raise EOBufferedWriteStream.Create(OBufferedStreams_SeekingNotPossible); end; end; function TOBufferedWriteStream.Write(const Buffer; Count: LongInt): LongInt; begin Result := Count; if fTempBufferUsedLength+Result > fBufferSize then EnsureTempBufferWritten;//WRITE TEMP BUFFER if Result > fBufferSize then begin //count to write bigger then buffer -> write directly fStream.WriteBuffer(Buffer, Result); end else if Result > 0 then begin //store to temp! if Result > fBufferSize-fTempBufferUsedLength then//store only what has space in buffer Result := fBufferSize-fTempBufferUsedLength; Move(Buffer, fTempBuffer[fTempBufferUsedLength], Result); fTempBufferUsedLength := fTempBufferUsedLength + Result; end; //older delphi versions need to return Result = Count !!! if (0 < Result) and (Result < Count) then begin Result := Write({%H-}Pointer({%H-}NativeInt(@Buffer)+NativeInt(Result))^, Count-Result) + Result; end; end; function TOBufferedWriteStream.Write(const Buffer: TBytes; Offset, Count: LongInt): LongInt; begin Result := Self.Write(Buffer[Offset], Count); end; { TOBufferedReadStream } procedure TOBufferedReadStream.BlockFlushTempBuffer; begin Inc(fBlockFlushTempBuffer); end; procedure TOBufferedReadStream.CheckTempBuffer; var xReadBytes, xRemainingTempLength, xNewLength: NativeInt; begin if fTempBufferPosition = fTempBufferUsedLength then begin //we reached end of the tempbuffer, clear or grow and read from stream if fBlockFlushTempBuffer = 0 then begin fTempBufferPosition := 0; fTempBufferUsedLength := 0; end; xReadBytes := fBufferSize; if xReadBytes > fStreamSize-fStreamPosition then//don't read from stream more than possible xReadBytes := fStreamSize-fStreamPosition; //CHECK THAT WE HAVE ALL NECESSARY BYTES IN TEMP BUFFER xRemainingTempLength := Length(fTempBuffer)-fTempBufferPosition; if xRemainingTempLength < xReadBytes then begin //tempbuffer has to grow xNewLength := Length(fTempBuffer) + xReadBytes - xRemainingTempLength; SetLength(fTempBuffer, xNewLength); end; fStream.ReadBuffer(fTempBuffer[fTempBufferPosition], xReadBytes); fStreamPosition := fStreamPosition + xReadBytes; fTempBufferUsedLength := fTempBufferUsedLength + xReadBytes; end; end; constructor TOBufferedReadStream.Create(const aStream: TStream; const aBufferSize: NativeInt); begin inherited Create; if aStream = nil then raise EOBufferedReadStream.Create(OBufferedStreams_NilStream); fStream := aStream; fStreamPosition := fStream.Position; fStreamSize := fStream.Size; fBufferSize := aBufferSize; SetLength(fTempBuffer, fBufferSize); end; function TOBufferedReadStream.GetSize: Int64; begin Result := fStreamSize; end; function TOBufferedReadStream.Read(Buffer: TBytes; Offset, Count: LongInt): LongInt; begin Result := Self.Read(Buffer[Offset], Count); end; function TOBufferedReadStream.Read(var Buffer; Count: LongInt): LongInt; begin if Count < 0 then begin Result := 0; Exit; end; CheckTempBuffer; Result := fTempBufferUsedLength - fTempBufferPosition; if Result > Count then Result := Count; if Result > 0 then begin Move(fTempBuffer[fTempBufferPosition], Buffer, Result); fTempBufferPosition := fTempBufferPosition + Result; end; //older delphi versions need to return Result = Count !!! if (0 < Result) and (Result < Count) then begin Result := Read({%H-}Pointer({%H-}NativeInt(@Buffer)+NativeInt(Result))^, Count-Result) + Result; end; end; {$IFDEF LONGINT64} function TOBufferedReadStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; var xAbsolutePosition: Int64; {$ELSE !LONGINT64} function TOBufferedReadStream.Seek(Offset: Integer; Origin: Word): LongInt; var xAbsolutePosition: NativeInt; {$ENDIF !LONGINT64} begin {$IFDEF LONGINT64} if (Origin = soCurrent) and (Offset = 0) then begin {$ELSE} if (Origin = soFromCurrent) and (Offset = 0) then begin {$ENDIF} //CURRENT POSITION Result := fStreamPosition - fTempBufferUsedLength + fTempBufferPosition; end else begin //SEEK TO POSITION AND CLEAR TEMP STREAM {$IFDEF LONGINT64} case Origin of soCurrent: xAbsolutePosition := fStreamPosition - fTempBufferUsedLength + fTempBufferPosition + Offset; soEnd: xAbsolutePosition := fStreamSize + Offset; else //soBeginning xAbsolutePosition := Offset; end; {$ELSE} case Origin of soFromCurrent: xAbsolutePosition := fStreamPosition - fTempBufferUsedLength + fTempBufferPosition + Offset; soFromEnd: xAbsolutePosition := fStreamSize + Offset; else //soFromBeginning xAbsolutePosition := Offset; end; {$ENDIF} if (xAbsolutePosition >= (fStreamPosition - fTempBufferUsedLength)) then begin //WITHIN TEMP RANGE fTempBufferPosition := xAbsolutePosition - (fStreamPosition - fTempBufferUsedLength); Result := fStreamPosition - fTempBufferUsedLength + fTempBufferPosition; end else begin //OUTSIDE TEMP RANGE, CLEAR TEMP STREAM {$IFDEF LONGINT64} Result := fStream.Seek(xAbsolutePosition, soBeginning); {$ELSE !LONGINT64} Result := fStream.Seek(soFromBeginning, xAbsolutePosition); {$ENDIF !LONGINT64} fStreamPosition := Result; fTempBufferUsedLength := 0; fTempBufferPosition := 0; end; end; end; procedure TOBufferedReadStream.UnblockFlushTempBuffer; begin if fBlockFlushTempBuffer > 0 then Dec(fBlockFlushTempBuffer); end; function TOBufferedReadStream.Write(const Buffer: TBytes; Offset, Count: LongInt): LongInt; begin Result := Self.Write(Buffer[Offset], Count); end; function TOBufferedReadStream.Write(const Buffer; Count: LongInt): LongInt; begin raise EOBufferedReadStream.Create(OBufferedStreams_WritingNotPossible); end; end.
//****************************************************************************** //*** LUA SCRIPT FUNCTIONS *** //*** *** //*** (c) Massimo Magnano 2005 *** //*** *** //*** *** //****************************************************************************** // File : Lua_FunctionsLog.pas // // Description : Do Log of Functions called inside a script. // //****************************************************************************** unit Lua_FunctionsLog; interface type Tfunction_LuaLog = procedure (FuncLog :PChar); stdcall; Var OnLuaLog :Tfunction_LuaLog =Nil; procedure DoFunctionLog(FuncName :String; Param1 :String=''; Param2 :String=''; Param3 :String=''; Param4 :String=''); implementation procedure DoFunctionLog(FuncName :String; Param1 :String=''; Param2 :String=''; Param3 :String=''; Param4 :String=''); Var xLog :String; begin if Assigned(OnLuaLog) then begin xLog := FuncName+'('; if (Param1<>'') then xLog :=xLog+Param1; if (Param2<>'') then xLog :=xLog+', '+Param2; if (Param3<>'') then xLog :=xLog+', '+Param3; if (Param4<>'') then xLog :=xLog+', '+Param4; xLog :=xLog+')'; OnLuaLog(PChar(xLog)); end; end; end.
unit UParcelas; interface type Parcelas = class protected numParcela : Integer; dias : Integer; porcentagem : Real; public Constructor CrieObjeto; Destructor Destrua_Se; Procedure setNumParcela (vNumParcela : Integer); Procedure setDias (vDias : Integer); Procedure setPorcentagem (vPorcentagem : Real); Function getNumParcela : Integer; Function getDias : Integer; Function getPorcentagem : Real; end; implementation { Parcelas } constructor Parcelas.CrieObjeto; begin numParcela := 0; dias := 0; porcentagem := 0; end; destructor Parcelas.Destrua_Se; begin end; function Parcelas.getDias: Integer; begin Result := dias; end; function Parcelas.getNumParcela: Integer; begin Result := numParcela; end; function Parcelas.getPorcentagem: Real; begin Result := porcentagem; end; procedure Parcelas.setDias(vDias: Integer); begin Dias := vDias; end; procedure Parcelas.setNumParcela(vNumParcela: Integer); begin NumParcela := vNumParcela end; procedure Parcelas.setPorcentagem(vPorcentagem: Real); begin Porcentagem := vPorcentagem; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { Connection classes } { } { Copyright (c) 1997,98 Inprise Corporation } { } {*******************************************************} unit MConnect; interface uses Messages, Windows, SysUtils, Classes, StdVcl, DBClient, ActiveX, ComObj; type { TCustomObjectBroker } TCustomObjectBroker = class(TComponent) public procedure SetConnectStatus(ComputerName: string; Success: Boolean); virtual; abstract; function GetComputerForGUID(GUID: TGUID): string; virtual; abstract; function GetComputerForProgID(const ProgID): string; virtual; abstract; function GetPortForComputer(const ComputerName: string): Integer; virtual; abstract; end; { TDispatchConnection } TLoginEvent = procedure(Sender: TObject; Username, Password: string) of object; TGetUsernameEvent = procedure(Sender: TObject; var Username: string) of object; TDispatchConnection = class(TCustomRemoteServer) private FServerGUID: TGUID; FServerName: string; FAppServer: Variant; FRegStdVclFailed: Boolean; FLoginPrompt: Boolean; FObjectBroker: TCustomObjectBroker; FOnLogin: TLoginEvent; FOnGetUsername: TGetUsernameEvent; function GetServerGUID: string; procedure SetServerGUID(const Value: string); procedure SetServerName(const Value: string); procedure SetObjectBroker(Value: TCustomObjectBroker); protected function GetAppServer: Variant; virtual; procedure SetAppServer(Value: Variant); virtual; procedure DoDisconnect; override; function GetConnected: Boolean; override; procedure SetConnected(Value: Boolean); override; procedure GetProviderNames(Proc: TGetStrProc); override; function GetServerCLSID: TGUID; procedure Notification(AComponent: TComponent; Operation: TOperation); override; property ObjectBroker: TCustomObjectBroker read FObjectBroker write SetObjectBroker; public constructor Create(AOwner: TComponent); override; function GetProvider(const ProviderName: string): IProvider; override; property AppServer: Variant read GetAppServer; published property Connected; property LoginPrompt: Boolean read FLoginPrompt write FLoginPrompt default False; property ServerGUID: string read GetServerGUID write SetServerGUID; property ServerName: string read FServerName write SetServerName; property AfterConnect; property AfterDisconnect; property BeforeConnect; property BeforeDisconnect; property OnGetUsername: TGetUsernameEvent read FOnGetUsername write FOnGetUsername; property OnLogin: TLoginEvent read FOnLogin write FOnLogin; end; { TCOMConnection } TCOMConnection = class(TDispatchConnection) protected procedure SetConnected(Value: Boolean); override; procedure DoConnect; override; end; { TDCOMConnection } TDCOMConnection = class(TCOMConnection) private FComputerName: string; procedure SetComputerName(const Value: string); function IsComputerNameStored: Boolean; protected procedure DoConnect; override; public constructor Create(AOwner: TComponent); override; published property ComputerName: string read FComputerName write SetComputerName stored IsComputerNameStored; property ObjectBroker; end; { TOLEnterpriseConnection } TOLEnterpriseConnection = class(TCOMConnection) private FComputerName: string; FBrokerName: string; procedure SetComputerName(const Value: string); procedure SetBrokerName(const Value: string); protected procedure DoConnect; override; published property ComputerName: string read FComputerName write SetComputerName; property BrokerName: string read FBrokerName write SetBrokerName; end; { TDispatchProvider } TDispatchProvider = class(TInterfacedObject, IProvider, ISupportErrorInfo) private FProvider: IProviderDisp; { IDispatch } function GetTypeInfoCount(out Count: Integer): HResult; stdcall; function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall; function GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall; function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall; { IProvider } function Get_Data: OleVariant; safecall; function ApplyUpdates(Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer): OleVariant; safecall; function GetMetaData: OleVariant; safecall; function GetRecords(Count: Integer; out RecsOut: Integer): OleVariant; safecall; function DataRequest(Input: OleVariant): OleVariant; safecall; function Get_Constraints: WordBool; safecall; procedure Set_Constraints(Value: WordBool); safecall; procedure Reset(MetaData: WordBool); safecall; procedure SetParams(Values: OleVariant); safecall; { ISupportErrorInfo } function InterfaceSupportsErrorInfo(const iid: TIID): HResult; stdcall; public constructor Create(const Provider: IProviderDisp); function SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; override; end; implementation uses Forms, Registry, MidConst, DBLogDlg; { TDispatchProvider } constructor TDispatchProvider.Create(const Provider: IProviderDisp); begin FProvider := Provider; end; { TDispatchProvider.IDispatch } function TDispatchProvider.GetTypeInfoCount(out Count: Integer): HResult; begin Result := IDispatch(FProvider).GetTypeInfoCount(Count); end; function TDispatchProvider.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; begin Result := IDispatch(FProvider).GetTypeInfo(Index, LocaleID, TypeInfo); end; function TDispatchProvider.GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; begin Result := IDispatch(FProvider).GetIDsOfNames(IID, Names, NameCount, LocaleID, DispIDs); end; function TDispatchProvider.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; begin Result := IDispatch(FProvider).Invoke(DispID, IID, LocaleID, Flags, Params, VarResult, ExcepInfo, ArgErr); end; { TDispatchProvider.IProvider } function TDispatchProvider.Get_Data: OleVariant; begin Result := FProvider.Data; end; function TDispatchProvider.ApplyUpdates(Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer): OleVariant; begin Result := FProvider.ApplyUpdates(Delta, MaxErrors, ErrorCount); end; function TDispatchProvider.GetMetaData: OleVariant; begin Result := FProvider.GetMetaData; end; function TDispatchProvider.GetRecords(Count: Integer; out RecsOut: Integer): OleVariant; begin Result := FProvider.GetRecords(Count, RecsOut); end; function TDispatchProvider.DataRequest(Input: OleVariant): OleVariant; begin Result := FProvider.DataRequest(Input); end; function TDispatchProvider.Get_Constraints: WordBool; begin Result := FProvider.Constraints; end; procedure TDispatchProvider.Set_Constraints(Value: WordBool); begin FProvider.Constraints := Value; end; procedure TDispatchProvider.Reset(MetaData: WordBool); begin FProvider.Reset(MetaData); end; procedure TDispatchProvider.SetParams(Values: OleVariant); safecall; begin FProvider.SetParams(Values); end; { TDispatchProvider.ISupportErrorInfo } function TDispatchProvider.InterfaceSupportsErrorInfo(const iid: TIID): HResult; begin if IsEqualGUID(IProvider, iid) then Result := S_OK else Result := S_FALSE; end; function TDispatchProvider.SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; begin Result := HandleSafeCallException(ExceptObject, ExceptAddr, IProvider, '', ''); end; { TDispatchConnection } constructor TDispatchConnection.Create(AOwner: TComponent); begin inherited Create(AOwner); FLoginPrompt := False; end; procedure TDispatchConnection.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FObjectBroker) then FObjectBroker := nil; end; procedure TDispatchConnection.SetObjectBroker(Value: TCustomObjectBroker); begin if Value = FObjectBroker then Exit; if Assigned(Value) then Value.FreeNotification(Self); FObjectBroker := Value; end; function TDispatchConnection.GetServerGUID: string; begin if (FServerGUID.D1 <> 0) or (FServerGUID.D2 <> 0) or (FServerGUID.D3 <> 0) then Result := GUIDToString(FServerGUID) else Result := ''; end; procedure TDispatchConnection.SetServerGUID(const Value: string); var ServerName: PWideChar; begin if not (csLoading in ComponentState) then SetConnected(False); if Value = '' then FillChar(FServerGUID, 0, SizeOf(FServerGUID)) else begin FServerGUID := StringToGUID(Value); if ProgIDFromCLSID(FServerGUID, ServerName) = 0 then begin FServerName := ServerName; CoTaskMemFree(ServerName); end; end; end; procedure TDispatchConnection.SetServerName(const Value: string); begin if Value <> FServerName then begin if not (csLoading in ComponentState) then begin SetConnected(False); if CLSIDFromProgID(PWideChar(WideString(Value)), FServerGUID) <> 0 then FillChar(FServerGUID, 0, SizeOf(FServerGUID)); end; FServerName := Value; end; end; function TDispatchConnection.GetConnected: Boolean; begin Result := (not VarIsNull(AppServer) and (IDispatch(AppServer) <> nil)); end; procedure TDispatchConnection.SetConnected(Value: Boolean); var Username, Password: string; Login: Boolean; begin Login := LoginPrompt and Value and not Connected; if Login then begin if Assigned(FOnGetUsername) then FOnGetUsername(Self, Username); if not RemoteLoginDialog(Username, Password) then Exit; end; inherited SetConnected(Value); if Login and Connected then if Assigned(FOnLogin) then FOnLogin(Self, Username, Password); end; procedure TDispatchConnection.DoDisconnect; begin SetAppServer(NULL); end; function TDispatchConnection.GetAppServer: Variant; begin Result := FAppServer; end; procedure TDispatchConnection.SetAppServer(Value: Variant); begin FAppServer := Value; end; function TDispatchConnection.GetProvider(const ProviderName: string): IProvider; function GetProperty(Obj: IDispatch; const Name: string): OleVariant; var ID: Integer; WideName: WideString; DispParams: TDispParams; ExcepInfo: TExcepInfo; Status: Integer; begin WideName := Name; if Obj.GetIDsOfNames(GUID_NULL, @WideName, 1, 0, @ID) <> 0 then raise Exception.CreateFmt(SInvalidProviderName, [Name]); FillChar(DispParams, SizeOf(DispParams), 0); FillChar(ExcepInfo, SizeOf(ExcepInfo), 0); Status := Obj.Invoke(ID, GUID_NULL, 0, DISPATCH_PROPERTYGET, DispParams, @Result, @ExcepInfo, nil); if Status <> 0 then DispatchInvokeError(Status, ExcepInfo); end; var ProviderDispatch: IDispatch; QIResult: HResult; begin Connected := True; ProviderDispatch := IDispatch(GetProperty(IDispatch(AppServer), ProviderName)); QIResult := ProviderDispatch.QueryInterface(IProvider, Result); if (QIResult = REGDB_E_IIDNOTREG) and not FRegStdVclFailed then try RegisterComServer('STDVCL40.DLL'); QIResult := ProviderDispatch.QueryInterface(IProvider, Result); except FRegStdVclFailed := True; end; if QIResult <> S_OK then Result := TDispatchProvider.Create(IProviderDisp(ProviderDispatch)); end; procedure TDispatchConnection.GetProviderNames(Proc: TGetStrProc); var List: Variant; I: Integer; begin Connected := True; VarClear(List); try List := AppServer.GetProviderNames; except { Assume any errors means the list is not available. } end; if VarIsArray(List) and (VarArrayDimCount(List) = 1) then for I := VarArrayLowBound(List, 1) to VarArrayHighBound(List, 1) do Proc(List[I]); end; function TDispatchConnection.GetServerCLSID: TGUID; begin if IsEqualGuid(FServerGuid, GUID_NULL) then begin if FServerName = '' then raise Exception.CreateFmt(SServerNameBlank, [Name]); Result := ProgIDToClassID(FServerName); end else Result := FServerGuid; end; { TCOMConnection } procedure TCOMConnection.SetConnected(Value: Boolean); begin if (not (csReading in ComponentState)) and (Value and not Connected) and IsEqualGuid(GetServerCLSID, GUID_NULL) then raise Exception.CreateFmt(SServerNameBlank, [Name]); inherited SetConnected(Value); end; procedure TCOMConnection.DoConnect; begin SetAppServer(CreateComObject(GetServerCLSID) as IDispatch); end; { TDCOMConnection } constructor TDCOMConnection.Create(AOwner: TComponent); begin inherited Create(AOwner); end; procedure TDCOMConnection.SetComputerName(const Value: string); begin if Value <> FComputerName then begin SetConnected(False); FComputerName := Value; end; end; function TDCOMConnection.IsComputerNameStored: Boolean; begin Result := (FObjectBroker = nil) and (ComputerName <> ''); end; procedure TDCOMConnection.DoConnect; begin if (FObjectBroker <> nil) then begin repeat if FComputerName = '' then FComputerName := FObjectBroker.GetComputerForGUID(GetServerCLSID); try SetAppServer(CreateRemoteComObject(ComputerName, GetServerCLSID) as IDispatch); FObjectBroker.SetConnectStatus(ComputerName, True); except FObjectBroker.SetConnectStatus(ComputerName, False); FComputerName := ''; end; until Connected; end else if (ComputerName <> '') then SetAppServer(CreateRemoteComObject(ComputerName, GetServerCLSID) as IDispatch) else inherited DoConnect; end; { TOLEnterpriseConnection } procedure TOLEnterpriseConnection.SetComputerName(const Value: string); begin if Value <> FComputerName then begin SetConnected(False); FComputerName := Value; end; if Value <> '' then FBrokerName := ''; end; procedure TOLEnterpriseConnection.SetBrokerName(const Value: string); begin if Value <> FBrokerName then begin SetConnected(False); FBrokerName := Value; end; if Value <> '' then FComputerName := ''; end; procedure TOLEnterpriseConnection.DoConnect; var Reg: TRegistry; procedure WriteValue(ValueName, Value: String); begin if not Reg.ValueExists(ValueName) then Reg.WriteString(ValueName, Value); end; const AgentDLL = 'oleaan40.dll'; var InprocKey, Inproc2Key, DllName, TempStr, TempStr2, ProgID: String; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey('Software\OpenEnvironment\InstallRoot', False) then begin DllName := Reg.ReadString(''); Reg.CloseKey; if Reg.OpenKey('Software\OpenEnvironment\OLEnterprise\AutomationAgent', False) then begin if not IsPathDelimiter(DllName, Length(DllName)) then DllName := DllName + '\'; DllName := DllName + Reg.ReadString(''); Reg.CloseKey; end else begin if not IsPathDelimiter(DllName, Length(DllName)) then DllName := DllName + '\'; DllName := DllName + AgentDLL; end; end else DllName := AgentDLL; { AgentDLL must be in the path } Reg.RootKey := HKEY_CLASSES_ROOT; InprocKey := Format('CLSID\%s\InprocServer32', [ServerGUID]); Inproc2Key := Format('CLSID\%s\_InprocServer32', [ServerGUID]); if ComputerName = '' then {Run via COM} begin if Reg.OpenKey(InprocKey, False) then begin TempStr := Reg.ReadString(''); Reg.CloseKey; if (AnsiPos(AgentDLL, AnsiLowerCase(TempStr)) > 0) or (AnsiPos(AnsiLowerCase(ExtractFileName(DllName)), AnsiLowerCase(TempStr)) > 0) then begin if Reg.OpenKey(Inproc2Key, False) then begin TempStr2 := Reg.ReadString(''); Reg.WriteString('',TempStr); Reg.CloseKey; Reg.OpenKey(InprocKey, False); Reg.WriteString('',TempStr2); Reg.CloseKey; end else Reg.DeleteKey(InprocKey); end; end; end else begin if Reg.OpenKey(InprocKey, False) then begin TempStr := Reg.ReadString(''); Reg.CloseKey; if (AnsiPos(AgentDLL, AnsiLowerCase(TempStr)) = 0) and (AnsiPos(AnsiLowerCase(ExtractFileName(DllName)), AnsiLowerCase(TempStr)) = 0) then Reg.MoveKey(InprocKey, Inproc2Key, True); end; Reg.OpenKey(InprocKey, True); Reg.WriteString('',DllName); Reg.WriteString('ThreadingModel','Apartment'); Reg.CloseKey; Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.OpenKey('Software\OpenEnvironment\OLEnterprise\Dap\DCEApp',True); if BrokerName <> '' then begin Reg.WriteString('Broker',Format('ncacn_ip_tcp:%s',[BrokerName])); WriteValue('LogLevel', '0'); WriteValue('LogFile',''); WriteValue('UseNaming','1'); WriteValue('UseSecurity','1'); end else Reg.WriteString('Broker','none'); Reg.CloseKey; Reg.RootKey := HKEY_CLASSES_ROOT; if Reg.OpenKey(Format('CLSID\%s\ProgID',[ServerGUID]), False) then begin ProgID := Reg.ReadString(''); Reg.CloseKey; end else begin ProgID := ServerName; if ProgID = '' then ProgID := ServerGUID else begin Reg.OpenKey(Format('%s\CLSID',[ProgID]), True); Reg.WriteString('',ServerGUID); Reg.CloseKey; end; Reg.OpenKey(Format('CLSID\%s\ProgID',[ServerGUID]), True); Reg.WriteString('',ProgID); Reg.CloseKey; end; Reg.OpenKey(Format('CLSID\%s\Dap\DCEClient\%s',[ServerGUID, ProgID]), True); WriteValue('ComTimeout','default'); Reg.WriteString('DisableNaming',IntToStr(Ord(BrokerName = ''))); WriteValue('ExtendedImport','1'); WriteValue('ImportName','%cell%/applications/services/%service%'); WriteValue('ProtectionLevel',''); WriteValue('Protseq','ncacn_ip_tcp'); if BrokerName <> '' then Reg.DeleteValue('ServerBinding') else Reg.WriteString('ServerBinding',Format('ncacn_ip_tcp:%s',[ComputerName])); WriteValue('ServerPrincipal',''); WriteValue('SetAuthentication','1'); WriteValue('TimerInterval','10'); WriteValue('VerifyAvailability','0'); Reg.CloseKey; Reg.CreateKey(Format('CLSID\%s\NotInsertable',[ServerGUID])); Reg.CreateKey(Format('CLSID\%s\Programmable',[ServerGUID])); end; finally Reg.Free; end; inherited DoConnect; end; end.
unit TestFile; { case class for a couple of testers that depend on format output files matching ref output } {(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is TestFile, released May 2003. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele. All Rights Reserved. Contributor(s): Anthony Steele. 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/NPL/ 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. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL") See http://www.gnu.org/licenses/gpl.html ------------------------------------------------------------------------------*) {*)} {$I JcfGlobal.inc} interface uses TestFrameWork; type TTestFile = class(TTestCase) protected procedure SetUp; override; procedure TestFileContentsSame(const psFileName1, psFileName2: string); end; implementation uses { delphi } SysUtils, { jcf } JcfStringUtils, JcfUnicodeFiles, TestConstants; procedure TTestFile.Setup; begin inherited; InitTestSettings; end; procedure TTestFile.TestFileContentsSame(const psFileName1, psFileName2: string); var lsFile1, lsFile2: WideString; leFileType1, leFileType2: TFileContentType; begin Check(FileExists(psFileName1), 'File ' + psFileName1 + ' does not exist'); Check(FileExists(psFileName2), 'File ' + psFileName2 + ' does not exist'); ReadTextFile(psFileName1, lsFile1, leFileType1); ReadTextFile(psFileName2, lsFile2, leFileType2); // check types Check(leFileType1 = leFileType2, 'File types differ'); // check lengths CheckEquals(Length(lsFile1), Length(lsFile2), 'Files lengths differ, ' + IntToStr(Length(lsFile1)) + ' vs ' + IntToStr(Length(lsFile2)) + ' ' + psFileName1 + ' and ' + psFileName2); // check contents the same if (lsFile1 <> lsFile2) then Fail('Files differ ' + psFileName1 + ' and ' + psFileName2); end; end.
unit ufrmSysGridColWidth; interface {$I ThsERP.inc} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, StrUtils, Vcl.Menus, Vcl.Samples.Spin, Vcl.AppEvnts, FireDAC.Stan.Option, FireDAC.Stan.Intf, FireDAC.Comp.Client, Ths.Erp.Helper.Edit, Ths.Erp.Helper.Memo, Ths.Erp.Helper.ComboBox, ufrmBase, ufrmBaseInputDB , Ths.Erp.Database.Table.View.SysViewTables , Ths.Erp.Database.Table.View.SysViewColumns ; type TfrmSysGridColWidth = class(TfrmBaseInputDB) lblTableName: TLabel; cbbTableName: TComboBox; lblColumnName: TLabel; cbbColumnName: TComboBox; lblColumnWidth: TLabel; edtColumnWidth: TEdit; lblSequenceNo: TLabel; edtSequenceNo: TEdit; procedure FormCreate(Sender: TObject);override; procedure RefreshData();override; procedure btnAcceptClick(Sender: TObject);override; procedure cbbTableNameChange(Sender: TObject); private vSysViewTables: TSysViewTables; vSysViewColumns: TSysViewColumns; public destructor Destroy; override; protected function ValidateInput(panel_groupbox_pagecontrol_tabsheet: TWinControl = nil): Boolean; override; published end; implementation uses Ths.Erp.Database.Table.SysGridColWidth , Ths.Erp.Database.Singleton , Ths.Erp.Database.Table , Ths.Erp.Functions , Ths.Erp.Constants ; {$R *.dfm} procedure TfrmSysGridColWidth.cbbTableNameChange(Sender: TObject); begin TSingletonDB.GetInstance.FillColNameForColWidth(TComboBox(cbbColumnName), ReplaceRealColOrTableNameTo(cbbTableName.Text)); end; destructor TfrmSysGridColWidth.Destroy; begin if Assigned(vSysViewTables) then vSysViewTables.Free; if Assigned(vSysViewColumns) then vSysViewColumns.Free; inherited; end; procedure TfrmSysGridColWidth.FormCreate(Sender: TObject); begin TSysGridColWidth(Table).TableName1.SetControlProperty(Table.TableName, cbbTableName); TSysGridColWidth(Table).ColumnName.SetControlProperty(Table.TableName, cbbColumnName); TSysGridColWidth(Table).ColumnWidth.SetControlProperty(Table.TableName, edtColumnWidth); TSysGridColWidth(Table).SequenceNo.SetControlProperty(Table.TableName, edtSequenceNo); inherited; cbbTableName.CharCase := ecNormal; cbbColumnName.CharCase := ecNormal; vSysViewTables := TSysViewTables.Create(Table.Database); vSysViewColumns := TSysViewColumns.Create(Table.Database); fillComboBoxData(cbbTableName, vSysViewTables, vSysViewTables.TableName1.FieldName, ''); cbbTableNameChange(cbbTableName); end; procedure TfrmSysGridColWidth.RefreshData(); begin //control içeriğini table class ile doldur cbbTableName.ItemIndex := cbbTableName.Items.IndexOf(TSysGridColWidth(Table).TableName1.Value); cbbTableNameChange(cbbTableName); if cbbColumnName.Items.IndexOf(TSysGridColWidth(Table).ColumnName.Value) = -1 then cbbColumnName.Items.Add(TSysGridColWidth(Table).ColumnName.Value); cbbColumnName.ItemIndex := cbbColumnName.Items.IndexOf(TSysGridColWidth(Table).ColumnName.Value); edtColumnWidth.Text := TSysGridColWidth(Table).ColumnWidth.Value; edtSequenceNo.Text := TSysGridColWidth(Table).SequenceNo.Value; end; function TfrmSysGridColWidth.ValidateInput( panel_groupbox_pagecontrol_tabsheet: TWinControl): Boolean; begin Result := inherited ValidateInput(); //arada rakam atlyacak şekilde giriş yapılmışsa rakamı otomatik olarak düzelt. //maks sequence no dan sonraki rakam gelmek zorunda. if (FormMode = ifmNewRecord) or (FormMode = ifmCopyNewRecord) then begin if StrToInt(edtSequenceNo.Text) > TSysGridColWidth(Table).GetMaxSequenceNo(cbbTableName.Text)+1 then edtSequenceNo.Text := IntToStr(TSysGridColWidth(Table).GetMaxSequenceNo(cbbTableName.Text) + 1) end else if (FormMode = ifmUpdate) then begin if StrToInt(edtSequenceNo.Text) > TSysGridColWidth(Table).GetMaxSequenceNo(TSysGridColWidth(Table).TableName1.Value) then edtSequenceNo.Text := IntToStr(TSysGridColWidth(Table).GetMaxSequenceNo(TSysGridColWidth(Table).TableName1.Value)); end; end; procedure TfrmSysGridColWidth.btnAcceptClick(Sender: TObject); begin if (FormMode = ifmNewRecord) or (FormMode = ifmCopyNewRecord) or (FormMode = ifmUpdate) then begin if (ValidateInput) then begin if (FormMode = ifmUpdate) then begin if TSysGridColWidth(Table).SequenceNo.Value = StrToInt(edtSequenceNo.Text) then TSysGridColWidth(Table).SequenceStatus := ssNone else if TSysGridColWidth(Table).SequenceNo.Value > StrToInt(edtSequenceNo.Text) then TSysGridColWidth(Table).SequenceStatus := ssAzalma else if TSysGridColWidth(Table).SequenceNo.Value < StrToInt(edtSequenceNo.Text) then TSysGridColWidth(Table).SequenceStatus := ssArtis; TSysGridColWidth(Table).OldValue := TSysGridColWidth(Table).SequenceNo.Value; end; if cbbTableName.Items.IndexOf(cbbTableName.Text) = -1 then raise Exception.Create( TranslateText('Listede olmayan bir Tablo Adı giremezsiniz!', '#1', LngMsgError, LngSystem) ); TSysGridColWidth(Table).TableName1.Value := cbbTableName.Text; TSysGridColWidth(Table).ColumnName.Value := cbbColumnName.Text; TSysGridColWidth(Table).ColumnWidth.Value := edtColumnWidth.Text; TSysGridColWidth(Table).SequenceNo.Value := edtSequenceNo.Text; inherited; end; end else inherited; end; end.
unit ncaFrmPesqDadosFiscais; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, cxControls, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, nxdb, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, Vcl.StdCtrls, cxButtons, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, cxCalendar, cxContainer, cxLabel, cxCurrencyEdit; type TFrmPesqDadosFiscais = class(TForm) panBusca: TLMDSimplePanel; btnOk: TcxButton; Grid: TcxGrid; TV: TcxGridDBTableView; TVFor: TcxGridDBTableView; TVForNome: TcxGridDBColumn; GL: TcxGridLevel; btnXML: TcxButton; Tab: TnxTable; TabID: TUnsignedAutoIncField; TabUID: TGuidField; TabChaveNFE: TStringField; TabNomeFor: TStringField; TabnItem: TWordField; TabProduto: TLongWordField; TabDataNF: TDateTimeField; TabCNPJFor: TStringField; TabQuant: TFloatField; TabQuantOrig: TFloatField; TabDadosFiscais: TnxMemoField; DS: TDataSource; TVChaveNFE: TcxGridDBColumn; TVNomeFor: TcxGridDBColumn; TVDataNF: TcxGridDBColumn; TVQuant: TcxGridDBColumn; cxLabel1: TcxLabel; TabCustoU: TCurrencyField; TVCustoU: TcxGridDBColumn; procedure btnOkClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnXMLClick(Sender: TObject); private { Private declarations } public function ObtemDadosFiscais(aProduto: Cardinal; var aFor: Cardinal; var aQuant: Double; var aCustoU: Currency; var aDadosFiscais: String): Boolean; { Public declarations } end; var FrmPesqDadosFiscais: TFrmPesqDadosFiscais; implementation {$R *.dfm} uses ncaDM, ncaFrmPri, ncaFrmLeXML; { TFrmPesqDadosFiscais } procedure TFrmPesqDadosFiscais.btnOkClick(Sender: TObject); begin if Tab.IsEmpty then raise Exception.Create('Não há XML de compra desse produto no banco de dados do NEX. Clique em "Adicionar XML de compra" para ler o XML de compra desse produto'); ModalResult := mrOk; end; procedure TFrmPesqDadosFiscais.btnXMLClick(Sender: TObject); begin TFrmLeXML.Create(Self).ShowModal; Tab.Refresh; end; procedure TFrmPesqDadosFiscais.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; function TFrmPesqDadosFiscais.ObtemDadosFiscais( aProduto: Cardinal; var aFor: Cardinal; var aQuant: Double; var aCustoU: Currency; var aDadosFiscais: String): Boolean; var S: String; begin if aFor>0 then begin S := Dados.ObtemCNPJFor(aFor); Tab.IndexName := 'ICNPJForProdutoDataNF'; Tab.SetRange([S, aProduto], [S, aProduto]); end else begin Tab.IndexName := 'IProdutoDataNF'; Tab.SetRange([aProduto], [aProduto]); end; if not Tab.IsEmpty then Tab.First; ShowModal; if (not Tab.IsEmpty) then begin aFor := Dados.ObtemCodFor(TabCNPJFor.Value); aQuant := TabQuant.Value; aDadosFiscais := TabDadosFiscais.Value; aCustoU := TabCustoU.Value; Result := True; end else Result := False; end; end.
unit UFrmPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ComCtrls, ComObj, Math, StrUtils, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtDlgs, System.Generics.Collections, IniFiles, UNFSe_ArqMagSigISS; type TTipoSistema = (tsSigISS, tsEL, tsNaoSelecionado); TFrmPrincipal = class(TForm) Pn_Top: TPanel; Label1: TLabel; Edt_Arquivo: TEdit; Btn_Arquivo: TBitBtn; Cmb_Sistema: TComboBox; Label2: TLabel; Pc_Sistemas: TPageControl; Ts_SigISS: TTabSheet; Pn_Bot: TPanel; Btn_SalvarArqMag: TBitBtn; Btn_Fechar: TBitBtn; Label3: TLabel; Edt_SigISS_InscPrestador: TEdit; Bevel1: TBevel; Label7: TLabel; Edt_SigISS_CodigoServico: TEdit; Label8: TLabel; Btn_Sobre: TBitBtn; Cmb_SigISS_SituacaoNota: TComboBox; Edt_SigISS_AliqSimplesNacional: TEdit; Label9: TLabel; Label11: TLabel; Label12: TLabel; Bevel2: TBevel; Label13: TLabel; OpenFile: TOpenTextFileDialog; Mem_SigISS_DescricaoAtividade: TMemo; SaveText: TSaveTextFileDialog; TabSheet1: TTabSheet; Btn_Configuracoes: TBitBtn; procedure FormCreate(Sender: TObject); procedure Btn_ArquivoClick(Sender: TObject); procedure Btn_FecharClick(Sender: TObject); procedure Btn_SalvarArqMagClick(Sender: TObject); procedure Btn_SobreClick(Sender: TObject); procedure Cmb_SistemaChange(Sender: TObject); procedure Btn_ConfiguracoesClick(Sender: TObject); private ListaNotasExcelSigISS: TNotaExcelListaSigISS; ArqMag: TNFSe_ArqMagSigISS; procedure ConfigPageControl; procedure GerarArquivoMagnetico; procedure GerarArquivoMagnetico_SigISS; procedure ImportarDadosExcel; procedure ImportarDadosExcel_SigISS; procedure ValidarDados; procedure ValidarDados_SigISS; function SigISS_IndiceSitNotaToStr(Valor: Integer): String; function VerifTamArqGerado(Arquivo: String): Double; function IndiceToTipoSistema(Indice: Integer): TTipoSistema; procedure SaveConfig(Sistema: TTipoSistema); procedure ReadConfig(Sistema: TTipoSistema); public end; var FrmPrincipal: TFrmPrincipal; implementation {$R *.dfm} uses funcoes, UFrmAdvertencias, UFrmSobre; procedure TFrmPrincipal.Btn_ArquivoClick(Sender: TObject); begin if OpenFile.Execute then Edt_Arquivo.Text := OpenFile.FileName; end; procedure TFrmPrincipal.Btn_ConfiguracoesClick(Sender: TObject); begin // Configurações Application.MessageBox('Em Desenvolvimento. Aguarde', 'Informação', MB_ICONINFORMATION + MB_OK); end; procedure TFrmPrincipal.Btn_FecharClick(Sender: TObject); begin Close; end; procedure TFrmPrincipal.Btn_SalvarArqMagClick(Sender: TObject); begin if IndiceToTipoSistema(Cmb_Sistema.ItemIndex) = tsNaoSelecionado then begin if Cmb_Sistema.CanFocus then Cmb_Sistema.SetFocus; raise Exception.Create('Sistema não selecionado.'); end; if not(Length(Trim(Edt_Arquivo.Text)) > 0) or not(FileExists(Trim(Edt_Arquivo.Text))) then begin if Edt_Arquivo.CanFocus then Edt_Arquivo.SetFocus; raise Exception.Create('Arquivo do Excel não selecionado.'); end; if Application.MessageBox('Confirma a geração do arquivo magnético?', 'Confirmação', MB_ICONQUESTION + MB_YESNO) = IDNO then Exit; ImportarDadosExcel; ValidarDados; GerarArquivoMagnetico; end; procedure TFrmPrincipal.Btn_SobreClick(Sender: TObject); begin FrmSobre := TFrmSobre.Create(Self); FrmSobre.showmodal; FrmSobre.Free; end; procedure TFrmPrincipal.SaveConfig(Sistema: TTipoSistema); procedure SaveSigISS; begin with TIniFile.Create(ExtractFileDir(Application.ExeName) + '\config.ini') do begin WriteString('SigISS', 'Inscricao_Prestador', Trim(Edt_SigISS_InscPrestador.Text)); WriteInteger('SigISS', 'Codigo_Servico', StrToIntDef(Trim(Edt_SigISS_CodigoServico.Text), 0)); WriteFloat('SigISS', 'Aliq_Simples_Nacional', StrToFloatDef(Trim(Edt_SigISS_AliqSimplesNacional.Text), 0)); WriteInteger('SigISS', 'Indice_Situacao_Nota', Cmb_SigISS_SituacaoNota.ItemIndex); WriteString('SigISS', 'Descricao_Atividade', StringReplace(Trim(Mem_SigISS_DescricaoAtividade.Text), #13#10, ' ', [rfReplaceAll])); end; end; procedure SaveEL; begin // end; begin case Sistema of tsSigISS: SaveSigISS; tsEL: SaveEL; end; end; procedure TFrmPrincipal.ReadConfig(Sistema: TTipoSistema); procedure ReadSigISS; begin with TIniFile.Create(ExtractFileDir(Application.ExeName) + '\config.ini') do begin Edt_SigISS_InscPrestador.Text := Trim(ReadString('SigISS', 'Inscricao_Prestador', '')); Edt_SigISS_CodigoServico.Text := IntToStr(ReadInteger('SigISS', 'Codigo_Servico', 0)); Edt_SigISS_AliqSimplesNacional.Text := FloatToStr(ReadFloat('SigISS', 'Aliq_Simples_Nacional', 0)); Cmb_SigISS_SituacaoNota.ItemIndex := ReadInteger('SigISS', 'Indice_Situacao_Nota', -1); Mem_SigISS_DescricaoAtividade.Lines.Clear; if Trim(ReadString('SigISS', 'Descricao_Atividade', '')) <> '' then Mem_SigISS_DescricaoAtividade.Lines.Add(ReadString('SigISS', 'Descricao_Atividade', '')); end; end; procedure ReadEL; begin // end; begin with TIniFile.Create(ExtractFileDir(Application.ExeName) + '\config.ini') do begin case Sistema of tsSigISS: ReadSigISS; tsEL: ReadEL; end; end; end; procedure TFrmPrincipal.FormCreate(Sender: TObject); begin {$IFDEF DEBUG} Cmb_Sistema.ItemIndex := 0; Pc_Sistemas.ActivePageIndex := 0; Edt_Arquivo.Text := 'D:\valterpatrick\Desenvolvimento\Projetos\Desktop\Delphi\NFSe - AM\Win32\ArqTeste.xlsx'; Edt_SigISS_InscPrestador.Text := '657726'; Edt_SigISS_CodigoServico.Text := '802'; Edt_SigISS_AliqSimplesNacional.Text := '3,96'; Mem_SigISS_DescricaoAtividade.Lines.Add('Curso Pré Vestibular Extensivo Noturno'); {$ENDIF} ConfigPageControl; Cmb_SistemaChange(nil); Self.Enabled := True; end; procedure TFrmPrincipal.Cmb_SistemaChange(Sender: TObject); begin Pc_Sistemas.ActivePageIndex := IfThen(Cmb_Sistema.ItemIndex = -1, 0, Cmb_Sistema.ItemIndex); ReadConfig(IndiceToTipoSistema(Pc_Sistemas.ActivePageIndex)); end; procedure TFrmPrincipal.ConfigPageControl; begin Pc_Sistemas.MultiLine := False; Pc_Sistemas.Align := alNone; Pc_Sistemas.Left := -4; Pc_Sistemas.Top := Pc_Sistemas.Top - 26; Pc_Sistemas.Width := ClientWidth + 8; Pc_Sistemas.Height := ClientHeight - Pn_Top.Height - Pn_Bot.Height + 27; Cmb_Sistema.ItemIndex := 0; Pc_Sistemas.ActivePageIndex := IfThen(Cmb_Sistema.ItemIndex = -1, 0, Cmb_Sistema.ItemIndex); end; procedure TFrmPrincipal.ValidarDados_SigISS; var vAliq: Double; vCodServ: Integer; I: Integer; ListaAdvertenciasNotas: TStringList; procedure AddAdvertencia(Linha: Integer; Advertencia: String); begin ListaAdvertenciasNotas.Add('LINHA: ' + IntToStr(Linha) + ' - ADVERTÊNCIA: ' + Advertencia.Trim); end; begin ListaAdvertenciasNotas := TStringList.Create; vCodServ := StrToIntDef(Trim(Edt_SigISS_CodigoServico.Text), 0); vAliq := StrToFloatDef(Trim(Edt_SigISS_AliqSimplesNacional.Text), 0); if Trim(Edt_Arquivo.Text) = '' then begin if Edt_Arquivo.CanFocus then Edt_Arquivo.SetFocus; raise Exception.Create('Arquivo do Excel não informado.'); end; if Trim(Edt_SigISS_InscPrestador.Text) = '' then begin if Edt_SigISS_InscPrestador.CanFocus then Edt_SigISS_InscPrestador.SetFocus; raise Exception.Create('Inscrição do prestador do serviço não informada.'); end; if Length(Trim(Edt_SigISS_InscPrestador.Text)) > 15 then begin if Edt_SigISS_InscPrestador.CanFocus then Edt_SigISS_InscPrestador.SetFocus; raise Exception.Create('Inscrição do prestador maior que o permitido [15 caracteres].'); end; if (Trim(Edt_SigISS_CodigoServico.Text) = '') or (Length(Trim(Edt_SigISS_CodigoServico.Text)) > 7) or (vCodServ <= 0) then begin if Edt_SigISS_CodigoServico.CanFocus then Edt_SigISS_CodigoServico.SetFocus; raise Exception.Create('Código do serviço padrão não informado, inválido ou maior que o permitido [7 digitos].'); end; if (Trim(Edt_SigISS_AliqSimplesNacional.Text) = '') or (vAliq < 0) then begin if Edt_SigISS_AliqSimplesNacional.CanFocus then Edt_SigISS_AliqSimplesNacional.SetFocus; raise Exception.Create('Alíquota Simples Nacional padrão não informada ou inválida.'); end; if vAliq = 0 then Application.MessageBox('A alíquota Simples Nacional padrão está zerada.', 'Aviso', MB_ICONWARNING + MB_OK); if Cmb_SigISS_SituacaoNota.ItemIndex = -1 then begin if Cmb_SigISS_SituacaoNota.CanFocus then Cmb_SigISS_SituacaoNota.SetFocus; raise Exception.Create('Situação da nota padrão não selecionada'); end; if Mem_SigISS_DescricaoAtividade.GetTextLen = 0 then begin if Mem_SigISS_DescricaoAtividade.CanFocus then Mem_SigISS_DescricaoAtividade.SetFocus; raise Exception.Create('Descrição da Atividade não informada.'); end; for I := 0 to ListaNotasExcelSigISS.Count - 1 do begin ListaNotasExcelSigISS.Items[I].A_CPFCNPJ := SomenteNumeros(ListaNotasExcelSigISS.Items[I].A_CPFCNPJ); if not Length(ListaNotasExcelSigISS.Items[I].A_CPFCNPJ) in [11, 14] then AddAdvertencia(I + 2, '"A - CPF/CNPJ" inválido.'); if (StrToFloatDef(ListaNotasExcelSigISS.Items[I].B_ValorServico, 0) <= 0) then AddAdvertencia(I + 2, '"B - Valor do Serviço" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].C_Email) > 0) and (Pos('@', ListaNotasExcelSigISS.Items[I].C_Email) <= 0) then AddAdvertencia(I + 2, '"C - Email" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].D_CodigoServico) > 0) then begin if (StrToIntDef(ListaNotasExcelSigISS.Items[I].D_CodigoServico, 0) <= 0) then AddAdvertencia(I + 2, '"D - Código do Serviço" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].D_CodigoServico) > 7) then AddAdvertencia(I + 2, '"D - Código do Serviço" maior que o permitido [7 caracteres].'); end; if (Length(ListaNotasExcelSigISS.Items[I].E_AliqSimplesNacional) > 0) and (StrToFloatDef(ListaNotasExcelSigISS.Items[I].E_AliqSimplesNacional, 0) <= 0) then AddAdvertencia(I + 2, '"E - Alíquota Simples Nacional" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].F_SituacaoNotaFiscal) > 0) then begin if (Length(ListaNotasExcelSigISS.Items[I].F_SituacaoNotaFiscal) > 1) then AddAdvertencia(I + 2, '"F - Situação da Nota Fiscal" maior que o permitido [1 caracter].'); if (StrInSet(ListaNotasExcelSigISS.Items[I].F_SituacaoNotaFiscal, ['T', 'R', 'C', 'I', 'N', 'U'])) then AddAdvertencia(I + 2, '"F - Situação da Nota Fiscal" inválido, o valor tem de estar entre os valores [T, R, C, I, N, U].'); end; if (Length(ListaNotasExcelSigISS.Items[I].G_ValorRetencaoISS) > 0) and (StrToFloatDef(ListaNotasExcelSigISS.Items[I].G_ValorRetencaoISS, 0) < 0) then AddAdvertencia(I + 2, '"G - Valor Retenção ISS" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].H_ValorRetencaoINSS) > 0) and (StrToFloatDef(ListaNotasExcelSigISS.Items[I].H_ValorRetencaoINSS, 0) < 0) then AddAdvertencia(I + 2, '"H - Valor Retenção INSS" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].I_ValorRetencaoCOFINS) > 0) and (StrToFloatDef(ListaNotasExcelSigISS.Items[I].I_ValorRetencaoCOFINS, 0) < 0) then AddAdvertencia(I + 2, '"I - Valor Retenção COFINS" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].J_ValorRetencaoPIS) > 0) and (StrToFloatDef(ListaNotasExcelSigISS.Items[I].J_ValorRetencaoPIS, 0) < 0) then AddAdvertencia(I + 2, '"J - Valor Retenção PIS" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].K_ValorRetencaoIR) > 0) and (StrToFloatDef(ListaNotasExcelSigISS.Items[I].K_ValorRetencaoIR, 0) < 0) then AddAdvertencia(I + 2, '"K - Valor Retenção IR" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].L_ValorRetencaoCSLL) > 0) and (StrToFloatDef(ListaNotasExcelSigISS.Items[I].L_ValorRetencaoCSLL, 0) < 0) then AddAdvertencia(I + 2, '"L - Valor Retenção CSLL" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].M_ValorAproximadoTributos) > 0) and (StrToFloatDef(ListaNotasExcelSigISS.Items[I].M_ValorAproximadoTributos, 0) < 0) then AddAdvertencia(I + 2, '"M - Valor Aproximado dos Tributos" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].N_IdentificadorSistema_Legado) > 12) then AddAdvertencia(I + 2, '"N - Identificador Sistema Legado" maior que o permitido [12 caracteres].'); if (Length(ListaNotasExcelSigISS.Items[I].O_InscricaoMunicipalTomador) > 15) then AddAdvertencia(I + 2, '"O - Inscrição Municipal Tomador" maior que o permitido [15 caracteres].'); if (Length(ListaNotasExcelSigISS.Items[I].P_InscricaoEstadualTomador) > 15) then AddAdvertencia(I + 2, '"P - Inscrição Estadual Tomador" maior que o permitido [15 caracteres].'); if (Length(ListaNotasExcelSigISS.Items[I].Q_NomeTomador) > 100) then AddAdvertencia(I + 2, '"Q - Nome/Razão Social do Tomador" maior que o permitido [100 caracteres].'); if (Length(ListaNotasExcelSigISS.Items[I].R_EnderecoTomador) > 50) then AddAdvertencia(I + 2, '"R - Endereço do Tomador" maior que o permitido [50 caracteres].'); if (Length(ListaNotasExcelSigISS.Items[I].S_NumeroEndereco) > 10) then AddAdvertencia(I + 2, '"S - Número do Endereço do Tomador" maior que o permitido [10 caracteres].'); if (Length(ListaNotasExcelSigISS.Items[I].T_ComplementoEndereco) > 30) then AddAdvertencia(I + 2, '"T - Complemento do Endereço do Tomador" maior que o permitido [30 caracteres].'); if (Length(ListaNotasExcelSigISS.Items[I].U_BairroTomador) > 30) then AddAdvertencia(I + 2, '"U - Bairro do Tomador" maior que o permitido [30 caracteres].'); if (Length(ListaNotasExcelSigISS.Items[I].V_CodCidadeTomador) > 0) then begin if (StrToIntDef(ListaNotasExcelSigISS.Items[I].V_CodCidadeTomador, 0) < 0) then AddAdvertencia(I + 2, '"V - Código da Cidade do Tomador" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].V_CodCidadeTomador) > 7) then AddAdvertencia(I + 2, '"V - Código da Cidade do Tomador" maior que o permitido [7 caracteres].'); end; if (Length(ListaNotasExcelSigISS.Items[I].W_UnidadeFederalTomador) > 0) then begin if (Length(ListaNotasExcelSigISS.Items[I].W_UnidadeFederalTomador) > 2) then AddAdvertencia(I + 2, '"W - Unidade Federal do Tomador" maior que o permitido [2 caracteres].'); if IsNumber(ListaNotasExcelSigISS.Items[I].W_UnidadeFederalTomador) or TemCaracteresEspeciais(ListaNotasExcelSigISS.Items[I].W_UnidadeFederalTomador) then AddAdvertencia(I + 2, '"W - Unidade Federal do Tomador" inválido.'); end; ListaNotasExcelSigISS.Items[I].X_CEPTomador := SomenteNumeros(ListaNotasExcelSigISS.Items[I].X_CEPTomador); if (Length(ListaNotasExcelSigISS.Items[I].X_CEPTomador) > 0) and (Length(ListaNotasExcelSigISS.Items[I].X_CEPTomador) <> 8) then AddAdvertencia(I + 2, '"X - CEP do Tomador" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].Y_CodCidPrestServ) > 0) then begin if (StrToIntDef(ListaNotasExcelSigISS.Items[I].Y_CodCidPrestServ, 0) <= 0) then AddAdvertencia(I + 2, '"Y - Código da Cidade do Local de Prestação de Serviço" inválido.'); if (Length(ListaNotasExcelSigISS.Items[I].Y_CodCidPrestServ) > 7) then AddAdvertencia(I + 2, '"Y - Código da Cidade do Local de Prestação de Serviço" maior que o permitido [7 caracteres].'); end; if (Length(ListaNotasExcelSigISS.Items[I].Z_DesricaoServico) > 0) and (Length(ListaNotasExcelSigISS.Items[I].Z_DesricaoServico) > 1000) then AddAdvertencia(I + 2, '"Z - Descrição do Serviço" maior que o permitido [1000 caracteres].'); end; if ListaAdvertenciasNotas.Count > 0 then begin FrmAdvertencias := TFrmAdvertencias.Create(Self, 'Advertências', ListaAdvertenciasNotas); FrmAdvertencias.showmodal; FrmAdvertencias.Free; Abort; end; end; procedure TFrmPrincipal.ValidarDados; begin if IndiceToTipoSistema(Cmb_Sistema.ItemIndex) = tsSigISS then ValidarDados_SigISS; end; procedure TFrmPrincipal.ImportarDadosExcel; begin if IndiceToTipoSistema(Cmb_Sistema.ItemIndex) = tsSigISS then ImportarDadosExcel_SigISS; end; procedure TFrmPrincipal.ImportarDadosExcel_SigISS; var ArqExcel: String; Excel: OleVariant; Linha: Integer; begin ArqExcel := Edt_Arquivo.Text; try // Cria o Objeto Excel Excel := CreateOleObject('Excel.Application'); // Esconde o Excel Excel.Visible := False; // Abre o Workbook Excel.WorkBooks.Open(ArqExcel); // Abre a primeira aba Excel.WorkSheets[1].Activate; except ShowMessage('Ocorreu um erro ao abrir o arquivo.'); end; // Realiza a leitura do arquivo, começando da segunda linha, já que a primeira é o cabeçalho Linha := 2; if Assigned(ListaNotasExcelSigISS) then ListaNotasExcelSigISS.Destroy; ListaNotasExcelSigISS := TNotaExcelListaSigISS.Create; try while VarToStrDef(Excel.Cells[Linha, 1].Value, '') <> '' do begin with ListaNotasExcelSigISS.New do begin A_CPFCNPJ := StringReplace(Trim(Excel.Cells[Linha, 1]), #13#10, ' ', [rfReplaceAll]); B_ValorServico := StringReplace(Trim(Excel.Cells[Linha, 2]), #13#10, ' ', [rfReplaceAll]); C_Email := StringReplace(Trim(Excel.Cells[Linha, 3]), #13#10, ' ', [rfReplaceAll]); D_CodigoServico := StringReplace(Trim(Excel.Cells[Linha, 4]), #13#10, ' ', [rfReplaceAll]); E_AliqSimplesNacional := StringReplace(Trim(Excel.Cells[Linha, 5]), #13#10, ' ', [rfReplaceAll]); F_SituacaoNotaFiscal := StringReplace(Trim(Excel.Cells[Linha, 6]), #13#10, ' ', [rfReplaceAll]); G_ValorRetencaoISS := StringReplace(Trim(Excel.Cells[Linha, 7]), #13#10, ' ', [rfReplaceAll]); H_ValorRetencaoINSS := StringReplace(Trim(Excel.Cells[Linha, 8]), #13#10, ' ', [rfReplaceAll]); I_ValorRetencaoCOFINS := StringReplace(Trim(Excel.Cells[Linha, 9]), #13#10, ' ', [rfReplaceAll]); J_ValorRetencaoPIS := StringReplace(Trim(Excel.Cells[Linha, 10]), #13#10, ' ', [rfReplaceAll]); K_ValorRetencaoIR := StringReplace(Trim(Excel.Cells[Linha, 11]), #13#10, ' ', [rfReplaceAll]); L_ValorRetencaoCSLL := StringReplace(Trim(Excel.Cells[Linha, 12]), #13#10, ' ', [rfReplaceAll]); M_ValorAproximadoTributos := StringReplace(Trim(Excel.Cells[Linha, 13]), #13#10, ' ', [rfReplaceAll]); N_IdentificadorSistema_Legado := StringReplace(Trim(Excel.Cells[Linha, 14]), #13#10, ' ', [rfReplaceAll]); O_InscricaoMunicipalTomador := StringReplace(Trim(Excel.Cells[Linha, 15]), #13#10, ' ', [rfReplaceAll]); P_InscricaoEstadualTomador := StringReplace(Trim(Excel.Cells[Linha, 16]), #13#10, ' ', [rfReplaceAll]); Q_NomeTomador := StringReplace(Trim(Excel.Cells[Linha, 17]), #13#10, ' ', [rfReplaceAll]); R_EnderecoTomador := StringReplace(Trim(Excel.Cells[Linha, 18]), #13#10, ' ', [rfReplaceAll]); S_NumeroEndereco := StringReplace(Trim(Excel.Cells[Linha, 19]), #13#10, ' ', [rfReplaceAll]); T_ComplementoEndereco := StringReplace(Trim(Excel.Cells[Linha, 20]), #13#10, ' ', [rfReplaceAll]); U_BairroTomador := StringReplace(Trim(Excel.Cells[Linha, 21]), #13#10, ' ', [rfReplaceAll]); V_CodCidadeTomador := StringReplace(Trim(Excel.Cells[Linha, 22]), #13#10, ' ', [rfReplaceAll]); W_UnidadeFederalTomador := StringReplace(Trim(Excel.Cells[Linha, 23]), #13#10, ' ', [rfReplaceAll]); X_CEPTomador := StringReplace(Trim(Excel.Cells[Linha, 24]), #13#10, ' ', [rfReplaceAll]); Y_CodCidPrestServ := StringReplace(Trim(Excel.Cells[Linha, 25]), #13#10, ' ', [rfReplaceAll]); Z_DesricaoServico := StringReplace(Trim(Excel.Cells[Linha, 26]), #13#10, ' ', [rfReplaceAll]); end; Linha := Linha + 1; end; if Linha = 2 then Application.MessageBox('Não foram encontrados dados na planilha', 'Aviso', MB_ICONWARNING + MB_OK); finally // Fecha o Excel if not VarIsEmpty(Excel) then begin Excel.Quit; Excel := Unassigned; end; end; end; function TFrmPrincipal.SigISS_IndiceSitNotaToStr(Valor: Integer): String; begin case Valor of 0: Result := 'T'; // Tributada 1: Result := 'R'; // Retida 2: Result := 'C'; // Cancelada 3: Result := 'I'; // Isenta 4: Result := 'N'; // Não Tributada 5: Result := 'U'; // Imune end; end; function TFrmPrincipal.IndiceToTipoSistema(Indice: Integer): TTipoSistema; begin case Indice of 0: Result := tsSigISS; 1: Result := tsEL; else Result := tsNaoSelecionado; end; end; procedure TFrmPrincipal.GerarArquivoMagnetico; begin if IndiceToTipoSistema(Cmb_Sistema.ItemIndex) = tsSigISS then begin GerarArquivoMagnetico_SigISS; SaveConfig(tsSigISS); end; end; procedure TFrmPrincipal.GerarArquivoMagnetico_SigISS; var I: Integer; vTamArq: Double; begin ArqMag := TNFSe_ArqMagSigISS.Create; Self.Enabled := False; try ArqMag.CabTipoRegistro := '1'; ArqMag.CabTipoArquivo := 'NFE_LOTE'; ArqMag.CabInscPrestador := Trim(Edt_SigISS_InscPrestador.Text); ArqMag.CabVersaoArquivo := '030'; ArqMag.CabDataArquivo := Date; ArqMag.ListaNotas := TNotaFiscalListaSigISS.Create; for I := 0 to ListaNotasExcelSigISS.Count - 1 do begin with ArqMag.ListaNotas.New do begin DetTipoRegistro := '2'; DetIdentSistema := ListaNotasExcelSigISS[I].N_IdentificadorSistema_Legado; DetTipoCodificacao := 1; DetCodServico := IfThen(StrToIntDef(ListaNotasExcelSigISS[I].D_CodigoServico, 0) = 0, StrToIntDef(Trim(Edt_SigISS_CodigoServico.Text), 0), StrToIntDef(ListaNotasExcelSigISS[I].D_CodigoServico, 0)); if Length(Trim(ListaNotasExcelSigISS[I].F_SituacaoNotaFiscal)) = 0 then DetSitNota := ArqMag.ListaNotas.StrToSituacaoNota(SigISS_IndiceSitNotaToStr(Cmb_SigISS_SituacaoNota.ItemIndex)) else DetSitNota := ArqMag.ListaNotas.StrToSituacaoNota(Trim(ListaNotasExcelSigISS[I].F_SituacaoNotaFiscal)); DetValorServico := StrToFloatDef(ListaNotasExcelSigISS[I].B_ValorServico, 0); DetValorBaseServico := DetValorServico; DetAliqSimplesNacional := IfThen(StrToFloatDef(ListaNotasExcelSigISS[I].E_AliqSimplesNacional, 0) = 0, StrToFloatDef(Trim(Edt_SigISS_AliqSimplesNacional.Text), 0), StrToFloatDef(ListaNotasExcelSigISS[I].E_AliqSimplesNacional, 0)); DetValorRetencaoISS := StrToFloatDef(ListaNotasExcelSigISS[I].G_ValorRetencaoISS, 0); DetValorRetencaoINSS := StrToFloatDef(ListaNotasExcelSigISS[I].H_ValorRetencaoINSS, 0); DetValorRetencaoCOFINS := StrToFloatDef(ListaNotasExcelSigISS[I].I_ValorRetencaoCOFINS, 0); DetValorRetencaoPIS := StrToFloatDef(ListaNotasExcelSigISS[I].J_ValorRetencaoPIS, 0); DetValorRetencaoIR := StrToFloatDef(ListaNotasExcelSigISS[I].K_ValorRetencaoIR, 0); DetValorRetencaoCSLL := StrToFloatDef(ListaNotasExcelSigISS[I].L_ValorRetencaoCSLL, 0); DetValorAproximadoTributos := StrToFloatDef(ListaNotasExcelSigISS[I].M_ValorAproximadoTributos, 0); DetTomadorCPF_CNPJ := ListaNotasExcelSigISS[I].A_CPFCNPJ; DetTomadorInscMunicipal := ListaNotasExcelSigISS[I].O_InscricaoMunicipalTomador; DetTomadorInscEstadual := ListaNotasExcelSigISS[I].P_InscricaoEstadualTomador; DetTomadorNome := ListaNotasExcelSigISS[I].Q_NomeTomador; DetTomadorEndLogradouro := ListaNotasExcelSigISS[I].R_EnderecoTomador; DetTomadorEndNumero := ListaNotasExcelSigISS[I].S_NumeroEndereco; DetTomadorEndComplemento := ListaNotasExcelSigISS[I].T_ComplementoEndereco; DetTomadorEndBairro := ListaNotasExcelSigISS[I].U_BairroTomador; DetTomadorEndCodCidade := StrToIntDef(ListaNotasExcelSigISS[I].V_CodCidadeTomador, 0); DetTomadorEndUF := ListaNotasExcelSigISS[I].W_UnidadeFederalTomador; DetTomadorEndCEP := ListaNotasExcelSigISS[I].X_CEPTomador; DetTomadorEmail := ListaNotasExcelSigISS[I].C_Email; DetCodCidadePrestServ := StrToIntDef(ListaNotasExcelSigISS[I].Y_CodCidPrestServ, 0); DetDescriminacaoServ := IfThen(Length(ListaNotasExcelSigISS[I].Z_DesricaoServico) > 0, ListaNotasExcelSigISS[I].Z_DesricaoServico, StringReplace(Trim(Mem_SigISS_DescricaoAtividade.Text), #13#10, ' ', [rfReplaceAll])); end; end; ArqMag.RodTipoRegistro := '9'; if SaveText.Execute then begin ArqMag.SaveToFile(SaveText.FileName); vTamArq := VerifTamArqGerado(SaveText.FileName); Application.MessageBox(PWideChar('Arquivo gerado com sucesso em "' + SaveText.FileName + '".' // + IfThen(vTamArq >= 4.99, ' Arquivos com tamanho igual ou superior a 5MB serão ignorados. Tamanho do arquivo: ' + FloatToStr(vTamArq) + 'MB.', '')), 'Informação', MB_ICONINFORMATION + MB_OK); end; finally Self.Enabled := True; ArqMag.ListaNotas.Destroy; ArqMag.Destroy; end; end; function TFrmPrincipal.VerifTamArqGerado(Arquivo: String): Double; begin with TFileStream.Create(Arquivo, fmOpenRead or fmShareExclusive) do begin try Result := Size; // Valor retornado em Bytes Result := (Result / 1024) / 1024; // Tem que dividir duas vezes para chegar em MB finally Free; end; end; end; end.
unit AGraficoAnaliseCidade; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, StdCtrls, Buttons, Componentes1, ExtCtrls, PainelGradiente, Localizacao, ComCtrls, Graficos; type TFGraficoAnaliseCidade = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; BGerar: TBitBtn; BFechar: TBitBtn; EDatInicio: TCalendario; EDatFim: TCalendario; Label1: TLabel; Label2: TLabel; Localiza: TConsultaPadrao; CAgruparpor: TRadioGroup; Label4: TLabel; PCidade: TPanelColor; Label3: TLabel; ECidade: TEditLocaliza; LCidade: TLabel; SpeedButton2: TSpeedButton; PVendedor: TPanelColor; EVendedor: TEditLocaliza; Label11: TLabel; SpeedButton4: TSpeedButton; LNomVendedor: TLabel; Label24: TLabel; SpeedButton5: TSpeedButton; LFilial: TLabel; EFilial: TEditLocaliza; GraficosTrio: TGraficosTrio; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BFecharClick(Sender: TObject); procedure BGerarClick(Sender: TObject); private { Private declarations } procedure MostraPanel(VpaTipoGrafico : Integer); procedure GeraGraficoCidade; procedure GeraGraficoVendedor; public { Public declarations } procedure GraficoCidade; procedure GraficoVendedor; end; var FGraficoAnaliseCidade: TFGraficoAnaliseCidade; implementation uses APrincipal, funData, FunSql, ConstMsg, Constantes; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFGraficoAnaliseCidade.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } CAgruparpor.ItemIndex := 1; EDatInicio.DateTime := decmes(PrimeiroDiaMes(Date),3); EDatFim.Datetime := UltimoDiaMes(Date); end; { ******************* Quando o formulario e fechado ************************** } procedure TFGraficoAnaliseCidade.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFGraficoAnaliseCidade.GraficoCidade; begin MostraPanel(1); showmodal; end; {******************************************************************************} procedure TFGraficoAnaliseCidade.GraficoVendedor; begin MostraPanel(2); Showmodal; end; {******************************************************************************} procedure TFGraficoAnaliseCidade.BFecharClick(Sender: TObject); begin close; end; {******************************************************************************} procedure TFGraficoAnaliseCidade.BGerarClick(Sender: TObject); begin if PCidade.Visible then GeraGraficoCidade else if PVendedor.Visible then GeraGraficoVendedor; end; {******************************************************************************} procedure TFGraficoAnaliseCidade.MostraPanel(VpaTipoGrafico : Integer); begin PCidade.Visible := false; PVendedor.Visible := false; case VpaTipoGrafico of 1 : begin PCidade.visible := true; PainelGradiente1.Caption := ' Análise Cidade '; Caption := 'Análise Cidade'; end; 2 : begin PVendedor.visible := true; PainelGradiente1.Caption := ' Análise Vendedor '; Caption := 'Análise Vendedor'; end; end; end; {******************************************************************************} procedure TFGraficoAnaliseCidade.GeraGraficoCidade; begin if ECidade.Text = '' then aviso('CIDADE INVÁLIDA!!!'#13'Para gerar o gráfico é necessário escolher a cidade') else begin case CAgruparpor.ItemIndex of 0 : graficostrio.info.ComandoSQL := 'Select Sum(Orc.N_Vlr_LIQ) Valor, Orc.D_DAT_ORC DATA1, Orc.D_DAT_ORC DATA '; 1 : graficostrio.info.ComandoSQL := 'Select Sum(Orc.N_Vlr_LIQ) Valor, ('+SQLTextoAno('orc.d_dat_orc')+' *100)+'+SQLTextoMes('orc.d_dat_orc')+' DATA1, '+SQLTextoMes('Orc.D_DAT_ORC')+'||''/''||'+ SQLTextoAno('ORC.D_DAT_ORC')+' DATA '; 2 : graficostrio.info.ComandoSQL := 'Select Sum(Orc.N_Vlr_LIQ) Valor, '+SQLTextoAno('ORC.D_DAT_ORC')+' DATA1,'+SQLTextoAno('ORC.D_DAT_ORC')+' DATA '; end; graficostrio.info.ComandoSQL := graficostrio.info.ComandoSQL + ' from CadOrcamentos Orc, '+ ' CadClientes Cli '+ ' Where Orc.I_Emp_Fil = ' + IntToStr(Varia.CodigoEmpFil)+ ' '+SQLTextoDataEntreAAAAMMDD('D_DAT_ORC', EDatInicio.Datetime,EDatFim.Datetime,true) + ' and ORC.I_COD_CLI = CLI.I_COD_CLI '+ ' AND CLI.C_CID_CLI = '''+LCidade.Caption+''''; case CAgruparpor.ItemIndex of 0 : graficostrio.info.ComandoSQL := graficostrio.info.ComandoSQL +' group by orc.d_dat_orc'; 1 : graficostrio.info.ComandoSQL := graficostrio.info.ComandoSQL +' group by ('+SQLTextoAno('orc.d_dat_orc')+' *100)+'+SQLTextoMes('orc.d_dat_orc')+', '+SQLTextoMes('Orc.D_DAT_ORC')+'||''/''||'+ SQLTextoAno('ORC.D_DAT_ORC'); 2 : graficostrio.info.ComandoSQL := graficostrio.info.ComandoSQL +' group by '+SQLTextoAno('orc.d_dat_orc'); end; graficostrio.info.ComandoSQL := graficostrio.info.ComandoSQL +' order by 2'; // aviso(GraficosTrio.info.ComandoSQL); graficostrio.info.CampoValor := 'Valor'; graficostrio.info.TituloY := 'Valor'; graficostrio.info.CampoRotulo := 'DATA'; graficostrio.info.TituloGrafico := 'Analise de Cidades - ' + LCidade.Caption; graficostrio.info.RodapeGrafico := ' Análise da Cidade - '+ varia.NomeFilial; graficostrio.info.TituloFormulario := ' Análise da Cidade '+ LCidade.Caption; graficostrio.info.TituloX := 'Datas'; graficostrio.execute; end; end; {******************************************************************************} procedure TFGraficoAnaliseCidade.GeraGraficoVendedor; begin if EVendedor.AInteiro = 0 then aviso('VENDEDOR INVÁLIDO!!!'#13'Para gerar o gráfico é necessário escolher o vendedor') else begin case CAgruparpor.ItemIndex of 0 : graficostrio.info.ComandoSQL := 'Select Sum(Orc.N_Vlr_LIQ) Valor, Orc.D_DAT_ORC DATA1, Orc.D_DAT_ORC DATA '; 1 : graficostrio.info.ComandoSQL := 'Select Sum(Orc.N_Vlr_LIQ) Valor, ('+SQLTextoAno('orc.d_dat_orc')+' *100)+ '+SQLTextoMes('orc.d_dat_orc')+' DATA1, '+SQLTextoMes('Orc.D_DAT_ORC')+' ||''/''|| '+SQLTextoAno('ORC.D_DAT_ORC')+' DATA '; 2 : graficostrio.info.ComandoSQL := 'Select Sum(Orc.N_Vlr_LIQ) Valor,'+SQLTextoAno('ORC.D_DAT_ORC')+' DATA1, '+SQLTextoAno('ORC.D_DAT_ORC')+' DATA '; end; graficostrio.info.ComandoSQL := graficostrio.info.ComandoSQL + ' from CadOrcamentos Orc '+ ' Where ORC.I_COD_VEN = '+ EVendedor.Text + ' '+SQLTextoDataEntreAAAAMMDD('D_DAT_ORC', EDatInicio.Datetime,EDatFim.Datetime,true) ; if EFilial.AInteiro <> 0 then graficostrio.info.ComandoSQL := graficostrio.info.ComandoSQL + 'and Orc.I_Emp_Fil = ' + EFilial.Text; case CAgruparpor.ItemIndex of 0 : graficostrio.info.ComandoSQL := graficostrio.info.ComandoSQL+ 'group by Orc.D_DAT_ORC DATA1, Orc.D_DAT_ORC DATA '; 1 : graficostrio.info.ComandoSQL := graficostrio.info.ComandoSQL+ 'group by ('+SQLTextoAno('orc.d_dat_orc')+' *100)+ '+SQLTextoMes('orc.d_dat_orc')+', '+SQLTextoMes('Orc.D_DAT_ORC')+' ||''/''|| '+SQLTextoAno('ORC.D_DAT_ORC'); 2 : graficostrio.info.ComandoSQL := graficostrio.info.ComandoSQL+ 'group by '+SQLTextoAno('ORC.D_DAT_ORC')+', '+SQLTextoAno('ORC.D_DAT_ORC'); end; graficostrio.info.ComandoSQL := graficostrio.info.ComandoSQL + ' order by 2'; graficostrio.info.CampoValor := 'Valor'; graficostrio.info.TituloY := 'Valor'; graficostrio.info.CampoRotulo := 'DATA'; graficostrio.info.TituloGrafico := 'Analise do Vendedor - ' + LNomVendedor.Caption; graficostrio.info.RodapeGrafico := ' Análise do Vendedor - '+ varia.NomeFilial; graficostrio.info.TituloFormulario := ' Análise do vendedor '+ LCidade.Caption; graficostrio.info.TituloX := 'Datas'; graficostrio.execute; end; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFGraficoAnaliseCidade]); end.
unit texture2raycast; {$IFDEF FPC}{$mode objfpc}{$H+}{$ENDIF} interface {$include opts.inc} uses {$IFDEF DGL} dglOpenGL, {$ELSE DGL} {$IFDEF COREGL}gl_core_matrix, glcorearb, {$ELSE} gl,glext, {$ENDIF} {$ENDIF DGL} {$IFNDEF FPC} Windows, {$ENDIF} raycast_common, {$IFDEF COREGL} raycast_core, {$ELSE} raycast_legacy, {$ENDIF} {$IFDEF USETRANSFERTEXTURE}texture_3d_unit_transfertexture, {$ELSE} texture_3d_unit,{$ENDIF} shaderu, clut,dialogs,Classes,define_types, sysUtils; procedure CreateGradientVolume (var Tex: TTexture; var gradientVolume : GLuint; var inRGBA : Bytep0; isOverlay: boolean); procedure CreateVolumeGL (var Tex: TTexture; var volumeID : GLuint; ptr: PChar); Procedure LoadTTexture(var Tex: TTexture); function CheckTextureMemory (var Tex: TTexture; isRGBA: boolean): boolean; implementation uses {$IFDEF FPC} LCLIntf,{$ENDIF} //{$IFDEF ENABLEOVERLAY}overlay, {$ENDIF} mainunit; type TRGBA = packed record //Next: analyze Format Header structure R,G,B,A : byte; end; tVolB = array of byte; tVolW = array of word; tVolS = array of single; tVolRGBA = array of TRGBA;//longword; const kRGBAclear : TRGBA = (r: 0; g: 0; b: 0; a:0); {$DEFINE GRADIENT_PRENORM} //pre-normalizing our data allows us to avoids the "normalize" in GLSL // gradientSample.rgb = normalize(gradientSample.rgb*2.0 - 1.0); //it is a bit slower and does provide a bit less precision //in 2017 we switched to the pre-norm so that the CPU and GLSL gradients match each other {$IFDEF GRADIENT_PRENORM} Function XYZIx (X1,X2,Y1,Y2,Z1,Z2: single): TRGBA; //input voxel intensity to the left,right,anterior,posterior,inferior,superior and center // Output RGBA image where values correspond to X,Y,Z gradients and ImageIntensity var X,Y,Z,Dx: single; begin Result := kRGBAclear; X := X1-X2; Y := Y1-Y2; Z := Z1-Z2; Dx := sqrt(X*X+Y*Y+Z*Z); if Dx = 0 then exit; //no gradient - set intensity to zero. result.r :=round((X/(Dx*2)+0.5)*255); result.g :=round((Y/(Dx*2)+0.5)*255); result.B := round((Z/(Dx*2)+0.5)*255); end; {$ELSE GRADIENT_PRENORM} Function XYZIx (X1,X2,Y1,Y2,Z1,Z2: single): TRGBA; {$IFDEF FPC} inline; {$ENDIF} //faster, more precise version of XYZI for computation, but requires "normalize" for display var X,Y,Z,Dx: single; begin Result := kRGBAclear; X := X1-X2; Y := Y1-Y2; Z := Z1-Z2; Dx := abs(X); if abs(Y) > Dx then Dx := abs(Y); if abs(Z) > Dx then Dx := abs(Z); if Dx = 0 then exit; //no gradient - set intensity to zero. Calculate_Transfer_Function Dx := Dx * 2; //scale vector lengths from 0..0.5, so we can pack -1..+1 in the range 0..255 result.r :=round((X/Dx+0.5)*255); //X result.g :=round((Y/Dx+0.5)*255); //Y result.B := round((Z/Dx+0.5)*255); //Z end; {$ENDIF GRADIENT_PRENORM} {$DEFINE SOBEL} {$IFDEF SOBEL} //use SOBEL function estimateGradients (rawData: tVolB; Xsz,Ysz, I : integer; var GradMag: single): TRGBA; {$IFDEF FPC} inline; {$ENDIF} //this computes intensity gradients using 3D Sobel filter. //This is slower than central difference but more accurate //http://www.aravind.ca/cs788h_Final_Project/gradient_estimators.htm var Y,Z,J: integer; Xp,Xm,Yp,Ym,Zp,Zm: single; begin Y := XSz; //each row is X voxels Z := YSz*XSz; //each plane is X*Y voxels //X:: cols: +Z +0 -Z, rows -Y +0 +Y J := I+1; Xp := rawData[J-Y+Z]+3*rawData[J-Y]+rawData[J-Y-Z] +3*rawData[J+Z]+6*rawData[J]+3*rawData[J-Z] +rawData[J+Y+Z]+3*rawData[J+Y]+rawData[J+Y-Z]; J := I-1; Xm := rawData[J-Y+Z]+3*rawData[J-Y]+rawData[J-Y-Z] +3*rawData[J+Z]+6*rawData[J]+3*rawData[J-Z] +rawData[J+Y+Z]+3*rawData[J+Y]+rawData[J+Y-Z]; //Y:: cols: +Z +0 -Z, rows -X +0 +X J := I+Y; Yp := rawData[J-1+Z]+3*rawData[J-1]+rawData[J-1-Z] +3*rawData[J+Z]+6*rawData[J]+3*rawData[J-Z] +rawData[J+1+Z]+3*rawData[J+1]+rawData[J+1-Z]; J := I-Y; Ym := rawData[J-1+Z]+3*rawData[J-1]+rawData[J-1-Z] +3*rawData[J+Z]+6*rawData[J]+3*rawData[J-Z] +rawData[J+1+Z]+3*rawData[J+1]+rawData[J+1-Z]; //Z:: cols: +Z +0 -Z, rows -X +0 +X J := I+Z; Zp := rawData[J-Y+1]+3*rawData[J-Y]+rawData[J-Y-1] +3*rawData[J+1]+6*rawData[J]+3*rawData[J-1] +rawData[J+Y+1]+3*rawData[J+Y]+rawData[J+Y-1]; J := I-Z; Zm := rawData[J-Y+1]+3*rawData[J-Y]+rawData[J-Y-1] +3*rawData[J+1]+6*rawData[J]+3*rawData[J-1] +rawData[J+Y+1]+3*rawData[J+Y]+rawData[J+Y-1]; result := XYZIx (Xm,Xp,Ym,Yp,Zm,Zp); GradMag := sqrt( sqr(Xm-Xp)+sqr(Ym-Yp)+sqr(Zm-Zp));//gradient magnitude //GradMag := abs( Xm-Xp)+abs(Ym-Yp)+abs(Zm-Zp);//gradient magnitude end; {$ELSE} //if SOBEL else Central difference function estimateGradients (rawData: tVolB; Xsz,Ysz, I : integer; var GradMag: single): TRGBA; inline; //slightly faster than Sobel var Y,Z: integer; Xp,Xm,Yp,Ym,Zp,Zm: single; begin //GradMag := 0;//gradient magnitude //Result := kRGBAclear; //if rawData[i] < 1 then // exit; //intensity less than threshold: make invisible Y := XSz; //each row is X voxels Z := YSz*XSz; //each plane is X*Y voxels //X:: cols: +Z +0 -Z, rows -Y +0 +Y Xp := rawData[I+1]; Xm := rawData[I-1]; //Y:: cols: +Z +0 -Z, rows -X +0 +X Yp := rawData[I+Y]; Ym := rawData[I-Y]; //Z:: cols: +Z +0 -Z, rows -X +0 +X Zp := rawData[I+Z]; Zm := rawData[I-Z]; //result := XYZIx (Xm,Xp,Ym,Yp,Zm,Zp,rawData[I]); result := XYZIx (Xm,Xp,Ym,Yp,Zm,Zp); GradMag := abs( Xm-Xp)+abs(Ym-Yp)+abs(Zm-Zp);//gradient magnitude end; {$ENDIF} procedure NormVol (var Vol: tVolS); var n,i: integer; mx,mn: single; begin n := length(Vol); if n < 1 then exit; mx := Vol[0]; mn := Vol[0]; for i := 0 to (n-1) do begin if Vol[i] > mx then mx := Vol[i]; if Vol[i] < mn then mn := Vol[i]; end; if mx = mn then exit; mx := mx-mn;//range for i := 0 to (n-1) do Vol[i] := (Vol[i]-mn)/mx; end; (*procedure SmoothVol (var rawData: tVolB; lXdim,lYdim,lZdim: integer); var lSmoothImg,lSmoothImg2: tVolW; lSliceSz,lnVox,i: integer; begin lSliceSz := lXdim*lYdim; lnVox := lSliceSz*lZDim; if (lnVox < 0) or (lXDim < 3) or (lYDim < 3) or (lZDim < 3) then exit; setlength(lSmoothImg,lnVox); setlength(lSmoothImg2,lnVox); //smooth with X neighbors (left and right) stride = 1 for i := 0 to (lnVox-2) do //output x5 input lSmoothImg[i] := rawData[i-1] + (rawData[i] * 3) + rawData[i+1]; //smooth with Y neighbors (anterior, posterior) stride = Xdim for i := lXdim to (lnVox-lXdim-1) do //output x5 (5x5=25) input lSmoothImg2[i] := lSmoothImg[i-lXdim] + (lSmoothImg[i] * 3) + lSmoothImg[i+lXdim]; //smooth with Z neighbors (inferior, superior) stride = lSliceSz for i := lSliceSz to (lnVox-lSliceSz-1) do // x5 input (25*5=125) rawData[i] := (lSmoothImg2[i-lSliceSz] + (lSmoothImg2[i] * 3) + lSmoothImg2[i+lSliceSz]) div 125; lSmoothImg := nil; lSmoothImg2 := nil; end; *) procedure SmoothVol (var rawData: tVolB; lXdim,lYdim,lZdim: integer); var lSmoothImg,lSmoothImg2: tVolW; lSliceSz,lnVox,i: integer; begin //exit; //blurring the gradients can hurt low resolution images, e.g. mni2009_256 with glass shader lSliceSz := lXdim*lYdim; lnVox := lSliceSz*lZDim; if (lnVox < 0) or (lXDim < 3) or (lYDim < 3) or (lZDim < 3) then exit; setlength(lSmoothImg,lnVox); setlength(lSmoothImg2,lnVox); //smooth with X neighbors (left and right) stride = 1 lSmoothImg[0] := rawData[0]; lSmoothImg[lnVox-1] := rawData[lnVox-1]; for i := 1 to (lnVox-2) do //output *4 input (8bit->10bit) lSmoothImg[i] := rawData[i-1] + (rawData[i] shl 1) + rawData[i+1]; //smooth with Y neighbors (anterior, posterior) stride = Xdim for i := lXdim to (lnVox-lXdim-1) do //output *4 input (10bit->12bit) lSmoothImg2[i] := lSmoothImg[i-lXdim] + (lSmoothImg[i] shl 1) + lSmoothImg[i+lXdim]; //smooth with Z neighbors (inferior, superior) stride = lSliceSz for i := lSliceSz to (lnVox-lSliceSz-1) do // *4 input (12bit->14bit) , >> 6 for 8 bit output rawData[i] := (lSmoothImg2[i-lSliceSz] + (lSmoothImg2[i] shl 1) + lSmoothImg2[i+lSliceSz]) shr 6; lSmoothImg := nil; lSmoothImg2 := nil; end; procedure CreateGradientVolumeCPU (var VolRGBA: tVolRGBA; dim1, dim2, dim3: integer); //compute gradients for each voxel... Output texture in form RGBA // RGB will represent as normalized X,Y,Z gradient vector: Alpha will store gradient magnitude const kEdgeSharpness = 255;//value 1..255: 1=all edges transparent, 255=edges very opaque var X, Y,Z,Index,nVox, dim1x2 : Integer; VolData: tVolB; GradMagS: tVolS; Begin nVox := dim1*dim2*dim3; SetLength (VolData,nVox); for Index := 0 to (nVox-1) do //we can not compute gradients for image edges, so initialize volume so all voxels are transparent VolData[Index] := VolRGBA[Index].A; SmoothVol (VolData, dim1,dim2, dim3); //blur data SetLength (GradMagS,nVox); //store magnitude values for Index := 0 to (nVox-1) do //we can not compute gradients for image edges, so initialize volume so all voxels are transparent VolRGBA[Index] := kRGBAclear; for Index := 0 to (nVox-1) do //we can not compute gradients for image edges, so initialize volume so all voxels are transparent GradMagS[Index] := 0; //The following trick saves very little time //Z := (Tex.FiltDim[1]*Tex.FiltDim[2]) + Tex.FiltDim[1] + 1; //for Index := Z to (nVox - Z) do // if (VolData[Index] <> 0) then // VolRGBA[Index] := estimateGradients (VolData, Tex.FiltDim[1],Tex.FiltDim[2], Index,GradMagS[Index]); dim1x2 := dim1 * dim2; //slice size for Z := 1 To dim3 - 2 do //for X,Y,Z dimensions indexed from zero, so := 1 gives 1 voxel border for Y := 1 To dim2 - 2 do for X := 1 To dim1 - 2 do begin Index := (Z * dim1x2) + (Y * dim1) + X; //estimate gradients using Sobel or Central Difference (depending on DEFINE SOBEL) if (VolData[Index] <> 0) then VolRGBA[Index] := estimateGradients (VolData, dim1,dim2, Index,GradMagS[Index]); end;//X VolData := nil;//FREE ---- //next: generate normalized gradient magnitude values NormVol (GradMagS);//FREE ---- for Index := 0 to (nVox-1) do VolRGBA[Index].A := round(GradMagS[Index]*kEdgeSharpness); GradMagS := nil; end; function CheckTextureMemory (var Tex: TTexture; isRGBA: boolean): boolean; var i : Integer; begin //Use PROXY to see if video card can support a texture... //http://www.opengl.org/resources/faq/technical/texture.htm //glTexImage3D(GL_PROXY_TEXTURE_2D, level, internalFormat, width, height, border, format, type, NULL); //Note the pixels parameter is NULL, because OpenGL doesn't load texel data when the target parameter is GL_PROXY_TEXTURE_2D. Instead, OpenGL merely considers whether it can accommodate a texture of the specified size and description. If the specified texture can't be accommodated, the width and height texture values will be set to zero. After making a texture proxy call, you'll want to query these values as follows: result := false; if not isRGBA then {$IFDEF COREGL} glTexImage3D(GL_PROXY_TEXTURE_3D, 0, GL_RED, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0,GL_RED, GL_UNSIGNED_BYTE, nil) {$ELSE} glTexImage3D(GL_PROXY_TEXTURE_3D, 0, GL_ALPHA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0,GL_ALPHA, GL_UNSIGNED_BYTE, nil) {$ENDIF} else glTexImage3D (GL_PROXY_TEXTURE_3D, 0, GL_RGBA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0,GL_RGBA, GL_UNSIGNED_BYTE, nil); glGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D, 0, GL_TEXTURE_WIDTH, @i); if i < 1 then begin showdebug('Your video card is unable to load an image that is this large: '+inttostr(Tex.FiltDim[1])); exit; end; result := true; end; procedure CreateGradientVolume (var Tex: TTexture; var gradientVolume : GLuint; var inRGBA : Bytep0; isOverlay: boolean); //calculate gradients on the CPU or GPU (using GLSL) var gradRGBA: tVolRGBA; starttime: dword; begin //copy memory to GPU's VRAM glDeleteTextures(1,@gradientVolume); if not CheckTextureMemory(Tex,true) then exit; glPixelStorei(GL_UNPACK_ALIGNMENT,1); glGenTextures(1, @gradientVolume); glBindTexture(GL_TEXTURE_3D, gradientVolume); {$IFNDEF COREGL}glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); {$ENDIF} //glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //FCX glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);//? glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);//? glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);//? startTime := gettickcount; if gPrefs.FasterGradientCalculations then begin //123454 if isOverlay then Tex.updateOverlayGradientsGLSL := true else Tex.updateBackgroundGradientsGLSL := true; glTexImage3D(GL_TEXTURE_3D, 0,GL_RGBA, Tex.FiltDim[1], Tex.FiltDim[2],Tex.FiltDim[3],0, GL_RGBA, GL_UNSIGNED_BYTE,PChar(inRGBA)); //glTexImage3D(GL_TEXTURE_3D, 0,GL_RGBA, Tex.FiltDim[1], Tex.FiltDim[2],Tex.FiltDim[3],0, GL_RGBA, GL_UNSIGNED_BYTE,PChar(Tex.FiltImg)); end else begin try SetLength (gradRGBA, 4*Tex.FiltDim[1]*Tex.FiltDim[2]*Tex.FiltDim[3]); except //ReleaseContext; {$IFDEF Linux} ShowMessage ('Memory exhausted: perhaps this image is too large. Restart with the CONTROL key down to reset'); {$ELSE} ShowMessage ('Memory exhausted: perhaps this image is too large. Restart with the SHIFT key down to reset'); {$ENDIF} end; //Move(Tex.FiltImg^,gradRGBA[0], 4*Tex.FiltDim[1]*Tex.FiltDim[2]*Tex.FiltDim[3]);//src, dest, bytes Move(inRGBA^,gradRGBA[0], 4*Tex.FiltDim[1]*Tex.FiltDim[2]*Tex.FiltDim[3]);//src, dest, bytes CreateGradientVolumeCPU (gradRGBA,Tex.FiltDim[1],Tex.FiltDim[2],Tex.FiltDim[3]); glBindTexture(GL_TEXTURE_3D, gradientVolume); glTexImage3D(GL_TEXTURE_3D, 0,GL_RGBA, Tex.FiltDim[1], Tex.FiltDim[2],Tex.FiltDim[3],0, GL_RGBA, GL_UNSIGNED_BYTE,PChar(gradRGBA) ); SetLength(gradRGBA,0); if gPrefs.Debug then GLForm1.Caption := 'CPU gradient '+inttostr(gettickcount-startTime)+'ms '; end; end; {$IFDEF USETRANSFERTEXTURE} Procedure iCreateColorTable (var transferTexture : GLuint; var CLUTrec: TCLUTrec);// Load image data var lCLUT: TLUT; begin GenerateLUT(CLUTrec, lCLUT); //if transferTexture <> 0 then glDeleteTextures(1,@transferTexture); glGenTextures(1, @transferTexture); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glBindTexture(GL_TEXTURE_1D, transferTexture); glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, @lCLUT[0]); end; {$ENDIF} (* CreateVolumeGL (var Tex: TTexture; var volumeID : GLuint; ptr: PChar); begin glDeleteTextures(1,@volumeID); if not CheckTextureMemory(Tex,true) then exit; glPixelStorei(GL_UNPACK_ALIGNMENT,1); glGenTextures(1, @volumeID); glBindTexture(GL_TEXTURE_3D, volumeID); //if gPrefs.InterpolateView then begin glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); //end else begin // glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //awful aliasing // glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //awful aliasing //end; glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);//? glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);//? glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);//? // glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //awful aliasing // glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //awful aliasing if Tex.DataType = GL_RGBA then begin {$IFDEF Darwin} //glTexImage3D (GL_TEXTURE_3D, 0, GL_RGBA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_RGBA, GL_UNSIGNED_BYTE, PChar(Tex.OverlayImgRGBA)); //OverlayImgRGBA glTexImage3D (GL_TEXTURE_3D, 0, GL_RGBA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_RGBA, GL_UNSIGNED_BYTE, ptr); //OverlayImgRGBA {$ELSE} //glTexImage3DExt (GL_TEXTURE_3D, 0, GL_RGBA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_RGBA, GL_UNSIGNED_BYTE, PChar(Tex.OverlayImgRGBA)); glTexImage3DExt (GL_TEXTURE_3D, 0, GL_RGBA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_RGBA, GL_UNSIGNED_BYTE, ptr); {$ENDIF} end else begin {$IFDEF Darwin} //glTexImage3D (GL_TEXTURE_3D, 0, GL_ALPHA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_ALPHA, GL_UNSIGNED_BYTE, PChar(Tex.FiltImg)); glTexImage3D (GL_TEXTURE_3D, 0, GL_ALPHA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_ALPHA, GL_UNSIGNED_BYTE, ptr); {$ELSE} //glTexImage3DExt (GL_TEXTURE_3D, 0, GL_ALPHA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_ALPHA, GL_UNSIGNED_BYTE, PChar(Tex.FiltImg)); glTexImage3DExt (GL_TEXTURE_3D, 0, GL_ALPHA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_ALPHA, GL_UNSIGNED_BYTE, ptr); {$ENDIF} end; end; *) procedure CreateVolumeGL (var Tex: TTexture; var volumeID : GLuint; ptr: PChar); begin glDeleteTextures(1,@volumeID); if not CheckTextureMemory(Tex,true) then exit; glPixelStorei(GL_UNPACK_ALIGNMENT,1); glGenTextures(1, @volumeID); glBindTexture(GL_TEXTURE_3D, volumeID); //if gPrefs.InterpolateView then begin glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); //end else begin // glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //awful aliasing // glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //awful aliasing //end; glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);//? glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);//? glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);//? // glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //awful aliasing // glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //awful aliasing if Tex.DataType = GL_RGBA then begin {$IFDEF Darwin} //glTexImage3D (GL_TEXTURE_3D, 0, GL_RGBA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_RGBA, GL_UNSIGNED_BYTE, PChar(Tex.OverlayImgRGBA)); //OverlayImgRGBA glTexImage3D (GL_TEXTURE_3D, 0, GL_RGBA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_RGBA, GL_UNSIGNED_BYTE, ptr); //OverlayImgRGBA {$ELSE} //glTexImage3DExt (GL_TEXTURE_3D, 0, GL_RGBA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_RGBA, GL_UNSIGNED_BYTE, PChar(Tex.OverlayImgRGBA)); glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_RGBA, GL_UNSIGNED_BYTE, ptr); {$ENDIF} end else begin {$IFDEF Darwin} {$IFDEF COREGL} glTexImage3D (GL_TEXTURE_3D, 0, GL_RED, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_RED, GL_UNSIGNED_BYTE, ptr); {$ELSE} glTexImage3D (GL_TEXTURE_3D, 0, GL_ALPHA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_ALPHA, GL_UNSIGNED_BYTE, ptr); {$ENDIF} {$ELSE} glTexImage3D(GL_TEXTURE_3D, 0, GL_INTENSITY, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, ptr); //glTexImage3DExt (GL_TEXTURE_3D, 0, GL_ALPHA8, Tex.FiltDim[1], Tex.FiltDim[2], Tex.FiltDim[3], 0, GL_ALPHA, GL_UNSIGNED_BYTE, ptr); {$ENDIF} end; end; Procedure LoadTTexture(var Tex: TTexture); begin CreateVolumeGL (Tex, gRayCast.intensityTexture3D, PChar(Tex.FiltImg)); CreateGradientVolume (Tex, gRayCast.gradientTexture3D, Tex.FiltImg, false); end; end.
{_______________________________________________________________ Fractal Landscape Generator Accompanies "Mimicking Mountains," by Tom Jeffery, BYTE, December 1987, page 337 revised: 8/22/88 by Art Steinmetz Version for IBM Turbo Pascal v.4.0 Combines 3-D.pas, Map.pas Uses more flexible 3-D plotting routines. Sped up wireframe. Added wireframe animate feature. ______________________________________________________________ } program FraclLand; {Wireframe or shaded representation of a fractal surface} (* {$DEFINE DEBUG} *) {$I FLOAT.INC} (* {$I TEXTMODE.INC }{ 40 COL flag } *) {$R+ Range checking } {$S+ Stack checking } uses Break, Crt, { ClrScr } graph, MathLib0, { Float } FracSurf, { DoFractal, Surface } FracStuf, { ActionType, AltView, GetInput, OpenGraph } TextDisp, {$IFDEF TextMode} GetField, {$ELSE} GRGetFld, {$ENDIF} ThreeD, { GetOrientation, WireFrame, Shaded, Animate, MapDisp } Windows, StopWtch ; VAR srf : SurfaceRec; col, row, range, cont : longint; Prm : InputParamRec; PrmStr : PrmStrArray; GMode : INTEGER; Action : ActionType; MoreThanOnePage : BOOLEAN; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} (* PROCEDURE ReadFile( DataFile : String); BEGIN { read data file writeln('Reading data file.'); assign(srfile,DataFile); reset(srfile); for row := 0 to size do for col := 0 to size do read(srfile, srf[row, col]); close(srfile); END; *) {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE CalcFractal; VAR done : BOOLEAN; mp : MessageRec; BEGIN Message(mp,'Wait... Computing Fractal'); DoFractal(Srf.surfptr^,Prm.Dimension,Prm.Algorithm); ClearMsg(mp); done := ErrorMsg('Finished Computing Fractal'); END; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE Display; BEGIN GetOrientation(srf,Prm.tilt,Prm.rota); StartWatch; {$IFDEF TextMode} SetGraphMode(GMode); {$ENDIF} IF MoreThanOnePage THEN BEGIN SetActivePage(1); SetVisualPage(1); END; ClearViewPort; CASE Prm.DisplayType OF 'M' : MapDisp(srf); 'W' : Wireframe(srf,1); 'S' : Shaded(srf,Prm.altitude,Prm.azimuth); 'A' : Animate(srf); END; IF NOT (Prm.DisplayType = 'A') THEN BEGIN OutTextXY(1,1,'Hit any key to exit'); WaitForExit; END; IF MoreThanOnePage THEN BEGIN SetActivePage(0); SetVisualPage(0); END ELSE BEGIN Release_Fields; SetupScreen; InitFields(PrmStr); END; END; { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} BEGIN {MAIN} OpenGraph(Gmode,MoreThanOnePage); {$IFDEF TextMode } MoreThanOnePage := FALSE; {$ELSE} SetGraphMode(GMode); {$ENDIF} InsertDefaults(PrmStr); ClearSurface(Srf.surfptr^); InitFields(PrmStr); REPEAT Action := GetInput(Prm,PrmStr,Srf.surfptr^); CASE Action OF Compute : CalcFractal; SwapScreen : IF MoreThanOnePage THEN AltView ELSE MoreThanOnePage := ErrorMsg('Only One Visual Page'); Render : Display; END; {case} UNTIL Action = Quit; Release_Fields; CloseGraph; (* IF SaveOn THEN SaveImage('fractal.dat'); *) END. {FracLand} 
unit TestObfuscate; {(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is TestObfuscate, released May 2003. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele. All Rights Reserved. Contributor(s): Anthony Steele. 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/NPL/ 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. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL") See http://www.gnu.org/licenses/gpl.html ------------------------------------------------------------------------------*) {*)} {$I JcfGlobal.inc} interface { obfuscate and reclarify all test files } uses TestFrameWork; type TTestObfuscate = class(TTestCase) private procedure TestFile(const psInFileName, psRefObsOutput, psRefClearOutput: string); overload; procedure TestFile(const psName: string); overload; procedure TestFileContentsSame(const psFileName1, psFileName2: string); protected procedure SetUp; override; published procedure Empty1; procedure fFormTest; procedure fBracketProp; procedure LittleTest1; procedure LittleTest2; procedure LittleTest3; procedure LittleTest4; procedure LittleTest5; procedure LittleTest6; procedure LittleTest7; procedure LittleTest8; procedure LittleTest9; procedure LittleTest10; procedure LittleTest11; procedure LittleTest12; procedure LittleTest13; procedure LittleTest14; procedure LittleTest15; procedure LittleTest16; procedure LittleTest17; procedure LittleTest18; procedure LittleTest19; procedure LittleTest20; procedure LittleTest21; procedure LittleTest22; procedure LittleTest23; procedure LittleTest24; procedure LittleTest25; procedure LittleTest26; procedure LittleTest27; procedure LittleTest28; procedure LittleTest29; procedure LittleTest30; procedure LittleTest31; procedure LittleTest32; procedure LittleTest33; procedure LittleTest34; procedure LittleTest35; procedure LittleTest36; procedure LittleTest37; procedure LittleTest38; procedure LittleTest39; procedure LittleTest40; procedure LittleTest41; procedure LittleTest42; procedure LittleTest43; procedure LittleTest44; procedure LittleTest45; procedure LittleTest46; procedure LittleTest47; procedure LittleTest48; procedure LittleTest49; procedure LittleTest50; procedure LittleTest51; procedure LittleTest52; procedure LittleTest53; procedure LittleTest54; procedure LittleTest55; procedure LittleTest56; procedure LittleTest57; procedure LittleTest58; procedure LittleTest59; procedure LittleTest60; procedure LittleTest61; procedure LittleTest62; procedure TestAbsolute; procedure TestAlign; procedure TestArray; procedure TestAsm; procedure TestAsmStructs; procedure TestAtExpr; procedure TestBlankLineRemoval; procedure TestBogusDirectives; procedure TestBogusTypes; procedure TestCaseBlock; procedure TestCaseIfFormat; procedure TestCast; procedure TestCastSimple; procedure TestCharLiterals; procedure TestClassLines; procedure TestCommentIndent; procedure TestCommentIndent2; procedure TestCondReturns; procedure TestConstRecords; procedure TestD6; procedure TestDeclarations; procedure TestDeclarations2; procedure TestDefaultParams; procedure TestDefines; procedure TestDeref; procedure TestEmptyCase; procedure TestEmptyClass; procedure TestEmptySquareBrackets; procedure TestEndElse; procedure TestEsotericKeywords; procedure TestExclusion; procedure TestExclusionFlags; procedure TestExternal; procedure TestForward; procedure TestGoto; procedure TestInheritedExpr; procedure TestInitFinal; procedure TestInline; procedure TestInterfaceImplements; procedure TestInterfaceMap; procedure TestInterfaces; procedure TestLayout; procedure TestLayoutBare; procedure TestLayoutBare2; procedure TestLayoutBare3; procedure TestLibExports; procedure TestLineBreaking; procedure TestLocalTypes; procedure TestLongStrings; procedure TestMarcoV; procedure TestMessages; procedure TestMixedModeCaps; procedure TestMVB; procedure TestNested; procedure TestNestedRecords; procedure TestNestedType; procedure TestOleParams; procedure TestOperators; procedure TestParams; procedure TestParamSpaces; procedure TestPointers; procedure TestProgram; procedure TestProperties; procedure TestPropertyLines; procedure TestPropertyInherited; procedure TestRaise; procedure TestRecords; procedure TestReg; procedure TestReint; procedure TestReturnRemoval; procedure TestReturns; procedure TestRunOnConst; procedure TestRunOnDef; procedure TestRunOnLine; procedure TestSimpleIfdef; procedure TestSimpleIfdef2; procedure TestSimpleIfdef3; procedure TestSimpleIfdef4; procedure TestSimpleIfdef5; procedure TestSimpleIfdef6; procedure TestTestMH; procedure TestTPObjects; procedure TestTry; procedure TestTypeDefs; procedure TestUnitAllDirectives; procedure TestUnitDeprecated; procedure TestUnitLibrary; procedure TestUnitPlatform; procedure TestUses; procedure TestUsesChanges; procedure TestVarParam; procedure TestWarnings; procedure TestWarnDestroy; procedure TestWith; procedure TestCases; procedure TestProcBlankLines; procedure TestCondCompBreaks; procedure TestCondCompBreaks2; procedure TestAsmLabel; procedure TestAsmOps; procedure TestComplexAsm2; procedure TestDelphiNetUses; procedure TestConstBug; procedure TestDottedName; procedure TestDelphiNetClass; procedure TestDelphiNetConst; procedure TestDelphiNetStatic; procedure TestTestDotNetForm1; procedure TestDelphiNetOperatorOverload; procedure TestDelphiNetHelperClass; procedure TestDelphiNetNestedType; procedure TestDelphiNetNestedType2; procedure TestDelphiNetRecordForward; procedure TestDelphiNetAttributes; procedure TestDelphiNetWebService; procedure TestDelphiNetWebService2; procedure TestDelphiNetKeywords; procedure TestDelphiNetClassVar; procedure TestDelphiNetSealedClass; procedure TestDelphiNetFinalMethod; procedure TestDelphiNetDottedType; procedure TestDelphiNetAmpersandMethod; procedure TestDelphiNetMulticast; procedure TestDelphiNetDynamicArray; procedure TestDelphiNetRecordProcs; procedure TestDelphiNetUnsafe; procedure TestDelphiNetRecordClassVars; procedure TestTryExceptRaise; procedure TestTrailingCommaParam; procedure TestForIn; procedure TestDprNoBegin; procedure TestDLLIndex; procedure TestIncAt; procedure TestAsmAnd; procedure TestVarArgs; procedure TestLabelKeyword; procedure TestSubrangeType; procedure TestAmpersand; procedure TestAutomated; procedure TestClassMethods; procedure TestExports; procedure TestAsmCaps; procedure TestAsmOffsetKeyword; procedure TestGenerics; procedure TestGenerics2; procedure TestGenericArray; procedure TestGenericClassHelper; procedure TestGenericClassOperators; procedure TestGenericConstraintConstructor; procedure TestGenericConstraints; procedure TestGenericConstructorStatic; procedure TestGenericDelegates; procedure TestGenericFunctions; procedure TestGenericHeritage; procedure TestGenericInheritance; procedure TestGenericInterface; procedure TestGenericMethod; procedure TestGenericMethods1; procedure TestGenericOperatorAs; procedure TestGenericOperatorIs; procedure TestGenericTypeNullable; procedure TestPackedObject; procedure TestClassVarEmpty; procedure TestRecordWithClassFunction; procedure TestOutKeyword; procedure TestExit; procedure TestHexConstantElse; procedure TestDelphiNetLibrary; procedure TestClassOf; procedure TestDelphi2009Inherited; procedure TestDelphi2009Generics; procedure TestDelphi2009AnonymousMethod; procedure TestAnonFunctionInInitialization; procedure TestLibrary; procedure TestUnicode_ansi; procedure TestUnicode_be_ucs2; procedure TestUnicode_be_ucs4; procedure TestUnicode_le_ucs2; procedure TestUnicode_le_ucs4; procedure TestUnicode_utf8; procedure TestUnicodeStrings; procedure TestAssignments; end; implementation uses { delphi } Windows, SysUtils, { local } JcfStringUtils, FileConverter, ConvertTypes, JcfSettings, JcfRegistrySettings, TestConstants; procedure TTestObfuscate.Setup; begin inherited; InitTestSettings; end; procedure TTestObfuscate.TestFile( const psInFileName, psRefObsOutput, psRefClearOutput: string); var lcConverter: TFileConverter; lsObsFileName: string; lsOutFileName: string; begin Check(FileExists(psInFileName), 'input file ' + psInFileName + ' not found'); JcfFormatSettings.Obfuscate.Enabled := True; GetRegSettings.OutputExtension := 'obs'; lcConverter := TFileConverter.Create; try lcConverter.YesAll := True; lcConverter.GuiMessages := False; lcConverter.SourceMode := fmSingleFile; lcConverter.BackupMode := cmSeparateOutput; JcfFormatSettings.Obfuscate.Enabled := True; lcConverter.Input := psInFileName; lcConverter.Convert; Check( not lcConverter.ConvertError, 'Obfuscate failed for ' + ExtractFileName(psInFileName)); lsObsFileName := lcConverter.OutFileName; Check(lsObsFileName <> '', 'No obfuscated file'); Check(FileExists(lsObsFileName), 'obfuscated file ' + lsObsFileName + ' not found'); TestFileContentsSame(lsObsFileName, psRefObsOutput); // now deobfuscate JcfFormatSettings.Obfuscate.Enabled := False; GetRegSettings.OutputExtension := 'out'; lcConverter.Clear; lcConverter.YesAll := True; lcConverter.GuiMessages := False; lcConverter.SourceMode := fmSingleFile; lcConverter.BackupMode := cmSeparateOutput; lcConverter.Input := lsObsFileName; lcConverter.Convert; Check( not lcConverter.ConvertError, 'Reclarify failed for ' + ExtractFileName(lsObsFileName)); lsOutFileName := lcConverter.OutFileName; Check(lsOutFileName <> '', 'No output file'); Check(FileExists(lsOutFileName), 'output file ' + lsObsFileName + ' not found'); TestFileContentsSame(lsOutFileName, psRefClearOutput); // clean up DeleteFile(lsOutFileName); DeleteFile(lsObsFileName); finally lcConverter.Free; JcfFormatSettings.Obfuscate.Enabled := False; end; end; procedure TTestObfuscate.TestFileContentsSame(const psFileName1, psFileName2: string); var lsFile1, lsFile2: string; begin Check(FileExists(psFileName1), 'File ' + psFileName1 + ' does not exist'); Check(FileExists(psFileName2), 'File ' + psFileName2 + ' does not exist'); lsFile1 := string(FileToString(psFileName1)); lsFile2 := string(FileToString(psFileName2)); // check contents the same if (lsFile1 <> lsFile2) then Fail('Files differ ' + psFileName1 + ' and ' + psFileName2); end; procedure TTestObfuscate.TestFile(const psName: string); var liLastDotPos: integer; lsInName, lsPrefix, lsObsFileName: string; lsRemadeFileName: string; begin Assert(psName <> ''); { does it have an file extension? } if Pos('.', psName) > 0 then begin liLastDotPos := StrLastPos('.', psName); lsInName := psName; lsPrefix := StrLeft(psName, liLastDotPos); lsObsFileName := lsPrefix + 'obs'; lsRemadeFileName := lsPrefix + 'out'; end else begin lsInName := psName + '.pas'; lsObsFileName := psName + '.obs'; lsRemadeFileName := psName + '.out'; end; GetRegSettings.OutputExtension := 'obs'; TestFile(GetTestFilesDir + lsInName, GetObsOutFilesDir + lsObsFileName, GetObsOutFilesDir + lsRemadeFileName) { // test re-obfuscating JcfFormatSettings.FileSettings.OutputExtension := 'out'; TestObfuscateFile(GetTestFilesDir + lsObsFileName, GetObsOutFilesDir + lsRemadeFileName) } end; procedure TTestObfuscate.TestDelphiNetLibrary; begin TestFile('TestDelphiNetLibrary'); end; procedure TTestObfuscate.Empty1; begin TestFile('EmptyTest1'); end; procedure TTestObfuscate.fFormTest; begin TestFile('fFormTest'); end; procedure TTestObfuscate.LittleTest1; begin TestFile('LittleTest1'); end; procedure TTestObfuscate.LittleTest2; begin TestFile('LittleTest2'); end; procedure TTestObfuscate.LittleTest3; begin TestFile('LittleTest3'); end; procedure TTestObfuscate.LittleTest4; begin TestFile('LittleTest4'); end; procedure TTestObfuscate.LittleTest5; begin TestFile('LittleTest5'); end; procedure TTestObfuscate.LittleTest6; begin TestFile('LittleTest6'); end; procedure TTestObfuscate.LittleTest7; begin TestFile('LittleTest7'); end; procedure TTestObfuscate.LittleTest8; begin TestFile('LittleTest8'); end; procedure TTestObfuscate.TestAbsolute; begin TestFile('TestAbsolute'); end; procedure TTestObfuscate.TestAlign; begin TestFile('TestAlign'); end; procedure TTestObfuscate.TestAmpersand; begin TestFile('TestAmpersand'); end; procedure TTestObfuscate.TestAnonFunctionInInitialization; begin TestFile('TestAnonFunctionInInitialization'); end; procedure TTestObfuscate.TestArray; begin TestFile('TestArray'); end; procedure TTestObfuscate.TestAsm; begin TestFile('TestAsm'); end; procedure TTestObfuscate.TestBlankLineRemoval; begin TestFile('TestBlankLineRemoval'); end; procedure TTestObfuscate.TestBogusDirectives; begin TestFile('TestBogusDirectives'); end; procedure TTestObfuscate.TestBogusTypes; begin TestFile('TestBogusTypes'); end; procedure TTestObfuscate.TestCaseBlock; begin TestFile('TestCaseBlock'); end; procedure TTestObfuscate.TestCast; begin TestFile('TestCast'); end; procedure TTestObfuscate.TestCastSimple; begin TestFile('TestCastSimple'); end; procedure TTestObfuscate.TestCharLiterals; begin TestFile('TestCharLiterals'); end; procedure TTestObfuscate.TestClassLines; begin TestFile('TestClassLines'); end; procedure TTestObfuscate.TestClassMethods; begin TestFile('TestClassMethods'); end; procedure TTestObfuscate.TestClassOf; begin TestFile('TestClassOf'); end; procedure TTestObfuscate.TestClassVarEmpty; begin TestFile('TestClassVarEmpty'); end; procedure TTestObfuscate.TestCommentIndent; begin TestFile('TestCommentIndent'); end; procedure TTestObfuscate.TestCommentIndent2; begin TestFile('TestCommentIndent2'); end; procedure TTestObfuscate.TestComplexAsm2; begin TestFile('TestComplexAsm2'); end; procedure TTestObfuscate.TestConstRecords; begin TestFile('TestConstRecords'); end; procedure TTestObfuscate.TestD6; begin TestFile('TestD6'); end; procedure TTestObfuscate.TestDelphi2009AnonymousMethod; begin TestFile('TestDelphi2009AnonymousMethod'); end; procedure TTestObfuscate.TestDelphi2009Generics; begin TestFile('TestDelphi2009Generics'); end; procedure TTestObfuscate.TestDelphi2009Inherited; begin TestFile('TestDelphi2009Inherited'); end; procedure TTestObfuscate.TestDeclarations; begin TestFile('TestDeclarations'); end; procedure TTestObfuscate.TestDeclarations2; begin TestFile('TestDeclarations2'); end; procedure TTestObfuscate.TestDefaultParams; begin TestFile('TestDefaultParams'); end; procedure TTestObfuscate.TestEmptyClass; begin TestFile('TestEmptyClass'); end; procedure TTestObfuscate.TestEsotericKeywords; begin TestFile('TestEsotericKeywords'); end; procedure TTestObfuscate.TestExclusion; begin TestFile('TestExclusion'); end; procedure TTestObfuscate.TestExclusionFlags; begin TestFile('TestExclusionFlags'); end; procedure TTestObfuscate.TestExit; begin TestFile('TestExit'); end; procedure TTestObfuscate.TestExports; begin TestFile('TestExports'); end; procedure TTestObfuscate.TestExternal; begin TestFile('TestExternal'); end; procedure TTestObfuscate.TestForward; begin TestFile('TestForward'); end; procedure TTestObfuscate.TestGenericArray; begin TestFile('TestGenericArray.dpr'); end; procedure TTestObfuscate.TestGenericClassHelper; begin TestFile('TestGenericClassHelper.dpr'); end; procedure TTestObfuscate.TestGenericClassOperators; begin TestFile('TestGenericClassOperators.dpr'); end; procedure TTestObfuscate.TestGenericConstraintConstructor; begin TestFile('TestGenericConstraintConstructor.dpr'); end; procedure TTestObfuscate.TestGenericConstraints; begin TestFile('TestGenericConstraints.dpr'); end; procedure TTestObfuscate.TestGenericConstructorStatic; begin TestFile('TestGenericConstructorStatic.dpr'); end; procedure TTestObfuscate.TestGenericDelegates; begin TestFile('TestGenericDelegates.dpr'); end; procedure TTestObfuscate.TestGenericFunctions; begin TestFile('TestGenericFunctions.dpr'); end; procedure TTestObfuscate.TestGenericHeritage; begin TestFile('TestGenericHeritage.dpr'); end; procedure TTestObfuscate.TestGenericInheritance; begin TestFile('TestGenericInheritance.dpr'); end; procedure TTestObfuscate.TestGenericInterface; begin TestFile('TestGenericInterface.dpr'); end; procedure TTestObfuscate.TestGenericMethod; begin TestFile('TestGenericMethod.dpr'); end; procedure TTestObfuscate.TestGenericMethods1; begin TestFile('TestGenericMethods1.dpr'); end; procedure TTestObfuscate.TestGenericOperatorAs; begin TestFile('TestGenericOperatorAs.dpr'); end; procedure TTestObfuscate.TestGenericOperatorIs; begin TestFile('TestGenericOperatorIs.dpr'); end; procedure TTestObfuscate.TestGenerics; begin TestFile('TestGenerics'); end; procedure TTestObfuscate.TestGenerics2; begin TestFile('TestGenerics2'); end; procedure TTestObfuscate.TestGenericTypeNullable; begin TestFile('TestGenericTypeNullable.dpr'); end; procedure TTestObfuscate.TestGoto; begin TestFile('TestGoto'); end; procedure TTestObfuscate.TestHexConstantElse; begin TestFile('TestHexConstantElse'); end; procedure TTestObfuscate.TestInitFinal; begin TestFile('TestInitFinal'); end; procedure TTestObfuscate.TestInterfaceImplements; begin TestFile('TestInterfaceImplements'); end; procedure TTestObfuscate.TestInterfaceMap; begin TestFile('TestInterfaceMap'); end; procedure TTestObfuscate.TestInterfaces; begin TestFile('TestInterfaces'); end; procedure TTestObfuscate.TestLabelKeyword; begin TestFile('TestLabelKeyword'); end; procedure TTestObfuscate.TestLayout; begin TestFile('TestLayout'); end; procedure TTestObfuscate.TestLayoutBare; begin TestFile('TestLayoutBare'); end; procedure TTestObfuscate.TestLayoutBare2; begin TestFile('TestLayoutBare2'); end; procedure TTestObfuscate.TestLayoutBare3; begin TestFile('TestLayoutBare3'); end; procedure TTestObfuscate.TestLibExports; begin TestFile('TestLibExports'); end; procedure TTestObfuscate.TestLibrary; begin TestFile('TestLibrary'); end; procedure TTestObfuscate.TestLineBreaking; begin TestFile('TestLineBreaking'); end; procedure TTestObfuscate.TestLocalTypes; begin TestFile('TestLocalTypes'); end; procedure TTestObfuscate.TestLongStrings; begin TestFile('TestLongStrings'); end; procedure TTestObfuscate.TestMarcoV; begin TestFile('TestMarcoV'); end; procedure TTestObfuscate.TestTestMH; begin TestFile('TestMH'); end; procedure TTestObfuscate.TestMixedModeCaps; begin TestFile('TestMixedModeCaps'); end; procedure TTestObfuscate.TestMVB; begin TestFile('TestMVB'); end; procedure TTestObfuscate.TestNested; begin TestFile('TestNested'); end; procedure TTestObfuscate.TestNestedRecords; begin TestFile('TestNestedRecords'); end; procedure TTestObfuscate.TestNestedType; begin TestFile('TestNestedType'); end; procedure TTestObfuscate.TestOleParams; begin TestFile('TestOleParams'); end; procedure TTestObfuscate.TestOperators; begin TestFile('TestOperators'); end; procedure TTestObfuscate.TestOutKeyword; begin TestFile('TestOutKeyword'); end; procedure TTestObfuscate.TestPackedObject; begin TestFile('TestPackedObject'); end; procedure TTestObfuscate.TestParams; begin TestFile('TestParams'); end; procedure TTestObfuscate.TestParamSpaces; begin TestFile('TestParamSpaces'); end; procedure TTestObfuscate.TestPointers; begin TestFile('TestPointers'); end; procedure TTestObfuscate.TestProgram; begin TestFile('TestProgram'); end; procedure TTestObfuscate.TestProperties; begin TestFile('TestProperties'); end; procedure TTestObfuscate.TestPropertyLines; begin TestFile('TestPropertyLines'); end; procedure TTestObfuscate.TestRecords; begin TestFile('TestRecords'); end; procedure TTestObfuscate.TestRecordWithClassFunction; begin TestFile('TestRecordWithClassFunction'); end; procedure TTestObfuscate.TestReg; begin TestFile('TestReg'); end; procedure TTestObfuscate.TestReint; begin TestFile('TestReint'); end; procedure TTestObfuscate.TestReturnRemoval; begin TestFile('TestReturnRemoval'); end; procedure TTestObfuscate.TestReturns; begin TestFile('TestReturns'); end; procedure TTestObfuscate.TestRunOnConst; begin TestFile('TestRunOnConst'); end; procedure TTestObfuscate.TestRunOnDef; begin TestFile('TestRunOnDef'); end; procedure TTestObfuscate.TestRunOnLine; begin TestFile('TestRunOnLine'); end; procedure TTestObfuscate.TestTPObjects; begin TestFile('TestTPObjects'); end; procedure TTestObfuscate.TestTry; begin TestFile('TestTry'); end; procedure TTestObfuscate.TestTypeDefs; begin TestFile('TestTypeDefs'); end; procedure TTestObfuscate.TestUses; begin TestFile('TestUses'); end; procedure TTestObfuscate.TestUsesChanges; begin TestFile('TestUsesChanges'); end; procedure TTestObfuscate.TestVarArgs; begin TestFile('TestVarArgs'); end; procedure TTestObfuscate.TestVarParam; begin TestFile('TestVarParam'); end; procedure TTestObfuscate.TestWarnings; begin TestFile('TestWarnings'); end; procedure TTestObfuscate.TestWith; begin TestFile('TestWith'); end; procedure TTestObfuscate.TestCases; begin TestFile('D11\Testcases.dpr'); end; procedure TTestObfuscate.TestProcBlankLines; begin TestFile('TestProcBlankLines.pas'); end; procedure TTestObfuscate.LittleTest9; begin TestFile('LittleTest9'); end; procedure TTestObfuscate.TestDeref; begin TestFile('TestDeref'); end; procedure TTestObfuscate.TestPropertyInherited; begin TestFile('TestPropertyInherited'); end; procedure TTestObfuscate.TestMessages; begin TestFile('TestMessages'); end; procedure TTestObfuscate.LittleTest10; begin TestFile('LittleTest10'); end; procedure TTestObfuscate.TestInheritedExpr; begin TestFile('TestInheritedExpr'); end; procedure TTestObfuscate.LittleTest11; begin TestFile('LittleTest11'); end; procedure TTestObfuscate.LittleTest12; begin TestFile('LittleTest12'); end; procedure TTestObfuscate.LittleTest13; begin TestFile('LittleTest13'); end; procedure TTestObfuscate.LittleTest14; begin TestFile('LittleTest14'); end; procedure TTestObfuscate.LittleTest15; begin TestFile('LittleTest15'); end; procedure TTestObfuscate.LittleTest16; begin TestFile('LittleTest16'); end; procedure TTestObfuscate.LittleTest17; begin TestFile('LittleTest17'); end; procedure TTestObfuscate.LittleTest18; begin TestFile('LittleTest18'); end; procedure TTestObfuscate.TestAtExpr; begin TestFile('TestAtExpr'); end; procedure TTestObfuscate.TestAutomated; begin TestFile('TestAutomated'); end; procedure TTestObfuscate.TestAsmStructs; begin TestFile('TestAsmStructs'); end; procedure TTestObfuscate.TestAssignments; begin TestFile('TestAssignments'); end; procedure TTestObfuscate.TestUnicodeStrings; begin TestFile('TestUnicodeStrings'); end; procedure TTestObfuscate.TestUnicode_ansi; begin TestFile('TestUnicode_ansi'); end; procedure TTestObfuscate.TestUnicode_be_ucs2; begin TestFile('TestUnicode_be_ucs2'); end; procedure TTestObfuscate.TestUnicode_be_ucs4; begin TestFile('TestUnicode_be_ucs4'); end; procedure TTestObfuscate.TestUnicode_le_ucs2; begin TestFile('TestUnicode_le_ucs2'); end; procedure TTestObfuscate.TestUnicode_le_ucs4; begin TestFile('TestUnicode_le_ucs4'); end; procedure TTestObfuscate.TestUnicode_utf8; begin TestFile('TestUnicode_utf8'); end; procedure TTestObfuscate.TestUnitAllDirectives; begin TestFile('TestUnitAllDirectives'); end; procedure TTestObfuscate.TestUnitDeprecated; begin TestFile('TestUnitDeprecated'); end; procedure TTestObfuscate.TestUnitLibrary; begin TestFile('TestUnitLibrary'); end; procedure TTestObfuscate.TestUnitPlatform; begin TestFile('TestUnitPlatform'); end; procedure TTestObfuscate.LittleTest19; begin TestFile('LittleTest19'); end; procedure TTestObfuscate.TestRaise; begin TestFile('TestRaise'); end; procedure TTestObfuscate.LittleTest20; begin TestFile('LittleTest20'); end; procedure TTestObfuscate.LittleTest21; begin TestFile('LittleTest21'); end; procedure TTestObfuscate.LittleTest22; begin TestFile('LittleTest22'); end; procedure TTestObfuscate.LittleTest23; begin TestFile('LittleTest23'); end; procedure TTestObfuscate.LittleTest24; begin TestFile('LittleTest24'); end; procedure TTestObfuscate.LittleTest25; begin TestFile('LittleTest25'); end; procedure TTestObfuscate.LittleTest26; begin TestFile('LittleTest26'); end; procedure TTestObfuscate.LittleTest27; begin TestFile('LittleTest27'); end; procedure TTestObfuscate.TestEmptySquareBrackets; begin TestFile('TestEmptySquareBrackets'); end; procedure TTestObfuscate.LittleTest28; begin TestFile('LittleTest28'); end; procedure TTestObfuscate.LittleTest29; begin TestFile('LittleTest29'); end; procedure TTestObfuscate.LittleTest30; begin TestFile('LittleTest30'); end; procedure TTestObfuscate.LittleTest31; begin TestFile('LittleTest31'); end; procedure TTestObfuscate.LittleTest32; begin TestFile('LittleTest32'); end; procedure TTestObfuscate.LittleTest33; begin TestFile('LittleTest33'); end; procedure TTestObfuscate.TestCaseIfFormat; begin TestFile('TestCaseIfFormat'); end; procedure TTestObfuscate.TestEmptyCase; begin TestFile('TestEmptyCase'); end; procedure TTestObfuscate.LittleTest34; begin TestFile('LittleTest34'); end; procedure TTestObfuscate.LittleTest35; begin TestFile('LittleTest35'); end; procedure TTestObfuscate.LittleTest36; begin TestFile('LittleTest36'); end; procedure TTestObfuscate.LittleTest37; begin TestFile('LittleTest37'); end; procedure TTestObfuscate.LittleTest38; begin TestFile('LittleTest38'); end; procedure TTestObfuscate.LittleTest39; begin TestFile('LittleTest39'); end; procedure TTestObfuscate.LittleTest40; begin TestFile('LittleTest40'); end; procedure TTestObfuscate.TestSimpleIfdef; begin TestFile('TestSimpleIfdef'); end; procedure TTestObfuscate.TestSimpleIfdef2; begin TestFile('TestSimpleIfdef2'); end; procedure TTestObfuscate.TestSimpleIfdef3; begin TestFile('TestSimpleIfdef3'); end; procedure TTestObfuscate.TestSimpleIfdef4; begin TestFile('TestSimpleIfdef4'); end; procedure TTestObfuscate.TestSimpleIfdef5; begin TestFile('TestSimpleIfdef5'); end; procedure TTestObfuscate.TestDefines; begin TestFile('TestDefines'); end; procedure TTestObfuscate.LittleTest41; begin TestFile('LittleTest41'); end; procedure TTestObfuscate.LittleTest42; begin TestFile('LittleTest42'); end; procedure TTestObfuscate.LittleTest43; begin TestFile('LittleTest43'); end; procedure TTestObfuscate.LittleTest44; begin TestFile('LittleTest44'); end; procedure TTestObfuscate.LittleTest45; begin TestFile('LittleTest45'); end; procedure TTestObfuscate.LittleTest46; begin TestFile('LittleTest46'); end; procedure TTestObfuscate.LittleTest47; begin TestFile('LittleTest47'); end; procedure TTestObfuscate.TestWarnDestroy; begin TestFile('TestWarnDestroy'); end; procedure TTestObfuscate.LittleTest48; begin TestFile('LittleTest48'); end; procedure TTestObfuscate.LittleTest49; begin TestFile('LittleTest49'); end; procedure TTestObfuscate.LittleTest50; begin TestFile('LittleTest50'); end; procedure TTestObfuscate.LittleTest51; begin TestFile('LittleTest51'); end; procedure TTestObfuscate.LittleTest52; begin TestFile('LittleTest52'); end; procedure TTestObfuscate.TestSimpleIfdef6; begin TestFile('TestSimpleIfdef6'); end; procedure TTestObfuscate.TestSubrangeType; begin TestFile('TestSubrangeType'); end; procedure TTestObfuscate.LittleTest53; begin TestFile('LittleTest53'); end; procedure TTestObfuscate.LittleTest54; begin TestFile('LittleTest54'); end; procedure TTestObfuscate.LittleTest55; begin TestFile('LittleTest55'); end; procedure TTestObfuscate.LittleTest56; begin TestFile('LittleTest56'); end; procedure TTestObfuscate.LittleTest57; begin TestFile('LittleTest57'); end; procedure TTestObfuscate.LittleTest58; begin TestFile('LittleTest58'); end; procedure TTestObfuscate.LittleTest59; begin TestFile('LittleTest59'); end; procedure TTestObfuscate.LittleTest60; begin TestFile('LittleTest60'); end; procedure TTestObfuscate.LittleTest61; begin TestFile('LittleTest61'); end; procedure TTestObfuscate.LittleTest62; begin TestFile('LittleTest62'); end; procedure TTestObfuscate.TestInline; begin TestFile('TestInline'); end; procedure TTestObfuscate.fBracketProp; begin TestFile('fBracketProp'); end; procedure TTestObfuscate.TestEndElse; begin TestFile('TestEndElse'); end; procedure TTestObfuscate.TestCondReturns; begin TestFile('TestCondReturns'); end; procedure TTestObfuscate.TestDelphiNetUnsafe; begin TestFile('TestDelphiNetUnsafe'); end; procedure TTestObfuscate.TestDelphiNetUses; begin TestFile('TestDelphiNetUses'); end; procedure TTestObfuscate.TestConstBug; begin TestFile('TestConstBug'); end; procedure TTestObfuscate.TestForIn; begin TestFile('TestForIn'); end; procedure TTestObfuscate.TestDottedName; begin TestFile('test.dotted.name.pas'); end; procedure TTestObfuscate.TestDelphiNetClass; begin TestFile('TestDelphiNetClass'); end; procedure TTestObfuscate.TestDelphiNetConst; begin TestFile('TestDelphiNetConst'); end; procedure TTestObfuscate.TestDelphiNetDottedType; begin TestFile('TestDelphiNetDottedType'); end; procedure TTestObfuscate.TestDelphiNetDynamicArray; begin TestFile('TestDelphiNetDynamicArray'); end; procedure TTestObfuscate.TestDelphiNetStatic; begin TestFile('TestDelphiNetStatic'); end; procedure TTestObfuscate.TestTestDotNetForm1; begin TestFile('TestDotNetForm1'); end; procedure TTestObfuscate.TestDelphiNetHelperClass; begin TestFile('TestDelphiNetHelperClass'); end; procedure TTestObfuscate.TestDelphiNetNestedType; begin TestFile('TestDelphiNetNestedType'); end; procedure TTestObfuscate.TestDelphiNetNestedType2; begin TestFile('TestDelphiNetNestedType2'); end; procedure TTestObfuscate.TestDelphiNetOperatorOverload; begin TestFile('TestDelphiNetOperatorOverload'); end; procedure TTestObfuscate.TestDelphiNetRecordClassVars; begin TestFile('TestDelphiNetRecordClassVars'); end; procedure TTestObfuscate.TestDelphiNetRecordForward; begin TestFile('TestDelphiNetRecordForward'); end; procedure TTestObfuscate.TestDelphiNetRecordProcs; begin TestFile('TestDelphiNetRecordProcs'); end; procedure TTestObfuscate.TestCondCompBreaks; begin TestFile('TestCondCompBreaks'); end; procedure TTestObfuscate.TestCondCompBreaks2; begin TestFile('TestCondCompBreaks2'); end; procedure TTestObfuscate.TestDelphiNetAmpersandMethod; begin TestFile('TestDelphiNetAmpersandMethod'); end; procedure TTestObfuscate.TestDelphiNetAttributes; begin TestFile('TestDelphiNetAttributes'); end; procedure TTestObfuscate.TestDelphiNetWebService; begin TestFile('TestDelphiNetWebService'); end; procedure TTestObfuscate.TestDelphiNetWebService2; begin TestFile('TestDelphiNetWebService2'); end; procedure TTestObfuscate.TestDelphiNetKeywords; begin TestFile('TestDelphiNetKeywords'); end; procedure TTestObfuscate.TestDelphiNetMulticast; begin TestFile('TestDelphiNetMulticast'); end; procedure TTestObfuscate.TestDelphiNetClassVar; begin TestFile('TestDelphiNetClassVar'); end; procedure TTestObfuscate.TestTrailingCommaParam; begin TestFile('TestTrailingCommaParam'); end; procedure TTestObfuscate.TestTryExceptRaise; begin TestFile('TestTryExceptRaise'); end; procedure TTestObfuscate.TestDprNoBegin; begin TestFile('TestDprNoBegin.dpr'); end; procedure TTestObfuscate.TestDLLIndex; begin TestFile('TestDLLIndex'); end; procedure TTestObfuscate.TestIncAt; begin TestFile('TestIncAt'); end; procedure TTestObfuscate.TestDelphiNetFinalMethod; begin TestFile('TestDelphiNetFinalMethod'); end; procedure TTestObfuscate.TestDelphiNetSealedClass; begin TestFile('TestDelphiNetSealedClass'); end; procedure TTestObfuscate.TestAsmAnd; begin TestFile('TestAsmAnd'); end; procedure TTestObfuscate.TestAsmCaps; begin TestFile('TestAsmCaps'); end; procedure TTestObfuscate.TestAsmLabel; begin TestFile('TestAsmLabel'); end; procedure TTestObfuscate.TestAsmOffsetKeyword; begin TestFile('TestAsmOffsetKeyword'); end; procedure TTestObfuscate.TestAsmOps; begin TestFile('TestAsmOps'); end; initialization TestFramework.RegisterTest(TTestObfuscate.Suite); end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OpenGL, ExtCtrls, StdCtrls; type TfrmGL = class(TForm) Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Timer1Timer(Sender: TObject); private DC : HDC; hrc: HGLRC; newCount, frameCount, lastCount : LongInt; fpsRate : GLfloat; protected procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; end; var frmGL: TfrmGL; implementation {$R *.DFM} const POINT_COUNT = 2000; var points: Array [0..POINT_COUNT - 1] of TGLArrayf3; motion: Array [0..POINT_COUNT - 1] of TGLArrayf3; procedure Reset; var i : 0..POINT_COUNT - 1; begin For i := 0 to POINT_COUNT - 1 do begin points[i][0] := 0.0; points[i][1] := -0.5; points[i][2] := 0.0; motion[i][0] := (Random - 0.5) / 20; motion[i][1] := Random / 7 + 0.01; motion[i][2] := (Random - 0.5) / 20; end; end; procedure UpdatePOINT(i: Word); begin points[i][0] := points[i][0] + motion[i][0]; points[i][1] := points[i][1] + motion[i][1]; points[i][2] := points[i][2] + motion[i][2]; If points[i][1] < -0.75 then begin points[i][0] := 0.0; points[i][1] := -0.5; points[i][2] := 0.0; motion[i][0] := (Random - 0.5) / 20; motion[i][1] := Random / 7 + 0.01; motion[i][2] := (Random - 0.5) / 20; end else motion[i][1] := motion[i][1] - 0.01; end; {======================================================================= Перерисовка окна} procedure TfrmGL.WMPaint(var Msg: TWMPaint); var ps : TPaintStruct; i : GLUint; begin BeginPaint(Handle, ps); glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POINTS); For i := 0 to POINT_COUNT - 1 do begin UpdatePOINT(i); glVertex3fv(@points[i]); end; glEnd; SwapBuffers(DC); EndPaint(Handle, ps); // определяем и выводим количество кадров в секунду newCount := GetTickCount; Inc(frameCount); If (newCount - lastCount) > 1000 then begin // прошла секунда fpsRate := frameCount * 1000 / (newCount - lastCount); Caption := 'FPS - ' + FloatToStr (fpsRate); lastCount := newCount; frameCount := 0; end; end; {======================================================================= Формат пикселя} procedure SetDCPixelFormat (hdc : HDC); var pfd : TPixelFormatDescriptor; nPixelFormat : Integer; begin FillChar (pfd, SizeOf (pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat (hdc, @pfd); SetPixelFormat (hdc, nPixelFormat, @pfd); end; {======================================================================= Создание формы} procedure TfrmGL.FormCreate(Sender: TObject); begin DC := GetDC (Handle); SetDCPixelFormat(DC); hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); lastCount := GetTickCount; frameCount := 0; glPointSize(2); Reset; glColor3f(0, 0.5, 1); end; {======================================================================= Конец работы приложения} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC (Handle, DC); DeleteDC (DC); end; procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close; If Key = VK_SPACE then Reset; end; procedure TfrmGL.Timer1Timer(Sender: TObject); begin InvalidateRect(Handle, nil, False); end; end.
unit generic_record_methods_1; interface implementation type TRec<T> = record F: T; procedure SetF(V: T); end; var R32: TRec<Int32>; procedure TRec<T>.SetF(V: T); begin F := V; end; procedure Test; begin R32.SetF(11); end; initialization Test(); finalization Assert(R32.F = 11); end.
unit dxForms; interface uses Classes, Forms, SysUtils, Controls; type TdxFormInfo = class private FCustomFormClass: TFormClass; FForm: TForm; FFormName: string; protected public constructor Create(ClassType: TFormClass; const AName: string = ''); procedure CreateForm(AOwner: TComponent); procedure DestroyForm; procedure ShowForm(AParent: TWinControl); property FormName: string read FFormName write FFormName; end; TdxFormManager = class private FFormList: TList; function GetCount: Integer; function GetItem(Index: Integer): TdxFormInfo; procedure AddNewItem(ANewItem: TdxFormInfo); protected function GetFormInfoByName(AName: string): TdxFormInfo; public constructor Create; destructor Destroy; override; procedure Clear; procedure RegisterForm(ClassType: TFormClass; const AName: string = ''); function ShowForm(AName: string; Parent: TWinControl): Boolean; procedure FreeForm(AName: string); property Count: Integer read GetCount; property Items[Index: Integer]: TdxFormInfo read GetItem; default; end; function dxFormManager: TdxFormManager; implementation var FInstance: TdxFormManager = nil; function dxFormManager: TdxFormManager; begin if not Assigned(FInstance) then FInstance := TdxFormManager.Create; Result := FInstance; end; { TdxFormInfo } constructor TdxFormInfo.Create(ClassType: TFormClass; const AName: string); begin inherited Create; FCustomFormClass := ClassType; if AName <> '' then FFormName := AName else FFormName := ClassType.ClassName; end; procedure TdxFormInfo.CreateForm(AOwner: TComponent); begin FForm := FCustomFormClass.Create(AOwner); end; procedure TdxFormInfo.DestroyForm; begin if Assigned(FForm) then begin FForm.Free; FForm := nil; end; end; procedure TdxFormInfo.ShowForm(AParent: TWinControl); begin if not Assigned(FForm) then CreateForm(AParent); FForm.BorderStyle := bsNone; FForm.Parent := AParent; FForm.Align := alClient; FForm.Show; FForm.SetFocus; end; { TdxFormManager } procedure TdxFormManager.Clear; var I: Integer; begin for I := FFormList.Count - 1 downto 0 do TdxFormInfo(FFormList[I]).Free; FFormList.Clear; end; constructor TdxFormManager.Create; begin inherited Create; FFormList := TList.Create; end; destructor TdxFormManager.Destroy; begin Clear; FFormList.Free; inherited Destroy; end; function TdxFormManager.GetCount: Integer; begin Result := FFormList.Count; end; function TdxFormManager.GetItem(Index: Integer): TdxFormInfo; begin Result := TdxFormInfo(FFormList.Items[Index]); end; procedure TdxFormManager.AddNewItem(ANewItem: TdxFormInfo); begin FFormList.Add(Pointer(ANewItem)); end; function TdxFormManager.GetFormInfoByName(AName: string): TdxFormInfo; var I: Integer; begin for I := 0 to Count - 1 do if Items[I].FormName = AName then begin Result := Items[I]; Exit; end; Result := nil; end; procedure TdxFormManager.RegisterForm(ClassType: TFormClass; const AName: string); var FI: TdxFormInfo; begin FI := TdxFormInfo.Create(ClassType, AName); AddNewItem(FI); end; function TdxFormManager.ShowForm(AName: string; Parent: TWinControl): Boolean; var FormInfo: TdxFormInfo; begin FormInfo := GetFormInfoByName(AName); if FormInfo <> nil then begin FormInfo.ShowForm(Parent); Result := True; end else Result := False; end; procedure TdxFormManager.FreeForm(AName: string); var FormInfo: TdxFormInfo; begin FormInfo := GetFormInfoByName(AName); if FormInfo <> nil then FormInfo.DestroyForm; end; initialization finalization if Assigned(FInstance) then FInstance.Free; end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2013-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit REST.Authenticator.OAuth; interface uses System.Classes, Data.Bind.ObjectScope, Data.Bind.Components, REST.Client, REST.Types, REST.Consts, REST.Utils, REST.BindSource; {$SCOPEDENUMS ON} type TOAuth1SignatureMethod = class; TOAuth1Authenticator = class; TOAuth2Authenticator = class; TOAuth1SignatureMethod = class(TPersistent) public class function GetName: string; virtual; abstract; function BuildSignature(ARequest: TCustomRESTRequest; AAuthenticator: TOAuth1Authenticator): string; virtual; abstract; property Name: string read GetName; end; TOAuth1SignatureMethodClass = class of TOAuth1SignatureMethod; TOAuth1SignatureMethod_PLAINTEXT = class(TOAuth1SignatureMethod) public class function GetName: string; override; function BuildSignature(ARequest: TCustomRESTRequest; AAuthenticator: TOAuth1Authenticator): string; override; end; TOAuth1SignatureMethod_HMAC_SHA1 = class(TOAuth1SignatureMethod) protected function Hash_HMAC_SHA1(const AData, AKey: string): string; virtual; public class function GetName: string; override; function BuildSignature(ARequest: TCustomRESTRequest; AAuthenticator: TOAuth1Authenticator): string; override; end; TSubOAuth1AuthenticationBindSource = class; TOAuth1Authenticator = class(TCustomAuthenticator) private FNonce: string; FSigningClass: TOAuth1SignatureMethod; FSigningClassName: string; FBindSource: TSubOAuth1AuthenticationBindSource; FTimestamp: string; FVersion: string; FAccessToken: string; FAccessTokenSecret: string; FAccessTokenEndpoint: string; FRequestTokenEndpoint: string; FAuthenticationEndpoint: string; FCallbackEndpoint: string; FConsumerKey: string; FConsumerSecret: string; FVerifierPIN: string; FRequestToken: string; FRequestTokenSecret: string; FIPImplementationID: string; procedure ReadConsumerSecret(Reader: TReader); procedure SetSigningClassName(const AValue: string); procedure SetSigningClass(const AValue: TOAuth1SignatureMethod); procedure SetAccessToken(const AValue: string); procedure SetAccessTokenEndpoint(const AValue: string); procedure SetAccessTokenSecret(const AValue: string); procedure SetAuthenticationEndpoint(const AValue: string); procedure SetCallbackEndpoint(const AValue: string); procedure SetConsumerSecret(const AValue: string); procedure SetConsumerKey(const AValue: string); procedure SetRequestToken(const AValue: string); procedure SetRequestTokenEndpoint(const AValue: string); procedure SetRequestTokenSecret(const AValue: string); procedure SetVerifierPIN(const AValue: string); function SigningClassNameIsStored: Boolean; procedure WriteConsumerSecret(Writer: TWriter); procedure AddCommonAuthParameters(const Params: TStrings; const QuoteChar: string); protected function CreateBindSource: TBaseObjectBindSource; override; procedure DefineProperties(Filer: TFiler); override; procedure DoAuthenticate(ARequest: TCustomRESTRequest); override; /// <summary> /// creates a 32 characters long unique string that will be used internally to identify a request /// </summary> class function GenerateNonce: string; virtual; /// <summary> /// creates the signature for OAuth1.0 requests /// </summary> function GenerateSignature(ARequest: TCustomRESTRequest): string; virtual; class function GenerateTimeStamp: string; virtual; function GetSignatureMethod: string; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(ASource: TOAuth1Authenticator); reintroduce; /// <summary> /// Resets all values of the authenticator to default values - empty strings in most cases. /// </summary> procedure ResetToDefaults; override; /// <summary> /// A random, unique string for each request. Automatically maintained by the authenticator-class. /// </summary> property Nonce: string read FNonce; property SignatureMethod: string read GetSignatureMethod; /// <summary> /// Timestamp of the current request. Automatically maintained by the authenticator-class. /// </summary> property Timestamp: string read FTimestamp; /// <summary> /// Version of OAuth that this Authenticator supports (is always 1.0(a)) /// </summary> property Version: string read FVersion; property SigningClass: TOAuth1SignatureMethod read FSigningClass write SetSigningClass; published /// <summary> /// the access-token provided by the service-provider. this value is used to sign the requests /// </summary> property AccessToken: string read FAccessToken write SetAccessToken; /// <summary> /// the access-token-secret provided by the service-provider. this value is used to sign the requests /// </summary> property AccessTokenSecret: string read FAccessTokenSecret write SetAccessTokenSecret; /// <summary> /// the request-token provided by the service-provider. a request-token is always /// a temporary token and must be changed to an access-token. after successfully /// requesting the access-token, the request-token becomes invalid. /// </summary> property RequestToken: string read FRequestToken write SetRequestToken; property RequestTokenSecret: string read FRequestTokenSecret write SetRequestTokenSecret; /// <summary> /// Complete address to the endpoint of the service-provider where an access-token can be obtained /// </summary> property AccessTokenEndpoint: string read FAccessTokenEndpoint write SetAccessTokenEndpoint; /// <summary> /// Complete address to the endpoint of the service-provider where an request-token can be obtained /// </summary> property RequestTokenEndpoint: string read FRequestTokenEndpoint write SetRequestTokenEndpoint; /// <summary> /// Complete address to the endpoint of the service-provider where the authentication can be done /// </summary> property AuthenticationEndpoint: string read FAuthenticationEndpoint write SetAuthenticationEndpoint; /// <summary> /// Complete address to the endpoint for redirecting the user to after authentication /// </summary> property CallbackEndpoint: string read FCallbackEndpoint write SetCallbackEndpoint; /// <summary> /// The consumer-key (or "client-id" or "app-id") is provided by the service-provider after registering an application /// </summary> property ConsumerKey: string read FConsumerKey write SetConsumerKey; /// <summary> /// The consumer-secret (or client-secret or app-secret) is provided by the service-provider after registering an application. DO NOT SHARE THIS VALUE. /// </summary> property ConsumerSecret: string read FConsumerSecret write SetConsumerSecret; property SigningClassName: string read FSigningClassName write SetSigningClassName stored SigningClassNameIsStored; /// <summary> /// The verifier ("pin", "auth-code") is used to change a request-token into an access-token and is provided by the service-provider. /// after changing the tokens, this value becomes invalid. /// </summary> property VerifierPIN: string read FVerifierPIN write SetVerifierPIN; /// <summary> /// HTTP abstraction implementation ID /// </summary> property IPImplementationID: string read FIPImplementationID write FIPImplementationID; property BindSource: TSubOAuth1AuthenticationBindSource read FBindSource; end; /// <summary> /// LiveBindings bindsource for TOAuth1Authenticator. Publishes subcomponent properties. /// </summary> TSubOAuth1AuthenticationBindSource = class(TRESTAuthenticatorBindSource<TOAuth1Authenticator>) protected function CreateAdapterT: TRESTAuthenticatorAdapter<TOAuth1Authenticator>; override; end; /// <summary> /// LiveBindings adapter for TOAuth1Authenticator. Create bindable members. /// </summary> TOAuth1AuthenticatorAdapter = class(TRESTAuthenticatorAdapter<TOAuth1Authenticator>) protected procedure AddFields; override; end; TOAuth2ResponseType = ( /// <summary> /// Default workflow including the authentication of the client /// </summary> rtCODE, /// <summary> /// Implicit workflow for direct requesting an accesstoken /// </summary> rtTOKEN); TOAuth2TokenType = (ttNONE, ttBEARER); /// <summary> Base OAuth exception class replacing non-standard named TOAuth2Exception </summary> EOAuth2Exception = class(ERESTException); TOAuth2Exception = EOAuth2Exception deprecated 'use EOAuth2Exception'; // do not localize TSubOAuth2AuthenticationBindSource = class; TOAuth2Authenticator = class(TCustomAuthenticator) private FBindSource: TSubOAuth2AuthenticationBindSource; FAccessToken: string; FAccessTokenEndpoint: string; FAccessTokenExpiry: TDateTime; FAccessTokenParamName: string; FAuthCode: string; FAuthorizationEndpoint: string; FClientID: string; FClientSecret: string; FLocalState: string; FRedirectionEndpoint: string; FRefreshToken: string; FResponseType: TOAuth2ResponseType; FScope: string; FTokenType: TOAuth2TokenType; procedure SetAccessTokenEndpoint(const AValue: string); procedure SetAccessTokenParamName(const AValue: string); procedure SetAuthCode(const AValue: string); procedure SetAuthorizationEndpoint(const AValue: string); procedure SetClientID(const AValue: string); procedure SetClientSecret(const AValue: string); procedure SetLocalState(const AValue: string); procedure SetRedirectionEndpoint(const AValue: string); procedure SetRefreshToken(const AValue: string); procedure SetResponseType(const AValue: TOAuth2ResponseType); procedure SetScope(const AValue: string); function ResponseTypeIsStored: Boolean; function TokenTypeIsStored: Boolean; function AccessTokenParamNameIsStored: Boolean; procedure ReadAccessTokenExpiryData(AReader: TReader); procedure SetAccessToken(const AValue: string); procedure SetAccessTokenExpiry(const AExpiry: TDateTime); procedure SetTokenType(const AType: TOAuth2TokenType); procedure WriteAccessTokenExpiryData(AWriter: TWriter); protected procedure DefineProperties(Filer: TFiler); override; procedure DoAuthenticate(ARequest: TCustomRESTRequest); override; function CreateBindSource: TBaseObjectBindSource; override; public constructor Create(AOwner: TComponent); override; procedure Assign(ASource: TOAuth2Authenticator); reintroduce; function AuthorizationRequestURI: string; procedure ChangeAuthCodeToAccesToken; /// <summary> /// Resets a request to default values and clears all entries. /// </summary> procedure ResetToDefaults; override; published property AccessToken: string read FAccessToken write SetAccessToken; property AccessTokenEndpoint: string read FAccessTokenEndpoint write SetAccessTokenEndpoint; property AccessTokenExpiry: TDateTime read FAccessTokenExpiry write SetAccessTokenExpiry; property AccessTokenParamName: string read FAccessTokenParamName write SetAccessTokenParamName stored AccessTokenParamNameIsStored; property AuthCode: string read FAuthCode write SetAuthCode; property AuthorizationEndpoint: string read FAuthorizationEndpoint write SetAuthorizationEndpoint; property ClientID: string read FClientID write SetClientID; property ClientSecret: string read FClientSecret write SetClientSecret; property LocalState: string read FLocalState write SetLocalState; property RedirectionEndpoint: string read FRedirectionEndpoint write SetRedirectionEndpoint; property RefreshToken: string read FRefreshToken write SetRefreshToken; property ResponseType: TOAuth2ResponseType read FResponseType write SetResponseType stored ResponseTypeIsStored; property Scope: string read FScope write SetScope; property TokenType: TOAuth2TokenType read FTokenType write SetTokenType stored TokenTypeIsStored; property BindSource: TSubOAuth2AuthenticationBindSource read FBindSource; end; /// <summary> /// LiveBindings bindsource for TOAuth2Authenticator. Publishes subcomponent properties. /// </summary> TSubOAuth2AuthenticationBindSource = class(TRESTAuthenticatorBindSource<TOAuth2Authenticator>) protected function CreateAdapterT: TRESTAuthenticatorAdapter<TOAuth2Authenticator>; override; end; /// <summary> /// LiveBindings adapter for TOAuth2Authenticator. Create bindable members. /// </summary> TOAuth2AuthenticatorAdapter = class(TRESTAuthenticatorAdapter<TOAuth2Authenticator>) protected procedure AddFields; override; end; function OAuth2ResponseTypeToString(const AType: TOAuth2ResponseType): string; function OAuth2ResponseTypeFromString(const ATypeString: string): TOAuth2ResponseType; function OAuth2TokenTypeToString(const AType: TOAuth2TokenType): string; function OAuth2TokenTypeFromString(const ATypeString: string): TOAuth2TokenType; var DefaultOAuth1SignatureClass: TOAuth1SignatureMethodClass = TOAuth1SignatureMethod_HMAC_SHA1; DefaultOAuth2ResponseType: TOAuth2ResponseType = TOAuth2ResponseType.rtCODE; DefaultOAuth2TokenType: TOAuth2TokenType = TOAuth2TokenType.ttNONE; DefaultOAuth2AccessTokenParamName: string = 'access_token'; // do not localize implementation uses System.SysUtils, System.DateUtils, System.NetEncoding, System.Hash, REST.HttpClient; function OAuth2ResponseTypeToString(const AType: TOAuth2ResponseType): string; begin case AType of TOAuth2ResponseType.rtCODE: result := 'code'; // do not localize TOAuth2ResponseType.rtTOKEN: result := 'token'; // do not localize else result := ''; // do not localize end; end; function OAuth2ResponseTypeFromString(const ATypeString: string): TOAuth2ResponseType; var LType: TOAuth2ResponseType; begin result := DefaultOAuth2ResponseType; for LType IN [Low(TOAuth2ResponseType) .. High(TOAuth2ResponseType)] do begin if SameText(ATypeString, OAuth2ResponseTypeToString(LType)) then begin result := LType; BREAK; end; end; end; function OAuth2TokenTypeToString(const AType: TOAuth2TokenType): string; begin case AType of TOAuth2TokenType.ttBEARER: result := 'bearer'; // do not localize else result := ''; // do not localize end; end; function OAuth2TokenTypeFromString(const ATypeString: string): TOAuth2TokenType; var LType: TOAuth2TokenType; begin result := DefaultOAuth2TokenType; for LType IN [Low(TOAuth2TokenType) .. High(TOAuth2TokenType)] do begin if SameText(ATypeString, OAuth2TokenTypeToString(LType)) then begin result := LType; BREAK; end; end; end; { TOAuth1SignatureMethod_PLAINTEXT } function TOAuth1SignatureMethod_PLAINTEXT.BuildSignature(ARequest: TCustomRESTRequest; AAuthenticator: TOAuth1Authenticator): string; begin (* oauth_signature is set to the concatenated encoded values of the Consumer Secret and Token Secret, separated by a ‘&’ character (ASCII code 38), even if either secret is empty. The result MUST be encoded again. *) result := URIEncode(AAuthenticator.ConsumerSecret + #38 + AAuthenticator.AccessTokenSecret); end; class function TOAuth1SignatureMethod_PLAINTEXT.GetName: string; begin result := 'PLAINTEXT'; // do not localize end; { TOAuthSignatureMethod_HMAC_SHA1 } function TOAuth1SignatureMethod_HMAC_SHA1.BuildSignature(ARequest: TCustomRESTRequest; AAuthenticator: TOAuth1Authenticator): string; var LPayLoadParams: TRESTRequestParameterArray; LParamList: TStringList; LURL: string; LParamsStr: string; LSigBaseStr: string; LSigningKey: string; LParam: TRESTRequestParameter; begin Assert(Assigned(ARequest) and Assigned(AAuthenticator)); Result := ''; // This code is duplicated. Use common representation of name/value pairs. Don't build the same list in two places. // Step #1 - collect all relevant parameters, this includes // all oauth_params as well as the params from the payload // (payload-params ==> params from client and request) LParamList := TStringList.Create; try AAuthenticator.AddCommonAuthParameters(LParamList, ''); // now collect the parameters from the payload. we do need the // union of the client-parameters and the request-parameters LPayLoadParams := ARequest.CreateUnionParameterList; for LParam in LPayLoadParams do if LParam.Kind in [TRESTRequestParameterKind.pkGETorPOST, TRESTRequestParameterKind.pkQUERY] then if poDoNotEncode in LParam.Options then LParamList.Values[LParam.Name] := LParam.Value else LParamList.Values[LParam.Name] := URIEncode(LParam.Value); // Step #2 - build a single string from the params // OAuth-spec requires the parameters to be sorted by their name LParamList.Sort; LParamList.LineBreak := '&'; LParamList.Options := LParamList.Options - [soTrailingLineBreak]; LParamsStr := LParamList.Text; finally LParamList.Free; end; // as per oauth-spec we do need the full URL without (!) any query-params LURL := ARequest.GetFullRequestURL(FALSE); // Step #3 - build the SignatureBaseString, the LSigningKey and the Signature LSigBaseStr := UpperCase(RESTRequestMethodToString(ARequest.Method)) + '&' + URIEncode(LURL) + '&' + URIEncode(LParamsStr); // do not localize LSigningKey := AAuthenticator.ConsumerSecret + '&'; if AAuthenticator.AccessTokenSecret <> '' then LSigningKey := LSigningKey + AAuthenticator.AccessTokenSecret // do not localize else if AAuthenticator.RequestTokenSecret <> '' then LSigningKey := LSigningKey + AAuthenticator.RequestTokenSecret; // do not localize Result := Hash_HMAC_SHA1(LSigBaseStr, LSigningKey); end; class function TOAuth1SignatureMethod_HMAC_SHA1.GetName: string; begin result := 'HMAC-SHA1'; // do not localize end; function TOAuth1SignatureMethod_HMAC_SHA1.Hash_HMAC_SHA1(const AData, AKey: string): string; begin Result := TNetEncoding.Base64.EncodeBytesToString(THashSHA1.GetHMACAsBytes(AData, AKey)); end; procedure TOAuth1Authenticator.AddCommonAuthParameters(const Params: TStrings; const QuoteChar: string); function FormatValue(const Value, QuoteChar: string): string; inline; begin Result := QuoteChar + URIEncode(Value) + QuoteChar; end; begin if CallbackEndpoint <> '' then Params.Values['oauth_callback'] := FormatValue(CallbackEndpoint, QuoteChar); // do not localize if ConsumerKey <> '' then Params.Values['oauth_consumer_key'] := FormatValue(ConsumerKey, QuoteChar); // do not localize Params.Values['oauth_nonce'] := FormatValue(Nonce, QuoteChar); // do not localize Params.Values['oauth_signature_method'] := FormatValue(SignatureMethod, QuoteChar); // do not localize Params.Values['oauth_timestamp'] := FormatValue(Timestamp, QuoteChar); // do not localize if AccessToken <> '' then Params.Values['oauth_token'] := FormatValue(AccessToken, QuoteChar) // do not localize else if RequestToken <> '' then Params.Values['oauth_token'] := FormatValue(RequestToken, QuoteChar); // do not localize if VerifierPIN <> '' then Params.Values['oauth_verifier'] := FormatValue(VerifierPIN, QuoteChar); // do not localize Params.Values['oauth_version'] := FormatValue(Version, QuoteChar); // do not localize end; procedure TOAuth1Authenticator.Assign(ASource: TOAuth1Authenticator); begin ResetToDefaults; AccessTokenEndpoint := ASource.AccessTokenEndpoint; RequestTokenEndpoint := ASource.RequestTokenEndpoint; AuthenticationEndpoint := ASource.AuthenticationEndpoint; CallbackEndpoint := ASource.CallbackEndpoint; AccessToken := ASource.AccessToken; AccessTokenSecret := ASource.AccessTokenSecret; RequestToken := ASource.RequestToken; RequestTokenSecret := ASource.RequestTokenSecret; VerifierPIN := ASource.VerifierPIN; ConsumerKey := ASource.ConsumerKey; ConsumerSecret := ASource.ConsumerSecret; SigningClassName := ASource.SigningClassName; end; constructor TOAuth1Authenticator.Create(AOwner: TComponent); begin inherited; ResetToDefaults; FVersion := '1.0'; end; function TOAuth1Authenticator.CreateBindSource: TBaseObjectBindSource; begin FBindSource := TSubOAuth1AuthenticationBindSource.Create(self); FBindSource.Name := 'BindSource'; { Do not localize } FBindSource.SetSubComponent(True); FBindSource.Authenticator := self; Result := FBindSource; end; procedure TOAuth1Authenticator.DefineProperties(Filer: TFiler); function DesignerDataStored: Boolean; begin if Filer.Ancestor <> nil then Result := TOAuth1Authenticator(Filer.Ancestor).ConsumerSecret <> ConsumerSecret else Result := ConsumerSecret <> ''; end; begin inherited DefineProperties(Filer); Filer.DefineProperty('ConsumerSecrect', ReadConsumerSecret, WriteConsumerSecret, DesignerDataStored); end; destructor TOAuth1Authenticator.Destroy; begin FreeAndNil(FSigningClass); inherited Destroy; end; { TOAuth1Authenticator } procedure TOAuth1Authenticator.DoAuthenticate(ARequest: TCustomRESTRequest); var LToken: string; LTokenBuilder: TStringList; begin // update timestamp and nonce for this request // --> these values must not change while a request is running FNonce := GenerateNonce; FTimestamp := GenerateTimeStamp; LTokenBuilder := TStringList.Create; try AddCommonAuthParameters(LTokenBuilder, '"'); LTokenBuilder.Values['oauth_timestamp'] := Format('"%s"', [URIEncode(Timestamp)]); LTokenBuilder.Values['oauth_signature'] := Format('"%s"', [URIEncode(GenerateSignature(ARequest))]); LTokenBuilder.Sort; LTokenBuilder.LineBreak := ', '; LTokenBuilder.Options := LTokenBuilder.Options - [soTrailingLineBreak]; LToken := 'OAuth ' + LTokenBuilder.Text; // do not localize, trailing space IS important ARequest.AddAuthParameter(HTTP_HEADERFIELD_AUTH, LToken, TRESTRequestParameterKind.pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]); finally LTokenBuilder.Free; end; end; class function TOAuth1Authenticator.GenerateNonce: string; begin Result := THashMD5.GetHashString(GenerateTimeStamp + IntToStr(Random(MAXINT))); end; function TOAuth1Authenticator.GenerateSignature(ARequest: TCustomRESTRequest): string; begin Assert(Assigned(FSigningClass)); Result := FSigningClass.BuildSignature(ARequest, self); end; class function TOAuth1Authenticator.GenerateTimeStamp: string; begin Result := IntToStr(DateTimeToUnix(TTimeZone.Local.ToUniversalTime(Now))); end; function TOAuth1Authenticator.GetSignatureMethod: string; begin Result := FSigningClass.Name; end; procedure TOAuth1Authenticator.ReadConsumerSecret(Reader: TReader); begin ConsumerSecret := Reader.ReadString; end; procedure TOAuth1Authenticator.ResetToDefaults; begin inherited; FreeAndNil(FSigningClass); FSigningClassName := DefaultOAuth1SignatureClass.ClassName; FSigningClass := DefaultOAuth1SignatureClass.Create; FAccessTokenEndpoint := ''; FRequestTokenEndpoint := ''; FAuthenticationEndpoint := ''; FCallbackEndpoint := ''; FAccessToken := ''; FAccessTokenSecret := ''; FRequestToken := ''; FRequestTokenSecret := ''; FVerifierPIN := ''; FConsumerKey := ''; FConsumerSecret := ''; FNonce := GenerateNonce; FTimestamp := GenerateTimeStamp; end; procedure TOAuth1Authenticator.SetAccessToken(const AValue: string); begin if AValue <> FAccessToken then begin FAccessToken := AValue; PropertyValueChanged; end; end; procedure TOAuth1Authenticator.SetAccessTokenEndpoint(const AValue: string); begin if AValue <> FAccessTokenEndpoint then begin FAccessTokenEndpoint := AValue; PropertyValueChanged; end; end; procedure TOAuth1Authenticator.SetAccessTokenSecret(const AValue: string); begin if AValue <> FAccessTokenSecret then begin FAccessTokenSecret := AValue; PropertyValueChanged; end; end; procedure TOAuth1Authenticator.SetAuthenticationEndpoint(const AValue: string); begin if AValue <> FAuthenticationEndpoint then begin FAuthenticationEndpoint := AValue; PropertyValueChanged; end; end; procedure TOAuth1Authenticator.SetCallbackEndpoint(const AValue: string); begin if AValue <> FCallbackEndpoint then begin FCallbackEndpoint := AValue; PropertyValueChanged; end; end; procedure TOAuth1Authenticator.SetConsumerSecret(const AValue: string); begin if AValue <> FConsumerSecret then begin FConsumerSecret := AValue; PropertyValueChanged; end; end; procedure TOAuth1Authenticator.SetConsumerKey(const AValue: string); begin if AValue <> FConsumerKey then begin FConsumerKey := AValue; PropertyValueChanged; end; end; procedure TOAuth1Authenticator.SetRequestToken(const AValue: string); begin if AValue <> FRequestToken then begin FRequestToken := AValue; PropertyValueChanged; end; end; procedure TOAuth1Authenticator.SetRequestTokenEndpoint(const AValue: string); begin if AValue <> FRequestTokenEndpoint then begin FRequestTokenEndpoint := AValue; PropertyValueChanged; end; end; procedure TOAuth1Authenticator.SetRequestTokenSecret(const AValue: string); begin if (AValue <> FRequestTokenSecret) then begin FRequestTokenSecret := AValue; PropertyValueChanged; end; end; procedure TOAuth1Authenticator.SetSigningClass(const AValue: TOAuth1SignatureMethod); begin if AValue <> FSigningClass then begin FreeAndNil(FSigningClass); FSigningClass := AValue; if FSigningClass <> nil then FSigningClassName := FSigningClass.ClassName else FSigningClassName := ''; end; end; procedure TOAuth1Authenticator.SetSigningClassName(const AValue: string); var LFinder: TClassFinder; LSignClass: TPersistentClass; begin if AValue <> FSigningClassName then begin FSigningClassName := AValue; // we want to allow "PLAINTEXT" or "HMAC-SHA1" as names and // translate them into the correct classnames if SameText(FSigningClassName, TOAuth1SignatureMethod_PLAINTEXT.GetName) then FSigningClassName := TOAuth1SignatureMethod_PLAINTEXT.ClassName else if SameText(FSigningClassName, TOAuth1SignatureMethod_HMAC_SHA1.GetName) then FSigningClassName := TOAuth1SignatureMethod_HMAC_SHA1.ClassName; FreeAndNil(FSigningClass); LFinder := TClassFinder.Create; try LSignClass := LFinder.GetClass(FSigningClassName); if LSignClass <> nil then FSigningClass := TOAuth1SignatureMethod(LSignClass.Create); finally FreeAndNil(LFinder); end; end; end; procedure TOAuth1Authenticator.SetVerifierPIN(const AValue: string); begin if AValue <> FVerifierPIN then begin FVerifierPIN := AValue; PropertyValueChanged; end; end; function TOAuth1Authenticator.SigningClassNameIsStored: Boolean; begin Result := SigningClassName <> DefaultOAuth1SignatureClass.ClassName; end; procedure TOAuth1Authenticator.WriteConsumerSecret(Writer: TWriter); begin Writer.WriteString(ConsumerSecret); end; { TOAuth2Authenticator } constructor TOAuth2Authenticator.Create(AOwner: TComponent); begin inherited Create(AOwner); ResetToDefaults; end; function TOAuth2Authenticator.CreateBindSource: TBaseObjectBindSource; begin FBindSource := TSubOAuth2AuthenticationBindSource.Create(self); FBindSource.Name := 'BindSource'; { Do not localize } FBindSource.SetSubComponent(True); FBindSource.Authenticator := self; Result := FBindSource; end; function TOAuth2Authenticator.AccessTokenParamNameIsStored: Boolean; begin Result := AccessTokenParamName <> DefaultOAuth2AccessTokenParamName; end; procedure TOAuth2Authenticator.Assign(ASource: TOAuth2Authenticator); begin ResetToDefaults; ClientID := ASource.ClientID; ClientSecret := ASource.ClientSecret; AuthCode := ASource.AuthCode; AccessToken := ASource.AccessToken; AccessTokenParamName := ASource.AccessTokenParamName; AccessTokenExpiry := ASource.AccessTokenExpiry; Scope := ASource.Scope; RefreshToken := ASource.RefreshToken; LocalState := ASource.LocalState; TokenType := ASource.TokenType; ResponseType := ASource.ResponseType; AuthorizationEndpoint := ASource.AuthorizationEndpoint; AccessTokenEndpoint := ASource.AccessTokenEndpoint; RedirectionEndpoint := ASource.RedirectionEndpoint; end; function TOAuth2Authenticator.AuthorizationRequestURI: string; begin Result := FAuthorizationEndpoint; Result := Result + '?response_type=' + URIEncode(OAuth2ResponseTypeToString(FResponseType)); if FClientID <> '' then Result := Result + '&client_id=' + URIEncode(FClientID); if FRedirectionEndpoint <> '' then Result := Result + '&redirect_uri=' + URIEncode(FRedirectionEndpoint); if FScope <> '' then Result := Result + '&scope=' + URIEncode(FScope); if FLocalState <> '' then Result := Result + '&state=' + URIEncode(FLocalState); end; procedure TOAuth2Authenticator.ChangeAuthCodeToAccesToken; var LClient: TRestClient; LRequest: TRESTRequest; LToken: string; LIntValue: int64; begin // we do need an authorization-code here, because we want // to send it to the servce and exchange the code into an // access-token. if FAuthCode = '' then raise EOAuth2Exception.Create(SAuthorizationCodeNeeded); LClient := TRestClient.Create(FAccessTokenEndpoint); try LRequest := TRESTRequest.Create(LClient); // The LClient now "owns" the Request and will free it. LRequest.Method := TRESTRequestMethod.rmPOST; // LRequest.Client := LClient; // unnecessary since the client "owns" the request it will assign the client LRequest.AddAuthParameter('code', FAuthCode, TRESTRequestParameterKind.pkGETorPOST); LRequest.AddAuthParameter('client_id', FClientID, TRESTRequestParameterKind.pkGETorPOST); LRequest.AddAuthParameter('client_secret', FClientSecret, TRESTRequestParameterKind.pkGETorPOST); LRequest.AddAuthParameter('redirect_uri', FRedirectionEndpoint, TRESTRequestParameterKind.pkGETorPOST); LRequest.AddAuthParameter('grant_type', 'authorization_code', TRESTRequestParameterKind.pkGETorPOST); LRequest.Execute; if LRequest.Response.GetSimpleValue('access_token', LToken) then FAccessToken := LToken; if LRequest.Response.GetSimpleValue('refresh_token', LToken) then FRefreshToken := LToken; // detect token-type. this is important for how using it later if LRequest.Response.GetSimpleValue('token_type', LToken) then FTokenType := OAuth2TokenTypeFromString(LToken); // if provided by the service, the field "expires_in" contains // the number of seconds an access-token will be valid if LRequest.Response.GetSimpleValue('expires_in', LToken) then begin LIntValue := StrToIntdef(LToken, -1); if (LIntValue > -1) then FAccessTokenExpiry := IncSecond(Now, LIntValue) else FAccessTokenExpiry := 0.0; end; // an authentication-code may only be used once. // if we succeeded here and got an access-token, then // we do clear the auth-code as is is not valid anymore // and also not needed anymore. if (FAccessToken <> '') then FAuthCode := ''; finally LClient.DisposeOf; end; end; procedure TOAuth2Authenticator.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('AccessTokenExpiryDate', ReadAccessTokenExpiryData, WriteAccessTokenExpiryData, (FAccessTokenExpiry > 0.1)); end; procedure TOAuth2Authenticator.DoAuthenticate(ARequest: TCustomRESTRequest); var LName: string; begin inherited; case FTokenType of TOAuth2TokenType.ttBEARER: begin ARequest.AddAuthParameter(HTTP_HEADERFIELD_AUTH, 'Bearer ' + FAccessToken, TRESTRequestParameterKind.pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]); end; else begin // depending on the service-provider, some of them want the access-token // submitted as "access_token", while others require it as "oauth_token" // please see documentation of your service-provider LName := FAccessTokenParamName; if (Trim(LName) = '') then LName := DefaultOAuth2AccessTokenParamName; ARequest.AddAuthParameter(LName, FAccessToken, TRESTRequestParameterKind.pkGETorPOST, [TRESTRequestParameterOption.poDoNotEncode]); end; end; end; procedure TOAuth2Authenticator.ReadAccessTokenExpiryData(AReader: TReader); begin FAccessTokenExpiry := AReader.ReadDate; end; procedure TOAuth2Authenticator.ResetToDefaults; begin inherited; ClientID := ''; ClientSecret := ''; AuthCode := ''; AccessToken := ''; FAccessTokenExpiry := 0.0; Scope := ''; RefreshToken := ''; LocalState := ''; FTokenType := DefaultOAuth2TokenType; ResponseType := DefaultOAuth2ResponseType; AccessTokenParamName := DefaultOAuth2AccessTokenParamName; AuthorizationEndpoint := ''; AccessTokenEndpoint := ''; RedirectionEndpoint := ''; end; function TOAuth2Authenticator.ResponseTypeIsStored: Boolean; begin Result := ResponseType <> DefaultOAuth2ResponseType; end; procedure TOAuth2Authenticator.SetAccessToken(const AValue: string); begin if AValue <> FAccessToken then begin FAccessToken := AValue; PropertyValueChanged; end; end; procedure TOAuth2Authenticator.SetAccessTokenEndpoint(const AValue: string); begin if AValue <> FAccessTokenEndpoint then begin FAccessTokenEndpoint := AValue; PropertyValueChanged; end; end; procedure TOAuth2Authenticator.SetAccessTokenExpiry(const AExpiry: TDateTime); begin if AExpiry <> FAccessTokenExpiry then begin FAccessTokenExpiry := AExpiry; PropertyValueChanged; end; end; procedure TOAuth2Authenticator.SetAccessTokenParamName(const AValue: string); begin if AValue <> FAccessTokenParamName then begin FAccessTokenParamName := AValue; PropertyValueChanged; end; end; procedure TOAuth2Authenticator.SetAuthCode(const AValue: string); begin if AValue <> FAuthCode then begin FAuthCode := AValue; PropertyValueChanged; end; end; procedure TOAuth2Authenticator.SetAuthorizationEndpoint(const AValue: string); begin if AValue <> FAuthorizationEndpoint then begin FAuthorizationEndpoint := AValue; PropertyValueChanged; end; end; procedure TOAuth2Authenticator.SetClientID(const AValue: string); begin if AValue <> FClientID then begin FClientID := AValue; PropertyValueChanged; end; end; procedure TOAuth2Authenticator.SetClientSecret(const AValue: string); begin if AValue <> FClientSecret then begin FClientSecret := AValue; PropertyValueChanged; end; end; procedure TOAuth2Authenticator.SetLocalState(const AValue: string); begin if AValue <> FLocalState then begin FLocalState := AValue; PropertyValueChanged; end; end; procedure TOAuth2Authenticator.SetRedirectionEndpoint(const AValue: string); begin if AValue <> FRedirectionEndpoint then begin FRedirectionEndpoint := AValue; PropertyValueChanged; end; end; procedure TOAuth2Authenticator.SetRefreshToken(const AValue: string); begin if AValue <> FRefreshToken then begin FRefreshToken := AValue; PropertyValueChanged; end; end; procedure TOAuth2Authenticator.SetResponseType(const AValue: TOAuth2ResponseType); begin if AValue <> FResponseType then begin FResponseType := AValue; PropertyValueChanged; end; end; procedure TOAuth2Authenticator.SetScope(const AValue: string); begin if AValue <> FScope then begin FScope := AValue; PropertyValueChanged; end; end; procedure TOAuth2Authenticator.SetTokenType(const AType: TOAuth2TokenType); begin if AType <> FTokenType then begin FTokenType := AType; PropertyValueChanged; end; end; function TOAuth2Authenticator.TokenTypeIsStored: Boolean; begin Result := TokenType <> DefaultOAuth2TokenType; end; procedure TOAuth2Authenticator.WriteAccessTokenExpiryData(AWriter: TWriter); begin AWriter.WriteDate(FAccessTokenExpiry); end; { TSubOAuth1AuthenticationBindSource } function TSubOAuth1AuthenticationBindSource.CreateAdapterT: TRESTAuthenticatorAdapter<TOAuth1Authenticator>; begin result := TOAuth1AuthenticatorAdapter.Create(self); end; { TOAuth1AuthenticatorAdapter } procedure TOAuth1AuthenticatorAdapter.AddFields; const sAccessToken = 'AccessToken'; sAccessTokenSecret = 'AccessTokenSecret'; sAccessTokenEndpoint = 'AccessTokenEndpoint'; sRequestToken = 'RequestToken'; sRequestTokenSecret = 'RequestTokenSecret'; sRequestTokenEndpoint = 'RequestTokenEndpoint'; sAuthenticationEndpoint = 'AuthenticationEndpoint'; sCallbackEndpoint = 'CallbackEndpoint'; sConsumerKey = 'ConsumerKey'; sConsumerSecret = 'ConsumerSecret'; sVerifierPIN = 'VerifierPIN'; var LGetMemberObject: IGetMemberObject; begin CheckInactive; ClearFields; if Authenticator <> nil then begin LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(self); CreateReadWriteField<string>(sAccessToken, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.AccessToken; end, procedure(AValue: string) begin Authenticator.AccessToken := AValue; end); CreateReadWriteField<string>(sAccessTokenSecret, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.AccessTokenSecret; end, procedure(AValue: string) begin Authenticator.AccessTokenSecret := AValue; end); CreateReadWriteField<string>(sAccessTokenEndpoint, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.AccessTokenEndpoint; end, procedure(AValue: string) begin Authenticator.AccessTokenEndpoint := AValue; end); CreateReadWriteField<string>(sRequestToken, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.RequestToken; end, procedure(AValue: string) begin Authenticator.RequestToken := AValue; end); CreateReadWriteField<string>(sRequestTokenSecret, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.RequestTokenSecret; end, procedure(AValue: string) begin Authenticator.RequestTokenSecret := AValue; end); CreateReadWriteField<string>(sRequestTokenEndpoint, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.RequestTokenEndpoint; end, procedure(AValue: string) begin Authenticator.RequestTokenEndpoint := AValue; end); CreateReadWriteField<string>(sAuthenticationEndpoint, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.AuthenticationEndpoint; end, procedure(AValue: string) begin Authenticator.AuthenticationEndpoint := AValue; end); CreateReadWriteField<string>(sCallbackEndpoint, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.CallbackEndpoint; end, procedure(AValue: string) begin Authenticator.CallbackEndpoint := AValue; end); CreateReadWriteField<string>(sConsumerKey, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.ConsumerKey; end, procedure(AValue: string) begin Authenticator.ConsumerKey := AValue; end); CreateReadWriteField<string>(sConsumerSecret, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.ConsumerSecret; end, procedure(AValue: string) begin Authenticator.ConsumerSecret := AValue; end); CreateReadWriteField<string>(sVerifierPIN, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.VerifierPIN; end, procedure(AValue: string) begin Authenticator.VerifierPIN := AValue; end); end; end; { TSubOAuth2AuthenticationBindSource } function TSubOAuth2AuthenticationBindSource.CreateAdapterT: TRESTAuthenticatorAdapter<TOAuth2Authenticator>; begin result := TOAuth2AuthenticatorAdapter.Create(self); end; { TOAuth2AuthenticatorAdapter } procedure TOAuth2AuthenticatorAdapter.AddFields; const sAccessToken = 'AccessToken'; sAccessTokenEndpoint = 'AccessTokenEndpoint'; sRefreshToken = 'RefreshToken'; sAuthCode = 'AuthCode'; sClientID = 'ClientID'; sClientSecret = 'ClientSecret'; sAuthorizationEndpoint = 'AuthorizationEndpoint'; sRedirectionEndpoint = 'RedirectionEndpoint'; sScope = 'Scope'; sLocalState = 'LocalState'; var LGetMemberObject: IGetMemberObject; begin CheckInactive; ClearFields; if Authenticator <> nil then begin LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(self); CreateReadWriteField<string>(sAccessToken, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.AccessToken; end, procedure(AValue: string) begin Authenticator.AccessToken := AValue; end); CreateReadWriteField<string>(sAccessTokenEndpoint, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.AccessTokenEndpoint; end, procedure(AValue: string) begin Authenticator.AccessTokenEndpoint := AValue; end); CreateReadWriteField<string>(sRefreshToken, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.RefreshToken; end, procedure(AValue: string) begin Authenticator.RefreshToken := AValue; end); CreateReadWriteField<string>(sAuthCode, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.AuthCode; end, procedure(AValue: string) begin Authenticator.AuthCode := AValue; end); CreateReadWriteField<string>(sClientID, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.ClientID; end, procedure(AValue: string) begin Authenticator.ClientID := AValue; end); CreateReadWriteField<string>(sClientSecret, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.ClientSecret; end, procedure(AValue: string) begin Authenticator.ClientSecret := AValue; end); CreateReadWriteField<string>(sAuthorizationEndpoint, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.AuthorizationEndpoint; end, procedure(AValue: string) begin Authenticator.AuthorizationEndpoint := AValue; end); CreateReadWriteField<string>(sRedirectionEndpoint, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.RedirectionEndpoint; end, procedure(AValue: string) begin Authenticator.RedirectionEndpoint := AValue; end); CreateReadWriteField<string>(sScope, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.Scope; end, procedure(AValue: string) begin Authenticator.Scope := AValue; end); CreateReadWriteField<string>(sLocalState, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.LocalState; end, procedure(AValue: string) begin Authenticator.LocalState := AValue; end); end; end; initialization RegisterClasses([TOAuth1SignatureMethod_PLAINTEXT, TOAuth1SignatureMethod_HMAC_SHA1]); end.
unit iaUnitTest.TCountdownEvent.BasicOperation; interface uses DUnitX.TestFramework, System.SyncObjs; type [TestFixture] TiaTestTCountdownEventBasicOperation = class(TObject) public [Test] procedure InitialZeroCount_IsImmediatelySignaled(); [Test] procedure InitialZeroCount_ResetToZeroSignals(); [Test] procedure InitialZeroCount_ResetGreaterThanZeroNotSignaled(); [Test] procedure InitialNegativeCount_ExceptionOnCreate(); [Test] procedure EventCountOverMaxInt_Exception(); [Test] procedure TryAddZero_Exception(); [Test] procedure TryAddNegative_Exception(); [Test] procedure ResetNegative_Exception(); [Test] procedure ResetChangesBothInitialAndCurrentCount(); [Test] procedure ZeroCount_TryAddFails(); [Test] procedure ZeroCount_ExceptionOnAddCount(); [Test] procedure ZeroCount_ExceptionOnSignal(); [Test] procedure SignalDefaultAmountIsOneCount(); [Test] procedure AddChangesCurrentCountButNotInitialCount(); //procedure SignalDefault_ZeroInitialCount = ZeroCount_ExceptionOnSignal [Test] procedure SignalDefault_OneInitialCountReturnsTrue(); [Test] procedure SignalDefault_MoreThanOneInitialCountReturnsFalse(); [Test] procedure SignalOne_OneInitalCountReturnsTrue(); [Test] procedure SignalOne_MoreThanOneIntialCountReturnsFalse(); [Test] procedure SignalTwo_TwoInitalCountReturnsTrue(); [Test] procedure SignalTwo_MoreThanTwoIntialCountReturnsFalse(); [Test] procedure SignalGreaterThanCount_Exception(); [Test] [TestCase('Created with 0 Count','0')] [TestCase('Created with 1 Count','1')] [TestCase('Created with 2 Count','2')] [TestCase('Created with 3 Count','3')] [TestCase('Created with 1000 Count','1000')] [TestCase('Created with MaxInt-1 Count','2147483646')] [TestCase('Created with MaxInt Count','2147483647')] procedure CountsMatchCreatedAmount(const pCreateCount:Integer); end; implementation uses System.SysUtils, System.Classes; procedure TiaTestTCountdownEventBasicOperation.InitialZeroCount_IsImmediatelySignaled(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(0); try Assert.IsTrue(obj.IsSet, 'Creating object with 0 count should be immediately signaled'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.InitialZeroCount_ResetToZeroSignals(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(0); try //variation 1: No argument passed, should use InitialCount obj.Reset; Assert.IsTrue(obj.IsSet, 'Resetting object with no argument and 0 initial count should be signaled'); //variation 2: Explicit count of 0 passed on reset obj.Reset(0); Assert.IsTrue(obj.IsSet, 'Resetting object with 0 new count should be signaled'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.InitialZeroCount_ResetGreaterThanZeroNotSignaled(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(0); try //variation 1: after creation with 0 count obj.Reset(1); Assert.IsFalse(obj.IsSet, 'Resetting object initially created with 0 but reset above 0 should not be be signaled'); obj.Reset(0); Assert.IsTrue(obj.IsSet, 'Resetting object with 0 new count should be signaled'); //variation 2: after reset to 0 count obj.Reset(1); Assert.IsFalse(obj.IsSet, 'Resetting object reset to 0 and reset > 0 should not be be signaled'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.ResetChangesBothInitialAndCurrentCount(); const INITIAL_COUNT = 0; NEW_COUNT = INITIAL_COUNT + 1; var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(INITIAL_COUNT); try obj.Reset(NEW_COUNT); Assert.AreEqual(obj.InitialCount, NEW_COUNT, 'Resetting count should change initial count'); Assert.AreEqual(obj.CurrentCount, NEW_COUNT, 'Resetting count should change current count'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.ZeroCount_TryAddFails(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(0); try //variant 1: Default (1) Assert.IsFalse(obj.TryAddCount(), 'TryAddCount() when count is zero should fail'); //variant 2: Explict 1 Assert.IsFalse(obj.TryAddCount(1), 'TryAddCount(1) when count is zero should fail'); //variant 3: Explicit > 1 Assert.IsFalse(obj.TryAddCount(2), 'TryAddCount(2) when count is zero should fail'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.ZeroCount_ExceptionOnAddCount(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(0); try Assert.WillRaise(procedure begin obj.AddCount(1); end, EInvalidOperation, 'AddCount when count is zero should raise an exception'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.ZeroCount_ExceptionOnSignal(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(0); try Assert.WillRaise(procedure begin obj.Signal; end, EInvalidOperation, 'Signal when count is zero should raise an exception'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.InitialNegativeCount_ExceptionOnCreate(); begin Assert.WillRaise(procedure begin TCountdownEvent.Create(-1); end, EArgumentOutOfRangeException, 'Negative initial count should raise an exception'); end; procedure TiaTestTCountdownEventBasicOperation.EventCountOverMaxInt_Exception(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(MaxInt); try //variant 1: Add a small amount to a large amount, total > MaxInt Assert.WillRaise(procedure begin obj.TryAddCount(1); end, EInvalidOperation, 'TryAddCount(1) pushing total count above MaxInt should raise an exception'); //variant 2: Add a large amount to a small amount, total > MaxInt obj.Reset(1); Assert.WillRaise(procedure begin obj.TryAddCount(MaxInt); end, EInvalidOperation, 'TryAddCount(MaxInt) pushing total count above MaxInt should raise an exception'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.TryAddZero_Exception(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(2); try Assert.WillRaise(procedure begin obj.TryAddCount(0); end, EArgumentOutOfRangeException, 'TryAddCount(0) should raise an exception'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.TryAddNegative_Exception(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(2); try Assert.WillRaise(procedure begin obj.TryAddCount(-1); end, EArgumentOutOfRangeException, 'TryAddCount(negative count) should raise an exception'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.ResetNegative_Exception(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(2); try Assert.WillRaise(procedure begin obj.Reset(-1); end, EArgumentOutOfRangeException, 'Reset(negative count) should raise an exception'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.SignalDefaultAmountIsOneCount(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(2); try obj.Signal; Assert.AreEqual(obj.CurrentCount, 1, 'Using Signal without a parameter should be a count of one'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.AddChangesCurrentCountButNotInitialCount(); const INITIAL_COUNT = 1; ADD_COUNT = 1; var obj:TCountdownEvent; vCurrentCountBeforeAdd:Integer; begin obj := TCountdownEvent.Create(INITIAL_COUNT); try vCurrentCountBeforeAdd := obj.CurrentCount; obj.AddCount(ADD_COUNT); Assert.AreEqual(obj.CurrentCount, vCurrentCountBeforeAdd + ADD_COUNT, 'Adding should reset current count'); Assert.AreEqual(obj.InitialCount, INITIAL_COUNT, 'Adding should not change initial count'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.SignalDefault_OneInitialCountReturnsTrue(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(1); try //variant 1: Signal with known creation count Assert.IsTrue(obj.Signal, 'When count reaches zero immediately after creation of count 1, Signal should return true'); //variant 2: Signal with known reset count obj.Reset(1); Assert.IsTrue(obj.Signal, 'When count reaches zero immediately after reset with count 1, Signal should return true'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.SignalDefault_MoreThanOneInitialCountReturnsFalse(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(2); try //variant 1: Signal with known creation count Assert.IsFalse(obj.Signal, 'When initial creation count above 1, Signal should return false'); //variant 2: Signal with known reset count obj.Reset(2); Assert.IsFalse(obj.Signal, 'When reset count above 1, Signal should return false'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.SignalOne_OneInitalCountReturnsTrue(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(1); try //variant 1: Signal with known creation count Assert.IsTrue(obj.Signal(1), 'When count reaches zero immediately after creation of count 1, Signal should return true'); //variant 2: Signal with known reset count obj.Reset(1); Assert.IsTrue(obj.Signal(1), 'When count reaches zero immediately after reset with count 1, Signal should return true'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.SignalOne_MoreThanOneIntialCountReturnsFalse(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(2); try //variant 1: Signal with known creation count Assert.IsFalse(obj.Signal(1), 'When initial creation count above 1, Signal should return false'); //variant 2: Signal with known reset count obj.Reset(2); Assert.IsFalse(obj.Signal(1), 'When reset count above 1, Signal should return false'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.SignalTwo_TwoInitalCountReturnsTrue(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(2); try //variant 1: Signal with known creation count Assert.IsTrue(obj.Signal(2), 'When count reaches zero immediately after creation of count 2, Signal(2) should return true'); //variant 2: Signal with known reset count obj.Reset(2); Assert.IsTrue(obj.Signal(2), 'When count reaches zero immediately after reset with count 2, Signal(2) should return true'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.SignalTwo_MoreThanTwoIntialCountReturnsFalse(); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(3); try //variant 1: Signal with known creation count Assert.IsFalse(obj.Signal(2), 'When initial creation count above 2, Signal(2) should return false'); //variant 2: Signal with known reset count obj.Reset(3); Assert.IsFalse(obj.Signal(2), 'When reset count above 2, Signal(2) should return false'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.SignalGreaterThanCount_Exception(); const SIGNALCOUNT = 2; var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(SIGNALCOUNT); try Assert.WillRaise(procedure begin obj.Signal(SIGNALCOUNT+1); end, EInvalidOperation, 'Signaling more than current count should raise an exception'); finally obj.Free(); end; end; procedure TiaTestTCountdownEventBasicOperation.CountsMatchCreatedAmount(const pCreateCount:Integer); var obj:TCountdownEvent; begin obj := TCountdownEvent.Create(pCreateCount); try Assert.AreEqual(pCreateCount, obj.InitialCount, 'When created, Initial count should match created count'); Assert.AreEqual(pCreateCount, obj.CurrentCount, 'When created, Current count should match created count'); finally obj.Free(); end; end; end.
{ (Opus) Last modified: 01.12.2000 10:22:16 by peo } { $Id: EmbeddableGUITestRunner.pas 7 2008-04-24 11:59:47Z judc $ } {: DUnit: An XTreme testing framework for Delphi programs. @author The DUnit Group. @version $Revision: 7 $ } (* * 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 Anez. * Portions created The Initial Developers are Copyright (C) 1999-2000. * Portions created by The DUnit Group are Copyright (C) 2000. * All rights reserved. * * Contributor(s): * Kent Beck <kentbeck@csi.com> * Erich Gamma <Erich_Gamma@oti.com> * Juanco Anez <juanco@users.sourceforge.net> * Chris Morris <chrismo@users.sourceforge.net> * Jeff Moore <JeffMoore@users.sourceforge.net> * Kenneth Semeijn <dunit@designtime.demon.nl> * The DUnit group at SourceForge <http://dunit.sourceforge.net> * *) unit EmbeddableGUITestRunner; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, ActnList, ImgList, StdCtrls, ComCtrls, ExtCtrls, Buttons, GUITestRunner; type {: Embeddable GUI test runner form. Sample usage: <pre> procedure TFormMain.FormCreate(Sender: TObject); begin inherited; FTestDialog:= TEmbeddableDUnitDialog.CreateInto( Self, TabTest ); FTestDialog.Suite:= RegisteredTests; end; procedure TFormMain.FormDestroy(Sender: TObject); begin if Assigned( FTestDialog ) then begin FTestDialog.RemoveFrom( Self, TabTest ); FreeAndNil( FTestDialog ); end; inherited; end; </pre> } TEmbeddableDUnitDialog = class(TGUITestRunner) pmHosted: TPopupMenu; pmiHostSave: TMenuItem; pmiHostRestore: TMenuItem; N3: TMenuItem; pmiHostAutoSave: TMenuItem; pmiHostAutoFocus: TMenuItem; pmiHostHideOnOpen: TMenuItem; N4: TMenuItem; pmiHostErrorBox: TMenuItem; pmiHostBreak: TMenuItem; cbBreakOnFailures: TCheckBox; private FHostForm: TForm; protected procedure ReParent(hostControl: TWinControl; preserveItems: boolean = True); procedure OnCloseHostForm(Sender: TObject); public {: Creates a DUnit GUI test runner into the supplied <code>hostControl</code> which must be contained in the form <code>hostForm</code>. The original GUI test runner main menu is replaced by a popup menu active anywhere in the embedded test runner except for the tests tree. } class function CreateInto(hostForm: TForm; hostControl: TWinControl): TEmbeddableDUnitDialog; {: Integrates the DUnit GUI test runner into the supplied <code>hostControl</code> which must be contained in the form <code>hostForm</code>. } procedure IntegrateInto(hostForm: TForm; hostControl: TWinControl); {: Removes the DUnit GUI test runner from the <code>hostControl</code> again. This <em>must</em> be done prior to destroying <code>hostForm</code>. I suggest you you place the call to this method in the host form's <code>OnDestroy</code> event. } procedure RemoveFrom(hostForm: TForm; hostControl: TWinControl); end {TDUnitDialogExt}; {==============================================================================} implementation {$R *.DFM} class function TEmbeddableDUnitDialog.CreateInto(hostForm: TForm; hostControl: TWinControl): TEmbeddableDUnitDialog; begin assert(Assigned(hostForm)); assert(Assigned(hostControl)); result:= TEmbeddableDUnitDialog.Create(hostForm); result.IntegrateInto(hostForm, hostControl); end; procedure TEmbeddableDUnitDialog.IntegrateInto( hostForm: TForm; hostControl: TWinControl ); begin FHostForm:= hostForm; ReParent(hostControl); CloseButton.OnClick := OnCloseHostForm; end; procedure TEmbeddableDUnitDialog.RemoveFrom(hostForm: TForm; hostControl: TWinControl); begin ReParent(Self, False); end; procedure TEmbeddableDUnitDialog.ReParent(hostControl: TWinControl; preserveItems: boolean = True); var subItemText: string; begin assert(Assigned(hostControl)); if preserveItems then begin { item and subitems get lost when the list view is re-parented; Delphi bug! } subItemText := ResultsView.Items[0].SubItems.Text; end; BottomPanel.Parent := hostControl; BodyPanel.Parent := hostControl; if preserveItems then begin with ResultsView.Items.Add do begin SubItems.Text := subItemText; end; end; end; procedure TEmbeddableDUnitDialog.OnCloseHostForm(Sender: TObject); begin assert(Assigned(FHostForm)); if FTestResult <> nil then FTestResult.stop; FHostForm.Close; end; end.
{******************************************************************************* 作者: dmzn@163.com 2012-02-03 描述: 业务常量定义 备注: *.所有In/Out数据,最好带有TBWDataBase基数据,且位于第一个元素. *******************************************************************************} unit UBusinessConst; interface uses UBusinessPacker; const {*channel type*} cBus_Channel_Connection = $0002; cBus_Channel_Business = $0005; {*business command*} cBC_GetSerialNO = $0001; //获取串行编号 cBC_ServerNow = $0002; //服务器当前时间 cBC_IsSystemExpired = $0003; //系统是否已过期 cBC_RemoteExecSQL = $0004; //执行数据库语句 cBC_SaveTruckIn = $0010; //保存车辆进厂 cBC_CapturePicture = $0011; //抓拍图片 cBC_HYReaderOpenDoor = $0012; //打开道闸 type PWorkerQueryFieldData = ^TWorkerQueryFieldData; TWorkerQueryFieldData = record FBase : TBWDataBase; FType : Integer; //类型 FData : string; //数据 end; PWorkerBusinessCommand = ^TWorkerBusinessCommand; TWorkerBusinessCommand = record FBase : TBWDataBase; FCommand : Integer; //命令 FData : string; //数据 FExtParam : string; //参数 end; resourcestring {*PBWDataBase.FParam*} sParam_NoHintOnError = 'NHE'; //不提示错误 {*plug module id*} sPlug_ModuleBus = '{DF261765-48DC-411D-B6F2-0B37B14E014E}'; //业务模块 sPlug_ModuleHD = '{B584DCD6-40E5-413C-B9F3-6DD75AEF1C62}'; //硬件守护 {*common function*} sSys_SweetHeart = 'Sys_SweetHeart'; //心跳指令 sSys_BasePacker = 'Sys_BasePacker'; //基本封包器 {*business mit function name*} sBus_ServiceStatus = 'Bus_ServiceStatus'; //服务状态 sBus_GetQueryField = 'Bus_GetQueryField'; //查询的字段 sBus_BusinessCommand = 'Bus_BusinessCommand'; //业务指令 sBus_HardwareCommand = 'Bus_HardwareCommand'; //硬件指令 {*client function name*} sCLI_ServiceStatus = 'CLI_ServiceStatus'; //服务状态 sCLI_GetQueryField = 'CLI_GetQueryField'; //查询的字段 sCLI_BusinessCommand = 'CLI_BusinessCommand'; //业务指令 sCLI_HardwareCommand = 'CLI_HardwareCommand'; //硬件指令 implementation end.
unit p2_baseless_VCL_example_main; interface uses Windows, Messages, SysUtils, Classes, Forms, AppEvnts, StdCtrls, Controls, ActiveX, OleServer, ComObj, P2ClientGate_TLB; // класс для получения времени с точностью до милисекунд type TPreciseTime = class(TComponent) private fTime: tDateTime; fStart: int64; fFreq: int64; public constructor Create(AOwner: TComponent); override; function Now: TDateTime; function Msecs: longint; end; // главная форма приложения type TForm1 = class(TForm) LogListBox: TListBox; ConnectButton: TButton; DisconnectButton: TButton; procedure FormCreate(Sender: TObject); procedure ConnectButtonClick(Sender: TObject); procedure DisconnectButtonClick(Sender: TObject); private fPreciseTime: TPreciseTime; fApp: TCP2Application; fConn: TCP2Connection; fStream: TCP2DataStream; procedure ProcessPlaza2Messages(Sender: TObject; var Done: Boolean); procedure ConnectionStatusChanged(Sender: TObject; var conn: OleVariant; newStatus: TConnectionStatus); procedure StreamStateChanged(Sender: TObject; var stream: OleVariant; newState: TDataStreamState); procedure StreamLifeNumChanged(Sender: TObject; var stream: OleVariant; LifeNum: Integer); procedure StreamDataBegin(Sender: TObject; var stream: OleVariant); procedure StreamDataInserted(Sender: TObject; var stream: OleVariant; var tableName: OleVariant; var rec: OleVariant); procedure StreamDataEnd(Sender: TObject; var stream: OleVariant); public function CheckAndReopen(AStream: TCP2DataStream): boolean; procedure log(const alogstr: string); overload; procedure log(const alogstr: string; const aparams: array of const); overload; end; var Form1: TForm1; implementation {$R *.DFM} { TPreciseTime } constructor TPreciseTime.Create(AOwner: TComponent); begin inherited Create(AOwner); QueryPerformanceFrequency(fFreq); FTime:= SysUtils.now; QueryPerformanceCounter(fStart); end; function TPreciseTime.Now: TDateTime; var fEnd : int64; begin QueryPerformanceCounter(fEnd); result:= fTime + (((fEnd - fStart) * 1000) div fFreq) / 86400000.0; end; function TPreciseTime.Msecs: longint; var fEnd : int64; begin QueryPerformanceCounter(fEnd); result:= (fEnd * 1000) div fFreq; end; { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin // устанавливаем обработчик события Application.OnIdle, в нем мы будем запускать // обработку сообщений plaza2 Application.OnIdle:= ProcessPlaza2Messages; // создаем счетчик времени fPreciseTime:= TPreciseTime.Create(Self); // проверяем наличие конфигурационного файла if not fileexists('P2ClientGate.ini') then begin // если файл отсутствует, выводим сообщение MessageBox(0, 'Отсутствует файл настроек P2ClientGate.ini', 'Ошибка', 0); // закрываем приложение PostMessage(Handle, WM_CLOSE, 0, 0); end; // создаем экземпляр приложения plaza2 fApp:= TCP2Application.Create(Self); // указываем имя ini-файла с настройками библиотеки fApp.StartUp('P2ClientGate.ini'); // создаем соединение plaza2 fConn:= TCP2Connection.create(Self); with fConn do begin // устанавливаем адрес машины с роутером (в данном случае - локальный) Host:= 'localhost'; // указываем порт, к которому подключается это приложение Port:= 4001; // задаем произвольное имя приложения AppName:= 'P2VCLTestApp'; // устанавливаем обработчик изменения статуса потока (connected, error...) OnConnectionStatusChanged:= ConnectionStatusChanged; end; // создаем поток plaza2 fStream := TCP2DataStream.create(Self); with fStream do begin // указываем режим открытия потока (в delphi слово type - ключевое, при импорте // библиотеки типов оно было автоматически переименовано type_:= RT_COMBINED_DYNAMIC; // задаем имя потока, например сделки по фьючерсам StreamName:= 'FORTS_FUTTRADE_REPL'; // устанавливаем обработчик изменения статуса потока (remote_snapshot, online...) OnStreamStateChanged:= StreamStateChanged; // устанавливаем обработчик смены номера жизни, он необходим для корректного // перехода потока в online OnStreamLifeNumChanged:= StreamLifeNumChanged; // устанавливаем обработчик "начало данных" OnStreamDataBegin:= StreamDataBegin; // устанавливаем обработчик получения данных (будем выводить все данные построчно в ListBox) OnStreamDataInserted:= StreamDataInserted; // устанавливаем обработчик "конец данных" OnStreamDataEnd:= StreamDataEnd; end; end; procedure TForm1.ProcessPlaza2Messages(Sender: TObject; var Done: Boolean); var cookie : longword; begin // проверяем статус потока и переоткрываем его, если это необходимо if assigned(fConn) and (fConn.Status and CS_CONNECTION_CONNECTED <> 0) then begin CheckAndReopen(fStream); // ... end; // запускаем обработку сообщения plaza2 cookie:= 0; if assigned(fConn) then fConn.ProcessMessage(cookie, 1); // указываем, что обработка не завершена, для того чтобы vcl не уходил в ожидание сообщений windows Done:= false; end; function TForm1.CheckAndReopen(AStream: TCP2DataStream): boolean; begin // проверка и переоткрытие потока result:= true; if assigned(AStream) then with AStream do try // если статус потока - ошибка или закрыт if (State = DS_STATE_ERROR) or (State = DS_STATE_CLOSE) then begin // ксли ошибка, то закрываем if (State = DS_STATE_ERROR) then Close; // далее пытаемся открыть его вновь if assigned(fConn) then Open(fConn.DefaultInterface); end; except result:= false; end; end; procedure TForm1.ConnectionStatusChanged(Sender: TObject; var conn: OleVariant; newStatus: TConnectionStatus); begin // выводим сообщение об изменении статуса соединения log('Connection status changed to: %.8x', [longint(newStatus)]); end; procedure TForm1.StreamStateChanged(Sender: TObject; var stream: OleVariant; newState: TDataStreamState); const state_unknown = -1; const streamstates: array[state_unknown..DS_STATE_ERROR] of pChar = ('UNKNOWN', 'DS_STATE_CLOSE', 'DS_STATE_LOCAL_SNAPSHOT', 'DS_STATE_REMOTE_SNAPSHOT', 'DS_STATE_ONLINE', 'DS_STATE_CLOSE_COMPLETE', 'DS_STATE_REOPEN', 'DS_STATE_ERROR'); var st: longint; begin // выводим сообщение об изменении статуса потока st:= newState; if (st < low(streamstates)) or (st > high(streamstates)) then st:= state_unknown; log('Stream %s state changed to %s (%.8x)', [stream.StreamName, streamstates[st], st]); end; procedure TForm1.StreamLifeNumChanged(Sender: TObject; var stream: OleVariant; LifeNum: Integer); begin // при изменении номера жизни потока, указываем потоку новый номер жизни stream.TableSet.LifeNum:= olevariant(lifenum); // выводим сообщение об этом log('Stream %s LifeNum changed to: %d', [string(stream.StreamName), lifenum]); end; procedure TForm1.StreamDataBegin(Sender: TObject; var stream: OleVariant); begin // выводим сообщение о том, что начата обработка пачки log('Stream: %s data begin', [string(stream.StreamName)]); end; procedure TForm1.StreamDataInserted(Sender: TObject; var stream, tableName, rec: OleVariant); var i : longint; data : string; begin // обработка пришедших данных // получаем имя потока и таблицы data:= format('%s %s ', [string(stream.StreamName), string(tableName)]); // последовательно получаем все поля записи в виде строк и помещаем в строку для последующего вывода with IP2Record(IUnknown(rec)) do for i:= 0 to Count - 1 do data:= data + GetValAsStringByIndex(i) + ','; // выводим подготовленную строку в лог log(data); end; procedure TForm1.StreamDataEnd(Sender: TObject; var stream: OleVariant); begin // выводим сообщение о том, что обработка данных закончена log('Stream: %s data end', [string(stream.StreamName)]); end; procedure TForm1.ConnectButtonClick(Sender: TObject); begin // установление соединения по кнопке connect // при импорте библиотеки типов метод Connect был автоматически переименован в // Connect1 для того, чтобы избежать пересечения со стандартным методом Connect // Ole-сервера дельфи if assigned(fConn) then try fConn.Connect1; except on e: exception do log('Connect exception: %s', [e.message]); end; end; procedure TForm1.DisconnectButtonClick(Sender: TObject); begin // разрыв соединения по кнопке disconnect // при импорте библиотеки типов метод Disconnect был автоматически переименован в // Disconnect1 для того, чтобы избежать пересечения со стандартным методом Connect // Ole-сервера дельфи if assigned(fConn) then try fConn.Disconnect1; except on e: exception do log('Disconnect exception: %s', [e.message]); end; end; procedure TForm1.log(const alogstr: string); begin // вывод информации в LogListBox if assigned(LogListBox) then with LogListBox.Items do begin // храним только 50 строк if (Count > 50) then Delete(Count - 1); // добавляем строки в начало Insert(0, formatdatetime('hh:nn:ss.zzz ', fPreciseTime.Now) + alogstr); end; end; procedure TForm1.log(const alogstr: string; const aparams: array of const); begin // вывод лога с форматированием строки log(format(alogstr, aparams)); end; initialization // инициализируем COM CoInitializeEx(nil, COINIT_APARTMENTTHREADED); finalization CoUnInitialize; end.
unit MainUnit; interface uses Types, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, Menus, ImgList, ExtCtrls; type TMainForm = class(TForm) PageControl: TPageControl; PageTest: TTabSheet; TestList: TListView; PopupTests: TPopupMenu; IAdd: TMenuItem; IDelete: TMenuItem; IProperties: TMenuItem; ImagesTest: TImageList; ISep0: TMenuItem; IOpen: TMenuItem; procedure FormCreate(Sender: TObject); procedure ShowList; procedure IOpenClick(Sender: TObject); procedure TestListDblClick(Sender: TObject); procedure IDeleteClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure IAddClick(Sender: TObject); procedure IPropertiesClick(Sender: TObject); procedure TestListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; var MainForm : TMainForm; Base : TBase; AParent : TObject; Def_grade : integer = 11; ClearBitMap : TBitMap; BaseName : string = 'Base.dat'; implementation uses AddTestUnit, AddQuestUnit, AddAnswerUnit; {$R *.DFM} Procedure TMainForm.ShowList; var I : integer; begin with TestList do begin Items.BeginUpdate; Items.Clear; If AParent is TBase then begin Columns[0].Caption := 'Тема теста'; Columns[2].Caption := 'Кол-во вопросов'; Columns[3].Caption := 'Шкала оценивания'; Columns[4].Caption := 'Время'; Columns[5].Caption := 'Обучающий'; For I := 0 to Base.Count - 1 do with Items.Add do begin Caption := Base.Items[I].Name; ImageIndex := 0; SubItems.Add(IntToStr(Base.Items[I].Mark)); SubItems.Add(IntToStr(Base.Items[I].Count)); SubItems.Add(IntTOStr(Base.Items[I].Grade)); SubItems.Add(IntTOStr(Base.Items[I].TotalTime)); If Base.Items[I].Teach then SubItems.Add('да') else SubItems.Add('нет'); SubItems.Objects[0] := Base.Items[I]; end; end else If AParent is TTest then begin Columns[0].Caption := 'Текст вопроса'; Columns[2].Caption := 'Кол-во ответов'; Columns[3].Caption := 'Рисунок'; Columns[4].Caption := ''; Columns[5].Caption := ''; Items.Add.Caption := '.. -> (' + (AParent as TTest).Name + ')'; For I := 0 to (AParent as TTest).Count - 1 do with Items.Add do begin Caption := (AParent as TTest).Questions[I].Text; ImageIndex := 1; SubItems.Add(IntToStr((AParent as TTest).Questions[I].Mark)); SubItems.Add(IntToStr((AParent as TTest).Questions[I].Count)); If (AParent as TTest).Questions[I].FaveImage then SubItems.Add('есть') else SubItems.Add('нет'); SubItems.Objects[0] := (AParent as TTest).Questions[I]; end; end else If AParent is TQuestion then begin Columns[0].Caption := 'Текст ответа'; Columns[2].Caption := 'Рисунок'; Columns[3].Caption := ''; Columns[4].Caption := ''; Columns[5].Caption := ''; with Items.Add do begin Caption := '.. -> (' + (AParent as TQuestion).Text + ')'; ImageIndex := 1; end; For I := 0 to (AParent as TQuestion).Count - 1 do with Items.Add do begin Caption := (AParent as TQuestion).Answers[I].Text; ImageIndex := 2; SubItems.Add(IntToStr((AParent as TQuestion).Answers[I].Mark)); If (AParent as TQuestion).Answers[I].FaveImage then SubItems.Add('есть') else SubItems.Add('нет'); SubItems.Objects[0] := (AParent as TQuestion).Answers[I]; end; end; Items.EndUpdate; end; end; procedure TMainForm.FormCreate(Sender: TObject); begin Base := TBase.Create; Base.Load(ExtractFilePath(ParamStr(0)) + BaseName); AParent := Base; ShowList; ClearBitMap := TBitMap.Create; ClearBitMap.Width := 1; ClearBitMap.Height := 1; end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Base.Save(ExtractFilePath(ParamStr(0)) + BaseName); end; procedure TMainForm.IOpenClick(Sender: TObject); begin If TestList.Selected <> nil then If AParent is TBase then begin AParent := TestList.Selected.SubItems.Objects[0]; ShowList; end else If TestList.Selected.Index = 0 then begin If AParent is TTest then AParent := Base else AParent := (AParent as TQuestion).Parent; ShowList; end else If AParent is TQuestion then IPropertiesClick(Self) else begin AParent := TestList.Selected.SubItems.Objects[0]; ShowList; end; end; procedure TMainForm.TestListDblClick(Sender: TObject); begin IOpenClick(Self); end; procedure TMainForm.IDeleteClick(Sender: TObject); begin If TestList.Selected <> nil then begin If AParent is TBase then begin If Application.MessageBox('Будет произведено удаление. Продолжить?','Удаление',MB_OKCANCEL + MB_ICONASTERISK) = ID_OK then begin Base.Delete(TestList.Selected.Index); TestList.Selected.Delete; end; end else If TestList.Selected.Index > 0 then If Application.MessageBox('Будет произведено удаление. Продолжить?','Удаление',MB_OKCANCEL + MB_ICONASTERISK) = ID_OK then begin If AParent is TTest then begin (AParent as TTest).Delete(TestList.Selected.Index); TestList.Selected.Delete; end else If AParent is TQuestion then begin (AParent as TQuestion).Delete(TestList.Selected.Index); TestList.Selected.Delete; end; end; end; ShowList; end; procedure TMainForm.IAddClick(Sender: TObject); begin If AParent is TBase then begin AddTestForm.Caption := 'Добавление теста'; AddTestForm.Tag := 0; AddTestForm.Show; Enabled := False; end else If AParent is TTest then begin AddQuestForm.Caption := 'Добавление вопроса в тест "' + (AParent as TTest).Name + '"'; AddQuestForm.Tag := 0; AddQuestForm.Show; Enabled := False; end else If AParent is TQuestion then begin AddAnswerForm.Caption := 'Добавление ответа на вопрос "' + (AParent as TQuestion).Text + '"'; AddAnswerForm.Tag := 0; AddAnswerForm.Show; Enabled := False; end; end; procedure TMainForm.IPropertiesClick(Sender: TObject); begin If TestList.Selected <> nil then If AParent is TBase then begin AddTestForm.Caption := 'Изменение свойств теста'; AddTestForm.Tag := 1; AddTestForm.Show; Enabled := False; end else If TestList.Selected <> nil then If AParent is TTest then begin AddQuestForm.Caption := 'Изменение вопроса в тесте "' + (AParent as TTest).Name + '"'; AddQuestForm.Tag := 1; AddQuestForm.Show; Enabled := False; end else If AParent is TQuestion then begin AddAnswerForm.Caption := 'Изменение ответа на вопрос "' + (AParent as TQuestion).Text + '"'; AddAnswerForm.Tag := 1; AddAnswerForm.Show; Enabled := False; end end; procedure TMainForm.TestListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin Case Key of VK_SPACE : IPropertiesClick(Self); VK_BACK : If not(AParent is TBase) then begin TestList.Items.Item[0].Selected := True; IOpenClick(Self); end; VK_RETURN : IOpenClick(Self); VK_DELETE : IDeleteClick(Self); VK_INSERT : IAddClick(Self); end; end; end.
unit formMailerExeLauncher; interface {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, CustApp, { you can add units after this } Interfaces, fileutil, strutils, dialogs, IniFiles, Process, Unix, baseUnix, strings, StdCtrls; // mlr procedure LaunchExe(MemoComponent: TMemo); // mlr implementation const READ_BYTES = 2048; Arg0 : PChar = '/bin/ls'; // mlr Arg1 : Pchar = '-l'; // mlr var OurCommand: String; OutputLines: TStringList; MemStream: TMemoryStream; OurProcess: TProcess; i, NumBytes, BytesRead: LongInt; sTemp: String; procedure WritelnStrToList(MemoComponent: TMemo; sLine: string); var sProgressStr: string; SenderStringList: TStrings; begin SenderStringList := MemoComponent.Lines; SenderStringList.add(sLine); MemoComponent.Refresh; end; procedure DumpExceptionCallStack(E: Exception; MemoComponent: TMemo); // from Lazarus Wiki tutorial var I: Integer; Frames: PPointer; Report: string; begin Report := 'Program exception! ' + LineEnding + 'Stacktrace:' + LineEnding + LineEnding; if E <> nil then begin Report := Report + 'Exception class: ' + E.ClassName + LineEnding + 'Message: ' + E.Message + LineEnding; end; Report := Report + BackTraceStrFunc(ExceptAddr); Frames := ExceptFrames; for I := 0 to ExceptFrameCount - 1 do Report := Report + LineEnding + BackTraceStrFunc(Frames[I]); //ShowMessage(Report); // non-re-entrant, causes exception when called inside a thread WritelnStrToList(MemoComponent, Report); //Writeln(Report); //Halt; // End of program execution or... //Terminate // end TProcess thread end; Procedure LaunchExe(MemoComponent: TMemo); var sProgressStr: string; SenderStringList: TStrings; iExitCode: integer = 0; begin SenderStringList := MemoComponent.Lines; // A temp Memorystream is used to buffer the output MemStream := TMemoryStream.Create; BytesRead := 0; OurProcess := TProcess.Create(nil); try MemoComponent.Refresh; // Run this //OurProcess.Executable := './Sample.py'; // or this: //OurProcess.Executable := '/usr/local/bin/bash echo $HOME'; {$DEFINE Windows} {$IFDEF UNIX} // To send a file to a printer via commandline EXE (UNIX): OurProcess.Executable := './bashrun.sh'; OurProcess.Parameters.Add('lpr'); //OurProcess.Parameters.Add('/usr/home/mrathbun/KTI/GitHub_Repos/formMailer-1/Saved_TreeViews/TTreeView-1.txt'); OurProcess.Parameters.Add('/usr/home/mrathbun/KTI/GitHub_Repos/formMailer-1/Sample_PDFs/KTI_Profit_and_Loss_Statement_Jan-Dec_2012.pdf'); //OurProcess.Parameters.Add('echo'); //OurProcess.Parameters.Add('$HOME'); {$ENDIF} {$IFDEF Windows} // To send a file to a printer via commandline EXE (Windows/DOS): // use UNIX console commandline utility "lpstat -s" to see the name and IP address of the printer // that must be feed as arguments to Windows' lpr -S and -P parameters. // C:\Junk>lpr -S 192.168.000.243 -P Brother-MFC-9320CW TestBootINI.txt // (make sure to DOUBLE quote filenames/paths that have embedded spaces or special characters.) // Type lpr /? at the Windows command prompt for help. // OurProcess.Executable := 'lpr'; // OurProcess.Parameters.Add('-S'); // OurProcess.Parameters.Add('192.168.000.243'); // OurProcess.Parameters.Add('-P'); // OurProcess.Parameters.Add('Brother-MFC-9320CW'); // OurProcess.Parameters.Add('\Junk\TestText-ANSI.txt'); OurProcess.Executable := 'CMD.EXE'; OurProcess.Parameters.Add('lpr'); OurProcess.Parameters.Add('-S'); OurProcess.Parameters.Add('192.168.000.243'); OurProcess.Parameters.Add('-P'); OurProcess.Parameters.Add('Brother-MFC-9320CW'); OurProcess.Parameters.Add('\Junk\TestText-ANSI.txt'); {$ENDIF} OurProcess.Parameters.Delimiter := ' '; WritelnStrToList(MemoComponent, 'External Program To Run: ' + OurProcess.Executable // + ' ' + DelChars(OurProcess.Parameters.Text, #10)); + ' ' + OurProcess.Parameters.DelimitedText); // We cannot use poWaitOnExit here since we don't // know the size of the output. On Linux the size of the // output pipe is 2 kB; if the output data is more, we // need to read the data. This isn't possible since we are // waiting. So we get a deadlock here if we use poWaitOnExit. OurProcess.Options := [poUsePipes]; WritelnStrToList(MemoComponent, 'Program Started -'); Try OurProcess.Execute; except on E: Eprocess do begin DumpExceptionCallStack(E, MemoComponent); // shows source code line number where exception was raised. end; on E: Exception do begin DumpExceptionCallStack(E, MemoComponent); // shows source code line number where exception was raised. end; else begin raise; end; end; iExitCode := OurProcess.ExitStatus; WritelnStrToList(MemoComponent, ''); sProgressStr := 'Running'; while True do begin // make sure we have room MemStream.SetSize(BytesRead + READ_BYTES); // try reading it NumBytes := OurProcess.Output.Read((MemStream.Memory + BytesRead)^, READ_BYTES); if NumBytes > 0 // All read() calls will block, except the final one. then begin Inc(BytesRead, NumBytes); AppendStr(sProgressStr, '.'); // Use the following rather than WritelnStrToList(MemoComponent, ...) // because this does a "Write()" rather than a "Writeln()" to the // string list. SenderStringList.Strings[SenderStringList.Count-1] := sProgressStr; MemoComponent.Refresh; end else BREAK // Program has finished execution. end; MemStream.SetSize(BytesRead); WritelnStrToList(MemoComponent, 'Program Completed.'); WritelnStrToList(MemoComponent, 'TProcess.Execute''s Exit Code: '+ IntToStr(iExitCode)); OutputLines := TStringList.Create; OutputLines.LoadFromStream(MemStream); WritelnStrToList(MemoComponent, 'Program Output Line Count = ''' + IntToStr(OutputLines.Count) +'''' ); WritelnStrToList(MemoComponent, '-- Output Dump --'); for NumBytes := 0 to OutputLines.Count - 1 do begin WritelnStrToList(MemoComponent,'Line '+ IntToStr(NumBytes) + ':'); WritelnStrToList(MemoComponent,OutputLines[NumBytes]); end; WritelnStrToList(MemoComponent, '-- End Of Output --'); finally OutputLines.Free; OurProcess.Free; MemStream.Free; end; end; Initialization begin end; Finalization begin end; end.
unit uFasade; interface uses SysUtils, Classes, pFIBQuery, ComCtrls, uLogger, uServerConnect, uGameItems, uStrategy, uDB, uProxyCheck, uDefs; type TMoonFasade = class private FServerURL: string; FServerID: integer; FUserName, FPassword: string; FProxy: TProxy; FWorking: boolean; FMoonServer: TMoonServerConnect; FDB: TMoonDB; FImperium: TImperium; FStExec: TStrategyExecutor; public constructor Create; destructor Destroy; override; procedure Clear; procedure Init; procedure Run; procedure CreateWorld; procedure AddProxyToDB(filename: string); procedure ClearProxy; procedure SetProxy(ip, port: string); procedure StatPlanetList(lv: TListView); function StrStat: string; property ServerURL: string read FServerURL write FServerURL; property ServerID: integer read FServerID write FServerID; property UserName: string read FUserName write FUserName; property Password: string read FPassword write FPassword; property Proxy: TProxy read FProxy; end; implementation { TMoonFasade } procedure TMoonFasade.AddProxyToDB(filename: string); var pc: TProxyChecker; sl: TStringList; prx: TProxies; begin try sl := TStringList.Create; sl.LoadFromFile(filename); pc := TProxyChecker.Create; prx := pc.CheckList(sl.Text); pc.Free; sl.Free; except end; end; procedure TMoonFasade.Clear; begin FMoonServer := nil; FImperium := nil; FStExec := nil; FWorking := false; ClearProxy; end; procedure TMoonFasade.ClearProxy; begin FProxy.Active := false; end; constructor TMoonFasade.Create; begin inherited; FDB := TMoonDB.GetInstance; end; procedure TMoonFasade.CreateWorld; var i, j: integer; begin FDB.ClearUniverse; AddLog('universe cleared...'); for i := 1 to 9 do for j := 1 to 499 do FDB.AddSystem(i, j); FDB.Commit; AddLog('universe commited.'); end; destructor TMoonFasade.Destroy; begin inherited; FStExec.Free; FMoonServer.Free; FImperium.Free; end; procedure TMoonFasade.Init; var qry: TpFIBQuery; id: integer; begin AddLog('starting...', 0); FDB := TMoonDB.GetInstance; FDB.Connect; FMoonServer := TMoonServerConnect.Create; FMoonServer.SetProxy(FProxy); FMoonServer.Login(FServerURL, FServerID, FUserName, FPassword); FImperium := TImperium.Create; FStExec := TStrategyExecutor.Create(FImperium, FMoonServer); // FMoonServer.UpdateImperium(FImperium); // FMoonServer.BuildBuilding(FImperium, 638, 'Рудник кристалла', 0, false); qry := FDB.GetStrategyList; while not qry.Eof do begin id := -1; try id := qry.FieldByName('ID').AsInteger; FStExec.AddStrategy( id, qry.FieldByName('TYPE_ID').AsInteger, qry.FieldByName('PARAMS').AsString); if qry.FieldByName('ACTIVE').AsInteger <> 0 then FStExec.ActivateStrategy(id); AddLog('init strategy(' + IntToStr(id) + '/' + qry.FieldByName('TYPE_ID').AsString + '): "' + qry.FieldByName('NAME').AsString + '" ac=' + qry.FieldByName('ACTIVE').AsString, 5); except FStExec.DeactivateStrategy(id); end; qry.Next; end; qry.Close; FStExec.ApplyMacroStrategy(-1); AddLog('init ok', 0); end; procedure TMoonFasade.Run; begin if FWorking then exit; FWorking := true; try if FStExec = nil then Init; FStExec.Execute; finally FWorking := false; end; end; procedure TMoonFasade.SetProxy(ip, port: string); begin FProxy.Active := false; if (ip = '') or (StrToIntDef(port, 0) <= 0) then exit; FProxy.Active := true; FProxy.IP := ip; FProxy.Port := port; end; procedure TMoonFasade.StatPlanetList(lv: TListView); var li: TListItem; i: Integer; pl: TPlanet; begin lv.Items.Clear; if (FImperium = nil) or (not FImperium.Valid) then exit; lv.Items.BeginUpdate; try for i := 0 to FImperium.PlanetsCount - 1 do begin pl := FImperium.GetPlanetI(i); li := lv.Items.Add; li.Caption := IntToStr(pl.ID); if not pl.isMoon then li.SubItems.Add(pl.Name) else li.SubItems.Add('(m)' + pl.Name); li.SubItems.Add(IntToStr(pl.FreeFieldsCount)); li.SubItems.Add(ResToStr(pl.FreeEnergy)); li.SubItems.Add(pl.StrBuildsBuilding); li.SubItems.Add(pl.StrShipsBuilding); li.SubItems.Add( ResToStr(pl.CurRes.Metal) + '/' + ResToStr(pl.CurRes.Crystal) + '/' + ResToStr(pl.CurRes.Deiterium)); if pl.BuildingPlan.EndPlaningDate > Now then begin li.SubItems.Add(pl.BuildingPlan.Item.Name + ' ' + DateTimeToStr(pl.BuildingPlan.EndPlaningDate)); end else li.SubItems.Add(' '); end; finally lv.Items.EndUpdate; end; end; function TMoonFasade.StrStat: string; begin if (FImperium = nil) then begin Result := 'imperium n/a'; exit; end; if (not FImperium.Valid) then begin Result := 'imperium not valid'; exit; end; Result := DateTimeToStr(FImperium.LastUpdate) + ': ' + ' dm=' + IntToStr(FImperium.DarkMatery) + ' pl=' + IntToStr(FImperium.PlanetsCount) + ' moon=' + IntToStr(FImperium.MoonsCount) + ' rsrch=' + IntToStr(FImperium.ResearchCount) + #10#13 + 'researching=' + FImperium.StrResearching + #10#13 + 'research plan=' + FImperium.StrResearcPlan; end; end.
unit record_props_1; interface implementation type TRec = record procedure SetCnt(value: Int32); property CNT: Int32 write SetCnt; end; var G: Int32; R: TRec; procedure TRec.SetCnt(value: Int32); begin G := Value; end; procedure Test; begin R.SetCnt(5); R.CNT := 5; end; initialization Test(); finalization Assert(G = 5); end.
unit uReceive; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, Spin; type { TfrmReceive } TfrmReceive = class(TForm) btnCancel: TButton; btnStart: TButton; edtTimeOut: TEdit; edtLnsRecd: TEdit; Label1: TLabel; lblTimeOut: TLabel; lblLnsRecd: TLabel; RecvTimout: TTimer; seMaxTimeOut: TSpinEdit; procedure btnCancelClick(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure RecvTimoutTimer(Sender: TObject); private public TimeoutCount: integer; // Count of seconds (RecvTimout events) since last recv RecvCount: integer; // lines received end; var frmReceive: TfrmReceive; implementation uses srcmain; {$R *.lfm} { TfrmReceive } procedure TfrmReceive.btnStartClick(Sender: TObject); begin frmMain.SynEdit.Modified:=True; // force prompt for save file try frmMain.Serial.Open; RecvCount := 0; TimeoutCount := 0; RecvTimout.Enabled := True; except on E: Exception do begin MessageDlg('Serial Error ' + E.ClassName + ' : ' + E.Message, mtError, [mbOK], 0); frmMain.Logger.Error(E.ClassName + ' : ' + E.Message); end; end; end; procedure TfrmReceive.btnCancelClick(Sender: TObject); begin RecvTimout.Enabled := False; frmMain.Serial.Close; end; procedure TfrmReceive.FormShow(Sender: TObject); begin RecvTimout.Enabled := False; TimeOutCount := 0; RecvCount := 0; edtTimeOut.Text := IntToStr(TimeoutCount); edtLnsRecd.Text := IntToStr(RecvCount); end; procedure TfrmReceive.RecvTimoutTimer(Sender: TObject); begin // Check how many times this has fired since last recv if TimeoutCount > seMaxTimeOut.Value then begin RecvTimout.Enabled := False; MessageDlg('Receive TimeOut Timer Expired, Receive Ended', mtInformation, [mbOK], 0); frmMain.Serial.Close; end else begin Inc(TimeOutCount); RecvTimout.Enabled := True; edtTimeOut.Text := IntToStr(TimeOutCount); end; end; end.
unit formTaxLkpMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, RzPanel, RsControls, Buttons, RzButton, StdCtrls, RzLabel, Mask, RzEdit, RsDialogs, clipbrd; type TfrmTaxLkpMain = class(TForm) pnlMain: TRsPanel; lblIncType: TRsLabel; edtIncome: TRsEdit; RsLabel3: TRsLabel; edtTax: TRsEdit; RsBitBtn1: TRsBitBtn; dlgOpen: TRsOpenDialog; chbOver65: TCheckBox; chbAnnual: TCheckBox; RsBitBtn2: TRsBitBtn; procedure FormCreate(Sender: TObject); procedure edtIncomeKeyPress(Sender: TObject; var Key: Char); procedure edtIncomeChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure chbOver65Click(Sender: TObject); procedure chbAnnualClick(Sender: TObject); procedure RsBitBtn2Click(Sender: TObject); private { Private declarations } fFileName : string; procedure ImportFile; procedure OnApplicationActivate(Sender: TObject); procedure LookupTax; public { Public declarations } end; var frmTaxLkpMain: TfrmTaxLkpMain; implementation {$R *.dfm} uses classXTaxTable, Math; procedure TfrmTaxLkpMain.FormCreate(Sender: TObject); begin fFileName := ExtractFilePath(Application.ExeName) + 'PAYE.xml'; if not FileExists(fFileName) then ImportFile else TheTaxTable.LoadFromFile(fFileName); end; procedure TfrmTaxLkpMain.ImportFile; begin dlgOpen.InitialDir := ExtractFilePath(Application.ExeName); dlgOpen.Filter := 'Text|*.txt'; if dlgOpen.Execute then TheTaxTable.ImportTextTable(dlgOpen.FileName); TheTaxTable.SaveToFile(fFileName); Caption := Format('The Tax Looker Upper (%d)', [TheTaxTable.TaxYear]); LookupTax; end; procedure TfrmTaxLkpMain.edtIncomeKeyPress(Sender: TObject; var Key: Char); begin if not (key in ['0','1','2','3','4','5','6','7','8','9','','.']) then abort; end; procedure TfrmTaxLkpMain.edtIncomeChange(Sender: TObject); begin LookupTax; end; procedure TfrmTaxLkpMain.FormShow(Sender: TObject); begin Caption := Format('The Tax Looker Upper (%d)', [TheTaxTable.TaxYear]); Application.OnActivate := OnApplicationActivate; edtIncome.SelectAll; end; procedure TfrmTaxLkpMain.OnApplicationActivate(Sender: TObject); begin edtIncome.SetFocus; edtIncome.SelectAll; end; procedure TfrmTaxLkpMain.RsBitBtn2Click(Sender: TObject); begin ImportFile; end; procedure TfrmTaxLkpMain.LookupTax; var cTax : Currency; begin cTax := 0; if edtIncome.Text > '' then begin cTax := TheTaxTable.LookupTax(StrToCurr(edtIncome.Text)); edtTax.Text := format('%m', [cTax]); end else edtTax.Text := format('%m', [cTax]); Clipboard.AsText := FloatToStr(cTax); end; procedure TfrmTaxLkpMain.chbOver65Click(Sender: TObject); begin TheTaxTable.IsOver65 := chbOver65.Checked; LookupTax; end; procedure TfrmTaxLkpMain.chbAnnualClick(Sender: TObject); begin TheTaxTable.IsAnnual := chbAnnual.Checked; if TheTaxTable.IsAnnual then lblIncType.Caption := 'Annual Income:' else lblIncType.Caption := 'Monthly Income:'; LookupTax; end; end.
unit ksLoadingIndicator; interface uses FMX.Forms, Classes, FMX.Controls, FMX.Objects, ksTypes, FMX.Graphics, FMX.StdCtrls, FMX.Layouts {$IFDEF IOS} , iOSapi.UIKit, iOSapi.Foundation {$ENDIF} ; type [ComponentPlatformsAttribute(pidWin32 or pidWin64 or {$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64 {$ELSE} pidiOSDevice {$ENDIF} or pidiOSSimulator or pidAndroid)] TksLoadingIndicator = class(TLayout) private FRectangle: TRectangle; FBackground: TRectangle; FLoadingText: string; FFadeBackground: Boolean; FIsModal: Boolean; FLabel: TLabel; FOpacity: single; procedure SetIsModal(const Value: Boolean); procedure SetFadeBackground(const Value: Boolean); procedure SetOpacity(const Value: single); protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ShowLoading; procedure HideLoading; published property IsModal: Boolean read FIsModal write SetIsModal default False; property LoadingText: string read FLoadingText write FLoadingText; property FadeBackground: Boolean read FFadeBackground write SetFadeBackground default False; property Opacity: single read FOpacity write SetOpacity; end; procedure ShowLoadingIndicator(AForm: TCommonCustomForm; AOpacity: single); overload; procedure ShowLoadingIndicator(AForm: TCommonCustomForm; const AFade: Boolean = False; const AModal: Boolean = False; const AOpacity: single = 1); overload; procedure HideLoadingIndicator(AForm: TCommonCustomForm); function IsLoadingIndicatorVisible(AForm: TCommonCustomForm): Boolean; function FindLoadingIndicator(AForm: TCommonCustomForm): TksLoadingIndicator; implementation uses System.UIConsts, FMX.Types, SysUtils, Types, FMX.Ani {$IFDEF IOS} ,iOSapi.CoreGraphics, FMX.Helpers.iOS {$ENDIF} ; function FindLoadingIndicator(AForm: TCommonCustomForm): TksLoadingIndicator; var ICount: integer; begin Result := nil; if AForm = nil then Exit; for ICount := AForm.ComponentCount-1 downto 0 do begin if AForm.Components[ICount] is TksLoadingIndicator then begin Result := (AForm.Components[ICount] as TksLoadingIndicator); Exit; end; end; end; function IsLoadingIndicatorVisible(AForm: TCommonCustomForm): Boolean; var ALoading: TksLoadingIndicator; begin Result := False; ALoading := FindLoadingIndicator(AForm); if ALoading <> nil then begin if ALoading.Parent = AForm then Result := True; end; end; procedure ShowLoadingIndicator(AForm: TCommonCustomForm; AOpacity: single); overload; begin ShowLoadingIndicator(AForm, False, False, AOpacity); end; procedure ShowLoadingIndicator(AForm: TCommonCustomForm; const AFade: Boolean = False; const AModal: Boolean = False; const AOpacity: single = 1); var ALoadingIndicator: TksLoadingIndicator; begin Application.ProcessMessages; try ALoadingIndicator := FindLoadingIndicator(AForm); if ALoadingIndicator = nil then ALoadingIndicator := TksLoadingIndicator.Create(AForm); ALoadingIndicator.FadeBackground := AFade; ALoadingIndicator.IsModal := AModal; ALoadingIndicator.Opacity := AOpacity; AForm.AddObject(ALoadingIndicator); ALoadingIndicator.BringToFront; except // end; Application.ProcessMessages; end; procedure HideLoadingIndicator(AForm: TCommonCustomForm); var ALoadingIndicator: TksLoadingIndicator; begin if AForm = nil then Exit; try ALoadingIndicator := FindLoadingIndicator(AForm); if ALoadingIndicator <> nil then AForm.RemoveObject(ALoadingIndicator); except // end; end; { TksLoadingIndicator } constructor TksLoadingIndicator.Create(AOwner: TComponent); begin inherited; Align := TAlignLayout.Contents; HitTest := False; FLoadingText := 'LOADING'; FFadeBackground := False; FIsModal := False; FBackground := TRectangle.Create(Self); FBackground.Align := TAlignLayout.Client; FBackground.Stroke.Kind := TBrushKind.None; FBackground.Fill.Kind := TBrushKind.Solid; FBackground.Fill.Color := claBlack; FBackground.HitTest := False; FBackground.Opacity := 0.3; AddObject(FBackground); FRectangle := TRectangle.Create(Self); FRectangle.Align := TAlignLayout.Center; FRectangle.Stroke.Kind := TBrushKind.None; FRectangle.Stroke.Color := claNull; FRectangle.Fill.Color := claBlack; FRectangle.Width := 90; FRectangle.Height := 70; FRectangle.XRadius := 5; FRectangle.YRadius := 5; FRectangle.Opacity := FOpacity; FLabel := TLabel.Create(Self); FLabel.Align := TAlignLayout.Client; FLabel.TextSettings.FontColor := claWhite; FLabel.Text := FLoadingText; FLabel.TextSettings.HorzAlign := TTextAlign.Center; FLabel.TextSettings.VertAlign := TTextAlign.Center; FLabel.StyledSettings := []; AddObject(FRectangle); AddObject(FLabel); end; destructor TksLoadingIndicator.Destroy; begin inherited; end; procedure TksLoadingIndicator.HideLoading; begin HideLoadingIndicator(Owner as TForm); end; procedure TksLoadingIndicator.SetFadeBackground(const Value: Boolean); begin FFadeBackground := Value; case Value of True: FBackground.Opacity := 0.3; False: FBackground.Opacity := 0; end; end; procedure TksLoadingIndicator.SetIsModal(const Value: Boolean); begin FIsModal := Value; FBackground.HitTest := Value; end; procedure TksLoadingIndicator.SetOpacity(const Value: single); begin FOpacity := Value; FRectangle.Opacity := Value; end; procedure TksLoadingIndicator.ShowLoading; begin ShowLoadingIndicator(Owner as TForm); end; end.
unit ApplicationGUI; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids , Generator , PropertyStyle , TechnoType ; type TApplicationGUIForm = class(TForm) lbClassName: TLabel; edClassName: TEdit; lbPropertyName: TLabel; edPropertyName: TEdit; lbPropertyType: TLabel; cbPropertyStyle: TComboBox; sgProperties: TStringGrid; lbProperties: TLabel; btAddProperty: TButton; btDeleteProperty: TButton; memoShortCutsEdProperty: TMemo; memoShortCutsSgProperties: TMemo; cbConfirmSuppress: TCheckBox; cbConfirmUpdate: TCheckBox; cbTechno: TComboBox; btGenerateClass: TButton; memoResultGeneration: TMemo; btnCopyToClipBoard: TButton; procedure btAddPropertyClick(Sender: TObject); procedure sgPropertiesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure edPropertyNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edPropertyNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btDeletePropertyClick(Sender: TObject); procedure sgPropertiesClick(Sender: TObject); procedure sgPropertiesKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btGenerateClassClick(Sender: TObject); procedure edClassNameChange(Sender: TObject); procedure btnCopyToClipBoardClick(Sender: TObject); private { Déclarations privées } FClassGenerator: TGenerator; function getPropertyStyleChoosen: TPropertyStyle; function getTechnoChoosen: TTechnoType; procedure iniPropertyList; procedure iniTechnoList; procedure addProperty(Sender: TObject; const bDoEmptyField: boolean); procedure deleteProperty(Sender: TObject); function selectTheFoundedProperty: boolean; procedure selectRowIndex(const aIndex: integer); procedure gridDeselectAll; procedure updateControlsWithGridSelection; procedure clearFirstDatasRow; procedure clearGrid; procedure fillGrid; procedure clearAndFillGrid; procedure changeType(const aKey: word); function canModify(const aIndex: integer; const aTypeModification: integer): boolean; public { Déclarations publiques } end; var ApplicationGUIForm: TApplicationGUIForm; implementation uses Properties, Controller, PropertyObj, UnitConst ; {$R *.dfm} procedure TApplicationGUIForm.btAddPropertyClick(Sender: TObject); const cDoEmptyField: boolean = false; begin addProperty(Sender, cDoEmptyField); end; procedure TApplicationGUIForm.btDeletePropertyClick(Sender: TObject); begin deleteProperty(Sender); end; procedure TApplicationGUIForm.btGenerateClassClick(Sender: TObject); var vTechno: TTechnoType; vResult: TStringList; begin memoResultGeneration.Lines.Clear; vTechno := getTechnoChoosen; vResult := TController.getClassGeneration(vTechno, FClassGenerator); if assigned(vResult) then begin memoResultGeneration.Lines.AddStrings(vResult); vResult.Free; end; end; procedure TApplicationGUIForm.btnCopyToClipBoardClick(Sender: TObject); begin memoResultGeneration.SelectAll; memoResultGeneration.CopyToClipboard; end; function TApplicationGUIForm.canModify(const aIndex: integer; const aTypeModification: integer): boolean; var vConfirmMsg: string; vName: string; vStyle: string; vbCheck: boolean; vModif: string; begin result := true; vbCheck := true; vModif := TYPE_MODIFICATION_PROPERTY_MODIFICATION_STRING; if aTypeModification = TYPE_MODIFICATION_PROPERTY_DELETE then begin vbCheck := cbConfirmSuppress.Checked; vModif := TYPE_MODIFICATION_PROPERTY_DELETE_STRING; end else if aTypeModification = TYPE_MODIFICATION_PROPERTY_UPDATE then begin vbCheck := cbConfirmUpdate.Checked; vModif := TYPE_MODIFICATION_PROPERTY_UPDATE_STRING; end; if vbCheck then begin result := false; if TController.getPropertyNameAndStyle(aIndex, FClassGenerator, vName, vStyle) then begin vConfirmMsg := format(CONFIRM_STRING,[vModif, vName, vStyle]); result := MessageDlg(vConfirmMsg,mtConfirmation,mbYesNo,0,mbNo) = mrYes; end; end; end; procedure TApplicationGUIForm.changeType(const aKey: word); begin if aKey = VK_UP then begin if cbPropertyStyle.ItemIndex = 0 then cbPropertyStyle.ItemIndex := cbPropertyStyle.Items.Count - 1 else cbPropertyStyle.ItemIndex := cbPropertyStyle.ItemIndex - 1 end else if aKey = VK_DOWN then begin if cbPropertyStyle.ItemIndex = cbPropertyStyle.Items.Count - 1 then cbPropertyStyle.ItemIndex := 0 else cbPropertyStyle.ItemIndex := cbPropertyStyle.ItemIndex + 1; end; end; procedure TApplicationGUIForm.clearAndFillGrid; begin clearGrid; fillGrid; end; procedure TApplicationGUIForm.clearFirstDatasRow; begin sgProperties.Cells[PROPERTY_COLUMN_POSITION,1] := ''; sgProperties.Cells[TYPE_COLUMN_POSITION,1] := ''; end; procedure TApplicationGUIForm.clearGrid; begin sgProperties.RowCount := 2; clearFirstDatasRow; end; procedure TApplicationGUIForm.deleteProperty(Sender: TObject); var vPropertyName: string; vIndex: integer; begin vPropertyName := edPropertyName.Text; if vPropertyName <> '' then begin vIndex := TController.propertyExists(vPropertyName, FClassGenerator); if vIndex > -1 then begin if canModify(vIndex, TYPE_MODIFICATION_PROPERTY_DELETE) and TController.deleteProperty(vIndex, FClassGenerator) then begin clearAndFillGrid; // force the selection of the row just above except if vindex = 0 if (vindex = 0) and (FClassGenerator.properties.Count > 0) then vindex := 1; selectRowIndex(vIndex); updateControlsWithGridSelection; end else showmessage(MSG_PROPERTY_NOT_DELETED); end else showmessage(MSG_PROPERTY_DOES_NOT_EXISTS); end else showmessage(MSG_PROPERTY_FIELD_EMPTY); end; procedure TApplicationGUIForm.edClassNameChange(Sender: TObject); begin FClassGenerator.name := edClassName.Text; end; procedure TApplicationGUIForm.edPropertyNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); const cDoEmptyField: boolean = true; begin if Key = VK_RETURN then begin if shift = [ssShift] then deleteProperty(sender) else addProperty(sender, cDoEmptyField); end else if Key = VK_UP then begin if Shift = [ssCtrl] then changeType(Key) else updateControlsWithGridSelection; end else if Key = VK_DOWN then begin if Shift = [ssCtrl] then changeType(Key) end; end; procedure TApplicationGUIForm.edPropertyNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin selectTheFoundedProperty; end; procedure TApplicationGUIForm.fillGrid; var i: Integer; vIndex: integer; vName: string; vStyle: string; begin if assigned(FClassGenerator) and (FClassGenerator.properties.Count > 0) and (sgProperties.RowCount = 2) then begin for i := 0 to FClassGenerator.properties.Count - 1 do begin if i > 0 then sgProperties.RowCount := sgProperties.RowCount + 1; vindex := i + 1; if TController.getPropertyNameAndStyle(i, FClassGenerator, vName, vStyle) then begin sgProperties.Cells[PROPERTY_COLUMN_POSITION,vIndex] := vName; sgProperties.Cells[TYPE_COLUMN_POSITION,vIndex] := vStyle; end; end; end; end; procedure TApplicationGUIForm.addProperty(Sender: TObject; const bDoEmptyField: boolean); var vNewPropertyName: string; vPropertyStyle: TPropertyStyle; vIndex: integer; begin vNewPropertyName := edPropertyName.Text; if vNewPropertyName <> '' then begin vIndex := TController.propertyExists(vNewPropertyName, FClassGenerator); if vIndex = -1 then begin vPropertyStyle := getPropertyStyleChoosen; if TController.addProperty(vNewPropertyName, vPropertyStyle, FClassGenerator) then begin clearAndFillGrid; // force the selection of the last row selectRowIndex(FClassGenerator.properties.Count); if bDoEmptyField then edPropertyName.Text := ''; // in order to allow introduce another property directly end else showmessage(MSG_PROPERTY_NOT_ADDED); end else begin if canModify(vIndex, TYPE_MODIFICATION_PROPERTY_UPDATE) then begin vPropertyStyle := getPropertyStyleChoosen; if TController.updateProperty(vIndex, vPropertyStyle, FClassGenerator) then begin clearAndFillGrid; // force the selection of the current row selectRowIndex(sgProperties.Row - 1); end else showmessage(MSG_PROPERTY_NOT_UPDATED); end; end; end else showmessage(MSG_PROPERTY_FIELD_EMPTY); end; procedure TApplicationGUIForm.FormCreate(Sender: TObject); var vProperties: TProperties; begin vProperties := TProperties.Create; FClassGenerator := TGenerator.Create(DEFAULT_NEW_CLASS_NAME, vProperties); iniPropertyList; iniTechnoList; gridDeselectAll; end; procedure TApplicationGUIForm.FormDestroy(Sender: TObject); begin FClassGenerator.Free; end; function TApplicationGUIForm.getPropertyStyleChoosen: TPropertyStyle; begin result := TPropertyStyle(cbPropertyStyle.ItemIndex); end; function TApplicationGUIForm.getTechnoChoosen: TTechnoType; begin result := TTechnoType(cbTechno.ItemIndex); end; procedure TApplicationGUIForm.gridDeselectAll; begin sgProperties.Selection := TGridRect(Rect(-1, -1, -1, -1)); end; procedure TApplicationGUIForm.iniPropertyList; var i: integer; begin cbPropertyStyle.Clear; for i := 0 to PROPERTY_STYLE_COUNT - 1 do cbPropertyStyle.Items.Add(TController.getPropertyStyleString(TPropertyStyle(i))); cbPropertyStyle.ItemIndex := 0; end; procedure TApplicationGUIForm.iniTechnoList; var i: integer; begin cbTechno.Clear; for i := 0 to TECHNO_TYPE_COUNT - 1 do cbTechno.Items.Add(TController.getTechnoString(TTechnoType(i))); cbTechno.ItemIndex := 0; end; procedure TApplicationGUIForm.selectRowIndex(const aIndex: integer); begin if (aIndex < sgProperties.RowCount) and (aIndex > 0) then begin sgProperties.Selection := TGridRect(Rect(0, aIndex, 1, aIndex)); end else begin gridDeselectAll; end; end; function TApplicationGUIForm.selectTheFoundedProperty: boolean; var index: integer; begin result := false; if edPropertyName.Text <> '' then begin index := TController.propertyExists(edPropertyName.Text, FClassGenerator); if index > -1 then selectRowIndex(index + 1); end; end; procedure TApplicationGUIForm.sgPropertiesClick(Sender: TObject); begin updateControlsWithGridSelection; end; procedure TApplicationGUIForm.updateControlsWithGridSelection; var vIndex: integer; vProperty: TProperty; begin if sgProperties.Row > 0 then begin vIndex := sgProperties.Row - 1; if TController.propertyExists(vIndex, FClassGenerator) then begin vProperty := FClassGenerator.properties.Items[vIndex]; edPropertyName.Text := vProperty.name; cbPropertyStyle.ItemIndex := ord(vProperty.style); end; end; end; procedure TApplicationGUIForm.sgPropertiesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); const cLeftGap: word = 5; cTopGap: word = 5; begin // titles of the columns if (ACol < sgProperties.FixedCols) or (ARow < sgProperties.FixedRows) then begin sgProperties.Canvas.Rectangle(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom); if aCol = 0 then sgProperties.Canvas.TextOut(rect.left + cLeftGap, rect.top + cTopGap,PROPERTY_COLUMN_TITLE) else if aCol = 1 then sgProperties.Canvas.TextOut(rect.left + cLeftGap, rect.top + cTopGap,TYPE_COLUMN_TITLE); end; end; procedure TApplicationGUIForm.sgPropertiesKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var vIndexProperty: integer; vbMove: boolean; begin vbMove := false; vIndexProperty := sgProperties.Row-1; if Shift = [ssCtrl] then begin if Key = VK_UP then begin if sgProperties.Row > 1 then begin FClassGenerator.properties.Move(vIndexProperty, vIndexProperty - 1); dec(vIndexProperty); vbMove := true; end; end else if Key = VK_DOWN then begin if sgProperties.Row < sgProperties.RowCount - 1 then begin FClassGenerator.properties.Move(vIndexProperty, vIndexProperty + 1); inc(vIndexProperty); vbMove := true; end; end; end; if vbMove then begin clearAndFillGrid; selectRowIndex(vIndexProperty + 1); end; end; end.
unit U_WE_DIAGRAM2; interface uses SysUtils, Windows, Classes, Controls, StdCtrls, U_WIRING_ERROR, GDIPOBJ, GDIPAPI, IniFiles, Forms, Dialogs, U_DIAGRAM_TYPE, system.UITypes, system.Types, Vcl.Graphics; type TDgMeterPhaseType = (dmptThree, dmptFour); TDgMeterEnergyType = (dmetActive, dmetReactive); TDgMeterPlugSign = (dmpsIa_in, dmpsUa, dmpsIa_out, dmpsIb_in, dmpsUb, dmpsIb_out, dmpsIc_in, dmpsUc, dmpsIc_out, dmpsUn1, dmpsUn2); type /// <summary> 电表 </summary> TDgMeter = class private FCanvas: TCanvas; FPos: TPoint; FPhaseType: TDgMeterPhaseType; FEnergyType: TdgMeterEnergyType; FVisible: Boolean; procedure DrawOutline; procedure DrawPlugs; procedure DrawDetail; function GetHeight: Integer; function GetWidth: Integer; function GetPlugCount: Integer; public constructor Create(ACanvas: TCanvas); procedure Draw; function GetPlugPos(Index: Integer): TPoint; overload; function GetPlugPos(APlugSign: TDgMeterPlugSign): TPoint; overload; public property Canvas: TCanvas read FCanvas write FCanvas; property Pos: TPoint read FPos write FPos; property Width: Integer read GetWidth; property Height: Integer read GetHeight; /// <summary> /// 相线类型 /// </summary> property PhaseType: TDgMeterPhaseType read FPhaseType write FPhaseType; /// <summary> /// 有功无功 /// </summary> property EnergyType: TdgMeterEnergyType read FEnergyType write FEnergyType; /// <summary> /// 端子数量 /// </summary> property PlugCount: Integer read GetPlugCount; /// <summary> /// 是否显示 /// </summary> property Visible: Boolean read FVisible write FVisible default True; end; type /// <summary> 电流互感器 </summary> TDgCT = class private FCanvas: TCanvas; FWindingPos: TPoint; FWindingWidth: Integer; FLeadLength: Integer; FVisible: Boolean; function GetLeftPlugPos: TPoint; function GetRightPlugPos: TPoint; public constructor Create(ACanvas: TCanvas); procedure Draw; public property Canvas: TCanvas read FCanvas write FCanvas; property WindingPos: TPoint read FWindingPos write FWindingPos; property WindingWidth: Integer read FWindingWidth write FWindingWidth; property LeadLength: Integer read FLeadLength write FLeadLength; property LeftPlugPos: TPoint read GetLeftPlugPos; property RightPlugPos: TPoint read GetRightPlugPos; property Visible: Boolean read FVisible write FVisible default True; end; type /// <summary> 电压互感器 </summary> TDgPT = class private FCanvas: TCanvas; FClientRect: TRect; FLeadLength: Integer; FVisible: Boolean; function GetLeftTPlugPos: TPoint; function GetLeftBPlugPos: TPoint; function GetRightTPlugPos: TPoint; function GetRightBPlugPos: TPoint; public constructor Create(ACanvas: TCanvas); procedure Draw; public property Canvas: TCanvas read FCanvas write FCanvas; property ClientRect: TRect read FClientRect write FClientRect; property LeadLength: Integer read FLeadLength write FLeadLength; property LeftTPlugPos: TPoint read GetLeftTPlugPos; property LeftBPlugPos: TPoint read GetLeftBPlugPos; property RightTPlugPos: TPoint read GetRightTPlugPos; property RightBPlugPos: TPoint read GetRightBPlugPos; property Visible: Boolean read FVisible write FVisible default True; end; type /// <summary> 接地符号 </summary> TDgGround = class private FCanvas: TCanvas; FPos: TPoint; FLeadLength: Integer; FVisible: Boolean; public constructor Create(ACanvas: TCanvas); procedure Draw; public property Canvas: TCanvas read FCanvas write FCanvas; property Pos: TPoint read FPos write FPos; property LeadLength: Integer read FLeadLength; property Visible: Boolean read FVisible write FVisible default True; end; type /// <summary> 电压互感器组 </summary> TDgPTGroup = class private FCanvas: TCanvas; FPos: TPoint; FPT1, FPT2, FPT3: TDgPT; FHasThreePT: Boolean; FVisible: Boolean; procedure SetPos(const Value: TPoint); procedure SetHasThreePT(const Value: Boolean); public constructor Create(ACanvas: TCanvas); destructor Destroy; override; procedure Draw; public property Canvas: TCanvas read FCanvas write FCanvas; property Pos: TPoint read FPos write SetPos; property PT1: TDgPT read FPT1; property PT2: TDgPT read FPT2; property PT3: TDgPT read FPT3; property HasThreePT: Boolean read FHasThreePT write SetHasThreePT default False; property Visible: Boolean read FVisible write FVisible default True; end; type /// <summary> 电线 </summary> TDgWire = class private FCanvas: TCanvas; FLength: Integer; FStartPos: TPoint; FBreakXPos2: Integer; FBreakXPos1: Integer; FText: string; FVisible: Boolean; public constructor Create(ACanvas: TCanvas); procedure Draw; public property Canvas: TCanvas read FCanvas write FCanvas; property StartPos: TPoint read FStartPos write FStartPos; property Length: Integer read FLength write FLength; property BreakXPos1: Integer read FBreakXPos1 write FBreakXPos1; property BreakXPos2: Integer read FBreakXPos2 write FBreakXPos2; property Text: string read FText write FText; property Visible: Boolean read FVisible write FVisible default True; end; TPointArray = array of TPoint; TDgLink = record InPortNo: Integer; OutPortNo: Integer; end; TDgLinkArray = array of TDgLink; type /// <summary> 跳线盒 </summary> TDgJunctionBox = class private FCanvas: TCanvas; FInPorts: TPointArray; FOutPorts: TPointArray; FLinks: TDgLinkArray; FVisible: Boolean; FBoxName: string; procedure SetLinkCount(const Value: Integer); function GetLinkCount: Integer; function GetPortCount: Integer; procedure SetPortCount(const Value: Integer); public constructor Create(ACanvas: TCanvas; APortCount: Integer); procedure SetOutPortOrder(AOrderArray: array of Integer); procedure Draw; overload; procedure Draw(HiPos: Integer); overload; public property Canvas: TCanvas read FCanvas write FCanvas; property InPorts: TPointArray read FInPorts; property OutPorts: TPointArray read FOutPorts; property PortCount: Integer read GetPortCount write SetPortCount; property Links: TDgLinkArray read FLinks; property LinkCount: Integer read GetLinkCount write SetLinkCount; property Visible: Boolean read FVisible write FVisible default True; property BoxName : string read FBoxName write FBoxName; end; procedure DgDrawCircle(ACanvas: TCanvas; ACenter: TPoint; ADiameter: Integer; AFillColor: TColor = clDefault); procedure DgDrawArc(ACanvas: TCanvas; ACenter, AStart, AEnd: TPoint; ARadius: Integer); procedure DgDrawJunction(ACanvas: TCanvas; ACenter: TPoint; ASolid: Boolean; ADiameter: Integer = 3); function DgOffsetPoint(APoint: TPoint; AX, AY: Integer): TPoint; function DgOffsetRectDef0(ARect: TRect; AX, AY: Integer): TRect; procedure DgSwapPoints(var APoint1, APoint2: TPoint); procedure DgDrawWinding(ACanvas: TCanvas; ARect: TRect; AIsDown: Boolean); procedure DgDrawConnection(ACanvas: TCanvas; APosStart, APosEnd: TPoint; AStraightLine : Boolean = False; AColor : TColor = clBlack); procedure DgDrawConnection3X(ACanvas: TCanvas; APosStart, APosEnd: TPoint; AXPos: Integer; AColor: TColor = clBlack); procedure DgDrawConnection3Y(ACanvas: TCanvas; APosStart, APosEnd: TPoint; AYPos: Integer; AColor: TColor = clBlack); type /// <summary> 接线图 </summary> TWE_Diagram2 = class(TCustomControl) private FBitmap: TBitmap; FDiagramType: TDiagramType; FWiringError: TWIRING_ERROR; FMeter1, FMeter2: TDgMeter; //电表1#、2# FCT1, FCT2, FCT3: TDgCT; //电流互感器A相, B相, C相 FPTGroup: TDgPTGroup; //电压互感器组 FCTGround, FPTGround: TDgGround; //CT及PT的接地标识符号 FWire1, FWire2, FWire3, FWire4: TDgWire; //电线A相, B相, C相,N相 FJunctionBoxCt: TDgJunctionBox; //电流进出线接线盒 FJunctionBoxCtA, FJunctionBoxCtB, FJunctionBoxCtC: TDgJunctionBox; //CT接线盒 A相, B相, C相 FJunctionBoxPtDown: TDgJunctionBox; //PT下接线盒 FJunctionBoxPtUp: TDgJunctionBox; //PT上接线盒 ptUbUp: TPoint; //PT出线B相公共点 ptUbDown: TPoint; //PT进线B相公共点 /// <summary> 清除画布 </summary> procedure ClearCanvas; /// <summary> 调整元件布局 </summary> procedure AdjustElementLayout; /// <summary> 画接线断开 </summary> procedure DrawBroken(APosStart, APosEnd: TPoint); /// <summary> 改变跳线顺序 </summary> procedure ChangeSequence(ALinks: TDgLinkArray; ASequence: TWE_SEQUENCE_TYPE); /// <summary> 画全部元件 </summary> procedure DrawAllElement; procedure DrawType3CTClear; //三相三线CT简化 procedure DrawType3M; //三相三线多功能 procedure DrawType3L4; //三相三线四线制 procedure DrawType4M_NoPT; //三相四线多功能无PT procedure DrawType4M_PT; //三相四线多功能有PT procedure DrawType4_PT_CT_CLear; //三相四线经PT,CT简化 procedure DrawType4_PT_L6; //三相四线经PT,六线制 procedure DrawType4_NoPT_L6; //三相四线无PT六线制 procedure DrawType4Direct; //三相四线直通 procedure SetDiagramType(const Value: TDiagramType); procedure SetWiringError(const Value: TWIRING_ERROR); /// <summary> 画接线图 </summary> procedure Draw; protected procedure Paint; override; procedure CreateWnd; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; /// <summary> 画接线图到指定画布 </summary> procedure DrawTo(ACanvas: TCanvas; ARect: TRect); overload; /// <summary> 画接线图到指定画布 </summary> procedure DrawTo(ACanvas: TCanvas; APos: TPoint); overload; public /// <summary> 接线错误 </summary> property WiringError: TWIRING_ERROR read FWiringError write SetWiringError; published /// <summary> 接线图类型 </summary> property DiagramType: TDiagramType read FDiagramType write SetDiagramType; property Visible; property Color default clWhite; property Anchors; end; implementation uses Math; const C_PLUG_DISTANCE = 20; //电表插孔间距 procedure DgDrawCircle(ACanvas: TCanvas; ACenter: TPoint; ADiameter: Integer; AFillColor: TColor); var OldColor: TColor; begin OldColor := ACanvas.Brush.Color; if AFillColor <> clDefault then ACanvas.Brush.Color := AFillColor; ACanvas.Ellipse(ACenter.X - ADiameter div 2, ACenter.Y - ADiameter div 2, ACenter.X + (ADiameter + 1) div 2, ACenter.Y + (ADiameter + 1) div 2); if AFillColor <> clDefault then ACanvas.Brush.Color := OldColor; end; procedure DgDrawArc(ACanvas: TCanvas; ACenter, AStart, AEnd: TPoint; ARadius: Integer); begin ACanvas.Arc(ACenter.X - ARadius, ACenter.Y - ARadius, ACenter.X + ARadius, ACenter.Y + ARadius, AStart.X, AStart.Y, AEnd.X, AEnd.Y); end; function DgOffsetPoint(APoint: TPoint; AX, AY: Integer): TPoint; begin Result.X := APoint.X + AX; Result.Y := APoint.Y + AY; end; function DgOffsetRectDef0(ARect: TRect; AX, AY: Integer): TRect; begin Result := ARect; if not OffsetRect(Result, AX, AY) then Result := Rect(0, 0, 0, 0); end; procedure DgSwapPoints(var APoint1, APoint2: TPoint); var ptTemp: TPoint; begin ptTemp := APoint1; APoint1 := APoint2; APoint2 := ptTemp; end; procedure DgDrawJunction(ACanvas: TCanvas; ACenter: TPoint; ASolid: Boolean; ADiameter: Integer); var OldColor: TColor; OldStyle: TBrushstyle; begin with ACanvas do begin OldColor := Brush.Color; OldStyle := Brush.Style; Brush.Style := bsSolid; if ASolid then Brush.Color := clBlack else Brush.Color := clWhite; if ADiameter >= 4 then DgDrawCircle(ACanvas, ACenter, ADiameter) else Rectangle(ACenter.X - ADiameter div 2, ACenter.Y - ADiameter div 2, ACenter.X + ADiameter div 2 + ADiameter mod 2, ACenter.Y + ADiameter div 2 + ADiameter mod 2); Brush.Style := OldStyle; Brush.Color := OldColor; end; end; procedure DgDrawConnection(ACanvas: TCanvas; APosStart, APosEnd: TPoint; AStraightLine: Boolean; AColor: TColor); var OldColor: TColor; begin with ACanvas do begin OldColor := Pen.Color; Pen.Color := AColor; if ( APosStart.X = APosEnd.X ) or ( APosStart.Y = APosEnd.Y ) or AStraightLine then Polyline( [ APosStart, APosEnd ] ) else begin Polyline( [ APosStart, Point( APosEnd.X, APosStart.Y ) ] ); Polyline( [ Point( APosEnd.X, APosStart.Y ), APosEnd ] ); end; Pen.Color := OldColor; end; end; procedure DgDrawConnection3X(ACanvas: TCanvas; APosStart, APosEnd: TPoint; AXPos: Integer; AColor: TColor); var OldColor: TColor; begin with ACanvas do begin OldColor := Pen.Color; Pen.Color := AColor; Polyline([APosStart, Point(AXPos, APosStart.Y)]); DgDrawConnection(ACanvas, APosEnd, Point(AXPos, APosStart.Y)); Pen.Color := OldColor; end; end; procedure DgDrawConnection3Y(ACanvas: TCanvas; APosStart, APosEnd: TPoint; AYPos: Integer; AColor: TColor); var OldColor: TColor; begin with ACanvas do begin OldColor := Pen.Color; Pen.Color := AColor; Polyline([APosStart, Point(APosStart.X, AYPos)]); DgDrawConnection(ACanvas, Point(APosStart.X, AYPos), APosEnd); Pen.Color := OldColor; end; end; procedure DgDrawWinding(ACanvas: TCanvas; ARect: TRect; AIsDown: Boolean); var nY, nX: Integer; begin nX := (ARect.Left + ARect.Right) div 2; if AIsDown then begin nY := ARect.Top + 1; Dec(ARect.Top, ARect.Bottom - ARect.Top); ACanvas.Arc(ARect.Left, ARect.Top, nX + 1, ARect.Bottom, ARect.Left, nY, ARect.Right, nY); ACanvas.Arc(nX, ARect.Top, ARect.Right + 1, ARect.Bottom, ARect.Left, nY, ARect.Right, nY); end else begin nY := ARect.Bottom; Inc(ARect.Bottom, ARect.Bottom - ARect.Top); ACanvas.Arc(ARect.Left, ARect.Top, nX + 1, ARect.Bottom, ARect.Right, nY, ARect.Left, nY); ACanvas.Arc(nX, ARect.Top, ARect.Right + 1, ARect.Bottom, ARect.Right, nY, ARect.Left, nY); end; end; { TWdMeter } constructor TDgMeter.Create(ACanvas: TCanvas); begin FCanvas := ACanvas; FPos := Point(0, 0); FVisible := True; end; procedure TDgMeter.Draw; begin if not FVisible then Exit; DrawOutline; DrawPlugs; DrawDetail; end; procedure TDgMeter.DrawDetail; var ptCircle1, ptCircle2, ptCircle3: TPoint; procedure DrawCircleAndPoint(ACenter: TPoint); var OldColor: TColor; begin with FCanvas do begin OldColor := Brush.Color; DgDrawCircle(FCanvas, ACenter, 25); Brush.Color := clBlack; Rectangle(Rect(ACenter.X - 5, ACenter.Y + 14, ACenter.X - 2, ACenter.Y + 17)); Rectangle(Rect(ACenter.X - 16, ACenter.Y - 5, ACenter.X - 13, ACenter.Y - 2)); Brush.Color := OldColor; end; end; procedure DrawThreeActive; begin with FCanvas do begin DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(0), 0, -14), DgOffsetPoint(GetPlugPos(2), 0, -14), ptCircle1.Y); DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(4), 0, -14), DgOffsetPoint(GetPlugPos(6), 0, -14), ptCircle2.Y); DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(1), 0, -14), DgOffsetPoint(GetPlugPos(5), 0, -14), ptCircle1.Y - 40); Polyline([DgOffsetPoint(GetPlugPos(3), 0, -14), Point(GetPlugPos(3).X, ptCircle1.Y - 40)]); DgDrawJunction(FCanvas, Point(GetPlugPos(3).X, ptCircle1.Y - 40), True); end; end; procedure DrawThreeReactive; var rRect1, rRect2: TRect; ptRightBottom: TPoint; begin rRect1.TopLeft := DgOffsetPoint(ptCircle1, -3, -30); rRect2.TopLeft := DgOffsetPoint(ptCircle2, -3, -30); rRect1.BottomRight := DgOffsetPoint(rRect1.TopLeft, 6, 10); rRect2.BottomRight := DgOffsetPoint(rRect2.TopLeft, 6, 10); ptRightBottom := DgOffsetPoint(GetPlugPos(6), 8, -26); with FCanvas do begin Rectangle(rRect1); Rectangle(rRect2); DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(0), 0, -14), DgOffsetPoint(GetPlugPos(2), 0, -14), ptCircle1.Y); DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(4), 0, -14), DgOffsetPoint(GetPlugPos(6), 0, -14), ptCircle2.Y); DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(1), 0, -14), Point(ptCircle2.X, rRect2.Bottom - 1), GetPlugPos(0).Y - 36); DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(3), 0, -14), Point(ptCircle1.X, rRect1.Bottom - 1), GetPlugPos(0).Y - 46); DgDrawConnection(FCanvas, ptRightBottom, DgOffsetPoint(GetPlugPos(5), 0, -14)); DgDrawConnection3Y(FCanvas, ptRightBottom, Point(ptCircle1.X, rRect1.Top), ptCircle1.Y - 40); Polyline([Point(ptCircle2.X, rRect2.Top), Point(ptCircle2.X, ptCircle2.Y - 40)]); end; end; procedure DrawFourActive; begin with FCanvas do begin DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(0), 0, -14), DgOffsetPoint(GetPlugPos(2), 0, -14), ptCircle1.Y); DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(3), 0, -14), DgOffsetPoint(GetPlugPos(5), 0, -14), ptCircle2.Y); DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(6), 0, -14), DgOffsetPoint(GetPlugPos(8), 0, -14), ptCircle3.Y); DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(9), 0, -14), DgOffsetPoint(GetPlugPos(10), 0, -14), GetPlugPos(10).Y - 50); DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(1), 0, -14), DgOffsetPoint(GetPlugPos(10), -10, -50), ptCircle1.Y - 40); Polyline([DgOffsetPoint(GetPlugPos(4), 0, -14), Point(GetPlugPos(4).X, ptCircle1.Y - 40)]); Polyline([DgOffsetPoint(GetPlugPos(7), 0, -14), Point(GetPlugPos(7).X, ptCircle1.Y - 40)]); end; end; procedure DrawFourReactive; var ptLeftBottom, ptRightBottom, ptRightBottom2: TPoint; begin ptLeftBottom := DgOffsetPoint(GetPlugPos(0), -8, -26); ptRightBottom := DgOffsetPoint(GetPlugPos(8), 8, -26); ptRightBottom2 := DgOffsetPoint(ptRightBottom, -4, -10); with FCanvas do begin DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(0), 0, -14), DgOffsetPoint(GetPlugPos(2), 0, -14), ptCircle1.Y); DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(3), 0, -14), DgOffsetPoint(GetPlugPos(5), 0, -14), ptCircle2.Y); DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(6), 0, -14), DgOffsetPoint(GetPlugPos(8), 0, -14), ptCircle3.Y); DgDrawConnection(FCanvas, ptLeftBottom, DgOffsetPoint(GetPlugPos(1), 0, -14)); DgDrawConnection3Y(FCanvas, ptLeftBottom, ptCircle2, ptCircle2.Y - 40); DgDrawConnection3Y(FCanvas, ptCircle2, DgOffsetPoint(ptCircle2, 30, -30), ptCircle2.Y + 20); Polyline([DgOffsetPoint(GetPlugPos(4), 0, -14), Point(GetPlugPos(4).X, ptRightBottom2.Y)]); DgDrawConnection(FCanvas, ptRightBottom, DgOffsetPoint(GetPlugPos(7), 0, -14)); DgDrawConnection3Y(FCanvas, ptCircle1, ptRightBottom, ptCircle1.Y - 30); DgDrawConnection(FCanvas, ptRightBottom2, ptCircle1); DgDrawConnection3Y(FCanvas, ptCircle3, ptRightBottom2, ptCircle3.Y - 20); DgDrawConnection(FCanvas, DgOffsetPoint(ptLeftBottom, 0, -20), ptCircle3); end; end; begin ptCircle1 := DgOffsetPoint(GetPlugPos(1), 0, -90); if FPhaseType = dmptFour then begin ptCircle2 := DgOffsetPoint(GetPlugPos(4), 0, -90); ptCircle3 := DgOffsetPoint(GetPlugPos(7), 0, -90); end else if FPhaseType = dmptThree then ptCircle2 := DgOffsetPoint(GetPlugPos(5), 0, -90); DrawCircleAndPoint(ptCircle1); if FPhaseType = dmptFour then begin DrawCircleAndPoint(ptCircle2); DrawCircleAndPoint(ptCircle3); if FEnergyType = dmetActive then DrawFourActive else DrawFourReactive; end else if FPhaseType = dmptThree then begin DrawCircleAndPoint(ptCircle2); if FEnergyType = dmetActive then DrawThreeActive else DrawThreeReactive; end; end; procedure TDgMeter.DrawOutline; const C_R = 10; //电表外框倒角半径 C_H = 20; //电表外框下端高度 var ptLeftTop, ptRightTop, ptLeftMiddle, ptRightMiddle, ptLeftBottom, ptRightBottom: TPoint; begin ptLeftTop := FPos; ptLeftMiddle := Point(FPos.X, FPos.Y + Height - C_H); ptLeftBottom := Point(FPos.X + C_R, FPos.Y + Height); ptRightTop := Point(FPos.X + Width, FPos.Y); ptRightMiddle := Point(FPos.X + Width, FPos.Y + Height - C_H); ptRightBottom := Point(FPos.X + Width - C_R, FPos.Y + Height); DgDrawArc(FCanvas, DgOffsetPoint(ptLeftTop, C_R + 1, C_R + 1), DgOffsetPoint(ptLeftTop, C_R, 0), DgOffsetPoint(ptLeftTop, 0, C_R), C_R); FCanvas.Polyline([DgOffsetPoint(ptLeftTop, C_R, 0), Point(ptRightTop.X - C_R + 1, ptRightTop.Y )]); DgDrawArc(FCanvas, DgOffsetPoint(ptRightTop, -C_R + 1, C_R + 1), DgOffsetPoint(ptRightTop, 0, C_R), DgOffsetPoint(ptRightTop, -C_R, 0), C_R); FCanvas.Polyline([DgOffsetPoint(ptRightTop, 0, C_R), Point(ptRightMiddle.X, ptRightMiddle.Y - C_R)]); DgDrawArc(FCanvas, DgOffsetPoint(ptRightMiddle, -C_R + 1, -C_R + 1), DgOffsetPoint(ptRightMiddle, -C_R, 0), DgOffsetPoint(ptRightMiddle, 0, -C_R), C_R); FCanvas.Polyline([DgOffsetPoint(ptRightMiddle, -C_R, 0), ptRightBottom]); FCanvas.Polyline([ptRightBottom, ptLeftBottom]); FCanvas.Polyline([ptLeftBottom, DgOffsetPoint(ptLeftMiddle, C_R, 0)]); DgDrawArc(FCanvas, DgOffsetPoint(ptLeftMiddle, C_R + 1, -C_R + 1), DgOffsetPoint(ptLeftMiddle, 0, -C_R), DgOffsetPoint(ptLeftMiddle, C_R, 0), C_R); FCanvas.Polyline([DgOffsetPoint(ptLeftMiddle, 0, -C_R), DgOffsetPoint(ptLeftTop, 0, C_R - 1)]); end; procedure TDgMeter.DrawPlugs; var I: Integer; APoint, APoint1 : TPoint; begin for I := 0 to PlugCount - 1 do begin APoint := DgOffsetPoint(GetPlugPos(I), -3, -14); APoint1 := DgOffsetPoint(GetPlugPos(I), 3, 1); FCanvas.Rectangle(Rect(APoint.X, APoint.Y, APoint1.X, APoint1.Y)); end; end; function TDgMeter.GetHeight: Integer; begin Result := 150; end; function TDgMeter.GetPlugCount: Integer; begin if FPhaseType = dmptFour then begin if FEnergyType = dmetActive then Result := 11 else Result := 9 end else if FPhaseType = dmptThree then Result := 7 else Result := 0; end; function TDgMeter.GetPlugPos(APlugSign: TDgMeterPlugSign): TPoint; begin if FPhaseType = dmptFour then begin Result := GetPlugPos(Ord(APlugSign)); end else begin case APlugSign of dmpsIa_in, dmpsUa, dmpsIa_out: Result := GetPlugPos(Ord(APlugSign)); dmpsUb: Result := GetPlugPos(3); dmpsIc_in, dmpsUc, dmpsIc_out: Result := GetPlugPos(Ord(APlugSign) - 2); else raise Exception.Create('No Plug'); end; end; end; function TDgMeter.GetPlugPos(Index: Integer): TPoint; begin if (Index >= 0) and (Index < PlugCount) then begin Result.X := FPos.X + 20 + Index * C_PLUG_DISTANCE; Result.Y := FPos.Y + Height - 6; end else raise Exception.Create('Error'); end; function TDgMeter.GetWidth: Integer; begin if PlugCount <= 0 then raise Exception.Create('Error'); Result := (PlugCount - 1) * C_PLUG_DISTANCE + 40 - 1; end; { TDgTransformer } constructor TDgCT.Create(ACanvas: TCanvas); begin FVisible := True; FCanvas := ACanvas; FWindingPos := Point(0, 0); FWindingWidth := 40; FLeadLength := 8; end; procedure TDgCT.Draw; var APoint : TPoint; begin if not FVisible then Exit; DgDrawJunction(FCanvas, DgOffsetPoint(LeftPlugPos, 0, 2), False, 4); DgDrawJunction(FCanvas, DgOffsetPoint(RightPlugPos, 0, 2), False, 4); DgDrawJunction(FCanvas, DgOffsetPoint(FWindingPos, -5, 4), True); DgDrawJunction(FCanvas, DgOffsetPoint(FWindingPos, -5, -4), True); DgDrawConnection(FCanvas, DgOffsetPoint(LeftPlugPos, 0, 4), FWindingPos, True); DgDrawConnection(FCanvas, DgOffsetPoint(RightPlugPos, 0, 4), DgOffsetPoint(FWindingPos, FwindingWidth, 0), True); APoint := DgOffsetPoint(FWindingPos, FWindingWidth, FWindingWidth div 4); DgDrawWinding(FCanvas, Rect(FWindingPos.X, FWindingPos.Y , APoint.X, APoint.Y), True); end; function TDgCT.GetLeftPlugPos: TPoint; begin Result := DgOffsetPoint(FWindingPos, 0, -FLeadLength - 2); end; function TDgCT.GetRightPlugPos: TPoint; begin Result := DgOffsetPoint(LeftPlugPos, FWindingWidth, 0); end; { TDgPT } constructor TDgPT.Create(ACanvas: TCanvas); begin FVisible := True; FCanvas := ACanvas; FClientRect := Rect(0, 0, 20, 20); FLeadLength := 4; end; procedure TDgPT.Draw; var nRadius: Integer; begin if not FVisible then Exit; with FClientRect do begin nRadius := (Right - Left) div 2; DgDrawJunction(FCanvas, TopLeft, False, 4); DgDrawJunction(FCanvas, Point(Left, Bottom), False, 4); DgDrawJunction(FCanvas, Point(Right, Top), False, 4); DgDrawJunction(FCanvas, BottomRight, False, 4); DgDrawJunction(FCanvas, Point(Left + 4, Top + FLeadLength), True, 2); DgDrawJunction(FCanvas, Point(Left + 4, Bottom - FLeadLength), True, 2); DgDrawConnection(FCanvas, Point(Left, Top + 2), Point(Left, Top + FLeadLength + 2), True); DgDrawConnection(FCanvas, Point(Left, Bottom - 2), Point(Left, Bottom - FLeadLength - 2), True); DgDrawConnection(FCanvas, Point(Right, Top + 2), Point(Right, Top + FLeadLength + 2), True); DgDrawConnection(FCanvas, Point(Right, Bottom - 2), Point(Right, Bottom - FLeadLength - 2), True); FCanvas.Polyline([Point(Left + 1, (Top + Bottom) div 2), Point(Right - 1, (Top + Bottom) div 2)]); DgDrawWinding(FCanvas, Rect(Left, Top + FLeadLength, Right, Top + FLeadLength + nRadius), True); DgDrawWinding(FCanvas, Rect(Left, Bottom - FLeadLength - nRadius, Right, Bottom - FLeadLength), False); end; end; function TDgPT.GetLeftBPlugPos: TPoint; begin Result := Point(FClientRect.Left, FClientRect.Bottom + 1); end; function TDgPT.GetLeftTPlugPos: TPoint; begin Result := Point(FClientRect.Left, FClientRect.Top - 2); end; function TDgPT.GetRightBPlugPos: TPoint; begin Result := Point(FClientRect.Right, FClientRect.Bottom + 1); end; function TDgPT.GetRightTPlugPos: TPoint; begin Result := Point(FClientRect.Right, FClientRect.Top - 2); end; { TDgPTGroup } constructor TDgPTGroup.Create(ACanvas: TCanvas); begin FCanvas := ACanvas; FVisible := True; FPT1 := TDgPT.Create(FCanvas); FPT2 := TDgPT.Create(FCanvas); FPT3 := TDgPT.Create(FCanvas); SetPos(Point(0, 0)); SetHasThreePT(False); end; destructor TDgPTGroup.Destroy; begin FPT1.Free; FPT2.Free; FPT3.Free; inherited; end; procedure TDgPTGroup.Draw; begin if not FVisible then Exit; FPT1.Draw; FPT2.Draw; FPT3.Draw; end; procedure TDgPTGroup.SetHasThreePT(const Value: Boolean); begin FHasThreePT := Value; FPT1.Visible := True; FPT2.Visible := True; FPT3.Visible := FHasThreePT; SetPos(FPos); end; procedure TDgPTGroup.SetPos(const Value: TPoint); begin FPos := Value; FPT1.ClientRect := Rect(FPos.X, FPos.Y, FPos.X + 13, FPos.Y + 25); FPT2.ClientRect := DgOffsetRectDef0(FPT1.ClientRect, 18, 0); FPT3.ClientRect := DgOffsetRectDef0(FPT2.ClientRect, 18, 0); end; { TDgGroud } constructor TDgGround.Create(ACanvas: TCanvas); begin FCanvas := ACanvas; FPos := Point(0, 0); FVisible := True; FLeadLength := 5; end; procedure TDgGround.Draw; begin if Not FVisible then Exit; FCanvas.Polyline([FPos, DgOffsetPoint(FPos, 0, FLeadLength)]); FCanvas.Polyline([DgOffsetPoint(FPos, -8, FLeadLength), DgOffsetPoint(FPos, 8, FLeadLength)]); FCanvas.Polyline([DgOffsetPoint(FPos, -6, FLeadLength + 3), DgOffsetPoint(FPos, 6, FLeadLength + 3)]); FCanvas.Polyline([DgOffsetPoint(FPos, -4, FLeadLength + 6), DgOffsetPoint(FPos, 4, FLeadLength + 6)]); end; { TDgWire } constructor TDgWire.Create(ACanvas: TCanvas); begin FVisible := True; FCanvas := ACanvas; FStartPos := Point(0, 0); FLength := 20; FText := ''; FBreakXPos1 := -1; FBreakXPos2 := -1; end; procedure TDgWire.Draw; var OldColor: TColor; ptEnd: TPoint; begin if not FVisible then Exit; OldColor := FCanvas.Brush.Color; ptEnd := Point(FStartPos.X + FLength, FStartPos.Y); FCanvas.Brush.Color := clWhite; DgDrawCircle(FCanvas, FStartPos, 6); if (FBreakXPos1 > FStartPos.X) and (FBreakXPos2 < ptEnd.X) and (FBreakXPos2 >= FBreakXPos1) then begin FCanvas.Polyline([DgOffsetPoint(FStartPos, 3, 0), Point(FBreakXPos1, FStartPos.Y)]); FCanvas.Polyline([Point(FBreakXPos2, FStartPos.Y), ptEnd]); end else begin FCanvas.Polyline([DgOffsetPoint(FStartPos, 3, 0), ptEnd]); end; FCanvas.TextOut(FStartPos.X - 15, FStartPos.Y - 6, FText); FCanvas.Brush.Color := clBlack; FCanvas.Polygon([ptEnd, DgOffsetPoint(ptEnd, -8, -3), DgOffsetPoint(ptEnd, -8, 3)]); FCanvas.Brush.Color := OldColor; end; { TDgJunctionBox } constructor TDgJunctionBox.Create(ACanvas: TCanvas; APortCount: Integer); begin FCanvas := ACanvas; SetPortCount(APortCount); SetLinkCount(APortCount); FVisible := True; end; procedure TDgJunctionBox.Draw; var I: Integer; begin if not FVisible then Exit; for I := 0 to High(FLinks) do FCanvas.Polyline([FInPorts[FLinks[I].InPortNo], FOutPorts[FLinks[I].OutPortNo]]); // for I := 0 to High(FLinks) do // begin // FCanvas.TextOut(InPorts[i].X + 10, InPorts[i].Y, 'A'); //// FCanvas.Polyline([FInPorts[FLinks[I].InPortNo], FOutPorts[FLinks[I].OutPortNo]]); // end; // // for I := 0 to High(FLinks) do // begin // FCanvas.TextOut(OutPorts[i].X + 10, OutPorts[i].Y, 'B'); // end; // FCanvas.TextOut(FInPorts[2].x, FInPorts[2].y, 'C'); // FCanvas.Font.Size := 5; // for i := 0 to Length(FInPorts) - 1 do // begin // FCanvas.Ellipse(FInPorts[i].x-1, FInPorts[i].y-1,FInPorts[i].x+1, FInPorts[i].y+1); // FCanvas.TextOut(FInPorts[i].x+3, FInPorts[i].y, FBoxName + 'I' + IntToStr(i+1)); // end; // // for i := 0 to Length(FOutPorts) - 1 do // begin // FCanvas.Ellipse(FOutPorts[i].x-1, FOutPorts[i].y-1,FOutPorts[i].x+1, FOutPorts[i].y+1); // FCanvas.TextOut(FOutPorts[i].x+3, FOutPorts[i].y, FBoxName + 'O' + IntToStr(i+1)); // end; end; function TDgJunctionBox.GetPortCount: Integer; begin Result := Length(FInPorts); end; procedure TDgJunctionBox.SetPortCount(const Value: Integer); begin SetLength(FInPorts, Value); SetLength(FOutPorts, Value); end; procedure TDgJunctionBox.Draw(HiPos: Integer); var I, nPos: Integer; begin if not FVisible then Exit; if HiPos < 0 then Exit; nPos := Min(High(FLinks), HiPos); for I := 0 to nPos do FCanvas.Polyline([FInPorts[FLinks[I].InPortNo], FOutPorts[FLinks[I].OutPortNo]]); end; function TDgJunctionBox.GetLinkCount: Integer; begin Result := Length(FLinks); end; procedure TDgJunctionBox.SetLinkCount(const Value: Integer); var I: Integer; begin SetLength(FLinks, Value); for I := 0 to High(FLinks) do begin FLinks[I].InPortNo := I; FLinks[I].OutPortNo := I; end; end; procedure TDgJunctionBox.SetOutPortOrder(AOrderArray: array of Integer); var I: Integer; begin if Length(AOrderArray) <> LinkCount then raise Exception.Create('Error'); for I := 0 to LinkCount - 1 do FLinks[I].OutPortNo := AOrderArray[I]; end; { TCkmMeterWiringDiagram } constructor TWE_Diagram2.Create(AOwner: TComponent); var //Fabc : Boolean; Fabc : Integer; begin inherited; with TIniFile.Create( ChangeFileExt( Application.ExeName, '.ini' ) ) do begin Fabc := ReadInteger( 'Like', 'abc', 0 ); Free; end; Color := clWhite; FBitmap := TBitmap.Create; FBitmap.SetSize(630, 700); Width := FBitmap.Width; Height := FBitmap.Height; FWiringError := TWIRING_ERROR.Create; FMeter1 := TDgMeter.Create(FBitmap.Canvas); FMeter2 := TDgMeter.Create(FBitmap.Canvas); FWire1 := TDgWire.Create(FBitmap.Canvas); FWire2 := TDgWire.Create(FBitmap.Canvas); FWire3 := TDgWire.Create(FBitmap.Canvas); FWire4 := TDgWire.Create(FBitmap.Canvas); {if not Fabc then begin FWire1.Text := 'U'; FWire2.Text := 'V'; FWire3.Text := 'W'; FWire4.Text := 'N'; end else begin FWire1.Text := 'A'; FWire2.Text := 'B'; FWire3.Text := 'C'; FWire4.Text := 'N'; end; } case Fabc of 0: begin FWire1.Text := 'A'; FWire2.Text := 'B'; FWire3.Text := 'C'; FWire4.Text := 'N'; end; 1: begin FWire1.Text := 'U'; FWire2.Text := 'V'; FWire3.Text := 'W'; FWire4.Text := 'N'; end; 2: begin FWire1.Text := '1'; FWire2.Text := '2'; FWire3.Text := '3'; FWire4.Text := 'N'; end; end; FCT1 := TDgCT.Create(FBitmap.Canvas); FCT2 := TDgCT.Create(FBitmap.Canvas); FCT3 := TDgCT.Create(FBitmap.Canvas); FPTGroup := TDgPTGroup.Create(FBitmap.Canvas); FCTGround := TDgGround.Create(FBitmap.Canvas); FPTGround := TDgGround.Create(FBitmap.Canvas); FJunctionBoxCt := TDgJunctionBox.Create(FBitmap.Canvas, 4); FJunctionBoxCt.BoxName := 'Ct'; FJunctionBoxCtA := TDgJunctionBox.Create(FBitmap.Canvas, 2); FJunctionBoxCtA.BoxName := 'CtA'; FJunctionBoxCtB := TDgJunctionBox.Create(FBitmap.Canvas, 2); FJunctionBoxCtB.BoxName := 'CtB'; FJunctionBoxCtC := TDgJunctionBox.Create(FBitmap.Canvas, 2); FJunctionBoxCtC.BoxName := 'CtC'; FJunctionBoxPtDown := TDgJunctionBox.Create(FBitmap.Canvas, 6); //原为4胡红明,2013.5.13 FJunctionBoxPtDown.BoxName := 'Down'; FJunctionBoxPtUp := TDgJunctionBox.Create(FBitmap.Canvas, 3); FJunctionBoxPtUp.BoxName := 'Up'; end; procedure TWE_Diagram2.CreateWnd; begin inherited; SetDiagramType(dt3CTClear); AdjustElementLayout; end; destructor TWE_Diagram2.Destroy; begin FWiringError.Free; FMeter1.Free; FMeter2.Free; FCT1.Free; FCT2.Free; FCT3.Free; FPTGroup.Free; FCTGround.Free; FPTGround.Free; FWire1.Free; FWire2.Free; FWire3.Free; FWire4.Free; FJunctionBoxCt.Free; FJunctionBoxCtA.Free; FJunctionBoxCtB.Free; FJunctionBoxCtC.Free; FJunctionBoxPtDown.Free; FJunctionBoxPtUp.Free; FBitmap.Free; inherited; end; procedure TWE_Diagram2.Paint; var g: TGPGraphics; gpBmp: TGPBitmap; begin Draw; g := TGPGraphics.Create(Canvas.Handle); gpBmp := TGPBitmap.Create(FBitmap.Handle, FBitmap.Palette); g.SetInterpolationMode(InterpolationModeHighQuality); g.DrawImage(gpBmp, MakeRect(ClientRect)); gpBmp.Free; g.Free; inherited; end; procedure TWE_Diagram2.AdjustElementLayout; var I: Integer; begin FMeter1.Pos := Point(120, 6); FMeter2.Pos := DgOffsetPoint(FMeter1.Pos, FMeter1.Width + 20, 0); FWire1.StartPos := Point(20, 450); FWire2.StartPos := DgOffsetPoint(FWire1.StartPos, 0, 30); FWire3.StartPos := DgOffsetPoint(FWire2.StartPos, 0, 30); FWire4.StartPos := DgOffsetPoint(FWire3.StartPos, 0, 30); FWire1.Length := FBitmap.Width - 23; FWire2.Length := FBitmap.Width - 23; FWire3.Length := FBitmap.Width - 23; FWire4.Length := FBitmap.Width - 23; FCT1.WindingPos := Point(FMeter1.GetPlugPos(dmpsIa_in).X, FWire1.StartPos.Y); FCT2.Visible := FMeter1.PhaseType = dmptFour; if FCT2.Visible then FCT2.WindingPos := Point(FMeter1.GetPlugPos(dmpsIb_in).X, FWire2.StartPos.Y); FCT3.WindingPos := Point(FMeter1.GetPlugPos(dmpsIc_in).X, FWire3.StartPos.Y); FCTGround.Pos := Point(FCT3.RightPlugPos.X + 80, FWire1.StartPos.Y - 20); FPTGroup.Pos := Point(FWire1.StartPos.X + 30, FWire1.StartPos.Y - 60); if FPTGroup.HasThreePT then FPTGround.Pos := DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 18, 6) //18 else FPTGround.Pos := DgOffsetPoint(FPTGroup.PT2.RightTPlugPos, 18, 6); FJunctionBoxCtA.InPorts[0] := FCT1.LeftPlugPos; FJunctionBoxCtA.InPorts[1] := FCT1.RightPlugPos; FJunctionBoxCtB.InPorts[0] := FCT2.LeftPlugPos; FJunctionBoxCtB.InPorts[1] := FCT2.RightPlugPos; FJunctionBoxCtC.InPorts[0] := FCT3.LeftPlugPos; FJunctionBoxCtC.InPorts[1] := FCT3.RightPlugPos; FJunctionBoxCtA.OutPorts[0] := DgOffsetPoint(FJunctionBoxCtA.InPorts[0], 0, -15); FJunctionBoxCtA.OutPorts[1] := DgOffsetPoint(FJunctionBoxCtA.InPorts[1], 0, -15); FJunctionBoxCtB.OutPorts[0] := DgOffsetPoint(FJunctionBoxCtB.InPorts[0], 0, -15); FJunctionBoxCtB.OutPorts[1] := DgOffsetPoint(FJunctionBoxCtB.InPorts[1], 0, -15); FJunctionBoxCtC.OutPorts[0] := DgOffsetPoint(FJunctionBoxCtC.InPorts[0], 0, -15); FJunctionBoxCtC.OutPorts[1] := DgOffsetPoint(FJunctionBoxCtC.InPorts[1], 0, -15); FJunctionBoxCtB.Visible := FCT2.Visible; FWire1.BreakXPos1 := -1; FWire1.BreakXPos2 := -1; FWire2.BreakXPos1 := -1; FWire2.BreakXPos2 := -1; FWire3.BreakXPos1 := -1; FWire3.BreakXPos2 := -1; FCT1.Visible := True; FCT3.Visible := True; FCTGround.Visible := True; case FDiagramType of dt3CTClear: begin FJunctionBoxCt.PortCount := 3; FJunctionBoxCt.LinkCount := 3; FJunctionBoxCt.InPorts[0] := Point(FCT1.LeftPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[1] := Point(FCT3.LeftPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[2] := Point(FCT3.RightPlugPos.X, FWire1.StartPos.Y - 50); end; dt3M, dt3L4: begin FJunctionBoxCt.PortCount := 4; FJunctionBoxCt.LinkCount := 4; FJunctionBoxCt.InPorts[0] := Point(FCT1.LeftPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[1] := Point(FCT1.RightPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[2] := Point(FCT3.LeftPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[3] := Point(FCT3.RightPlugPos.X, FWire1.StartPos.Y - 50); end; dt4M_NoPT: begin FJunctionBoxCt.PortCount := 6; FJunctionBoxCt.LinkCount := 6; FJunctionBoxCt.InPorts[0] := Point(FCT1.LeftPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[1] := Point(FCT2.LeftPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[2] := Point(FCT3.LeftPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[3] := Point(FCT1.RightPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[4] := Point(FCT2.RightPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[5] := Point(FCT3.RightPlugPos.X, FWire1.StartPos.Y - 50); end; dt4_PT_CT_CLear: begin FJunctionBoxCt.PortCount := 3; FJunctionBoxCt.LinkCount := 3; FJunctionBoxCt.InPorts[0] := Point(FCT1.LeftPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[1] := Point(FCT2.LeftPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[2] := Point(FCT3.LeftPlugPos.X, FWire1.StartPos.Y - 50); end; dt4M_PT, dt4_PT_L6, dt4_NoPT_L6: begin // FJunctionBoxCt.PortCount := 3; // FJunctionBoxCt.LinkCount := 3; // FJunctionBoxCt.InPorts[0] := Point(FCT1.LeftPlugPos.X, FWire1.StartPos.Y - 50); // FJunctionBoxCt.InPorts[1] := Point(FCT2.LeftPlugPos.X, FWire1.StartPos.Y - 50); // FJunctionBoxCt.InPorts[2] := Point(FCT3.LeftPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.PortCount := 6; FJunctionBoxCt.LinkCount := 6; FJunctionBoxCt.InPorts[0] := Point(FCT1.LeftPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[1] := Point(FCT2.LeftPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[2] := Point(FCT3.LeftPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[3] := Point(FCT1.RightPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[4] := Point(FCT2.RightPlugPos.X, FWire1.StartPos.Y - 50); FJunctionBoxCt.InPorts[5] := Point(FCT3.RightPlugPos.X, FWire1.StartPos.Y - 50); end; dt4Direct: begin FJunctionBoxCt.PortCount := 0; FJunctionBoxCt.LinkCount := 0; FWire1.BreakXPos1 := FMeter1.GetPlugPos(dmpsIa_in).X; FWire1.BreakXPos2 := FMeter2.GetPlugPos(dmpsIa_out).X; FWire2.BreakXPos1 := FMeter1.GetPlugPos(dmpsIb_in).X; FWire2.BreakXPos2 := FMeter2.GetPlugPos(dmpsIb_out).X; FWire3.BreakXPos1 := FMeter1.GetPlugPos(dmpsIc_in).X; FWire3.BreakXPos2 := FMeter2.GetPlugPos(dmpsIc_out).X; FCT1.Visible := False; FCT2.Visible := False; FCT3.Visible := False; FCTGround.Visible := False; end; end; for I := 0 to FJunctionBoxCt.PortCount - 1 do FJunctionBoxCt.OutPorts[I] := DgOffsetPoint(FJunctionBoxCt.InPorts[I], 0, -20); case FDiagramType of dt3M, dt3L4, dt3CTClear: begin FJunctionBoxPtDown.PortCount := 4; FJunctionBoxPtDown.LinkCount := 4; end else begin FJunctionBoxPtDown.PortCount := 6; FJunctionBoxPtDown.LinkCount := 6; end; end; // FJunctionBoxPtDown.InPorts[0] := FPTGroup.PT1.LeftTPlugPos; FJunctionBoxPtDown.InPorts[1] := FPTGroup.PT1.RightTPlugPos; FJunctionBoxPtDown.InPorts[2] := FPTGroup.PT2.LeftTPlugPos; FJunctionBoxPtDown.InPorts[3] := FPTGroup.PT2.RightTPlugPos; if FJunctionBoxPtDown.PortCount = 6 then begin FJunctionBoxPtDown.InPorts[4] := FPTGroup.PT3.LeftTPlugPos; FJunctionBoxPtDown.InPorts[5] := FPTGroup.PT3.RightTPlugPos; end; for I := 0 to FJunctionBoxPtDown.PortCount - 1 do FJunctionBoxPtDown.OutPorts[I] := DgOffsetPoint(FJunctionBoxPtDown.InPorts[I], 0, -10); ptUbUp := DgOffsetPoint(FJunctionBoxPtDown.OutPorts[1], (FJunctionBoxPtDown.OutPorts[2].X - FJunctionBoxPtDown.OutPorts[1].X) div 2, 0); ptUbDown := DgOffsetPoint(FPTGroup.PT1.RightBPlugPos, (FPTGroup.PT2.LeftBPlugPos.X - FPTGroup.PT1.RightBPlugPos.X) div 2, 5); if FDiagramType = dt4Direct then begin FJunctionBoxPtUp.InPorts[0] := DgOffsetPoint(FMeter1.GetPlugPos(dmpsIa_in), 0, 120); FJunctionBoxPtUp.InPorts[1] := DgOffsetPoint(FMeter1.GetPlugPos(dmpsIb_in), 0, 120); FJunctionBoxPtUp.InPorts[2] := DgOffsetPoint(FMeter1.GetPlugPos(dmpsIc_in), 0, 120); for I := 0 to FJunctionBoxPtUp.PortCount - 1 do FJunctionBoxPtUp.OutPorts[I] := DgOffsetPoint(FJunctionBoxPtUp.InPorts[I], 0, -30); end else if FMeter1.PhaseType = dmptThree then begin FJunctionBoxPtUp.InPorts[0] := DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -40); FJunctionBoxPtUp.InPorts[1] := DgOffsetPoint(ptUbUp, 0, -30); FJunctionBoxPtUp.InPorts[2] := DgOffsetPoint(FPTGroup.PT2.RightTPlugPos, 0, -40); for I := 0 to FJunctionBoxPtUp.PortCount - 1 do FJunctionBoxPtUp.OutPorts[I] := DgOffsetPoint(FJunctionBoxPtUp.InPorts[I], 0, -10); end else begin FJunctionBoxPtUp.InPorts[0] := DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -40); FJunctionBoxPtUp.InPorts[1] := DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, -40); FJunctionBoxPtUp.InPorts[2] := DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, -40); for I := 0 to FJunctionBoxPtUp.PortCount - 1 do FJunctionBoxPtUp.OutPorts[I] := DgOffsetPoint(FJunctionBoxPtUp.InPorts[I], 0, -10); end; end; procedure TWE_Diagram2.ChangeSequence(ALinks: TDgLinkArray; ASequence: TWE_SEQUENCE_TYPE); procedure SetInPortOrder(APortNo0, APortNo1, APortNo2: Integer); begin ALinks[0].InPortNo := APortNo0; ALinks[1].InPortNo := APortNo1; ALinks[2].InPortNo := APortNo2; end; procedure SetInPortOrder1(APortNo0, APortNo1, APortNo2: Integer); begin ALinks[0].InPortNo := APortNo0; ALinks[1].InPortNo := APortNo1; ALinks[2].InPortNo := APortNo2; ALinks[3].InPortNo := APortNo0+3; ALinks[4].InPortNo := APortNo1+3; ALinks[5].InPortNo := APortNo2+3; // ALinks[0].InPortNo := APortNo0*2; // ALinks[1].InPortNo := APortNo0*2 + 1; // ALinks[2].InPortNo := APortNo1*2; // ALinks[3].InPortNo := APortNo1*2 + 1; // ALinks[4].InPortNo := APortNo2*2; // ALinks[5].InPortNo := APortNo2*2 + 1; end; var I: Integer; begin if (Length(ALinks) <> 3) and (Length(ALinks) <> 6) then raise Exception.Create('Errors'); if Length(ALinks) = 3 then begin for I := 0 to 2 do ALinks[I].OutPortNo := i; case ASequence of stABC: SetInPortOrder(0, 1, 2); stACB: SetInPortOrder(0, 2, 1); stBAC: SetInPortOrder(1, 0, 2); stBCA: SetInPortOrder(1, 2, 0); stCAB: SetInPortOrder(2, 0, 1); stCBA: SetInPortOrder(2, 1, 0); end; end else if Length(ALinks) = 6 then begin for I := 0 to 5 do ALinks[I].OutPortNo := i; case ASequence of stABC: SetInPortOrder1(0, 1, 2); stACB: SetInPortOrder1(0, 2, 1); stBAC: SetInPortOrder1(1, 0, 2); stBCA: SetInPortOrder1(1, 2, 0); stCAB: SetInPortOrder1(2, 0, 1); stCBA: SetInPortOrder1(2, 1, 0); end; end; end; procedure TWE_Diagram2.ClearCanvas; var g: TGPGraphics; begin g := TGPGraphics.Create(FBitmap.Canvas.Handle); g.Clear(ColorRefToARGB(Color)); g.Free; end; procedure TWE_Diagram2.Draw; begin ClearCanvas; AdjustElementLayout; DrawAllElement; case FDiagramType of dt3CTClear: DrawType3CTClear; dt3M: DrawType3M; dt3L4: DrawType3L4; dt4M_NoPT: DrawType4M_NoPT; dt4M_PT: DrawType4M_PT; dt4_PT_CT_CLear: DrawType4_PT_CT_CLear; dt4_PT_L6: DrawType4_PT_L6; dt4_NoPT_L6: DrawType4_NoPT_L6; dt4Direct: DrawType4Direct; end; end; procedure TWE_Diagram2.DrawAllElement; begin if FDiagramType = dt4_PT_CT_CLear then begin FMeter1.Draw; end else begin FMeter1.Draw; FMeter2.Draw; end; FCT1.Draw; FCT2.Draw; FCT3.Draw; FPTGroup.Draw; FCTGround.Draw; FWire1.Draw; FWire2.Draw; FWire3.Draw; FWire4.Draw; if FCT1.Visible then begin DgDrawConnection(FBitmap.Canvas, FCTGround.Pos, DgOffsetPoint(FCT1.RightPlugPos, 6, -6)); DgDrawConnection(FBitmap.Canvas, DgOffsetPoint(FCT1.RightPlugPos, 6, -6), FCT1.RightPlugPos, True); end; if FCT2.Visible then begin DgDrawConnection(FBitmap.Canvas, FCTGround.Pos, DgOffsetPoint(FCT2.RightPlugPos, 6, -6)); DgDrawConnection(FBitmap.Canvas, DgOffsetPoint(FCT2.RightPlugPos, 6, -6), FCT2.RightPlugPos, True); DgDrawJunction(FBitmap.Canvas, Point(FCT2.RightPlugPos.X + 6, FCTGround.Pos.Y), True); end; if FCT3.Visible then begin DgDrawConnection(FBitmap.Canvas, FCTGround.Pos, DgOffsetPoint(FCT3.RightPlugPos, 6, -6)); DgDrawConnection(FBitmap.Canvas, DgOffsetPoint(FCT3.RightPlugPos, 6, -6), FCT3.RightPlugPos, True); DgDrawJunction(FBitmap.Canvas, Point(FCT3.RightPlugPos.X + 6, FCTGround.Pos.Y), True); end; if FPTGroup.Visible and FPTGround.Visible then begin //地线 FPTGround.Draw; if FMeter1.PhaseType = dmptThree then begin DgDrawConnection(FBitmap.Canvas, DgOffsetPoint(ptUbUp, 0, -5), FPTGround.Pos); DgDrawJunction(FBitmap.Canvas, DgOffsetPoint(ptUbUp, 0, -5), True); end else begin //胡红明2013.5.14更改以下3句,旧代码屏蔽 DgDrawConnection(FBitmap.Canvas,Point(FPTGroup.PT1.RightTPlugPos.X, FPTGroup.PT1.RightTPlugPos.Y - 10),FPTGround.Pos); DgDrawConnection(FBitmap.Canvas,Point(FPTGroup.PT2.RightTPlugPos.X, FPTGroup.PT2.RightTPlugPos.Y - 10),FPTGround.Pos); DgDrawConnection(FBitmap.Canvas,Point(FPTGroup.PT3.RightTPlugPos.X, FPTGroup.PT3.RightTPlugPos.Y - 10),FPTGround.Pos); DgDrawJunction(FBitmap.Canvas, DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, -10), True); end; end; end; procedure TWE_Diagram2.DrawBroken(APosStart, APosEnd: TPoint); var pO : TPoint; OldColor: TColor; begin pO.X := (APosStart.X + APosEnd.X) div 2; pO.Y := (APosStart.Y + APosEnd.Y) div 2; with FBitmap.Canvas do begin OldColor := Pen.Color; // 清连接线 Pen.Color := Pixels[0, 0]; Polyline([ APosStart, APosEnd ] ); // 画 X Pen.Color := clRed; Polyline([Point(po.X - 4, pO.Y - 4),Point(pO.X + 5, pO.Y + 5)]); Polyline([Point(po.X - 4, pO.Y + 4),Point(pO.X + 5, pO.Y - 5)]); Pen.Color := OldColor; end; end; procedure TWE_Diagram2.DrawTo(ACanvas: TCanvas; ARect: TRect); var g: TGPGraphics; gpBmp: TGPBitmap; begin Draw; g := TGPGraphics.Create(ACanvas.Handle); g.SetInterpolationMode(InterpolationModeHighQuality); gpBmp := TGPBitmap.Create(FBitmap.Handle, FBitmap.Palette); g.DrawImage(gpBmp, MakeRect(ARect)); gpBmp.Free; g.Free; end; procedure TWE_Diagram2.DrawTo(ACanvas: TCanvas; APos: TPoint); begin Draw; ACanvas.Draw(APos.X, APos.Y, FBitmap); end; procedure TWE_Diagram2.DrawType3CTClear; procedure SetInPortOrder(APortNo0, APortNo1, APortNo2: Integer); begin with FWiringError do begin FJunctionBoxCt.Links[0].InPortNo := APortNo0; FJunctionBoxCt.Links[1].InPortNo := APortNo1; FJunctionBoxCt.Links[2].InPortNo := APortNo2; end; end; /// <param name="nType">0: 元件1反接 1: 元件2反接</param> procedure Draw(nType : Integer = 0); procedure DrawReverse(APosStart, APosEnd, APosStart1, APosEnd1: TPoint); var OldColor: TColor; begin with FBitmap.Canvas do begin OldColor := Pen.Color; Pen.Color := clWhite; //填充 Polyline([ APosStart, APosStart1 ] ); Polyline([ APosEnd1, APosEnd ] ); Pen.Color := OldColor; // 画 X Polyline([ APosStart, APosEnd ] ); Polyline([ APosStart1, APosEnd1 ] ); end; end; begin if nType = 0 then begin DrawReverse(DgOffsetPoint(FMeter1.GetPlugPos(0), 0, 95), DgOffsetPoint(FMeter2.GetPlugPos(2), 0, 125), DgOffsetPoint(FMeter1.GetPlugPos(0), 0, 125), DgOffsetPoint(FMeter2.GetPlugPos(2), 0, 95)); end else begin DrawReverse(DgOffsetPoint(FMeter1.GetPlugPos(4), 0, 135), DgOffsetPoint(FMeter2.GetPlugPos(6), 0, 165), DgOffsetPoint(FMeter1.GetPlugPos(4), 0, 165), DgOffsetPoint(FMeter2.GetPlugPos(6), 0, 135)); end; end; var I: Integer; ptMeterOutPut: TPoint; begin //外部电线到PT的连线 FBitmap.Canvas.Polyline([FPTGroup.PT1.LeftBPlugPos, Point(FPTGroup.PT1.LeftBPlugPos.X, FWire1.StartPos.Y)]); FBitmap.Canvas.Polyline([FPTGroup.PT2.RightBPlugPos, Point(FPTGroup.PT2.RightBPlugPos.X, FWire3.StartPos.Y)]); FBitmap.Canvas.Polyline([ptUbDown, Point(ptUbDown.X, FWire2.StartPos.Y)]); DgDrawConnection(FBitmap.Canvas, ptUbDown, FPTGroup.PT1.RightBPlugPos); DgDrawConnection(FBitmap.Canvas, ptUbDown, FPTGroup.PT2.LeftBPlugPos); //两个PT接线盒之间的连线 FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[1], DgOffsetPoint(FJunctionBoxPtDown.OutPorts[2], 1, 0)]); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[0], FJunctionBoxPtUp.InPorts[0]]); FBitmap.Canvas.Polyline([ptUbUp, FJunctionBoxPtUp.InPorts[1]]); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[3], FJunctionBoxPtUp.InPorts[2]]); //PT上接线盒到电表的连线 DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[0], FMeter1.GetPlugPos(dmpsUa), FMeter1.GetPlugPos(0).Y + 60); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[0], FMeter2.GetPlugPos(dmpsUa), FMeter1.GetPlugPos(0).Y + 60); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[1], FMeter1.GetPlugPos(dmpsUb), FMeter1.GetPlugPos(0).Y + 70); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[1], FMeter2.GetPlugPos(dmpsUb), FMeter1.GetPlugPos(0).Y + 70); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[2], FMeter1.GetPlugPos(dmpsUc), FMeter1.GetPlugPos(0).Y + 80); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[2], FMeter2.GetPlugPos(dmpsUc), FMeter1.GetPlugPos(0).Y + 80); //PT一次断相 if FWiringError.UaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftBPlugPos, 0, 15), DgOffsetPoint(FPTGroup.PT1.LeftBPlugPos, 0, 25)); if FWiringError.UbBroken then DrawBroken(DgOffsetPoint(ptUbDown, 0, 10), DgOffsetPoint(ptUbDown, 0, 20)); if FWiringError.UcBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.RightBPlugPos, 0, 15), DgOffsetPoint(FPTGroup.PT2.RightBPlugPos, 0, 25)); //PT二次断相 if FWiringError.UsaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -30)); if FWiringError.UsbBroken then DrawBroken(DgOffsetPoint(ptUbUp, 0, -10), DgOffsetPoint(ptUbUp, 0, -20)); if FWiringError.UscBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.RightTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT2.RightTPlugPos, 0, -30)); // 接地 if FWiringError.GroundBroken then DrawBroken(DgOffsetPoint(FPTGround.Pos, 0, -10), DgOffsetPoint(FPTGround.Pos, 0, 0)); //PT极性反接 if not FWiringError.PT1Reverse then begin FJunctionBoxPtDown.Links[0].OutPortNo := 0; FJunctionBoxPtDown.Links[1].OutPortNo := 1; end else begin FJunctionBoxPtDown.Links[0].OutPortNo := 1; FJunctionBoxPtDown.Links[1].OutPortNo := 0; end; if not FWiringError.PT2Reverse then begin FJunctionBoxPtDown.Links[2].OutPortNo := 2; FJunctionBoxPtDown.Links[3].OutPortNo := 3; end else begin FJunctionBoxPtDown.Links[2].OutPortNo := 3; FJunctionBoxPtDown.Links[3].OutPortNo := 2; end; FJunctionBoxPtDown.Draw; //PT表尾接线 ChangeSequence(FjunctionBoxPtUp.Links, FWiringError.USequence); FJunctionBoxPtUp.Draw; //CT极性反接 if not FWiringError.CT1Reverse then FJunctionBoxCtA.SetOutPortOrder([0, 1]) else FJunctionBoxCtA.SetOutPortOrder([1, 0]); FJunctionBoxCtA.Draw; if not FWiringError.CT2Reverse then FJunctionBoxCtC.SetOutPortOrder([0, 1]) else FJunctionBoxCtC.SetOutPortOrder([1, 0]); FJunctionBoxCtC.Draw; //CT短路 if FWiringError.CT1Short then DgDrawConnection(FBitmap.Canvas, FCT1.LeftPlugPos, FCT1.RightPlugPos); if FWiringError.CT2Short then DgDrawConnection(FBitmap.Canvas, FCT3.LeftPlugPos, FCT3.RightPlugPos); // 电流开路 if FWiringError.IaBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 25)); end; if FWiringError.IbBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 25)); end; if FWiringError.IcBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 25)); end; //CT到CT接线盒的连线 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[0], FJunctionBoxCt.InPorts[0]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[1], FJunctionBoxCt.InPorts[2]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[0], FJunctionBoxCt.InPorts[1]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[1], FJunctionBoxCt.InPorts[2]); //CT接线盒到电表的连线, 以及电表之间的电流端子接线 ptMeterOutPut.X := (FMeter2.GetPlugPos(dmpsIa_out).X + FMeter2.GetPlugPos(dmpsIc_out).X) div 2; ptMeterOutPut.Y := FMeter2.GetPlugPos(dmpsIa_out).Y + 190; DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[0], FMeter1.GetPlugPos(dmpsIa_in), FJunctionBoxCt.OutPorts[0].Y - 40); //40 DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[1], FMeter1.GetPlugPos(dmpsIc_in), FJunctionBoxCt.OutPorts[0].Y - 30); //30 DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[2], ptMeterOutPut, FJunctionBoxCt.OutPorts[0].Y - 25); //25 DgDrawConnection3Y(FBitmap.Canvas, FMeter2.GetPlugPos(dmpsIa_out), FMeter2.GetPlugPos(dmpsIc_out), ptMeterOutPut.Y); DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIa_out), FMeter2.GetPlugPos(dmpsIa_in), FMeter1.GetPlugPos(0).Y + 20); //20 DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIc_out), FMeter2.GetPlugPos(dmpsIc_in), FMeter1.GetPlugPos(0).Y + 30); //30 // 电流接地断开 if FWiringError.IaGroundBroken then DrawBroken( DgOffsetPoint(FCT1.RightPlugPos, 6, -10), DgOffsetPoint(FCT1.RightPlugPos, 6, -10)); if FWiringError.IbGroundBroken then DrawBroken( DgOffsetPoint(FCT2.RightPlugPos, 6, -10), DgOffsetPoint(FCT2.RightPlugPos, 6, -10)); if FWiringError.IcGroundBroken then DrawBroken( DgOffsetPoint(FCT3.RightPlugPos, 6, -10), DgOffsetPoint(FCT3.RightPlugPos, 6, -10)); // 接地 if FWiringError.IGroundBroken then DrawBroken(DgOffsetPoint(FCTGround.Pos, -15, -5), DgOffsetPoint(FCTGround.Pos, -15, 5)); //CT接线盒连线 for I := 0 to 2 do FJunctionBoxCt.Links[I].OutPortNo := I; with FWiringError do begin //ac if (I1In in [plA, plN]) and (I1Out in [plA, plN]) and (I2In in [plC, plN]) and (I2Out in [plC, plN]) then begin SetInPortOrder(0, 1, 2); if (I1In = plN) and (I1Out = plA) then begin Draw; end; if (I2In = plN) and (I2Out = plC) then begin Draw(1); end; end; //ca if (I1In in [plC, plN]) and (I1Out in [plC, plN]) and (I2In in [plA, plN]) and (I2Out in [plA, plN]) then begin SetInPortOrder(1, 0, 2); if (I1In = plN) and (I1Out = plC) then begin Draw; end; if (I2In = plN) and (I2Out = plA) then begin Draw(1); end; end; //ab if (I1In in [plA, plC]) and (I1Out in [plA, plC]) and (I2In in [plC, plN]) and (I2Out in [plC, plN]) then begin SetInPortOrder(0, 2, 1); if (I1In = plC) and (I1Out = plA) then begin Draw; end; if (I2In = plC) and (I2Out = plN) then begin Draw(1); end; end; //cb if (I1In in [plC, plA]) and (I1Out in [plC, plA]) and (I2In in [plA, plN]) and (I2Out in [plA, plN]) then begin SetInPortOrder(1, 2, 0); if (I1In = plA) and (I1Out = plC) then begin Draw; end; if (I2In = plA) and (I2Out = plN) then begin Draw(1); end; end; //bc if (I1In in [plN, plA]) and (I1Out in [plN, plA]) and (I2In in [plC, plA]) and (I2Out in [plC, plA]) then begin SetInPortOrder(2, 1, 0); if (I1In = plA) and (I1Out = plN) then begin Draw; end; if (I2In = plA) and (I2Out = plC) then begin Draw(1); end; end; //ba if (I1In in [plN, plC]) and (I1Out in [plN, plC]) and (I2In in [plA, plC]) and (I2Out in [plA, plC]) then begin SetInPortOrder(2, 0, 1); if (I1In = plC) and (I1Out = plN) then begin Draw; end; if (I2In = plC) and (I2Out = plA) then begin Draw(1); end; end; end; FJunctionBoxCt.Draw; end; procedure TWE_Diagram2.DrawType3L4; var I: Integer; begin //外部电线到PT的连线 FBitmap.Canvas.Polyline([FPTGroup.PT1.LeftBPlugPos, Point(FPTGroup.PT1.LeftBPlugPos.X, FWire1.StartPos.Y)]); FBitmap.Canvas.Polyline([FPTGroup.PT2.RightBPlugPos, Point(FPTGroup.PT2.RightBPlugPos.X, FWire3.StartPos.Y)]); FBitmap.Canvas.Polyline([ptUbDown, Point(ptUbDown.X, FWire2.StartPos.Y)]); DgDrawConnection(FBitmap.Canvas, ptUbDown, FPTGroup.PT1.RightBPlugPos); DgDrawConnection(FBitmap.Canvas, ptUbDown, FPTGroup.PT2.LeftBPlugPos); //两个PT接线盒之间的连线 FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[1], DgOffsetPoint(FJunctionBoxPtDown.OutPorts[2], 1, 0)]); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[0], FJunctionBoxPtUp.InPorts[0]]); FBitmap.Canvas.Polyline([ptUbUp, FJunctionBoxPtUp.InPorts[1]]); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[3], FJunctionBoxPtUp.InPorts[2]]); //PT上接线盒到电表的连线 DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[0], FMeter1.GetPlugPos(dmpsUa), FMeter1.GetPlugPos(0).Y + 60); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[0], FMeter2.GetPlugPos(dmpsUa), FMeter1.GetPlugPos(0).Y + 60); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[1], FMeter1.GetPlugPos(dmpsUb), FMeter1.GetPlugPos(0).Y + 70); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[1], FMeter2.GetPlugPos(dmpsUb), FMeter1.GetPlugPos(0).Y + 70); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[2], FMeter1.GetPlugPos(dmpsUc), FMeter1.GetPlugPos(0).Y + 80); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[2], FMeter2.GetPlugPos(dmpsUc), FMeter1.GetPlugPos(0).Y + 80); //PT一次断相 if FWiringError.UaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftBPlugPos, 0, 15), DgOffsetPoint(FPTGroup.PT1.LeftBPlugPos, 0, 25)); if FWiringError.UbBroken then DrawBroken(DgOffsetPoint(ptUbDown, 0, 10), DgOffsetPoint(ptUbDown, 0, 20)); if FWiringError.UcBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.RightBPlugPos, 0, 15), DgOffsetPoint(FPTGroup.PT2.RightBPlugPos, 0, 25)); //PT二次断相 if FWiringError.UsaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -30)); if FWiringError.UsbBroken then DrawBroken(DgOffsetPoint(ptUbUp, 0, -10), DgOffsetPoint(ptUbUp, 0, -20)); if FWiringError.UscBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.RightTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT2.RightTPlugPos, 0, -30)); // 接地 if FWiringError.GroundBroken then DrawBroken(DgOffsetPoint(FPTGround.Pos, 0, -10), DgOffsetPoint(FPTGround.Pos, 0, 0)); //PT极性反接 if not FWiringError.PT1Reverse then begin FJunctionBoxPtDown.Links[0].OutPortNo := 0; FJunctionBoxPtDown.Links[1].OutPortNo := 1; end else begin FJunctionBoxPtDown.Links[0].OutPortNo := 1; FJunctionBoxPtDown.Links[1].OutPortNo := 0; end; if not FWiringError.PT2Reverse then begin FJunctionBoxPtDown.Links[2].OutPortNo := 2; FJunctionBoxPtDown.Links[3].OutPortNo := 3; end else begin FJunctionBoxPtDown.Links[2].OutPortNo := 3; FJunctionBoxPtDown.Links[3].OutPortNo := 2; end; FJunctionBoxPtDown.Draw(3); //PT表尾接线 ChangeSequence(FjunctionBoxPtUp.Links, FWiringError.USequence); FJunctionBoxPtUp.Draw; //CT接线盒连线 for I := 0 to 3 do FJunctionBoxCt.Links[I].OutPortNo := I; case FWiringError.I1In of plA: FJunctionBoxCt.Links[0].InPortNo := 0; plC: FJunctionBoxCt.Links[0].InPortNo := 2; plN: FJunctionBoxCt.Links[0].InPortNo := 1; end; case FWiringError.I1Out of plA: FJunctionBoxCt.Links[1].InPortNo := 0; plC: FJunctionBoxCt.Links[1].InPortNo := 2; plN: FJunctionBoxCt.Links[1].InPortNo := 1; end; case FWiringError.I2In of plA: FJunctionBoxCt.Links[2].InPortNo := 0; plC: FJunctionBoxCt.Links[2].InPortNo := 2; plN: FJunctionBoxCt.Links[2].InPortNo := 3; end; case FWiringError.I2Out of plA: FJunctionBoxCt.Links[3].InPortNo := 0; plC: FJunctionBoxCt.Links[3].InPortNo := 2; plN: FJunctionBoxCt.Links[3].InPortNo := 3; end; FJunctionBoxCt.Draw; //CT极性反接 if not FWiringError.CT1Reverse then FJunctionBoxCtA.SetOutPortOrder([0, 1]) else FJunctionBoxCtA.SetOutPortOrder([1, 0]); FJunctionBoxCtA.Draw; if not FWiringError.CT2Reverse then FJunctionBoxCtC.SetOutPortOrder([0, 1]) else FJunctionBoxCtC.SetOutPortOrder([1, 0]); FJunctionBoxCtC.Draw; //CT短路 if FWiringError.CT1Short then DgDrawConnection(FBitmap.Canvas, FCT1.LeftPlugPos, FCT1.RightPlugPos); if FWiringError.CT2Short then DgDrawConnection(FBitmap.Canvas, FCT3.LeftPlugPos, FCT3.RightPlugPos); // 电流开路 if FWiringError.IaBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 25)); end; if FWiringError.IbBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 25)); end; if FWiringError.IcBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 25)); end; //CT到CT接线盒的连线 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[0], FJunctionBoxCt.InPorts[0]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[1], FJunctionBoxCt.InPorts[1]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[0], FJunctionBoxCt.InPorts[2]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[1], FJunctionBoxCt.InPorts[3]); //CT接线盒到电表的连线, 以及电表之间的电流端子接线 DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[0], FMeter1.GetPlugPos(dmpsIa_in), FJunctionBoxCt.OutPorts[0].Y - 40); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[1], FMeter2.GetPlugPos(dmpsIa_out), FJunctionBoxCt.OutPorts[0].Y - 35); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[2], FMeter1.GetPlugPos(dmpsIc_in), FJunctionBoxCt.OutPorts[0].Y - 30); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[3], FMeter2.GetPlugPos(dmpsIc_out), FJunctionBoxCt.OutPorts[0].Y - 25); DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIa_out), FMeter2.GetPlugPos(dmpsIa_in), FMeter1.GetPlugPos(0).Y + 20); DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIc_out), FMeter2.GetPlugPos(dmpsIc_in), FMeter1.GetPlugPos(0).Y + 30); // 电流接地断开 if FWiringError.IaGroundBroken then DrawBroken( DgOffsetPoint(FCT1.RightPlugPos, 6, -10), DgOffsetPoint(FCT1.RightPlugPos, 6, -10)); if FWiringError.IcGroundBroken then DrawBroken( DgOffsetPoint(FCT3.RightPlugPos, 6, -10), DgOffsetPoint(FCT3.RightPlugPos, 6, -10)); // 接地 if FWiringError.IGroundBroken then DrawBroken(DgOffsetPoint(FCTGround.Pos, -15, -5), DgOffsetPoint(FCTGround.Pos, -15, 5)); end; procedure TWE_Diagram2.DrawType3M; var I: Integer; begin //外部电线到PT的连线 FBitmap.Canvas.Polyline([FPTGroup.PT1.LeftBPlugPos, Point(FPTGroup.PT1.LeftBPlugPos.X, FWire1.StartPos.Y)]); FBitmap.Canvas.Polyline([FPTGroup.PT2.RightBPlugPos, Point(FPTGroup.PT2.RightBPlugPos.X, FWire3.StartPos.Y)]); FBitmap.Canvas.Polyline([ptUbDown, Point(ptUbDown.X, FWire2.StartPos.Y)]); DgDrawConnection(FBitmap.Canvas, ptUbDown, FPTGroup.PT1.RightBPlugPos); DgDrawConnection(FBitmap.Canvas, ptUbDown, FPTGroup.PT2.LeftBPlugPos); //两个PT接线盒之间的连线 FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[1], DgOffsetPoint(FJunctionBoxPtDown.OutPorts[2], 1, 0)]); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[0], FJunctionBoxPtUp.InPorts[0]]); FBitmap.Canvas.Polyline([ptUbUp, FJunctionBoxPtUp.InPorts[1]]); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[3], FJunctionBoxPtUp.InPorts[2]]); //PT上接线盒到电表的连线 DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[0], FMeter1.GetPlugPos(dmpsUa), FMeter1.GetPlugPos(0).Y + 60); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[1], FMeter1.GetPlugPos(dmpsUb), FMeter1.GetPlugPos(0).Y + 70); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[2], FMeter1.GetPlugPos(dmpsUc), FMeter1.GetPlugPos(0).Y + 80); //PT一次断相 if FWiringError.UaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftBPlugPos, 0, 15), DgOffsetPoint(FPTGroup.PT1.LeftBPlugPos, 0, 25)); if FWiringError.UbBroken then DrawBroken(DgOffsetPoint(ptUbDown, 0, 10), DgOffsetPoint(ptUbDown, 0, 20)); if FWiringError.UcBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.RightBPlugPos, 0, 15), DgOffsetPoint(FPTGroup.PT2.RightBPlugPos, 0, 25)); //PT二次断相 if FWiringError.UsaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -30)); if FWiringError.UsbBroken then DrawBroken(DgOffsetPoint(ptUbUp, 0, -10), DgOffsetPoint(ptUbUp, 0, -20)); if FWiringError.UscBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.RightTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT2.RightTPlugPos, 0, -30)); // 接地 if FWiringError.GroundBroken then DrawBroken(DgOffsetPoint(FPTGround.Pos, 0, -10), DgOffsetPoint(FPTGround.Pos, 0, 0)); // //PT极性反接 // if not FWiringError.PT1Reverse then // begin // FJunctionBoxPtDown.Links[0].OutPortNo := 0; // FJunctionBoxPtDown.Links[1].OutPortNo := 1; // end // else // begin // FJunctionBoxPtDown.Links[0].OutPortNo := 1; // FJunctionBoxPtDown.Links[1].OutPortNo := 0; // end; // if not FWiringError.PT2Reverse then // begin // FJunctionBoxPtDown.Links[2].OutPortNo := 2; // FJunctionBoxPtDown.Links[3].OutPortNo := 3; // end // else // begin // FJunctionBoxPtDown.Links[2].OutPortNo := 3; // FJunctionBoxPtDown.Links[3].OutPortNo := 2; // end; // FJunctionBoxPtDown.Draw; //PT极性反接 if not FWiringError.PT1Reverse then begin FJunctionBoxPtDown.Links[0].OutPortNo := 0; FJunctionBoxPtDown.Links[1].OutPortNo := 1; end else begin FJunctionBoxPtDown.Links[0].OutPortNo := 1; FJunctionBoxPtDown.Links[1].OutPortNo := 0; end; if not FWiringError.PT2Reverse then begin FJunctionBoxPtDown.Links[2].OutPortNo := 2; FJunctionBoxPtDown.Links[3].OutPortNo := 3; end else begin FJunctionBoxPtDown.Links[2].OutPortNo := 3; FJunctionBoxPtDown.Links[3].OutPortNo := 2; end; FJunctionBoxPtDown.Draw; //PT表尾接线 ChangeSequence(FjunctionBoxPtUp.Links, FWiringError.USequence); FJunctionBoxPtUp.Draw; //CT接线盒连线 for I := 0 to 3 do FJunctionBoxCt.Links[I].OutPortNo := I; case FWiringError.I1In of plA: FJunctionBoxCt.Links[0].InPortNo := 0; plC: FJunctionBoxCt.Links[0].InPortNo := 2; plN: FJunctionBoxCt.Links[0].InPortNo := 1; end; case FWiringError.I1Out of plA: FJunctionBoxCt.Links[1].InPortNo := 0; plC: FJunctionBoxCt.Links[1].InPortNo := 2; plN: FJunctionBoxCt.Links[1].InPortNo := 1; end; case FWiringError.I2In of plA: FJunctionBoxCt.Links[2].InPortNo := 0; plC: FJunctionBoxCt.Links[2].InPortNo := 2; plN: FJunctionBoxCt.Links[2].InPortNo := 3; end; case FWiringError.I2Out of plA: FJunctionBoxCt.Links[3].InPortNo := 0; plC: FJunctionBoxCt.Links[3].InPortNo := 2; plN: FJunctionBoxCt.Links[3].InPortNo := 3; end; FJunctionBoxCt.Draw; //CT极性反接 if not FWiringError.CT1Reverse then FJunctionBoxCtA.SetOutPortOrder([0, 1]) else FJunctionBoxCtA.SetOutPortOrder([1, 0]); FJunctionBoxCtA.Draw; if not FWiringError.CT2Reverse then FJunctionBoxCtC.SetOutPortOrder([0, 1]) else FJunctionBoxCtC.SetOutPortOrder([1, 0]); FJunctionBoxCtC.Draw; //CT短路 if FWiringError.CT1Short then DgDrawConnection(FBitmap.Canvas, FCT1.LeftPlugPos, FCT1.RightPlugPos); if FWiringError.CT2Short then DgDrawConnection(FBitmap.Canvas, FCT3.LeftPlugPos, FCT3.RightPlugPos); // 电流开路 if FWiringError.IaBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 25)); end; if FWiringError.IbBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 25)); end; if FWiringError.IcBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 25)); end; // //CT到CT接线盒的连线 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[0], FJunctionBoxCt.InPorts[0]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[1], FJunctionBoxCt.InPorts[1]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[0], FJunctionBoxCt.InPorts[2]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[1], FJunctionBoxCt.InPorts[3]); //CT接线盒到电表的连线 DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[0], FMeter1.GetPlugPos(dmpsIa_in), FJunctionBoxCt.OutPorts[0].Y - 40); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[1], FMeter1.GetPlugPos(dmpsIa_out), FJunctionBoxCt.OutPorts[0].Y - 35); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[2], FMeter1.GetPlugPos(dmpsIc_in), FJunctionBoxCt.OutPorts[0].Y - 30); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[3], FMeter1.GetPlugPos(dmpsIc_out), FJunctionBoxCt.OutPorts[0].Y - 25); // 电流接地断开 if FWiringError.IaGroundBroken then DrawBroken( DgOffsetPoint(FCT1.RightPlugPos, 6, -10), DgOffsetPoint(FCT1.RightPlugPos, 6, -10)); if FWiringError.IbGroundBroken then DrawBroken( DgOffsetPoint(FCT2.RightPlugPos, 6, -10), DgOffsetPoint(FCT2.RightPlugPos, 6, -10)); if FWiringError.IcGroundBroken then DrawBroken( DgOffsetPoint(FCT3.RightPlugPos, 6, -10), DgOffsetPoint(FCT3.RightPlugPos, 6, -10)); // 接地 if FWiringError.IGroundBroken then DrawBroken(DgOffsetPoint(FCTGround.Pos, -15, -5), DgOffsetPoint(FCTGround.Pos, -15, 5)); end; procedure TWE_Diagram2.DrawType4Direct; begin //外部电线到接线盒的连线 FBitmap.Canvas.Polyline([FJunctionBoxPtUp.InPorts[0], Point(FJunctionBoxPtUp.InPorts[0].X, FWire1.StartPos.Y)]); FBitmap.Canvas.Polyline([FJunctionBoxPtUp.InPorts[1], Point(FJunctionBoxPtUp.InPorts[1].X, FWire2.StartPos.Y)]); FBitmap.Canvas.Polyline([FJunctionBoxPtUp.InPorts[2], Point(FJunctionBoxPtUp.InPorts[2].X, FWire3.StartPos.Y)]); //PT上接线盒到电表的连线 DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[0], FMeter1.GetPlugPos(dmpsIa_in), FMeter1.GetPlugPos(0).Y + 60); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[1], FMeter1.GetPlugPos(dmpsIb_in), FMeter1.GetPlugPos(0).Y + 70); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[2], FMeter1.GetPlugPos(dmpsIc_in), FMeter1.GetPlugPos(0).Y + 80); //PT断相 if FWiringError.UaBroken then DrawBroken(DgOffsetPoint(FJunctionBoxPtUp.InPorts[0], 0, 30), DgOffsetPoint(FJunctionBoxPtUp.InPorts[0], 0, 20)); if FWiringError.UbBroken then DrawBroken(DgOffsetPoint(FJunctionBoxPtUp.InPorts[1], 0, 30), DgOffsetPoint(FJunctionBoxPtUp.InPorts[1], 0, 20)); if FWiringError.UcBroken then DrawBroken(DgOffsetPoint(FJunctionBoxPtUp.InPorts[2], 0, 30), DgOffsetPoint(FJunctionBoxPtUp.InPorts[2], 0, 20)); if FWiringError.UnBroken then DrawBroken(Point(FMeter1.GetPlugPos(dmpsUn1).X, FJunctionBoxPtUp.InPorts[0].Y + 30), Point(FMeter1.GetPlugPos(dmpsUn1).X, FJunctionBoxPtUp.InPorts[0].Y + 20)); //表尾进线接线 ChangeSequence(FjunctionBoxPtUp.Links, FWiringError.USequence); FJunctionBoxPtUp.Draw; DgDrawConnection(FBitmap.Canvas, Point(FWire1.BreakXPos2, FWire1.StartPos.Y), FMeter2.GetPlugPos(dmpsIa_out)); DgDrawConnection(FBitmap.Canvas, Point(FWire2.BreakXPos2, FWire2.StartPos.Y), FMeter2.GetPlugPos(dmpsIb_out)); DgDrawConnection(FBitmap.Canvas, Point(FWire3.BreakXPos2, FWire3.StartPos.Y), FMeter2.GetPlugPos(dmpsIc_out)); FBitmap.Canvas.Polyline([FMeter1.GetPlugPos(dmpsUn1), Point(FMeter1.GetPlugPos(dmpsUn1).X, FWire4.StartPos.Y)]); DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIa_out), FMeter2.GetPlugPos(dmpsIa_in), FMeter1.GetPlugPos(0).Y + 20); DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIb_out), FMeter2.GetPlugPos(dmpsIb_in), FMeter1.GetPlugPos(0).Y + 30); DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIc_out), FMeter2.GetPlugPos(dmpsIc_in), FMeter1.GetPlugPos(0).Y + 40); end; procedure TWE_Diagram2.DrawType4M_NoPT; var nTemp : Integer; begin //外部电线到接线盒的连线 FBitmap.Canvas.Polyline([FJunctionBoxPtUp.InPorts[0], Point(FJunctionBoxPtUp.InPorts[0].X, FWire1.StartPos.Y)]); FBitmap.Canvas.Polyline([FJunctionBoxPtUp.InPorts[1], Point(FJunctionBoxPtUp.InPorts[1].X, FWire2.StartPos.Y)]); FBitmap.Canvas.Polyline([FJunctionBoxPtUp.InPorts[2], Point(FJunctionBoxPtUp.InPorts[2].X, FWire3.StartPos.Y)]); //PT上接线盒到电表的连线 DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[0], FMeter1.GetPlugPos(dmpsUa), FMeter1.GetPlugPos(0).Y + 60); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[1], FMeter1.GetPlugPos(dmpsUb), FMeter1.GetPlugPos(0).Y + 70); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[2], FMeter1.GetPlugPos(dmpsUc), FMeter1.GetPlugPos(0).Y + 80); DgDrawConnection3Y(FBitmap.Canvas, Point(FPTGroup.PT3.RightTPlugPos.X, FWire4.StartPos.Y), FMeter1.GetPlugPos(dmpsUn1), FMeter1.GetPlugPos(0).Y + 90); //PT断相 if FWiringError.UaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -30)); if FWiringError.UbBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, -30)); if FWiringError.UcBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, -30)); if FWiringError.UnBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, -30)); //PT表尾接线 ChangeSequence(FjunctionBoxPtUp.Links, FWiringError.USequence); FJunctionBoxPtUp.Draw; //CT接线盒连线 ChangeSequence(FJunctionBoxCt.Links, FWiringError.ISequence); // 表尾电流反接 if FWiringError.I1Reverse then begin nTemp := FJunctionBoxCt.Links[0].InPortNo; FJunctionBoxCt.Links[0].InPortNo:=FJunctionBoxCt.Links[3].InPortNo; FJunctionBoxCt.Links[3].InPortNo:=nTemp; end; if FWiringError.I2Reverse then begin nTemp := FJunctionBoxCt.Links[1].InPortNo; FJunctionBoxCt.Links[1].InPortNo:=FJunctionBoxCt.Links[4].InPortNo; FJunctionBoxCt.Links[4].InPortNo:=nTemp; end; if FWiringError.I3Reverse then begin nTemp := FJunctionBoxCt.Links[2].InPortNo; FJunctionBoxCt.Links[2].InPortNo:=FJunctionBoxCt.Links[5].InPortNo; FJunctionBoxCt.Links[5].InPortNo:=nTemp; end; FJunctionBoxCt.Draw; //CT极性反接 if not FWiringError.CT1Reverse then FJunctionBoxCtA.SetOutPortOrder([0, 1]) else FJunctionBoxCtA.SetOutPortOrder([1, 0]); FJunctionBoxCtA.Draw; if not FWiringError.CT2Reverse then FJunctionBoxCtB.SetOutPortOrder([0, 1]) else FJunctionBoxCtB.SetOutPortOrder([1, 0]); FJunctionBoxCtB.Draw; if not FWiringError.CT3Reverse then FJunctionBoxCtC.SetOutPortOrder([0, 1]) else FJunctionBoxCtC.SetOutPortOrder([1, 0]); FJunctionBoxCtC.Draw; //CT短路 if FWiringError.CT1Short then DgDrawConnection(FBitmap.Canvas, FCT1.LeftPlugPos, FCT1.RightPlugPos); if FWiringError.CT2Short then DgDrawConnection(FBitmap.Canvas, FCT2.LeftPlugPos, FCT2.RightPlugPos); if FWiringError.CT3Short then DgDrawConnection(FBitmap.Canvas, FCT3.LeftPlugPos, FCT3.RightPlugPos); // 电流开路 if FWiringError.IaBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 25)); end; if FWiringError.IbBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 25)); end; if FWiringError.IcBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 25)); end; //CT到CT接线盒的连线 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[0], FJunctionBoxCt.InPorts[0]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[0], FJunctionBoxCt.InPorts[1]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[0], FJunctionBoxCt.InPorts[2]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[1], FJunctionBoxCt.InPorts[3]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[1], FJunctionBoxCt.InPorts[4]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[1], FJunctionBoxCt.InPorts[5]); //CT接线盒到电表的连线, 以及电表之间的电流端子接线 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[0], FMeter1.GetPlugPos(dmpsIa_in)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[1], FMeter1.GetPlugPos(dmpsIb_in)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[2], FMeter1.GetPlugPos(dmpsIc_in)); FJunctionBoxCtA.OutPorts[1].Y := FJunctionBoxCt.OutPorts[0].Y; FJunctionBoxCtB.OutPorts[1].Y := FJunctionBoxCt.OutPorts[1].Y; FJunctionBoxCtC.OutPorts[1].Y := FJunctionBoxCt.OutPorts[2].Y; DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[1], FMeter1.GetPlugPos(dmpsIa_out)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[1], FMeter1.GetPlugPos(dmpsIb_out)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[1], FMeter1.GetPlugPos(dmpsIc_out)); // 电流接地断开 if FWiringError.IaGroundBroken then DrawBroken( DgOffsetPoint(FCT1.RightPlugPos, 6, -10), DgOffsetPoint(FCT1.RightPlugPos, 6, -10)); if FWiringError.IbGroundBroken then DrawBroken( DgOffsetPoint(FCT2.RightPlugPos, 6, -10), DgOffsetPoint(FCT2.RightPlugPos, 6, -10)); if FWiringError.IcGroundBroken then DrawBroken( DgOffsetPoint(FCT3.RightPlugPos, 6, -10), DgOffsetPoint(FCT3.RightPlugPos, 6, -10)); // 接地 if FWiringError.IGroundBroken then DrawBroken(DgOffsetPoint(FCTGround.Pos, -15, -5), DgOffsetPoint(FCTGround.Pos, -15, 5)); end; procedure TWE_Diagram2.DrawType4M_PT; var nTemp : Integer; begin //外部电线到PT的连线 FBitmap.Canvas.Polyline([FPTGroup.PT1.LeftBPlugPos, Point(FPTGroup.PT1.LeftBPlugPos.X, FWire1.StartPos.Y)]); FBitmap.Canvas.Polyline([FPTGroup.PT2.LeftBPlugPos, Point(FPTGroup.PT2.LeftBPlugPos.X, FWire2.StartPos.Y)]); FBitmap.Canvas.Polyline([FPTGroup.PT3.LeftBPlugPos, Point(FPTGroup.PT3.LeftBPlugPos.X, FWire3.StartPos.Y)]); FBitmap.Canvas.Polyline([FPTGroup.PT3.RightBPlugPos, Point(FPTGroup.PT3.RightBPlugPos.X, FWire3.StartPos.Y)]); DgDrawConnection(FBitmap.Canvas, DgOffsetPoint(FPTGroup.PT3.RightBPlugPos, 0, 10), FPTGroup.PT1.RightBPlugPos); DgDrawConnection(FBitmap.Canvas, DgOffsetPoint(FPTGroup.PT3.RightBPlugPos, 0, 10), FPTGroup.PT2.RightBPlugPos); // //PT到PT接线盒之间的连线 // FBitmap.Canvas.Polyline([FPTGroup.PT1.LeftTPlugPos, FJunctionBoxPtUp.InPorts[0]]); // FBitmap.Canvas.Polyline([FPTGroup.PT2.LeftTPlugPos, FJunctionBoxPtUp.InPorts[1]]); // FBitmap.Canvas.Polyline([FPTGroup.PT3.LeftTPlugPos, FJunctionBoxPtUp.InPorts[2]]); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[0], FJunctionBoxPtUp.InPorts[0]]); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[2], FJunctionBoxPtUp.InPorts[1]]); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[4], FJunctionBoxPtUp.InPorts[2]]); //PT上接线盒到电表的连线 DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[0], FMeter1.GetPlugPos(dmpsUa), FMeter1.GetPlugPos(0).Y + 60); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[1], FMeter1.GetPlugPos(dmpsUb), FMeter1.GetPlugPos(0).Y + 70); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[2], FMeter1.GetPlugPos(dmpsUc), FMeter1.GetPlugPos(0).Y + 80); DgDrawConnection3Y(FBitmap.Canvas, FPTGroup.PT3.RightTPlugPos, FMeter1.GetPlugPos(dmpsUn1), FMeter1.GetPlugPos(0).Y + 90); //PT二次断相 if FWiringError.UsaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -30)); if FWiringError.UsbBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, -30)); if FWiringError.UscBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, -30)); if FWiringError.UsnBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, -30)); //PT一次断相 if FWiringError.UaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, 40), DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, 50)); if FWiringError.UbBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, 40), DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, 50)); if FWiringError.UcBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, 40), DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, 50)); if FWiringError.UnBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, 40), DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, 50)); // 接地 if FWiringError.GroundBroken then DrawBroken(DgOffsetPoint(FPTGround.Pos, 0, -10), DgOffsetPoint(FPTGround.Pos, 0, 0)); //PT极性反接 if not FWiringError.PT1Reverse then begin FJunctionBoxPtDown.Links[0].OutPortNo := 0; FJunctionBoxPtDown.Links[1].OutPortNo := 1; end else begin FJunctionBoxPtDown.Links[0].OutPortNo := 1; FJunctionBoxPtDown.Links[1].OutPortNo := 0; end; if not FWiringError.PT2Reverse then begin FJunctionBoxPtDown.Links[2].OutPortNo := 2; FJunctionBoxPtDown.Links[3].OutPortNo := 3; end else begin FJunctionBoxPtDown.Links[2].OutPortNo := 3; FJunctionBoxPtDown.Links[3].OutPortNo := 2; end; if not FWiringError.PT3Reverse then begin FJunctionBoxPtDown.Links[4].OutPortNo := 4; FJunctionBoxPtDown.Links[5].OutPortNo := 5; end else begin FJunctionBoxPtDown.Links[4].OutPortNo := 5; FJunctionBoxPtDown.Links[5].OutPortNo := 4; end; FJunctionBoxPtDown.Draw; //PT表尾接线 ChangeSequence(FjunctionBoxPtUp.Links, FWiringError.USequence); FJunctionBoxPtUp.Draw; //CT接线盒连线 ChangeSequence(FJunctionBoxCt.Links, FWiringError.ISequence); // 表尾电流反接 if FWiringError.I1Reverse then begin nTemp := FJunctionBoxCt.Links[0].InPortNo; FJunctionBoxCt.Links[0].InPortNo:=FJunctionBoxCt.Links[3].InPortNo; FJunctionBoxCt.Links[3].InPortNo:=nTemp; end; if FWiringError.I2Reverse then begin nTemp := FJunctionBoxCt.Links[1].InPortNo; FJunctionBoxCt.Links[1].InPortNo:=FJunctionBoxCt.Links[4].InPortNo; FJunctionBoxCt.Links[4].InPortNo:=nTemp; end; if FWiringError.I3Reverse then begin nTemp := FJunctionBoxCt.Links[2].InPortNo; FJunctionBoxCt.Links[2].InPortNo:=FJunctionBoxCt.Links[5].InPortNo; FJunctionBoxCt.Links[5].InPortNo:=nTemp; end; FJunctionBoxCt.Draw; //CT极性反接 if not FWiringError.CT1Reverse then FJunctionBoxCtA.SetOutPortOrder([0, 1]) else FJunctionBoxCtA.SetOutPortOrder([1, 0]); FJunctionBoxCtA.Draw; if not FWiringError.CT2Reverse then FJunctionBoxCtB.SetOutPortOrder([0, 1]) else FJunctionBoxCtB.SetOutPortOrder([1, 0]); FJunctionBoxCtB.Draw; if not FWiringError.CT3Reverse then FJunctionBoxCtC.SetOutPortOrder([0, 1]) else FJunctionBoxCtC.SetOutPortOrder([1, 0]); FJunctionBoxCtC.Draw; //CT短路 if FWiringError.CT1Short then DgDrawConnection(FBitmap.Canvas, FCT1.LeftPlugPos, FCT1.RightPlugPos); if FWiringError.CT2Short then DgDrawConnection(FBitmap.Canvas, FCT2.LeftPlugPos, FCT2.RightPlugPos); if FWiringError.CT3Short then DgDrawConnection(FBitmap.Canvas, FCT3.LeftPlugPos, FCT3.RightPlugPos); // 电流开路 if FWiringError.IaBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 25)); end; if FWiringError.IbBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 25)); end; if FWiringError.IcBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 25)); end; // //CT到CT接线盒的连线 // DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[0], FJunctionBoxCt.InPorts[0]); // DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[0], FJunctionBoxCt.InPorts[1]); // DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[0], FJunctionBoxCt.InPorts[2]); // // //CT接线盒到电表的连线, 以及电表之间的电流端子接线 // DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[0], FMeter1.GetPlugPos(dmpsIa_in)); // DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[1], FMeter1.GetPlugPos(dmpsIb_in)); // DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[2], FMeter1.GetPlugPos(dmpsIc_in)); // DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[1], FMeter1.GetPlugPos(dmpsIa_out)); // DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[1], FMeter1.GetPlugPos(dmpsIb_out)); // DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[1], FMeter1.GetPlugPos(dmpsIc_out)); //CT到CT接线盒的连线 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[0], FJunctionBoxCt.InPorts[0]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[0], FJunctionBoxCt.InPorts[1]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[0], FJunctionBoxCt.InPorts[2]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[1], FJunctionBoxCt.InPorts[3]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[1], FJunctionBoxCt.InPorts[4]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[1], FJunctionBoxCt.InPorts[5]); //CT接线盒到电表的连线, 以及电表之间的电流端子接线 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[0], FMeter1.GetPlugPos(dmpsIa_in)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[1], FMeter1.GetPlugPos(dmpsIb_in)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[2], FMeter1.GetPlugPos(dmpsIc_in)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[3], FMeter1.GetPlugPos(dmpsIa_out)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[4], FMeter1.GetPlugPos(dmpsIb_out)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[5], FMeter1.GetPlugPos(dmpsIc_out)); // 电流接地断开 if FWiringError.IaGroundBroken then DrawBroken( DgOffsetPoint(FCT1.RightPlugPos, 6, -10), DgOffsetPoint(FCT1.RightPlugPos, 6, -10)); if FWiringError.IbGroundBroken then DrawBroken( DgOffsetPoint(FCT2.RightPlugPos, 6, -10), DgOffsetPoint(FCT2.RightPlugPos, 6, -10)); if FWiringError.IcGroundBroken then DrawBroken( DgOffsetPoint(FCT3.RightPlugPos, 6, -10), DgOffsetPoint(FCT3.RightPlugPos, 6, -10)); // 接地 if FWiringError.IGroundBroken then DrawBroken(DgOffsetPoint(FCTGround.Pos, -15, -5), DgOffsetPoint(FCTGround.Pos, -15, 5)); end; procedure TWE_Diagram2.DrawType4_NoPT_L6; var nTemp : Integer; begin // //外部电线到PT上接线盒的连线 FBitmap.Canvas.Polyline([FJunctionBoxPtUp.InPorts[0], Point(FPTGroup.PT1.LeftBPlugPos.X, FWire1.StartPos.Y)]); FBitmap.Canvas.Polyline([FJunctionBoxPtUp.InPorts[1], Point(FPTGroup.PT2.LeftBPlugPos.X, FWire2.StartPos.Y)]); FBitmap.Canvas.Polyline([FJunctionBoxPtUp.InPorts[2], Point(FPTGroup.PT3.LeftBPlugPos.X, FWire3.StartPos.Y)]); FBitmap.Canvas.Polyline([FPTGroup.PT3.RightBPlugPos, Point(FPTGroup.PT3.RightBPlugPos.X, FWire3.StartPos.Y)]); //PT上接线盒到电表的连线 DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[0], FMeter1.GetPlugPos(dmpsUa), FMeter1.GetPlugPos(0).Y + 60); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[0], FMeter2.GetPlugPos(dmpsUa), FMeter1.GetPlugPos(0).Y + 60); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[1], FMeter1.GetPlugPos(dmpsUb), FMeter1.GetPlugPos(0).Y + 70); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[1], FMeter2.GetPlugPos(dmpsUb), FMeter1.GetPlugPos(0).Y + 70); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[2], FMeter1.GetPlugPos(dmpsUc), FMeter1.GetPlugPos(0).Y + 80); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[2], FMeter2.GetPlugPos(dmpsUc), FMeter1.GetPlugPos(0).Y + 80); DgDrawConnection3Y(FBitmap.Canvas, FPTGroup.PT3.RightTPlugPos, FMeter1.GetPlugPos(dmpsUn1), FMeter1.GetPlugPos(0).Y + 90); DgDrawConnection3Y(FBitmap.Canvas, Point(FPTGroup.PT3.RightTPlugPos.X, FWire4.StartPos.Y), FMeter1.GetPlugPos(dmpsUn1), FMeter1.GetPlugPos(0).Y + 90); //PT断相 if FWiringError.UaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -30)); if FWiringError.UbBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, -30)); if FWiringError.UcBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, -30)); if FWiringError.UnBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, -30)); //PT表尾接线 ChangeSequence(FjunctionBoxPtUp.Links, FWiringError.USequence); FJunctionBoxPtUp.Draw; //CT接线盒连线 ChangeSequence(FJunctionBoxCt.Links, FWiringError.ISequence); // 表尾电流反接 if FWiringError.I1Reverse then begin nTemp := FJunctionBoxCt.Links[0].InPortNo; FJunctionBoxCt.Links[0].InPortNo:=FJunctionBoxCt.Links[3].InPortNo; FJunctionBoxCt.Links[3].InPortNo:=nTemp; end; if FWiringError.I2Reverse then begin nTemp := FJunctionBoxCt.Links[1].InPortNo; FJunctionBoxCt.Links[1].InPortNo:=FJunctionBoxCt.Links[4].InPortNo; FJunctionBoxCt.Links[4].InPortNo:=nTemp; end; if FWiringError.I3Reverse then begin nTemp := FJunctionBoxCt.Links[2].InPortNo; FJunctionBoxCt.Links[2].InPortNo:=FJunctionBoxCt.Links[5].InPortNo; FJunctionBoxCt.Links[5].InPortNo:=nTemp; end; FJunctionBoxCt.Draw; //CT极性反接 if not FWiringError.CT1Reverse then FJunctionBoxCtA.SetOutPortOrder([0, 1]) else FJunctionBoxCtA.SetOutPortOrder([1, 0]); FJunctionBoxCtA.Draw; if not FWiringError.CT2Reverse then FJunctionBoxCtB.SetOutPortOrder([0, 1]) else FJunctionBoxCtB.SetOutPortOrder([1, 0]); FJunctionBoxCtB.Draw; if not FWiringError.CT3Reverse then FJunctionBoxCtC.SetOutPortOrder([0, 1]) else FJunctionBoxCtC.SetOutPortOrder([1, 0]); FJunctionBoxCtC.Draw; //CT短路 if FWiringError.CT1Short then DgDrawConnection(FBitmap.Canvas, FCT1.LeftPlugPos, FCT1.RightPlugPos); if FWiringError.CT2Short then DgDrawConnection(FBitmap.Canvas, FCT2.LeftPlugPos, FCT2.RightPlugPos); if FWiringError.CT3Short then DgDrawConnection(FBitmap.Canvas, FCT3.LeftPlugPos, FCT3.RightPlugPos); // 电流开路 if FWiringError.IaBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 25)); end; if FWiringError.IbBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 25)); end; if FWiringError.IcBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 25)); end; //CT到CT接线盒的连线 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[0], FJunctionBoxCt.InPorts[0]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[0], FJunctionBoxCt.InPorts[1]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[0], FJunctionBoxCt.InPorts[2]); //CT接线盒到电表的连线, 以及电表之间的电流端子接线 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[0], FMeter1.GetPlugPos(dmpsIa_in)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[1], FMeter1.GetPlugPos(dmpsIb_in)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[2], FMeter1.GetPlugPos(dmpsIc_in)); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[3], FMeter2.GetPlugPos(dmpsIa_out), FJunctionBoxCt.OutPorts[0].Y - 20); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[4], FMeter2.GetPlugPos(dmpsIb_out), FJunctionBoxCt.OutPorts[0].Y - 15); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[5], FMeter2.GetPlugPos(dmpsIc_out), FJunctionBoxCt.OutPorts[0].Y - 10); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[1], FJunctionBoxCt.InPorts[3]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[1], FJunctionBoxCt.InPorts[4]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[1], FJunctionBoxCt.InPorts[5]); DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIa_out), FMeter2.GetPlugPos(dmpsIa_in), FMeter1.GetPlugPos(0).Y + 20); DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIb_out), FMeter2.GetPlugPos(dmpsIb_in), FMeter1.GetPlugPos(0).Y + 30); DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIc_out), FMeter2.GetPlugPos(dmpsIc_in), FMeter1.GetPlugPos(0).Y + 40); // 电流接地断开 if FWiringError.IaGroundBroken then DrawBroken( DgOffsetPoint(FCT1.RightPlugPos, 6, -10), DgOffsetPoint(FCT1.RightPlugPos, 6, -10)); if FWiringError.IbGroundBroken then DrawBroken( DgOffsetPoint(FCT2.RightPlugPos, 6, -10), DgOffsetPoint(FCT2.RightPlugPos, 6, -10)); if FWiringError.IcGroundBroken then DrawBroken( DgOffsetPoint(FCT3.RightPlugPos, 6, -10), DgOffsetPoint(FCT3.RightPlugPos, 6, -10)); // 接地 if FWiringError.IGroundBroken then DrawBroken(DgOffsetPoint(FCTGround.Pos, -15, -5), DgOffsetPoint(FCTGround.Pos, -15, 5)); end; procedure TWE_Diagram2.DrawType4_PT_CT_CLear; var AInLinks, AOutLinks : array of TPoint; nI1Value, nI2Value, nI3Value : integer; procedure DrawLine(nStartValue, nMidValue, nEndValue : Integer); procedure DrawConnection(nValue : Integer; APoint : TPoint); var OldColor: TColor; begin if nValue <> 8 then DgDrawConnection(FBitmap.Canvas, FMeter1.GetPlugPos(nValue), APoint); OldColor := FBitmap.Canvas.Brush.Color; FBitmap.Canvas.Brush.Color := clBlack; FBitmap.Canvas.Rectangle(Rect(APoint.X - 1, APoint.Y - 1, APoint.X + 2, APoint.Y + 2)); FBitmap.Canvas.Brush.Color := OldColor; end; var AStartPoint, AMidPoint, AEndPoint : TPoint; begin AStartPoint := Point(FMeter1.GetPlugPos(nStartValue).x, FMeter1.GetPlugPos(nStartValue).y + 80); DrawConnection(nStartValue, AStartPoint); AMidPoint := Point(FMeter1.GetPlugPos(nMidValue).x, FMeter1.GetPlugPos(nMidValue).y + 80); DrawConnection(nMidValue, AMidPoint); AEndPoint := Point(FMeter1.GetPlugPos(nEndValue).x, FMeter1.GetPlugPos(nEndValue).y + 80); DrawConnection(nEndValue, AEndPoint); DgDrawConnection(FBitmap.Canvas, AStartPoint, AEndPoint); end; /// <summary> /// 初始化话连线坐标 /// </summary> procedure InioLinks; var i : Integer; nPlus : Integer; begin for i := 0 to Length(AInLinks) - 1 do begin if i = Length(AInLinks) - 1 then nPlus := i * 3 - 1 else nPlus := i * 3; AInLinks[i] := Point(FMeter1.GetPlugPos(nPlus).x, FMeter1.GetPlugPos(nPlus).y + 187); AOutLinks[i] := Point(FMeter1.GetPlugPos(nPlus).x, FMeter1.GetPlugPos(nPlus).y + 227); end; end; procedure DrawLinks; var nArry : array of Integer; i : Integer; OldColor: TColor; begin SetLength(nArry, Length(AInLinks)); nArry[0] := nI1Value; nArry[1] := nI2Value; nArry[2] := nI3Value; nArry[3] := 6 - nI1Value - nI2Value - nI3Value; for i := 0 to Length(AInLinks) - 1 do begin if nArry[i] <> i then begin FBitmap.Canvas.Polyline([AInLinks[i],AOutLinks[nArry[i]]]); OldColor := FBitmap.Canvas.Pen.Color; FBitmap.Canvas.Pen.Color := clWhite; FBitmap.Canvas.Polyline([AInLinks[i],AOutLinks[i]]); FBitmap.Canvas.Pen.Color := OldColor; end; end; SetLength(nArry, 0); end; /// <param name="nValue">哪个元件[1,2,3]</param> procedure DrawReverse(nValue : Integer); var AIn1Point, AOut1Point, AIn2Point, AOut2Point : TPoint; nInValue, nOutValue : integer; OldColor : TColor; begin nInValue := (nValue - 1) * 3; nOutValue := nInValue + 2; AIn1Point := Point(FMeter1.GetPlugPos(nInValue).x, FMeter1.GetPlugPos(nInValue).y + 18); AOut1Point := Point(FMeter1.GetPlugPos(nInValue).x, FMeter1.GetPlugPos(nInValue).y + 50); AIn2Point := Point(FMeter1.GetPlugPos(nOutValue).x, FMeter1.GetPlugPos(nOutValue).y + 18); AOut2Point := Point(FMeter1.GetPlugPos(nOutValue).x, FMeter1.GetPlugPos(nOutValue).y + 50); FBitmap.Canvas.Polyline([AIn1Point,AOut2Point]); FBitmap.Canvas.Polyline([AIn2Point,AOut1Point]); OldColor := FBitmap.Canvas.pen.Color; FBitmap.Canvas.pen.Color := clWhite; FBitmap.Canvas.Polyline([AIn1Point,AOut1Point]); FBitmap.Canvas.Polyline([AIn2Point,AOut2Point]); FBitmap.Canvas.pen.Color := OldColor; end; begin //外部电线到PT的连线 FBitmap.Canvas.Polyline([FPTGroup.PT1.LeftBPlugPos, Point(FPTGroup.PT1.LeftBPlugPos.X, FWire1.StartPos.Y)]); FBitmap.Canvas.Polyline([FPTGroup.PT2.LeftBPlugPos, Point(FPTGroup.PT2.LeftBPlugPos.X, FWire2.StartPos.Y)]); FBitmap.Canvas.Polyline([FPTGroup.PT3.LeftBPlugPos, Point(FPTGroup.PT3.LeftBPlugPos.X, FWire3.StartPos.Y)]); FBitmap.Canvas.Polyline([FPTGroup.PT3.RightBPlugPos, Point(FPTGroup.PT3.RightBPlugPos.X, FWire3.StartPos.Y)]); DgDrawConnection(FBitmap.Canvas, DgOffsetPoint(FPTGroup.PT3.RightBPlugPos, 0, 10), FPTGroup.PT1.RightBPlugPos); DgDrawConnection(FBitmap.Canvas, DgOffsetPoint(FPTGroup.PT3.RightBPlugPos, 0, 10), FPTGroup.PT2.RightBPlugPos); DgDrawJunction(FBitmap.Canvas, DgOffsetPoint(FPTGroup.PT3.RightBPlugPos, 0, 10), True); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[0], FJunctionBoxPtUp.InPorts[0]]); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[2], FJunctionBoxPtUp.InPorts[1]]); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[4], FJunctionBoxPtUp.InPorts[2]]); // for I := 0 to 2 do // FJunctionBoxCt.Links[I].OutPortNo := I; // // with FWiringError do // begin // //ac // if (I1In in [plA, plN]) and (I1Out in [plA, plN]) and (I2In in [plC, plN]) and (I2Out in [plC, plN]) then // begin // SetInPortOrder(0, 1, 2); // // if (I1In = plN) and (I1Out = plA) then // begin // DrawLine; // end; // // if (I2In = plN) and (I2Out = plC) then // begin // DrawLine(1); // end; // end; // end; FJunctionBoxCt.Draw; // //PT上接线盒到电表的连线 DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[0], FMeter1.GetPlugPos(dmpsUa), FMeter1.GetPlugPos(0).Y + 90); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[1], FMeter1.GetPlugPos(dmpsUb), FMeter1.GetPlugPos(0).Y + 100); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[2], FMeter1.GetPlugPos(dmpsUc), FMeter1.GetPlugPos(0).Y + 110); DgDrawConnection3Y(FBitmap.Canvas, FPTGroup.PT3.RightTPlugPos, FMeter1.GetPlugPos(dmpsUn1), FMeter1.GetPlugPos(0).Y + 120); //PT二次断相 if FWiringError.UsaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -30)); if FWiringError.UsbBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, -30)); if FWiringError.UscBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, -30)); if FWiringError.UsnBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, -30)); //PT一次断相 if FWiringError.UaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, 40), DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, 50)); if FWiringError.UbBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, 40), DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, 50)); if FWiringError.UcBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, 40), DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, 50)); if FWiringError.UnBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, 40), DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, 50)); // 接地 if FWiringError.GroundBroken then DrawBroken(DgOffsetPoint(FPTGround.Pos, 0, -10), DgOffsetPoint(FPTGround.Pos, 0, 0)); // //PT极性反接 if not FWiringError.PT1Reverse then begin FJunctionBoxPtDown.Links[0].OutPortNo := 0; FJunctionBoxPtDown.Links[1].OutPortNo := 1; end else begin FJunctionBoxPtDown.Links[0].OutPortNo := 1; FJunctionBoxPtDown.Links[1].OutPortNo := 0; end; if not FWiringError.PT2Reverse then begin FJunctionBoxPtDown.Links[2].OutPortNo := 2; FJunctionBoxPtDown.Links[3].OutPortNo := 3; end else begin FJunctionBoxPtDown.Links[2].OutPortNo := 3; FJunctionBoxPtDown.Links[3].OutPortNo := 2; end; if not FWiringError.PT3Reverse then begin FJunctionBoxPtDown.Links[4].OutPortNo := 4; FJunctionBoxPtDown.Links[5].OutPortNo := 5; end else begin FJunctionBoxPtDown.Links[4].OutPortNo := 5; FJunctionBoxPtDown.Links[5].OutPortNo := 4; end; FJunctionBoxPtDown.Draw; // // //PT表尾接线 ChangeSequence(FjunctionBoxPtUp.Links, FWiringError.USequence); FJunctionBoxPtUp.Draw; //CT接线盒连线 // ChangeSequence(FJunctionBoxCt.Links, FWiringError.ISequence); // FJunctionBoxCt.Draw; //CT极性反接 if not FWiringError.CT1Reverse then FJunctionBoxCtA.SetOutPortOrder([0, 1]) else FJunctionBoxCtA.SetOutPortOrder([1, 0]); FJunctionBoxCtA.Draw; if not FWiringError.CT2Reverse then FJunctionBoxCtB.SetOutPortOrder([0, 1]) else FJunctionBoxCtB.SetOutPortOrder([1, 0]); FJunctionBoxCtB.Draw; if not FWiringError.CT3Reverse then FJunctionBoxCtC.SetOutPortOrder([0, 1]) else FJunctionBoxCtC.SetOutPortOrder([1, 0]); FJunctionBoxCtC.Draw; //CT短路 if FWiringError.CT1Short then DgDrawConnection(FBitmap.Canvas, FCT1.LeftPlugPos, FCT1.RightPlugPos); if FWiringError.CT2Short then DgDrawConnection(FBitmap.Canvas, FCT2.LeftPlugPos, FCT2.RightPlugPos); if FWiringError.CT3Short then DgDrawConnection(FBitmap.Canvas, FCT3.LeftPlugPos, FCT3.RightPlugPos); // 电流开路 if FWiringError.IaBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 5), DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 15)); end; if FWiringError.IbBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 5), DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 15)); end; if FWiringError.IcBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 5), DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 15)); end; //CT到CT接线盒的连线 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[0], FJunctionBoxCt.InPorts[0]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[0], FJunctionBoxCt.InPorts[1]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[0], FJunctionBoxCt.InPorts[2]); //CT接线盒到电表的连线, 以及电表之间的电流端子接线 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[0], FMeter1.GetPlugPos(dmpsIa_in)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[1], FMeter1.GetPlugPos(dmpsIb_in)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[2], FMeter1.GetPlugPos(dmpsIc_in)); //新增--- DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[1], FMeter1.GetPlugPos(dmpsIc_out)); //原始 //DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[1], FMeter2.GetPlugPos(dmpsIa_out), FJunctionBoxCt.InPorts[0].Y + 20); //新增 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[1], FMeter1.GetPlugPos(dmpsIc_out)); // DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[1], FMeter2.GetPlugPos(dmpsIb_out), FJunctionBoxCt.InPorts[0].Y + 20); // DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[1], FMeter2.GetPlugPos(dmpsIc_out), FJunctionBoxCt.InPorts[0].Y + 20); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[1], Point(FJunctionBoxCtB.OutPorts[1].X, FJunctionBoxCtB.OutPorts[1].Y - 30)); // DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIa_out), FMeter2.GetPlugPos(dmpsIa_in), FMeter1.GetPlugPos(0).Y + 20); // DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIb_out), FMeter2.GetPlugPos(dmpsIb_in), FMeter1.GetPlugPos(0).Y + 30); // DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIc_out), FMeter2.GetPlugPos(dmpsIc_in), FMeter1.GetPlugPos(0).Y + 40); // 电流接地断开 if FWiringError.IaGroundBroken then DrawBroken( DgOffsetPoint(FCT1.RightPlugPos, 6, -10), DgOffsetPoint(FCT1.RightPlugPos, 6, -10)); if FWiringError.IbGroundBroken then DrawBroken( DgOffsetPoint(FCT2.RightPlugPos, 6, -10), DgOffsetPoint(FCT2.RightPlugPos, 6, -10)); if FWiringError.IcGroundBroken then DrawBroken( DgOffsetPoint(FCT3.RightPlugPos, 6, -10), DgOffsetPoint(FCT3.RightPlugPos, 6, -10)); // 接地 if FWiringError.IGroundBroken then DrawBroken(DgOffsetPoint(FCTGround.Pos, -15, -5), DgOffsetPoint(FCTGround.Pos, -15, 5)); ///////////////////////////////////////////////////////////////////////// DrawLine(2, 5, 8); ///////////////////////////////////////////////////////////////////////// /////////////////////////////表尾接法////////////////////////////////// SetLength(AInLinks, 4); SetLength(AOutLinks, 4); InioLinks; with FWiringError do begin nI1Value := Ord(I1In); nI2Value := Ord(I2In); nI3Value := Ord(I3In); if I1Reverse then begin DrawReverse(1); nI1Value := Ord(I1Out); end; if I2Reverse then begin DrawReverse(2); nI2Value := Ord(I2Out); end; if I3Reverse then begin DrawReverse(3); nI3Value := Ord(I3Out); end; DrawLinks; end; /////////////////////////////////////////////////////////////////////// end; procedure TWE_Diagram2.DrawType4_PT_L6; var nTemp : Integer; begin //外部电线到PT的连线 FBitmap.Canvas.Polyline([FPTGroup.PT1.LeftBPlugPos, Point(FPTGroup.PT1.LeftBPlugPos.X, FWire1.StartPos.Y)]); FBitmap.Canvas.Polyline([FPTGroup.PT2.LeftBPlugPos, Point(FPTGroup.PT2.LeftBPlugPos.X, FWire2.StartPos.Y)]); FBitmap.Canvas.Polyline([FPTGroup.PT3.LeftBPlugPos, Point(FPTGroup.PT3.LeftBPlugPos.X, FWire3.StartPos.Y)]); FBitmap.Canvas.Polyline([FPTGroup.PT3.RightBPlugPos, Point(FPTGroup.PT3.RightBPlugPos.X, FWire4.StartPos.Y)]); DgDrawConnection(FBitmap.Canvas, DgOffsetPoint(FPTGroup.PT3.RightBPlugPos, 0, 10), FPTGroup.PT1.RightBPlugPos); DgDrawConnection(FBitmap.Canvas, DgOffsetPoint(FPTGroup.PT3.RightBPlugPos, 0, 10), FPTGroup.PT2.RightBPlugPos); DgDrawJunction(FBitmap.Canvas, DgOffsetPoint(FPTGroup.PT3.RightBPlugPos, 0, 10), True); //PT到PT接线盒之间的连线 //胡红明2013.5.14更改以下三句,旧代码屏蔽 FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[0], FJunctionBoxPtUp.InPorts[0]]); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[2], FJunctionBoxPtUp.InPorts[1]]); FBitmap.Canvas.Polyline([FJunctionBoxPtDown.OutPorts[4], FJunctionBoxPtUp.InPorts[2]]); // FBitmap.Canvas.Polyline([FPTGroup.PT1.LeftTPlugPos, FJunctionBoxPtUp.InPorts[0]]); // FBitmap.Canvas.Polyline([FPTGroup.PT2.LeftTPlugPos, FJunctionBoxPtUp.InPorts[1]]); // FBitmap.Canvas.Polyline([FPTGroup.PT3.LeftTPlugPos, FJunctionBoxPtUp.InPorts[2]]); // //PT上接线盒到电表的连线 DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[0], FMeter1.GetPlugPos(dmpsUa), FMeter1.GetPlugPos(0).Y + 60); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[0], FMeter2.GetPlugPos(dmpsUa), FMeter1.GetPlugPos(0).Y + 60); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[1], FMeter1.GetPlugPos(dmpsUb), FMeter1.GetPlugPos(0).Y + 70); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[1], FMeter2.GetPlugPos(dmpsUb), FMeter1.GetPlugPos(0).Y + 70); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[2], FMeter1.GetPlugPos(dmpsUc), FMeter1.GetPlugPos(0).Y + 80); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxPtUp.OutPorts[2], FMeter2.GetPlugPos(dmpsUc), FMeter1.GetPlugPos(0).Y + 80); //胡红明2013.5.14更改以下一句,旧代码屏蔽 DgDrawConnection3Y(FBitmap.Canvas, Point(FPTGroup.PT3.RightTPlugPos.X, FPTGroup.PT3.RightTPlugPos.Y - 10), FMeter1.GetPlugPos(dmpsUn1), FMeter1.GetPlugPos(0).Y + 90); // DgDrawConnection3Y(FBitmap.Canvas, FPTGroup.PT3.RightTPlugPos, FMeter1.GetPlugPos(dmpsUn1), FMeter1.GetPlugPos(0).Y + 90); //PT断相 胡红明2013.5.13 将几个负数改成正数 if FWiringError.UaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, 50), DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, 40)); if FWiringError.UbBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, 50), DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, 40)); if FWiringError.UcBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, 50), DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, 40)); if FWiringError.UnBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, 50), DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, 40)); //PT二次断相 胡红明2013.5.13 if FWiringError.UsaBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT1.LeftTPlugPos, 0, -30)); if FWiringError.UsbBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT2.LeftTPlugPos, 0, -30)); if FWiringError.UscBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT3.LeftTPlugPos, 0, -30)); if FWiringError.UsnBroken then DrawBroken(DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, -20), DgOffsetPoint(FPTGroup.PT3.RightTPlugPos, 0, -30)); if FWiringError.GroundBroken then DrawBroken(DgOffsetPoint(FPTGround.Pos, 0, -11), DgOffsetPoint(FPTGround.Pos, 0, -1)); //PT二次极性反 胡红明2013.5.13 if not FWiringError.PT1Reverse then begin FJunctionBoxPtDown.Links[0].OutPortNo := 0; FJunctionBoxPtDown.Links[1].OutPortNo := 1; end else begin FJunctionBoxPtDown.Links[0].OutPortNo := 1; FJunctionBoxPtDown.Links[1].OutPortNo := 0; end; if not FWiringError.PT2Reverse then begin FJunctionBoxPtDown.Links[2].OutPortNo := 2; FJunctionBoxPtDown.Links[3].OutPortNo := 3; end else begin FJunctionBoxPtDown.Links[2].OutPortNo := 3; FJunctionBoxPtDown.Links[3].OutPortNo := 2; end; if not FWiringError.PT3Reverse then begin FJunctionBoxPtDown.Links[4].OutPortNo := 4; FJunctionBoxPtDown.Links[5].OutPortNo := 5; end else begin FJunctionBoxPtDown.Links[4].OutPortNo := 5; FJunctionBoxPtDown.Links[5].OutPortNo := 4; end; FJunctionBoxPtDown.Draw; //PT表尾接线 ChangeSequence(FjunctionBoxPtUp.Links, FWiringError.USequence); FJunctionBoxPtUp.Draw; //CT接线盒连线 ChangeSequence(FJunctionBoxCt.Links, FWiringError.ISequence); // 表尾电流反接 if FWiringError.I1Reverse then begin nTemp := FJunctionBoxCt.Links[0].InPortNo; FJunctionBoxCt.Links[0].InPortNo:=FJunctionBoxCt.Links[3].InPortNo; FJunctionBoxCt.Links[3].InPortNo:=nTemp; end; if FWiringError.I2Reverse then begin nTemp := FJunctionBoxCt.Links[1].InPortNo; FJunctionBoxCt.Links[1].InPortNo:=FJunctionBoxCt.Links[4].InPortNo; FJunctionBoxCt.Links[4].InPortNo:=nTemp; end; if FWiringError.I3Reverse then begin nTemp := FJunctionBoxCt.Links[2].InPortNo; FJunctionBoxCt.Links[2].InPortNo:=FJunctionBoxCt.Links[5].InPortNo; FJunctionBoxCt.Links[5].InPortNo:=nTemp; end; FJunctionBoxCt.Draw; //CT极性反接 if not FWiringError.CT1Reverse then FJunctionBoxCtA.SetOutPortOrder([0, 1]) else FJunctionBoxCtA.SetOutPortOrder([1, 0]); FJunctionBoxCtA.Draw; if not FWiringError.CT2Reverse then FJunctionBoxCtB.SetOutPortOrder([0, 1]) else FJunctionBoxCtB.SetOutPortOrder([1, 0]); FJunctionBoxCtB.Draw; if not FWiringError.CT3Reverse then FJunctionBoxCtC.SetOutPortOrder([0, 1]) else FJunctionBoxCtC.SetOutPortOrder([1, 0]); FJunctionBoxCtC.Draw; //CT短路 if FWiringError.CT1Short then DgDrawConnection(FBitmap.Canvas, FCT1.LeftPlugPos, FCT1.RightPlugPos); if FWiringError.CT2Short then DgDrawConnection(FBitmap.Canvas, FCT2.LeftPlugPos, FCT2.RightPlugPos); if FWiringError.CT3Short then DgDrawConnection(FBitmap.Canvas, FCT3.LeftPlugPos, FCT3.RightPlugPos); // 电流开路 if FWiringError.IaBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[0], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[3], 0, 25)); end; if FWiringError.IbBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[1], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[4], 0, 25)); end; if FWiringError.IcBroken then begin DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[2], 0, 25)); // DrawBroken(DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 15), DgOffsetPoint(FJunctionBoxCt.InPorts[5], 0, 25)); end; //CT到CT接线盒的连线 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[0], FJunctionBoxCt.InPorts[0]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[0], FJunctionBoxCt.InPorts[1]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[0], FJunctionBoxCt.InPorts[2]); //CT接线盒到电表的连线, 以及电表之间的电流端子接线 DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[0], FMeter1.GetPlugPos(dmpsIa_in)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[1], FMeter1.GetPlugPos(dmpsIb_in)); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCt.OutPorts[2], FMeter1.GetPlugPos(dmpsIc_in)); // DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[1], FMeter2.GetPlugPos(dmpsIa_out), FJunctionBoxCt.InPorts[0].Y + 10); // DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[1], FMeter2.GetPlugPos(dmpsIb_out), FJunctionBoxCt.InPorts[0].Y + 15); // DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[1], FMeter2.GetPlugPos(dmpsIc_out), FJunctionBoxCt.InPorts[0].Y + 20); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[3], FMeter2.GetPlugPos(dmpsIa_out), FJunctionBoxCt.OutPorts[0].Y - 20); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[4], FMeter2.GetPlugPos(dmpsIb_out), FJunctionBoxCt.OutPorts[0].Y - 15); DgDrawConnection3Y(FBitmap.Canvas, FJunctionBoxCt.OutPorts[5], FMeter2.GetPlugPos(dmpsIc_out), FJunctionBoxCt.OutPorts[0].Y - 10); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtA.OutPorts[1], FJunctionBoxCt.InPorts[3]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtB.OutPorts[1], FJunctionBoxCt.InPorts[4]); DgDrawConnection(FBitmap.Canvas, FJunctionBoxCtC.OutPorts[1], FJunctionBoxCt.InPorts[5]); DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIa_out), FMeter2.GetPlugPos(dmpsIa_in), FMeter1.GetPlugPos(0).Y + 20); DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIb_out), FMeter2.GetPlugPos(dmpsIb_in), FMeter1.GetPlugPos(0).Y + 30); DgDrawConnection3Y(FBitmap.Canvas, FMeter1.GetPlugPos(dmpsIc_out), FMeter2.GetPlugPos(dmpsIc_in), FMeter1.GetPlugPos(0).Y + 40); // 电流接地断开 if FWiringError.IaGroundBroken then DrawBroken( DgOffsetPoint(FCT1.RightPlugPos, 6, -10), DgOffsetPoint(FCT1.RightPlugPos, 6, -10)); if FWiringError.IbGroundBroken then DrawBroken( DgOffsetPoint(FCT2.RightPlugPos, 6, -10), DgOffsetPoint(FCT2.RightPlugPos, 6, -10)); if FWiringError.IcGroundBroken then DrawBroken( DgOffsetPoint(FCT3.RightPlugPos, 6, -10), DgOffsetPoint(FCT3.RightPlugPos, 6, -10)); // 接地 if FWiringError.IGroundBroken then DrawBroken(DgOffsetPoint(FCTGround.Pos, -15, -5), DgOffsetPoint(FCTGround.Pos, -15, 5)); end; procedure TWE_Diagram2.SetDiagramType(const Value: TDiagramType); begin FDiagramType := Value; if FDiagramType < dt4M_NoPT then begin FWiringError.PhaseType := ptThree; FWiringError.Clear; FMeter1.PhaseType := dmptThree; FMeter2.PhaseType := dmptThree; end else begin FWiringError.PhaseType := ptFour; FWiringError.Clear; FMeter1.PhaseType := dmptFour; FMeter2.PhaseType := dmptFour; end; FMeter2.Visible := FDiagramType in [dt3CTClear, dt3L4, dt4_PT_CT_CLear, dt4_PT_L6, dt4_NoPT_L6, dt4Direct]; FMeter2.EnergyType := dmetReactive; FPTGroup.HasThreePT := FMeter1.PhaseType = dmptFour; FPTGroup.Visible := not (FDiagramType in [dt4M_NoPT, dt4_NoPT_L6, dt4Direct]); Invalidate; end; procedure TWE_Diagram2.SetWiringError(const Value: TWIRING_ERROR); begin if (Value.PhaseType = ptThree) and not (FDiagramType in [dt3CTClear..dt3L4]) then FDiagramType := dt3L4 else if (Value.PhaseType = ptFour) and not (FDiagramType in [dt4M_NoPT..dt4_NoPT_L6]) then FDiagramType := dt4_NoPT_L6 else if (Value.PhaseType = ptFourPT) and not (FDiagramType in [dt4M_PT..dt4_PT_L6]) then FDiagramType := dt4_PT_L6; FWiringError.Assign(Value); // if ((FDiagramType < dt4M_PT) and (Value.PhaseType = ptThree)) // or (Value.PhaseType = ptFour) // or (Value.PhaseType = ptFourPT) then //这是新加的,胡红明2013.5.10 // FWiringError.Assign(Value) // else // raise Exception.Create('Phase type conflict'); Invalidate; end; end.
unit UUsuario; interface uses UFuncionario, SysUtils; type Usuario = class private Protected IdUsuario : Integer; Login : string[30]; Senha : string[10]; Status : string[15]; Perfil : string[3]; umFuncionario : Funcionario; DataCadastro : TDateTime; DataAlteracao : TDateTime; Public verificaLogin, verificaFunc : Boolean; Constructor CrieObjeto; Destructor Destrua_Se; Procedure setIdUsuario (vIdUsuario : integer); Procedure setLogin (vLogin : string); Procedure setSenha (vSenha : string); Procedure setStatus (vStatus : string); Procedure setPerfil (vPerfil : string); Procedure setUmFuncionario (vFuncionario : Funcionario); Procedure setDataCadastro (vDataCadastro : TDateTime); Procedure setDataAlteracao (vDataAlteracao : TDateTime); Function getIdUsuario : integer; Function getLogin : string; Function getSenha : string; Function getStatus : string; Function getPerfil : string; Function getUmFuncionario : Funcionario; Function getDataCadastro :TDateTime; Function getDataAlteracao : TDateTime; End; implementation { Usuario } constructor Usuario.CrieObjeto; var dataAtual : TDateTime; begin dataAtual := Date; IdUsuario := 0; Login := ''; Senha := ''; Status := ''; Perfil := ''; umFuncionario := Funcionario.CrieObjeto; DataCadastro := dataAtual; DataAlteracao := dataAtual; end; destructor Usuario.Destrua_Se; begin end; function Usuario.getDataAlteracao: TDateTime; begin Result := DataAlteracao; end; function Usuario.getDataCadastro: TDateTime; begin Result := DataCadastro; end; function Usuario.getIdUsuario: integer; begin Result := IdUsuario; end; function Usuario.getLogin: string; begin Result := Login; end; function Usuario.getPerfil: string; begin Result := Perfil; end; function Usuario.getSenha: string; begin Result := Senha; end; function Usuario.getStatus: string; begin Result := Status; end; function Usuario.getUmFuncionario: Funcionario; begin Result := umFuncionario; end; procedure Usuario.setDataAlteracao(vDataAlteracao: TDateTime); begin DataAlteracao := vDataAlteracao; end; procedure Usuario.setDataCadastro(vDataCadastro: TDateTime); begin DataCadastro := vDataCadastro; end; procedure Usuario.setIdUsuario(vIdUsuario: integer); begin IdUsuario := vIdUsuario; end; procedure Usuario.setLogin(vLogin: string); begin Login := vLogin; end; procedure Usuario.setPerfil(vPerfil: string); begin Perfil := vPerfil; end; procedure Usuario.setSenha(vSenha: string); begin Senha := vSenha; end; procedure Usuario.setStatus(vStatus: string); begin Status := vStatus; end; procedure Usuario.setUmFuncionario(vFuncionario: Funcionario); begin umFuncionario := vFuncionario; end; end.
unit u_millesecond_timer; interface uses windows, sysutils; type tmillisecond_timer = record start:int64; millisecond:double; end; procedure milliseconds_start(var timer:tmillisecond_timer); function milliseconds_get(var timer:tmillisecond_timer):double; function milliseconds_str(var timer:tmillisecond_timer):string; implementation procedure milliseconds_start(var timer:tmillisecond_timer); var freq:int64; begin with timer do begin QueryPerformanceFrequency(freq); QueryPerformanceCounter(start); millisecond := freq / 1000; end; end; function milliseconds_get(var timer:tmillisecond_timer):double; var current:int64; begin result := 0; with timer do begin QueryPerformanceCounter(current); if millisecond = 0 then result := 0 else result:=(current-start)/millisecond; end; end; function milliseconds_str(var timer:tmillisecond_timer):string; begin result:= FloatTostrf(milliseconds_get(timer), ffFixed,4,3); end; end.
unit Global; interface uses // Delphi/Windows Windows, Forms, Registry, Variants, Classes, Controls, UITypes, // TPerlRegEx PerlRegEx ; {==================================================================================================} const APPLICATION_NAME = 'SysTool'; APPLICATION_VERSION = 1; type TSysToolModule = ( stmNone = -1, stmBitPattern, stmFileAnalysis, stmConvertPathLocalUNC, stmConvertPathUNCLocal ); {==================================================================================================} type TCommandLineSwitch = ( clsNone = -1, clsStartupNoMenu, clsStartupSilent ); const COMMAND_LINE_SWITCH_PREFIX = [ '-', '/' ]; COMMAND_LINE_SWITCH_STR: array[TCommandLineSwitch] of String = ( '', // clsNone 'nomenu', // clsStartupNoMenu 'silent' // clsStartupSilent ); {==================================================================================================} const V_NULL = $00000000; type TUTF8StringPair = record Key: UTF8String; Val: UTF8String; end; {==================================================================================================} type TRegistryKey = record KeyName: String; KeyType: Integer; // variant type mask Default: String; end; function GetRegistryKeyValue( const Root: HKEY; const Path: String; const Key: TRegistryKey; out Value: Variant): Boolean; overload; function GetRegistryKeyValue( const Key: TRegistryKey; out Value: Variant): Boolean; overload; function SetRegistryKeyValue( const Root: HKEY; const Path: String; const Key: TRegistryKey; const Value: Variant): Boolean; overload; function SetRegistryKeyValue( const Key: TRegistryKey; const Value: Variant): Boolean; overload; procedure ShowRegistryAccessErrorDialog(const ModeID: Cardinal; const Key: TRegistryKey); const REGKEY_ROOT_DEFAULT = HKEY_CURRENT_USER; REGKEY_PATH_DEFAULT = '\Software\Aircraft Performance Systems\'; REGKEY_COMMON_STAY_ON_TOP : TRegistryKey = ( KeyName: 'Common_StayOnTop'; KeyType: varBoolean; Default: 'FALSE' ); REGKEY_FORMBITPATTERN_FORM_X : TRegistryKey = ( KeyName: 'FormBitPattern_X'; KeyType: varInteger; Default: '120' ); REGKEY_FORMBITPATTERN_FORM_Y : TRegistryKey = ( KeyName: 'FormBitPattern_Y'; KeyType: varInteger; Default: '120' ); REGKEY_FORMBITPATTERN_FORM_WIDTH : TRegistryKey = ( KeyName: 'FormBitPattern_Width'; KeyType: varInteger; Default: '735' ); REGKEY_FORMBITPATTERN_FORM_HEIGHT : TRegistryKey = ( KeyName: 'FormBitPattern_Height'; KeyType: varInteger; Default: '768' ); REGKEY_FORMBITPATTERN_GROUP_BASES : TRegistryKey = ( KeyName: 'FormBitPattern_Groups'; KeyType: varBoolean; Default: 'False' ); REGKEY_FORMFILEANALYSIS_FORM_X : TRegistryKey = ( KeyName: 'FormFileAnalysis_X'; KeyType: varInteger; Default: '120' ); REGKEY_FORMFILEANALYSIS_FORM_Y : TRegistryKey = ( KeyName: 'FormFileAnalysis_Y'; KeyType: varInteger; Default: '120' ); REGKEY_FORMFILEANALYSIS_FORM_WIDTH : TRegistryKey = ( KeyName: 'FormFileAnalysis_Width'; KeyType: varInteger; Default: '800' ); REGKEY_FORMFILEANALYSIS_FORM_HEIGHT : TRegistryKey = ( KeyName: 'FormFileAnalysis_Height'; KeyType: varInteger; Default: '420' ); REGKEY_FORMFILEANALYSIS_BROWSER_WIDTH : TRegistryKey = ( KeyName: 'FormFileAnalysis_BrowserWidth'; KeyType: varInteger; Default: '260' ); REGKEY_FORMFILEANALYSIS_DIR_LIST_HEIGHT : TRegistryKey = ( KeyName: 'FormFileAnalysis_DirListHeight'; KeyType: varInteger; Default: '132' ); {==================================================================================================} type TSessionVarID = ( svUser, svHost ); TSessionVarQuery = record BufferSize: Cardinal; Subroutine: function(lpBuffer: PWideChar; var nSize: DWORD): BOOL; stdcall; end; {==================================================================================================} type TCommonRegExMatchType = ( creFilePath ); TCommonRegExMatch = record Instance: TPerlRegEx; Options: TPerlRegExOptions; Pattern: UTF8String; end; var CommonRegExMatch: array[TCommonRegExMatchType] of TCommonRegExMatch = ( ( // creFilePath Instance: nil; Options: [ preCaseLess, preSingleLine, preExtended ]; Pattern: '^(?:(?:[a-z]:|\\\\[a-z0-9_.$\-]+\\[a-z0-9_.$\-]+)\\|\\?[^\\/:*?"<>|\r\n]+\\?)(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$'; ) ); function GetSpecialPath(const PathID: Cardinal): String; overload; function GetSpecialPath(const Owner: Cardinal; const PathID: Cardinal): String; overload; function GetUNCPath(const LocalPath: String): String; function GetLocalPath(const UNCPath: String): String; function PromptForFileOrDir(Title: String): String; function GetSessionKey(const Key: TSessionVarID): String; function GetSessionIdentifier(): String; function GetApplicationNameString(): String; function GetApplicationVersionString(): String; function GetApplicationNameVersionString(): String; function GetApplicationExePath(): String; function GetCurrentDateTimeString(): String; function GetCommandLineSwitch(const Switch: TCommandLineSwitch): Boolean; function IsMatch(const Subject: String; const RegEx: TCommonRegExMatchType): Boolean; procedure EnableChildControls(const Control: TWinControl; const Enable: Boolean; const EnableSelf: Boolean; const Ignore: array of TWinControl); overload; procedure EnableChildControls(const Control: TWinControl; const Enable: Boolean; const Ignore: array of TWinControl); overload; procedure EnableChildControls(const Control: TWinControl; const Enable: Boolean; const EnableSelf: Boolean); overload; procedure EnableChildControls(const Control: TWinControl; const Enable: Boolean); overload; procedure DebugLog(const Formatting: String; const Data: array of const); type // callback typedefs TProcedureArg<T> = reference to procedure(const Arg: T); TAssertion = reference to function: Boolean; function TryCloseConsoleProcess(hHwnd: HWND; dwData: LPARAM): Boolean; stdcall; procedure CloseConsoleProcess(ProcessInfo: TProcessInformation); procedure CaptureConsoleOutput(const ACommand, AParameters: String; const CReadBuffer: Cardinal; const HandleOutput: TProcedureArg<PAnsiChar>; const ContinueProcess: TAssertion); const MAX_USERNAME_LENGTH = $0100; // Size field from UNLEN constant in LMCons.h SESSION_KEY_QUERY : array[TSessionVarID] of TSessionVarQuery = ( ( BufferSize: MAX_USERNAME_LENGTH; Subroutine: Windows.GetUserName ), ( BufferSize: MAX_COMPUTERNAME_LENGTH; Subroutine: Windows.GetComputerName ) ); const CSIDL_DESKTOP = $0000; { <desktop> } CSIDL_INTERNET = $0001; { Internet Explorer (icon on desktop) } CSIDL_PROGRAMS = $0002; { Start Menu\Programs } CSIDL_CONTROLS = $0003; { My Computer\Control Panel } CSIDL_PRINTERS = $0004; { My Computer\Printers } CSIDL_PERSONAL = $0005; { My Documents. This is equivalent to CSIDL_MYDOCUMENTS in XP and above } CSIDL_FAVORITES = $0006; { <user name>\Favorites } CSIDL_STARTUP = $0007; { Start Menu\Programs\Startup } CSIDL_RECENT = $0008; { <user name>\Recent } CSIDL_SENDTO = $0009; { <user name>\SendTo } CSIDL_BITBUCKET = $000a; { <desktop>\Recycle Bin } CSIDL_STARTMENU = $000b; { <user name>\Start Menu } CSIDL_MYDOCUMENTS = $000c; { logical "My Documents" desktop icon } CSIDL_MYMUSIC = $000d; { "My Music" folder } CSIDL_MYVIDEO = $000e; { "My Video" folder } CSIDL_DESKTOPDIRECTORY = $0010; { <user name>\Desktop } CSIDL_DRIVES = $0011; { My Computer } CSIDL_NETWORK = $0012; { Network Neighborhood (My Network Places) } CSIDL_NETHOOD = $0013; { <user name>\nethood } CSIDL_FONTS = $0014; { windows\fonts } CSIDL_TEMPLATES = $0015; CSIDL_COMMON_STARTMENU = $0016; { All Users\Start Menu } CSIDL_COMMON_PROGRAMS = $0017; { All Users\Start Menu\Programs } CSIDL_COMMON_STARTUP = $0018; { All Users\Startup } CSIDL_COMMON_DESKTOPDIRECTORY = $0019; { All Users\Desktop } CSIDL_APPDATA = $001a; { <user name>\Application Data } CSIDL_PRINTHOOD = $001b; { <user name>\PrintHood } CSIDL_LOCAL_APPDATA = $001c; { <user name>\Local Settings\Application Data (non roaming) } CSIDL_ALTSTARTUP = $001d; { non localized startup } CSIDL_COMMON_ALTSTARTUP = $001e; { non localized common startup } CSIDL_COMMON_FAVORITES = $001f; CSIDL_INTERNET_CACHE = $0020; CSIDL_COOKIES = $0021; CSIDL_HISTORY = $0022; CSIDL_COMMON_APPDATA = $0023; { All Users\Application Data } CSIDL_WINDOWS = $0024; { GetWindowsDirectory() } CSIDL_SYSTEM = $0025; { GetSystemDirectory() } CSIDL_PROGRAM_FILES = $0026; { C:\Program Files } CSIDL_MYPICTURES = $0027; { C:\Program Files\My Pictures } CSIDL_PROFILE = $0028; { USERPROFILE } CSIDL_SYSTEMX86 = $0029; { x86 system directory on RISC } CSIDL_PROGRAM_FILESX86 = $002a; { x86 C:\Program Files on RISC } CSIDL_PROGRAM_FILES_COMMON = $002b; { C:\Program Files\Common } CSIDL_PROGRAM_FILES_COMMONX86 = $002c; { x86 C:\Program Files\Common on RISC } CSIDL_COMMON_TEMPLATES = $002d; { All Users\Templates } CSIDL_COMMON_DOCUMENTS = $002e; { All Users\Documents } CSIDL_COMMON_ADMINTOOLS = $002f; { All Users\Start Menu\Programs\Administrative Tools } CSIDL_ADMINTOOLS = $0030; { <user name>\Start Menu\Programs\Administrative Tools } CSIDL_CONNECTIONS = $0031; { Network and Dial-up Connections } CSIDL_COMMON_MUSIC = $0035; { All Users\My Music } CSIDL_COMMON_PICTURES = $0036; { All Users\My Pictures } CSIDL_COMMON_VIDEO = $0037; { All Users\My Video } CSIDL_RESOURCES = $0038; { Resource Directory } CSIDL_RESOURCES_LOCALIZED = $0039; { Localized Resource Directory } CSIDL_COMMON_OEM_LINKS = $003a; { Links to All Users OEM specific apps } CSIDL_CDBURN_AREA = $003b; { USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning } CSIDL_COMPUTERSNEARME = $003d; { Computers Near Me (computered from Workgroup membership) } CSIDL_PROFILES = $003e; {==================================================================================================} type TNumberType = ( ntNONE, ntByte, ntShortInt, ntWord, ntSmallInt, ntCardinal, ntInteger, ntUInt64, ntInt64, ntSingle, ntDouble ); const BITS_IN_TYPE: array[TNumberType] of Byte = ( 0, // ntNONE 8, // ntByte 8, // ntShortInt 16, // ntWord 16, // ntSmallInt 32, // ntCardinal 32, // ntInteger 64, // ntUInt64 64, // ntInt64 32, // ntSingle 64 // ntDouble ); const TYPE_8_BIT = [ ntByte, ntShortInt ]; TYPE_16_BIT = [ ntWord, ntSmallInt ]; TYPE_32_BIT = [ ntCardinal, ntInteger, ntSingle ]; TYPE_64_BIT = [ ntUInt64, ntInt64, ntDouble ]; TYPE_FLOAT = [ ntSingle, ntDouble ]; TYPE_SIGNED = [ ntShortInt, ntSmallInt, ntInteger, ntInt64 ]; function BinaryString(Value: UInt64; Width: Byte): String; function UInt64ToOct(Value: UInt64; Width: Byte): String; function RemoveLeadingZeros(const Value: String): String; function TryStrToUInt64(SValue: String; var UValue: UInt64): Boolean; function StrToUInt64(Value: String): UInt64; function IsValidIntOfType(IntType: TNumberType; ValueAddress: Pointer): Boolean; function GroupCharsL2R(SValue: String; Width: Byte): String; function GroupCharsR2L(SValue: String; Width: Byte): String; function StripAllWhitespace(SValue: String): String; {==================================================================================================} implementation uses // Delphi/Windows SysUtils, StrUtils, ShlObj, ShLwApi, Messages, Dialogs, Character; function GetSpecialPath(const PathID: Cardinal): String; const DEFAULT_OWNER_ID = 0; begin Result := GetSpecialPath(DEFAULT_OWNER_ID, PathID); end; function GetSpecialPath(const Owner: Cardinal; const PathID: Cardinal): String; var Length: Cardinal; begin Length := MAX_PATH - 1; Result := StringOfChar(Char(V_NULL), Length); SHGetSpecialFolderPath(Owner, PWideChar(Result), PathID, False); Result := Trim(Result); end; function GetUNCPath(const LocalPath: String): String; var PromptedPath: String; CanonicalPath: array[0 .. MAX_PATH - 1] of Char; begin Result := ''; // verify the string is somewhat passable as a (Windows) file path if IsMatch(LocalPath, creFilePath) then begin if PathIsRelative(PChar(LocalPath)) then begin PathCanonicalize(@CanonicalPath[0], PChar(LocalPath)); Result := CanonicalPath; end else begin // returns local path for local drives, UNC path for network drives Result := ExpandUNCFileName(LocalPath); end; end else begin // prompt for filepath PromptedPath := PromptForFileOrDir('Select file or directory...'); if FileExists(PromptedPath) or DirectoryExists(PromptedPath) then Result := GetUNCPath(PromptedPath); end; end; function GetLocalPath(const UNCPath: String): String; var PromptedPath: String; CanonicalPath: array[0 .. MAX_PATH - 1] of Char; ShareName: String; CurrDrive: Char; R: TPerlRegEx; begin Result := ''; // verify the string is somewhat passable as a (Windows) file path if IsMatch(UNCPath, creFilePath) then begin if PathIsRelative(PChar(UNCPath)) then begin PathCanonicalize(@CanonicalPath[0], PChar(UNCPath)); Result := CanonicalPath; end else begin R := TPerlRegex.Create; // step through each drive letter and get its fully-qual'd UNC name for CurrDrive := 'A' to 'Z' do begin // if this drive is currently mapped and identified as a remote resource case GetDriveType(PChar(CurrDrive + ':\')) of DRIVE_REMOTE: begin // compare our local path's fully-qual'd UNC name to this drive's ShareName := ExpandUNCFileName(CurrDrive + ':\'); R.Subject := UTF8String(UNCPath); R.Regex := UTF8String(TPerlRegEx.EscapeRegExChars(ShareName)); // match pattern R.Replacement := UTF8String(CurrDrive + ':\'); // and replace the share name with the current drive letter if R.Match then begin R.Replace; Result := Trim(String(R.Subject)); break; end; end; end; end; end; end else begin // prompt for filepath PromptedPath := PromptForFileOrDir('Select file or directory...'); if FileExists(PromptedPath) or DirectoryExists(PromptedPath) then Result := GetLocalPath(PromptedPath); end; end; function GetSessionKey(const Key: TSessionVarID): String; var Length: Cardinal; begin Length := SESSION_KEY_QUERY[Key].BufferSize; Result := StringOfChar(Char(V_NULL), Length); SESSION_KEY_QUERY[Key].Subroutine(PChar(Result), Length); Result := Trim(Result); end; function GetSessionIdentifier(): String; begin Result := Format('%s@%s', [ GetSessionKey(svUser), GetSessionKey(svHost) ]); end; function GetApplicationNameString(): String; begin Result := Format('%s', [ APPLICATION_NAME ]); end; function GetApplicationVersionString(): String; begin Result := Format('v%d', [ APPLICATION_VERSION ]); end; function GetApplicationNameVersionString(): String; begin Result := Format('%s %s', [ GetApplicationNameString(), GetApplicationVersionString() ]); end; function GetApplicationExePath(): String; begin Result := Format('%s', [ExtractFilePath(Application.ExeName)]); end; function GetCurrentDateTimeString(): String; begin Result := DateTimeToStr(Now); end; function GetCommandLineSwitch(const Switch: TCommandLineSwitch): Boolean; begin Result := FindCmdLineSwitch( COMMAND_LINE_SWITCH_STR[Switch], COMMAND_LINE_SWITCH_PREFIX, FALSE{IgnoreCase}); end; function IsMatch(const Subject: String; const RegEx: TCommonRegExMatchType): Boolean; begin if not Assigned(CommonRegExMatch[RegEx].Instance) then begin CommonRegExMatch[RegEx].Instance := TPerlRegex.Create; CommonRegExMatch[RegEx].Instance.Regex := CommonRegExMatch[RegEx].Pattern; CommonRegExMatch[RegEx].Instance.Options := CommonRegExMatch[RegEx].Options; CommonRegExMatch[RegEx].Instance.Study; end; CommonRegExMatch[RegEx].Instance.Subject := UTF8String(Subject); Result := CommonRegExMatch[RegEx].Instance.Match; end; procedure EnableChildControls(const Control: TWinControl; const Enable: Boolean; const EnableSelf: Boolean; const Ignore: array of TWinControl); var Child: TWinControl; IgnoreCount: Integer; Ignored: Boolean; i: Integer; j: Integer; begin IgnoreCount := Length(Ignore); for i := 0 to Control.ControlCount - 1 do begin Ignored := FALSE; for j := 0 to IgnoreCount - 1 do Ignored := Ignored or (Control.Controls[i] = Ignore[j]); if not Ignored then try Child := Control.Controls[i] as TWinControl; EnableChildControls(Child, Enable, Enable{do NOT pass EnableSelf to children!}, Ignore); Child.Enabled := Enable; except on Ex: EInvalidCast do begin Continue; end; end; end; Control.Enabled := EnableSelf; end; procedure EnableChildControls(const Control: TWinControl; const Enable: Boolean; const Ignore: array of TWinControl); begin EnableChildControls(Control, Enable, Enable, Ignore); end; procedure EnableChildControls(const Control: TWinControl; const Enable: Boolean; const EnableSelf: Boolean); begin EnableChildControls(Control, Enable, EnableSelf, []); end; procedure EnableChildControls(const Control: TWinControl; const Enable: Boolean); begin EnableChildControls(Control, Enable, Enable, []); end; procedure DebugLog(const Formatting: String; const Data: array of const); begin OutputDebugString(PWideChar(Format(Formatting, Data))); end; function TryCloseConsoleProcess(hHwnd: HWND; dwData: LPARAM): Boolean; stdcall; var dID: DWORD; begin GetWindowThreadProcessID(hHwnd, @dID); if dID = DWORD(dwData) then begin PostMessage(hHwnd, WM_CLOSE, 0, 0); // graceful request to DIE IN A FIRE Result := FALSE; end else begin Result := TRUE; end; end; procedure CloseConsoleProcess(ProcessInfo: TProcessInformation); var vExitCode: UINT; begin GetExitCodeProcess(ProcessInfo.hProcess, vExitCode); if STILL_ACTIVE = vExitCode then begin EnumWindows(@TryCloseConsoleProcess, ProcessInfo.dwProcessId); if WAIT_OBJECT_0 <> WaitForSingleObject(ProcessInfo.hProcess, 100) then begin if not TerminateProcess(ProcessInfo.hProcess, 0) then begin // didn't close! end; end; end; CloseHandle(ProcessInfo.hProcess); CloseHandle(ProcessInfo.hThread); end; // // procedure CaptureConsoleOutput taken from: // http://thundaxsoftware.blogspot.co.uk/2012/12/capturing-console-output-with-delphi.html // // author: Jordi Corbilla // retrieved: 01 December 2014 // // changes: // - changed read buffer size from constant to function parameter // - added callback to provide caller a way to kill the process // procedure CaptureConsoleOutput( const ACommand, AParameters: String; const CReadBuffer: Cardinal; const HandleOutput: TProcedureArg<PAnsiChar>; const ContinueProcess: TAssertion); var saSecurity : TSecurityAttributes; hRead : THandle; hWrite : THandle; suiStartup : TStartupInfo; piProcess : TProcessInformation; dRead : DWORD; dRunning : DWORD; dAvailable : DWORD; pBuffer : array of AnsiChar; dBuffer : array of AnsiChar; bContinue : Boolean; begin SetLength(pBuffer, CReadBuffer); SetLength(dBuffer, CReadBuffer); saSecurity.nLength := SizeOf(TSecurityAttributes); saSecurity.bInheritHandle := true; saSecurity.lpSecurityDescriptor := nil; if CreatePipe(hRead, hWrite, @saSecurity, 0) then begin try FillChar(suiStartup, SizeOf(TStartupInfo), #0); suiStartup.cb := SizeOf(TStartupInfo); suiStartup.hStdInput := hRead; suiStartup.hStdOutput := hWrite; suiStartup.hStdError := hWrite; suiStartup.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW; suiStartup.wShowWindow := SW_HIDE; if CreateProcess( nil, // lpApplicationName PChar(ACommand + ' ' + AParameters), // lpCommandLine @saSecurity, // lpProcessAttributes @saSecurity, // lpThreadAttributes TRUE, // bInheritHandles NORMAL_PRIORITY_CLASS, // dwCreationFlags nil, // lpEnvironment nil, // lpCurrentDirectory suiStartup, // lpStartupInfo piProcess // lpProcessInformation ) then try repeat dRunning := WaitForSingleObject(piProcess.hProcess, 100); PeekNamedPipe(hRead, nil, 0, nil, @dAvailable, nil); bContinue := TRUE; if (dAvailable > 0) then begin repeat dRead := 0; ReadFile(hRead, pBuffer[0], CReadBuffer, dRead, nil); pBuffer[dRead] := #0; OemToCharA(PAnsiChar(pBuffer), PAnsiChar(dBuffer)); HandleOutput(PAnsiChar(dBuffer)); bContinue := ContinueProcess; until not bContinue or (dRead < CReadBuffer); end; Application.ProcessMessages; until not bContinue or (dRunning <> WAIT_TIMEOUT); finally CloseConsoleProcess(piProcess); end; finally CloseHandle(hRead); CloseHandle(hWrite); end; end; end; function BinaryString(Value: UInt64; Width: Byte): String; begin Result := ''; while Width > 0 do begin Dec(Width); Result := Result + IntToStr((Value shr Width) and 1); end; end; function PromptForFileOrDir(Title: String): String; var BrowseInfo : TBrowseInfo; ItemID : PItemIDList; DisplayName : array[0 .. MAX_PATH - 1] of Char; SelectedPath : array[0 .. MAX_PATH - 1] of Char; begin Result := ''; FillChar(BrowseInfo, sizeof(BrowseInfo), #0); with BrowseInfo do begin hwndOwner := Application.Handle; pszDisplayName := @DisplayName; lpszTitle := PChar(Title); ulFlags := BIF_BROWSEINCLUDEFILES; end; ItemID := SHBrowseForFolder(BrowseInfo); if ItemID <> nil then begin SHGetPathFromIDList(ItemID, SelectedPath); Result := SelectedPath; GlobalFreePtr(ItemID); end; end; function UInt64ToOct(Value: UInt64; Width: Byte): String; var Rem: UInt64; begin Result := ''; while Value > 0 do begin Rem := Value mod 8; Value := Value div 8; Result := Format('%d%s', [Rem, Result]); end; while Length(Result) < Width do begin Result := Format('0%s', [Result]); end; end; function RemoveLeadingZeros(const Value: String): String; var i: Integer; begin for i := 1 to Length(Value) do begin if Value[i] <> '0' then begin Result := Copy(Value, i, MaxInt); Exit; end; end; Result := ''; end; function TryStrToUInt64(SValue: String; var UValue: UInt64): Boolean; var Start: Integer; Base: Integer; Digit: Integer; n: Integer; Nextvalue: UInt64; begin Result := FALSE; Digit := 0; Base := 10; Start := 1; SValue := Trim(UpperCase(SValue)); if (SValue = '') or (SValue[1] = '-') then Exit; if SValue[1] = '$' then begin Base := 16; Start := 2; // $+16 hex digits = max hex length. if Length(SValue) > 17 then Exit; end; UValue := 0; for n := Start to Length(SValue) do begin if Character.IsDigit(SValue[n]) then Digit := Ord(SValue[n]) - Ord('0') else if (Base = 16) and (SValue[n] >= 'A') and (SValue[n] <= 'F') then Digit := (Ord(SValue[n]) - Ord('A')) + 10 else Exit; // invalid digit. NextValue := (UValue * Base) + Digit; if (NextValue < UValue) then Exit; UValue := NextValue; end; Result := TRUE; // success. end; function StrToUInt64(Value: String): UInt64; begin if not TryStrToUInt64(Value, Result) then raise EConvertError.Create('Invalid UInt64 value'); end; function IsValidIntOfType(IntType: TNumberType; ValueAddress: Pointer): Boolean; var MaxSigned, MinSigned : Int64; MaxUnsigned, MinUnsigned : UInt64; begin Result := FALSE; if not (IntType in TYPE_FLOAT) then begin MaxSigned := Int64( ( UInt64(1) shl (BITS_IN_TYPE[IntType] - 1) ) - 1 ); MinSigned := -Int64( ( UInt64(1) shl (BITS_IN_TYPE[IntType] - 1) ) ); MaxUnsigned := UInt64( ( UInt64(1) shl (BITS_IN_TYPE[IntType] ) ) - 1 ); MinUnsigned := 0; case IntType of ntByte: //Result := Value = (Value and $00000000000000FF); Result := (Byte(ValueAddress^) >= MinUnsigned) and (Byte(ValueAddress^) <= MaxUnsigned); ntShortInt: //Result := Value = (Value and $00000000000000FF); Result := (ShortInt(ValueAddress^) >= MinSigned) and (ShortInt(ValueAddress^) <= MaxSigned); ntWord: //Result := Value = (Value and $000000000000FFFF); Result := (Word(ValueAddress^) >= MinUnsigned) and (Word(ValueAddress^) <= MaxUnsigned); ntSmallInt: //Result := Value = (Value and $000000000000FFFF); Result := (SmallInt(ValueAddress^) >= MinSigned) and (SmallInt(ValueAddress^) <= MaxSigned); ntCardinal: //Result := Value = (Value and $00000000FFFFFFFF); Result := (Cardinal(ValueAddress^) >= MinUnsigned) and (Cardinal(ValueAddress^) <= MaxUnsigned); ntInteger: //Result := Value = (Value and $00000000FFFFFFFF); Result := (Integer(ValueAddress^) >= MinSigned) and (Integer(ValueAddress^) <= MaxSigned); ntUInt64: //Result := Value = (Value and $FFFFFFFFFFFFFFFF); Result := (UInt64(ValueAddress^) >= MinUnsigned) and (UInt64(ValueAddress^) <= MaxUnsigned); ntInt64: //Result := Value = (Value and $FFFFFFFFFFFFFFFF); Result := (Int64(ValueAddress^) >= MinSigned) and (Int64(ValueAddress^) <= MaxSigned); end; end; end; function GroupCharsL2R(SValue: String; Width: Byte): String; var R: TPerlRegEx; begin R := TPerlRegex.Create; R.Subject := UTF8String(SValue); R.Regex := UTF8String(Format('(.{%d})', [Width])); // match pattern R.Replacement := UTF8String('\1 '); R.ReplaceAll; Result := Trim(String(R.Subject)); end; function GroupCharsR2L(SValue: String; Width: Byte): String; begin Result := ReverseString(GroupCharsL2R(ReverseString(SValue), Width)); end; function StripAllWhitespace(SValue: String): String; var R: TPerlRegEx; begin R := TPerlRegex.Create; R.Subject := UTF8String(SValue); R.Regex := UTF8String('\s'); // match pattern R.Replacement := UTF8String(''); R.ReplaceAll; Result := String(R.Subject); end; function GetRegistryKeyValue( const Root: HKEY; const Path: String; const Key: TRegistryKey; out Value: Variant): Boolean; var Registry: TRegistry; begin try Registry := TRegistry.Create(KEY_READ); try Registry.RootKey := Root; if Registry.OpenKey(Path, TRUE) then begin case Key.KeyType of varBoolean: if Registry.ValueExists(Key.KeyName) then Value := Registry.ReadBool(Key.KeyName) else Value := SysUtils.StrToBool(Key.Default); varInteger: if Registry.ValueExists(Key.KeyName) then Value := Registry.ReadInteger(Key.KeyName) else Value := SysUtils.StrToInt(Key.Default); varDouble: if Registry.ValueExists(Key.KeyName) then Value := Registry.ReadFloat(Key.KeyName) else Value := SysUtils.StrToFloat(Key.Default); varString: if Registry.ValueExists(Key.KeyName) then Value := Registry.ReadString(Key.KeyName) else Value := Key.Default; else Value := NULL; end; Result := TRUE; end else begin Value := NULL; Result := FALSE; end; finally Registry.CloseKey(); Registry.Free(); end; except on Ex: Exception do begin Value := NULL; Result := FALSE; end; end; if not Result then ShowRegistryAccessErrorDialog(KEY_READ, Key); end; function SetRegistryKeyValue( const Root: HKEY; const Path: String; const Key: TRegistryKey; const Value: Variant): Boolean; var Registry: TRegistry; begin try Registry := TRegistry.Create(KEY_WRITE); try Registry.RootKey := Root; if Registry.OpenKey(Path, TRUE) then begin case Key.KeyType of varBoolean: Registry.WriteBool(Key.KeyName, Value); varInteger: Registry.WriteInteger(Key.KeyName, Value); varDouble: Registry.WriteFloat(Key.KeyName, Value); varString: Registry.WriteString(Key.KeyName, Value); end; Result := TRUE; end else begin Result := FALSE; end; finally Registry.CloseKey(); Registry.Free(); end; except on Ex: Exception do begin Result := FALSE; end; end; if not Result then ShowRegistryAccessErrorDialog(KEY_WRITE, Key); end; function GetRegistryKeyValue(const Key: TRegistryKey; out Value: Variant): Boolean; begin Result := GetRegistryKeyValue(REGKEY_ROOT_DEFAULT, REGKEY_PATH_DEFAULT, Key, Value); end; function SetRegistryKeyValue(const Key: TRegistryKey; const Value: Variant): Boolean; begin Result := SetRegistryKeyValue(REGKEY_ROOT_DEFAULT, REGKEY_PATH_DEFAULT, Key, Value); end; procedure ShowRegistryAccessErrorDialog(const ModeID: Cardinal; const Key: TRegistryKey); var Mode: String; begin case ModeID of KEY_READ: Mode := 'READ'; KEY_WRITE: Mode := 'WRITE'; else Mode := 'ACCESS'; end; MessageDlg(Format('Unable to "%s" registry key "%s"', [Mode, Key.KeyName]), mtError, [mbOk], 0); end; end.
unit Creditos; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Tabs, ComCtrls, jpeg, ShellAPI; type TFormCredito = class(TForm) Label2 : TLabel; Label8 : TLabel; LbTitiShadow: TLabel; LbTitiOver: TLabel; LbVer: TLabel; TabSet1: TTabSet; Notebook: TNotebook; Memo: TMemo; MemoTXT: TMemo; Shape1: TShape; Panel1: TPanel; Image1: TImage; procedure TabSet1Change(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); procedure FormShow(Sender: TObject); //Funçoes para pegar os dados de versão do arquivo definidos no projeto (Delphi) function MyFileVersionAtributes(const FileName: string;var FileInfo: TStringList): Boolean; function MyFileVerInfo(const FileName: string; var versao: string): Boolean; procedure SendVars(strfn,strmemo:string); procedure Label2Click(Sender: TObject); private public arquivo : string; procedure ExibeCreditos(auxtitpchar, auxpchar, auxmemopchar: String); end; var FormCredito: TFormCredito; implementation {$R *.DFM} procedure TFormCredito.SendVars(strfn,strmemo:string); begin arquivo:=strfn; MemoTXT.Lines.Add(strmemo); end; procedure TFormCredito.TabSet1Change(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); begin Notebook.PageIndex:=NewTab; end; procedure TFormCredito.FormShow(Sender: TObject); var StrAthVersao:string; auxstrlst:TStringList; i:integer; begin memo.clear; LbVer.Caption:=''; if (MyFileVerInfo(arquivo, StrAthVersao))then begin LbVer.Caption:=StrAthVersao; auxstrlst:=TStringList.create; MyFileVersionAtributes(arquivo,auxstrlst); for i:=0 to auxstrlst.count-1 do memo.lines.add(auxstrlst[i]); auxstrlst.free; end end; //PEGA TODOS OS DADOS RELATIVOS A VERSÃO DO ARQUIVO EXECUTAVEL function TFormCredito.MyFileVersionAtributes(const FileName: string;var FileInfo: TStringList): Boolean; const Key: array[1..9] of string =('CompanyName' , 'FileDescription', 'FileVersion', 'InternalName', 'LegalCopyright' , 'OriginalFilename', 'ProductName' , 'ProductVersion' , 'Comments'); KeyBr: array [1..9] of string = ('Empresa', 'Descrição', 'Versão do Arquivo', 'Nome Interno', 'Copyright', 'Nome Original do Arquivo', 'Produto', 'Versão do Produto', 'Comentários'); var Dummy : THandle; BufferSize, Len : Integer; Buffer : PChar; LoCharSet, HiCharSet : Word; Translate, Return : Pointer; StrFileInfo, Flags : string; TargetOS, TypeArq : string; FixedFileInfo : Pointer; i : Byte; begin Result := False; { Obtemos o tamanho em bytes do "version information" } BufferSize := GetFileVersionInfoSize(PChar(FileName), Dummy); if BufferSize <> 0 then begin GetMem(Buffer, Succ(BufferSize)); try if GetFileVersionInfo(PChar(FileName), 0, BufferSize, Buffer) then { Executamos a funcao "VerQueryValue" e conseguimos informacoes sobre o idioma/character-set } if VerQueryValue(Buffer, '\VarFileInfo\Translation', Translate, UINT(Len)) then begin LoCharSet := LoWord(Longint(Translate^)); HiCharSet := HiWord(Longint(Translate^)); for i := 1 to 9 do begin { Montamos a string de pesquisa } StrFileInfo := Format('\StringFileInfo\0%x0%x\%s', [LoCharSet, HiCharSet, Key[i]]); { Adicionamos cada key pré-definido } if VerQueryValue(Buffer,PChar(StrFileInfo), Return, UINT(Len)) then FileInfo.Add(KeyBr[i] + ': ' + PChar(Return)); end; if VerQueryValue(Buffer,'\',FixedFileInfo, UINT(Len)) then with TVSFixedFileInfo(FixedFileInfo^) do begin Flags := ''; { Efetuamos um bitmask e obtemos os "flags" do arquivo } if (dwFileFlags and VS_FF_DEBUG) = VS_FF_DEBUG then Flags := Concat(Flags,'*Debug* '); if (dwFileFlags and VS_FF_SPECIALBUILD) = VS_FF_SPECIALBUILD then Flags := Concat(Flags,'*Special Build* '); if (dwFileFlags and VS_FF_PRIVATEBUILD) = VS_FF_PRIVATEBUILD then Flags := Concat(Flags,'*Private Build* '); if (dwFileFlags and VS_FF_PRERELEASE) = VS_FF_PRERELEASE then Flags := Concat(Flags,'*Pre-Release Build* '); if (dwFileFlags and VS_FF_PATCHED) = VS_FF_PATCHED then Flags := Concat(Flags,'*Patched* '); if Flags <> '' then FileInfo.Add('Atributos: ' + Flags); TargetOS := 'Plataforma (OS): '; { Plataforma } case dwFileOS of VOS_UNKNOWN: TargetOS := Concat(TargetOS, 'Desconhecido'); VOS_DOS : TargetOS := Concat(TargetOS, 'MS-DOS'); VOS_OS216 : TargetOS := Concat(TargetOS, '16-bit OS/2'); VOS_OS232 : TargetOS := Concat(TargetOS, '32-bit OS/2'); VOS_NT : TargetOS := Concat(TargetOS, 'Windows NT'); VOS_NT_WINDOWS32, 4: TargetOS := Concat(TargetOS, 'Win32 API'); VOS_DOS_WINDOWS16 : TargetOS := Concat(TargetOS, '16-bit Windows ', 'sob MS-DOS'); else TargetOS := Concat(TargetOS, 'Fora do Padrão. Código: ', IntToStr(dwFileOS)); end; FileInfo.Add(TargetOS); TypeArq := 'Tipo de Arquivo: '; { Tipo de Arquivo } case dwFileType of VFT_UNKNOWN : TypeArq := Concat(TypeArq,'Desconhecido'); VFT_APP : TypeArq := Concat(TypeArq,'Aplicacao'); VFT_DLL : TypeArq := Concat(TypeArq,'Dynamic-Link Lib.'); VFT_DRV : begin TypeArq := Concat(TypeArq,'Device driver - Driver '); case dwFileSubtype of VFT2_UNKNOWN : TypeArq := Concat(TypeArq,'Desconhecido'); VFT2_DRV_PRINTER : TypeArq := Concat(TypeArq,'de Impressão'); VFT2_DRV_KEYBOARD : TypeArq := Concat(TypeArq,'de Teclado'); VFT2_DRV_LANGUAGE : TypeArq := Concat(TypeArq,'de Idioma'); VFT2_DRV_DISPLAY : TypeArq := Concat(TypeArq,'de Vídeo'); VFT2_DRV_MOUSE : TypeArq := Concat(TypeArq,'de Mouse'); VFT2_DRV_NETWORK : TypeArq := Concat(TypeArq,'de Rede'); VFT2_DRV_SYSTEM : TypeArq := Concat(TypeArq,'de Sistema'); VFT2_DRV_INSTALLABLE: TypeArq := Concat(TypeArq,'Instalavel'); VFT2_DRV_SOUND : TypeArq := Concat(TypeArq,'Multimida'); end; end; VFT_FONT : begin TypeArq := Concat(TypeArq,'Fonte - Fonte '); case dwFileSubtype of VFT2_UNKNOWN : TypeArq := Concat(TypeArq, 'Desconhecida'); VFT2_FONT_RASTER : TypeArq := Concat(TypeArq,'Raster'); VFT2_FONT_VECTOR : TypeArq := Concat(TypeArq,'Vetorial'); VFT2_FONT_TRUETYPE : TypeArq := Concat(TypeArq,'TrueType'); end; end; VFT_VXD : TypeArq := Concat(TypeArq,'Virtual Device'); VFT_STATIC_LIB : TypeArq := Concat(TypeArq,'Static-Link Lib.'); end; FileInfo.Add(TypeArq); end; end; finally FreeMem(Buffer, Succ(BufferSize)); Result := FileInfo.Text <> ''; end; end; end; //PEGA APENAS A VERSÃO DO PROGRAMA function TFormCredito.MyFileVerInfo(const FileName: string; var versao: string): Boolean; var Dummy : THandle; BufferSize, Len : Integer; Buffer : PChar; LoCharSet, HiCharSet : Word; Translate, Return : Pointer; StrFileInfo : string; begin Result := False; { Obtemos o tamanho em bytes do "version information" } BufferSize := GetFileVersionInfoSize(PChar(FileName), Dummy); if BufferSize <> 0 then begin GetMem(Buffer, Succ(BufferSize)); try if GetFileVersionInfo(PChar(FileName), 0, BufferSize,Buffer) then { Executamos a funcao "VerQueryValue" e conseguimos informacoes sobre o idioma/character-set } if VerQueryValue(Buffer, '\VarFileInfo\Translation',Translate, UINT(Len)) then begin LoCharSet := LoWord(Longint(Translate^)); HiCharSet := HiWord(Longint(Translate^)); { Montamos a string de pesquisa } StrFileInfo := Format('\StringFileInfo\0%x0%x\%s',[LoCharSet, HiCharSet, 'FileVersion']); { Adicionamos cada key pré-definido } if VerQueryValue(Buffer,PChar(StrFileInfo), Return,UINT(Len)) then versao:=PChar(Return); end; finally FreeMem(Buffer, Succ(BufferSize)); Result := versao <> ''; end; end; end; procedure TFormCredito.Label2Click(Sender: TObject); begin ShellExecute(0,nil,'http://www.athenas.com.br',nil,nil,0); end; procedure TFormCredito.ExibeCreditos(auxtitpchar, auxpchar, auxmemopchar: String); begin FormCredito.LbTitiOver.Caption :=auxtitpchar; FormCredito.LbTitiShadow.Caption:=auxtitpchar; FormCredito.SendVars(auxpchar,auxmemopchar); FormCredito.ShowModal; end; end.
unit uFramUserList; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, System.Rtti, FMX.Grid.Style, FMX.Grid, FMX.ScrollBox, FMX.Menus, System.Actions, FMX.ActnList, uUserInfo, FMX.DialogService; type TfamUserList = class(TFrame) strGrdUser: TStringGrid; strngclmn1: TStringColumn; strngclmn2: TStringColumn; strngclmn3: TStringColumn; PopupMenu1: TPopupMenu; ActionList1: TActionList; actAddUser: TAction; MenuItem1: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; MenuItem6: TMenuItem; MenuItem7: TMenuItem; actRefresh: TAction; actEditUser: TAction; actDel: TAction; actUserUpPass: TAction; procedure actAddUserExecute(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure actEditUserExecute(Sender: TObject); procedure actDelExecute(Sender: TObject); procedure actUserUpPassExecute(Sender: TObject); private { Private declarations } procedure AddUserList(AUser : TUser); procedure OnDoubleClick(Sender: TObject); public { Public declarations } procedure LoadData; end; implementation uses uUserControl, uNewUser, uUpUsPass; {$R *.fmx} { TfamUserList } procedure TfamUserList.actAddUserExecute(Sender: TObject); var AUser : TUser; begin with TfNewUser.Create(nil) do begin AUser := TUser.Create; ShowInfo(AUser); if ShowModal = mrOk then begin SaveInfo; if Assigned(UserControl) then begin UserControl.SaveUser(AUser); AddUserList(AUser); TDialogService.MessageDialog('新增成功!',TMsgDlgType.mtInformation, [TMsgDlgBtn.mbOK], TMsgDlgBtn.mbOK, 0, nil); end; end; Free; end; end; procedure TfamUserList.actDelExecute(Sender: TObject); var AUser : TUser; begin if strGrdUser.Selected <> -1 then begin TDialogService.MessageDialog('确认要删除选择的记录吗?',TMsgDlgType.mtInformation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], TMsgDlgBtn.mbOK, 0, procedure(const AResult: TModalResult) begin if AResult = mrYes then begin if Assigned(UserControl) then begin AUser := UserControl.GetUserInfo(strGrdUser.Cells[0, strGrdUser.Selected]); if Assigned(AUser) then begin UserControl.DelUser(AUser); LoadData; TDialogService.MessageDialog('删除用户成功!',TMsgDlgType.mtInformation, [], TMsgDlgBtn.mbOK, 0, nil); end; end; end; end); end; end; procedure TfamUserList.actEditUserExecute(Sender: TObject); var AUser : TUser; nIndex : Integer; sUserName : string; begin nIndex := strGrdUser.Selected; if nIndex <> -1 then begin sUserName := strGrdUser.Cells[0, nIndex]; if Assigned(UserControl) then begin AUser := UserControl.GetUserInfo(sUserName); if Assigned(AUser) then begin with TfNewUser.Create(nil) do begin ShowInfo(AUser); if ShowModal = mrOk then begin SaveInfo; UserControl.SaveUser(AUser); TDialogService.MessageDialog('编辑成功!',TMsgDlgType.mtInformation, [TMsgDlgBtn.mbOK], TMsgDlgBtn.mbOK, 0, nil); end; Free; end; end; end; end else begin TDialogService.MessageDialog('请选择需要编辑的用户!',TMsgDlgType.mtInformation, [TMsgDlgBtn.mbOK], TMsgDlgBtn.mbOK, 0, nil); end; end; procedure TfamUserList.actRefreshExecute(Sender: TObject); begin LoadData; end; procedure TfamUserList.actUserUpPassExecute(Sender: TObject); var AUser : TUser; begin if strGrdUser.Selected <> -1 then begin if Assigned(UserControl) then begin AUser := UserControl.GetUserInfo(strGrdUser.Cells[0, strGrdUser.Selected]); UserControl.UserUpass(AUser); end; end; end; procedure TfamUserList.AddUserList(AUser: TUser); var nGrdRowNum : Integer; begin strGrdUser.RowCount := strGrdUser.RowCount + 1; nGrdRowNum := strGrdUser.RowCount - 1; with strGrdUser, AUser do begin Cells[0, nGrdRowNum] := LoginName; Cells[1, nGrdRowNum] := FullName; Cells[2, nGrdRowNum] := Description; end; end; procedure TfamUserList.LoadData; var i : integer; begin strGrdUser.RowCount := 0; strGrdUser.OnDblClick := OnDoubleClick; if Assigned(UserControl) then begin with UserControl.UserList do begin for i := 0 to Count - 1 do AddUserList(TUser(Objects[i])); end; end; end; procedure TfamUserList.OnDoubleClick(Sender: TObject); begin actEditUserExecute(nil); end; end.
unit ADAPT.UnitTests.Maths.Averagers; interface {$I ADAPT.inc} uses {$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES} System.Classes, System.SysUtils, {$ELSE} Classes, SysUtils, {$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES} DUnitX.TestFramework, ADAPT.Collections.Intf, ADAPT.Math.Averagers.Intf; type [TestFixture] TAdaptUnitTestMathAveragerFloatMean = class(TObject) public [Test] procedure TestAverageFromSortedList; end; [TestFixture] TAdaptUnitTestMathAveragerFloatMedian = class(TObject) public [Test] procedure TestAverageFromSortedList; end; [TestFixture] TAdaptUnitTestMathAveragerFloatRange = class(TObject) public [Test] procedure TestAverageFromSortedList; end; [TestFixture] TAdaptUnitTestMathAveragerIntegerMean = class(TObject) public [Test] procedure TestAverageFromSortedList; end; [TestFixture] TAdaptUnitTestMathAveragerIntegerMedian = class(TObject) public [Test] procedure TestAverageFromSortedList; end; [TestFixture] TAdaptUnitTestMathAveragerIntegerRange = class(TObject) public [Test] procedure TestAverageFromSortedList; end; implementation uses ADAPT.Intf, ADAPT.Collections, ADAPT.Comparers, ADAPT.Math.Common, ADAPT.Math.Averagers; { TAdaptUnitTestMathAveragerFloatMean } procedure TAdaptUnitTestMathAveragerFloatMean.TestAverageFromSortedList; var LSeries: IADSortedList<ADFloat>; LAverage: ADFloat; begin LSeries := TADSortedList<ADFloat>.Create(ADFloatComparer); LSeries.AddItems([1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00, 10.00]); LAverage := ADAveragerFloatMean.CalculateAverage(LSeries); Assert.IsTrue(LAverage = 5.5, Format('Expected Average of 5.5, got %n.', [LAverage])); end; { TAdaptUnitTestMathAveragerFloatMedian } procedure TAdaptUnitTestMathAveragerFloatMedian.TestAverageFromSortedList; var LSeries: IADSortedList<ADFloat>; LAverage: ADFloat; begin LSeries := TADSortedList<ADFloat>.Create(ADFloatComparer); LSeries.AddItems([1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00, 10.00]); LAverage := ADAveragerFloatMedian.CalculateAverage(LSeries); Assert.IsTrue(LAverage = 5.00, Format('Expected Average of 5.00, got %n.', [LAverage])); end; { TAdaptUnitTestMathAveragerFloatRange } procedure TAdaptUnitTestMathAveragerFloatRange.TestAverageFromSortedList; var LSeries: IADSortedList<ADFloat>; LAverage: ADFloat; begin LSeries := TADSortedList<ADFloat>.Create(ADFloatComparer); LSeries.AddItems([1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00, 10.00]); LAverage := ADAveragerFloatRange.CalculateAverage(LSeries); Assert.IsTrue(LAverage = 9.00, Format('Expected Average of 9.00, got %n.', [LAverage])); end; { TAdaptUnitTestMathAveragerIntegerMean } procedure TAdaptUnitTestMathAveragerIntegerMean.TestAverageFromSortedList; var LSeries: IADSortedList<Integer>; LAverage: Integer; begin LSeries := TADSortedList<Integer>.Create(ADIntegerComparer); LSeries.AddItems([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); LAverage := ADAveragerIntegerMean.CalculateAverage(LSeries); Assert.IsTrue(LAverage = 5, Format('Expected Average of 5, got %d.', [LAverage])); end; { TAdaptUnitTestMathAveragerIntegerMedian } procedure TAdaptUnitTestMathAveragerIntegerMedian.TestAverageFromSortedList; var LSeries: IADSortedList<Integer>; LAverage: Integer; begin LSeries := TADSortedList<Integer>.Create(ADIntegerComparer); LSeries.AddItems([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); LAverage := ADAveragerIntegerMedian.CalculateAverage(LSeries); Assert.IsTrue(LAverage = 5, Format('Expected Average of 5, got %d.', [LAverage])); end; { TAdaptUnitTestMathAveragerIntegerRange } procedure TAdaptUnitTestMathAveragerIntegerRange.TestAverageFromSortedList; var LSeries: IADSortedList<Integer>; LAverage: Integer; begin LSeries := TADSortedList<Integer>.Create(ADIntegerComparer); LSeries.AddItems([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); LAverage := ADAveragerIntegerRange.CalculateAverage(LSeries); Assert.IsTrue(LAverage = 9, Format('Expected Average of 9, got %d.', [LAverage])); end; end.
unit XWM; {$mode objfpc}{$H+} interface uses Classes, Sysutils, X, Xlib, XAtom, XUtil, ctypes, BaseWM, XRootWindow, XFrames, NETAtoms, XAtoms, fpg_base, fpg_main, cursorfont; type { TXWindowManager } // This class will do the 'dirty' work of managing the window and will have // abstract methods for descendants to implement. i.e. TfpGUIWindowManager or so // all painting will be done in a descendant TXWindowManager = class(TBaseWindowManager) private fQuit: Boolean; fDisplay: PXDisplay; fRootWindowList: TWMRootWindowList; fLastErrorHandler: TXErrorHandler; fNetAtoms: TNetAtoms; fCurrentEvent: PXEvent; function GrabRootWindows: Boolean; public constructor Create(const ADisplayName: String); virtual; destructor Destroy; override; function WindowToFrame(const AWindow: TWindow): TXFrame; procedure CreateDisplay(ADisplayName: String); virtual; procedure InitWM(QueryWindows: Boolean = True); override; procedure MainLoop; override; // event related methods function XEventCB(const AEvent: TXEvent): Boolean; virtual; function GetCurrentEvent: PXEvent; // create and destroy frame windows function CreateNewWindowFrame(Sender: TWMRootWindow; const AScreen: PScreen; const AChild: TWindow; AX, AY, AWidth, AHeight: Integer; AOverrideDirect: TBool): TXFrame; virtual; abstract; procedure DestroyWindowFrame(var AWindow: TXFrame); virtual; abstract; // methods to send X messages procedure SendXSimpleMessage(const ADestWindow: TWindow; AMessage: TAtom; AValue: Integer); procedure SendXMessage(const ADestWindow: TWindow; AMessage: PXEvent; AMask: LongWord); procedure SendXClientMessage(const ADestWindow: TWindow; AType: TAtom); // manage window properties procedure WindowChangeProperty(AWindow: TWindow; AProperty: TAtom; AType: TAtom; AFormat: cint; AMode: cint; const AData: Pointer; Elements: cint); procedure WindowDeleteProperty(AWindow: TWindow; AProperty: TAtom); function WindowSupportsProto(AWindow: TWindow; AProto: TAtom): Boolean; function WindowGetTitle(const AWindow: TWindow): String; function WindowGetUserTime(const AWindow: TWindow): LongWord; function WindowGetPID(const AWindow: TWindow): Integer; procedure WindowSetStandardEventMask(const AClientWindow: TWindow); virtual; function WindowGetParent(AWindow: TWindow): TWindow; // procedures to initialize the ICCCM and Extended WM hints procedure InitICCCMHints; virtual; procedure InitNETHints; virtual; procedure InitAtoms; virtual; property Display: PXDisplay read fDisplay write fDisplay; property _NET: TNetAtoms read fNetAtoms; property RootWindows: TWMRootWindowList read fRootWindowList; end; const WindowManagerEventMask = SubstructureRedirectMask or SubstructureNotifyMask or ColormapChangeMask or EnterWindowMask; implementation // Creates an exception function X11_Error(Display :PXDisplay; ErrEvent :PXErrorEvent):cint; cdecl; var ErrorStr: String; begin Result := 0; SetLength(ErrorStr, 1024); XGetErrorText(Display, ErrEvent^.error_code, @ErrorStr[1], 1024); WriteLn('<<<<>>>>>>>>>>> ', ErrorStr); //Raise Exception.Create(ErrorStr); end; { TXWindowManager } { Returns True for success } function TXWindowManager.GrabRootWindows: Boolean; var Attributes: TXSetWindowAttributes; I: Integer; AWindow: TWindow; ARootWindow: TWMRootWindow; xc: LongWord; begin Result := False; for I := 0 to XScreenCount(fDisplay)-1 do begin AWindow := RootWindow(fDisplay, I); FillChar(Attributes, SizeOf(TXSetWindowAttributes), 0); // Set the event mask for the root window Attributes.event_mask := WindowManagerEventMask; try XChangeWindowAttributes(fDisplay, AWindow, CWEventMask, @Attributes); Result := True; ARootWindow := TWMRootWindow.Create(Self, XScreenOfDisplay(fDisplay, I), AWindow); fRootWindowList.Add(ARootWindow); xc := XCreateFontCursor(Display, XC_left_ptr); XDefineCursor(Display, AWindow, XC); XFreeCursor(Display, xc); except Result := False; end; end; end; procedure TXWindowManager.CreateDisplay(ADisplayName: String); begin fDisplay := XOpenDisplay(PChar(ADisplayName)); end; constructor TXWindowManager.Create(const ADisplayName: String); begin fLastErrorHandler := XSetErrorHandler(@X11_Error); fRootWindowList := TWMRootWindowList.Create; CreateDisplay(ADisplayName); InitAtoms; end; destructor TXWindowManager.Destroy; begin fRootWindowList.Free; if Assigned(fDisplay) then XCloseDisplay(fDisplay); inherited Destroy; end; // finds our TXFrame from a TWindow function TXWindowManager.WindowToFrame(const AWindow: TWindow): TXFrame; var I: Integer; J: Integer; Frames: TXFrameList; begin //Writeln('Looking for TXFrame for window: ', AWindow); Result := nil; for I := 0 to RootWindows.Count-1 do begin if Assigned(Result) then Break; Frames := RootWindows.Windows[I].Frames; for J := 0 to Frames.Count-1 do begin if (Frames.Frame[J].ClientWindow = AWindow) or (Frames.Frame[J].FrameWindow = AWindow) then begin Result := Frames.Frame[J]; Break; end; end; end; //Writeln('Found TXFrame for : ', AWindow, ' = ', Assigned(Result)); end; procedure TXWindowManager.InitWM(QueryWindows: Boolean = True); var I: Integer; begin if not GrabRootWindows then exit; // Look for windows which need to be managed and add them to the list; if QueryWindows then begin for I := 0 to fRootWindowList.Count-1 do fRootWindowList.Windows[I].GrabExistingWindows; end; end; procedure TXWindowManager.MainLoop; begin fpgApplication.Run; end; function GetXEventName(Event: LongInt): String; const EventNames: array[2..34] of String = ( 'KeyPress', 'KeyRelease', 'ButtonPress', 'ButtonRelease', 'MotionNotify', 'EnterNotify', 'LeaveNotify', 'FocusIn', 'FocusOut', 'KeymapNotify', 'Expose', 'GraphicsExpose', 'NoExpose', 'VisibilityNotify', 'CreateNotify', 'DestroyNotify', 'UnmapNotify', 'MapNotify', 'MapRequest', 'ReparentNotify', 'ConfigureNotify', 'ConfigureRequest', 'GravityNotify', 'ResizeRequest', 'CirculateNotify', 'CirculateRequest', 'PropertyNotify', 'SelectionClear', 'SelectionRequest', 'SelectionNotify', 'ColormapNotify', 'ClientMessage', 'MappingNotify'); begin if (Event >= Low(EventNames)) and (Event <= High(EventNames)) then Result := EventNames[Event] else Result := '#' + IntToStr(Event); end; function TXWindowManager.XEventCB(const AEvent: TXEvent): Boolean; var Frame: TXFrame; RootWindow: TWMRootWindow; Ev: TXConfigureEvent; begin Result := False; //Return True to stop the event from being handled by the toolkit //WriteLn('BeginEvent: ', GetXEventName(AEvent.xany._type)); fCurrentEvent := @AEvent; Frame := WindowToFrame(AEvent.xany.window); if (Frame <> nil) and (Frame.ClientWindow = AEvent.xany.window) then WriteLn('BeginEvent: ', GetXEventName(AEvent.xany._type)); case AEvent._type of PropertyNotify: begin if Frame <> nil then Frame.PropertyChangeEv(AEvent.xproperty); end; ConfigureRequest: begin Frame := WindowToFrame(AEvent.xconfigurerequest.window); if Frame <> nil then Result := Frame.ConfigureWindowEv(@AEvent.xconfigurerequest); end; ConfigureNotify: begin {if Frame <> nil then if Frame.FrameWindow = AEvent.xconfigure.event then begin Ev := AEvent.xconfigure; Inc(Ev.width, 20); Inc(Ev.height, 40); XSendEvent(Display, Frame.FrameWindow, False, StructureNotifyMask, @Ev); Result := True; end; } end; MapRequest: begin Frame := WindowToFrame(AEvent.xmaprequest.window); if Frame <> nil then begin Frame.MapWindow; Result := True; end; end; MapNotify: begin Frame := WindowToFrame(AEvent.xmap.window); if Frame <> nil then begin Frame.MapWindow; Result := True; end; end; CreateNotify: begin Result := True; Frame := WindowToFrame(AEvent.xcreatewindow.window); RootWindow := RootWindows.RootWindowFromXWindow(AEvent.xcreatewindow.parent); if (Frame = nil) and (RootWindow <> nil) then Frame := RootWindow.AddNewClient(AEvent.xcreatewindow.window, AEvent.xcreatewindow.x, AEvent.xcreatewindow.y, AEvent.xcreatewindow.width, AEvent.xcreatewindow.height, AEvent.xcreatewindow.override_redirect); end; ClientMessage: begin if Frame <> nil then begin Result := Frame.HandleClientMessage(AEvent.xclient); end; REsult := True; end; UnmapNotify: begin Frame := WindowToFrame(AEvent.xunmap.window); if (Frame <> nil) and (Frame.ClientWindow = AEvent.xunmap.window) then begin // do nothing end; end; //MapNotify:; //UnmapNotify:; //CreateNotify:;// do we need to do anything here? DestroyNotify: begin wRITElN('Destroy Notify'); // only react to the destruction of client windows not of our frame windows Frame := WindowToFrame(AEvent.xdestroywindow.window); if (Frame <> nil) and (Frame.ClientWindow = AEvent.xdestroywindow.window) then begin DestroyWindowFrame(Frame); Result := True; end; end; Expose: begin if (Frame <> nil) and (Frame.FrameWindow = AEvent.xany.window) then begin Result := Frame.PaintWindowFrame; end; end; ButtonPress, ButtonRelease: begin {Frame := WindowToFrame(AEvent.xbutton.window); if Frame <> nil then Result := Frame.ClientWindow = AEvent.xbutton.window; if Frame.FrameWindow = Frame.ClientWindow then Result := True; // how is this possible?!} end; KeyPress, KeyRelease: begin WriteLn('Key Event'); Frame := WindowToFrame(AEvent.xkey.window); if Frame <> nil then begin WriteLn('Frame = ', Frame.FrameWindow); WriteLn('Client = ', Frame.ClientWindow); WriteLn('Event = ', AEvent.xkey.window); Result := Frame.ClientWindow = AEvent.xkey.window; if Frame.FrameWindow = Frame.ClientWindow then Result := True; // how is this possible?! WriteLn('Drop Event = ', Result); end; end else begin //if AEvent._type <> MotionNotify then // WriteLn('Got Unhandled Event: ', GetXEventName(AEvent.xany._type)); Result := False; end; end; //WriteLn('DoneEvent: ', GetXEventName(AEvent.xany._type)); fCurrentEvent := nil; if (Result = False) and Assigned(Frame) and(AEvent.xany.window <> Frame.FrameWindow) then Result := True; //result := False //XSync(Display, false); end; function TXWindowManager.GetCurrentEvent: PXEvent; begin Result := fCurrentEvent; end; procedure TXWindowManager.SendXSimpleMessage(const ADestWindow: TWindow; AMessage: TAtom; AValue: Integer); var ClientMsg: TXClientMessageEvent; begin FillChar(ClientMsg, sizeof(ClientMsg), #0); ClientMsg._type := ClientMessage; ClientMsg.window := ADestWindow; ClientMsg.message_type := AMessage; ClientMsg.format := 32; ClientMsg.data.l[0] := AValue; ClientMsg.data.l[1] := CurrentTime; SendXMessage(ADestWindow, @ClientMsg, 0); end; procedure TXWindowManager.SendXMessage(const ADestWindow: TWindow; AMessage: PXEvent; AMask: LongWord); begin XSendEvent(Display, ADestWindow, False, AMask, AMessage); end; procedure TXWindowManager.SendXClientMessage(const ADestWindow: TWindow; AType: TAtom); var Ev : TXClientMessageEvent; begin Ev._type := ClientMessage; Ev.window := ADestWindow; Ev.message_type := AType; //Ev.data :=; //SendXmessage, AWindow, True); //XSendEvent(para1:PDisplay; para2:TWindow; para3:TBool; para4:clong; para5:PXEvent):TStatus;cdecl;external libX11; end; // AFormat is the size of the type of elements in bits. so a cardinal is 32 char is 8 etc // Elements is how many items there are // AMode is PropModeAppend, PropModePrepend, or PropModeReplace procedure TXWindowManager.WindowChangeProperty(AWindow: TWindow; AProperty: TAtom; AType: TAtom; AFormat: cint; AMode: cint; const AData: Pointer; Elements: cint); begin XChangeProperty(Display, AWindow, AProperty, AType, AFormat, AMode, AData, Elements); end; procedure TXWindowManager.WindowDeleteProperty(AWindow: TWindow; AProperty: TAtom); begin XDeleteProperty(Display, AWindow, AProperty); end; function TXWindowManager.WindowSupportsProto(AWindow: TWindow; AProto: TAtom): Boolean; var Protocols: PAtom; I, ProtoCount: Integer; begin Result := False; if (XGetWMProtocols(display, AWindow, @Protocols, @ProtoCount) <> 0) then begin for I := 0 to ProtoCount-1 do begin if (Protocols[i] = AProto) then begin Result := True; Break; end; end; if (Protocols <> nil) then XFree(Protocols); end; end; function TXWindowManager.WindowGetTitle(const AWindow: TWindow): String; var TypeAtom: TAtom; FormatAtom: TAtom; NumItems, BytesAfter: LongWord; ATitle: PChar; begin Result := ''; repeat BytesAfter := 0; if (XGetWindowProperty(Display, AWindow, _NET[_WM_NAME], 0, MaxINt, False, UTF8_STRING, @TypeAtom, @FormatAtom, @NumItems, @BytesAfter, @ATitle)=Success) or (XGetWindowProperty(Display, AWindow, XA_WM_NAME, 0, 24, False, XA_STRING, @TypeAtom, @FormatAtom, @NumItems, @BytesAfter, @ATitle)=Success) or (XGetWindowProperty(Display, AWindow, XA_WM_ICON_NAME, 0, 24, False, XA_STRING, @TypeAtom, @FormatAtom, @NumItems, @BytesAfter, @ATitle)=Success) then begin Result := Result + ATitle; XFree(ATitle); end; until BytesAfter = 0; if Result = '' then Result := 'Untitled'; end; function TXWindowManager.WindowGetUserTime(const AWindow: TWindow): LongWord; var TypeAtom: TAtom; FormatAtom: TAtom; NumItems, BytesAfter: LongWord; begin // Return 0 if property is unset Result := 0; if XGetWindowProperty(Display, AWindow, _NET[_WM_USER_TIME], 0, 1, False, XA_CARDINAL, @TypeAtom, @FormatAtom, @NumItems, @BytesAfter, @Result)<>Success then Result := 0; end; function TXWindowManager.WindowGetPID(const AWindow: TWindow): Integer; var TypeAtom: TAtom; FormatAtom: TAtom; NumItems, BytesAfter: LongWord; begin // Return -1 if no PID available Result := -1; if XGetWindowProperty(Display, AWindow, _NET[_WM_PID], 0, MaxInt, False, XA_CARDINAL, @TypeAtom, @FormatAtom, @NumItems, @BytesAfter, @Result)<>Success then Result := -1; end; procedure TXWindowManager.WindowSetStandardEventMask( const AClientWindow: TWindow); var GetAttr: TXWindowAttributes; SetAttr: TXSetWindowAttributes; begin if XGetWindowAttributes(Display, AClientWindow,@GetAttr) = 0 then ; SetAttr.event_mask := PropertyChangeMask ;//else // SetAttr.event_mask := GetAttr.all_event_masks or PropertyChangeMask; XChangeWindowAttributes(Display, AClientWindow, CWEventMask, @SetAttr); //XSync(Display, False); end; function TXWindowManager.WindowGetParent ( AWindow: TWindow ) : TWindow; var I: Integer; WindowCount: cuint; WindowsRoot, WindowsParent: TWindow; ChildrenList: PWindow; begin if XQueryTree(Display,AWindow, @WindowsRoot, @WindowsParent, @ChildrenList, @WindowCount) <> 0 then XFree(ChildrenList); Result := WindowsParent; end; procedure TXWindowManager.InitICCCMHints; begin // currently all ICCCM atoms are defined in XAtom; end; procedure TXWindowManager.InitNETHints; begin Init_NETAtoms(fDisplay, fNetAtoms); end; procedure TXWindowManager.InitAtoms; begin InitICCCMHints; InitNETHints; WM_DELETE_WINDOW := XInternAtom(Display, 'WM_DELETE_WINDOW', False); WM_PROTOCOLS := XInternAtom(Display, 'WM_PROTOCOLS', False); UTF8_STRING := XInternAtom(Display, 'UTF8_STRING', False);; end; end.
{******************************************} { TTowerSeries Editor Dialog } { Copyright (c) 2002-2004 by David Berneda } {******************************************} unit TeeTowerEdit; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, {$ENDIF} Chart, TeeSurfa, TeCanvas, TeePenDlg, TeeProcs; type TTowerSeriesEditor = class(TForm) ButtonPen1: TButtonPen; Button1: TButton; CBDark3D: TCheckBox; GroupBox1: TGroupBox; CBOrigin: TCheckBox; EOrigin: TEdit; Label1: TLabel; CBStyle: TComboFlat; GroupBox2: TGroupBox; Label2: TLabel; Edit1: TEdit; UDDepth: TUpDown; Label3: TLabel; Edit2: TEdit; UDWidth: TUpDown; Label4: TLabel; Edit3: TEdit; UDTransp: TUpDown; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure CBDark3DClick(Sender: TObject); procedure CBOriginClick(Sender: TObject); procedure EOriginChange(Sender: TObject); procedure CBStyleChange(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure Edit2Change(Sender: TObject); procedure Edit3Change(Sender: TObject); private { Private declarations } Tower : TTowerSeries; Grid3DForm : TCustomForm; public { Public declarations } end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses TeeBrushDlg, TeeGriEd; procedure TTowerSeriesEditor.FormShow(Sender: TObject); begin Tower:=TTowerSeries(Tag); if Assigned(Tower) then begin With Tower do begin ButtonPen1.LinkPen(Pen); CBDark3D.Checked:=Dark3D; CBOrigin.Checked:=UseOrigin; EOrigin.Text:=FloatToStr(Origin); CBStyle.ItemIndex:=Ord(TowerStyle); UDDepth.Position:=PercentDepth; UDWidth.Position:=PercentWidth; UDTransp.Position:=Transparency; end; if not Assigned(Grid3DForm) then Grid3DForm:=TeeInsertGrid3DForm(Parent,Tower); end; end; procedure TTowerSeriesEditor.FormCreate(Sender: TObject); begin BorderStyle:=TeeBorderStyle; end; procedure TTowerSeriesEditor.Button1Click(Sender: TObject); begin EditChartBrush(Self,Tower.Brush); end; procedure TTowerSeriesEditor.CBDark3DClick(Sender: TObject); begin Tower.Dark3D:=CBDark3D.Checked; end; procedure TTowerSeriesEditor.CBOriginClick(Sender: TObject); begin Tower.UseOrigin:=CBOrigin.Checked; end; procedure TTowerSeriesEditor.EOriginChange(Sender: TObject); begin Tower.Origin:=StrToFloatDef(EOrigin.Text,Tower.Origin) end; procedure TTowerSeriesEditor.CBStyleChange(Sender: TObject); begin Tower.TowerStyle:=TTowerStyle(CBStyle.ItemIndex); end; procedure TTowerSeriesEditor.Edit1Change(Sender: TObject); begin if Showing then Tower.PercentDepth:=UDDepth.Position; end; procedure TTowerSeriesEditor.Edit2Change(Sender: TObject); begin if Showing then Tower.PercentWidth:=UDWidth.Position; end; procedure TTowerSeriesEditor.Edit3Change(Sender: TObject); begin if Showing then Tower.Transparency:=UDTransp.Position; end; initialization RegisterClass(TTowerSeriesEditor); end.
unit SinglePage; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.WebBrowser; type TLoadThread = class(TThread) private FChapter: string; FBrowser: TWebBrowser; FHtmlFile: TFileName; procedure SetHtmlFile; procedure ParseImageList(AHtmlDoc: string); procedure LoadBrowser; protected procedure Execute; override; public constructor Create(ABrowser: TWebBrowser; AChapter: string); end; TFrmSingle = class(TForm) ToolBar1: TToolBar; LblJudul: TLabel; Browser: TWebBrowser; BtnBack: TButton; procedure BtnBackClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); private FChapter: string; FTitle: string; procedure Refresh; public constructor Create(AOwner: TComponent; AChapter: string; ATitle: string); reintroduce; end; implementation {$R *.fmx} {$R *.LgXhdpiPh.fmx ANDROID} {$R *.NmXhdpiPh.fmx ANDROID} {$R *.LgXhdpiTb.fmx ANDROID} {$R *.XLgXhdpiTb.fmx ANDROID} uses Commons, System.Net.HttpClient, HtmlParser, System.IOUtils; const sSource = 'http://www.mangacanblog.com/baca-komik-one_piece-' + '%s-%d-bahasa-indonesia-one_piece-%s-terbaru.html'; sIndex = '<!DOCTYPE html><html lang="id"><head><meta charset="UTF-8">' + '<meta name="viewport" content="width=device-width, initial-scale=1">' + '<style>#responsive-image{width:100%%;height:auto;margin:auto}</style>' + '</head><body>%s</body></html>'; sImage = '<img src="%s" id="responsive-image">'; constructor TFrmSingle.Create(AOwner: TComponent; AChapter, ATitle: string); begin inherited Create(AOwner); FChapter := AChapter; FTitle := ATitle; LblJudul.Text := Format('%s : %s', [FChapter, FTitle]); end; procedure TFrmSingle.FormShow(Sender: TObject); begin Refresh; end; procedure TFrmSingle.BtnBackClick(Sender: TObject); begin Close; end; procedure TFrmSingle.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := TCloseAction.caFree; end; procedure TFrmSingle.Refresh; var FLoadThread : TLoadThread; begin FLoadThread := TLoadThread.Create(Browser, FChapter); FLoadThread.Start; end; { TLoadThread } constructor TLoadThread.Create(ABrowser: TWebBrowser; AChapter: string); begin inherited Create(True); FreeOnTerminate := True; FBrowser := ABrowser; FChapter := AChapter; FHtmlFile := TPath.Combine(CachePath, Format('%s.html', [AChapter])); end; procedure TLoadThread.SetHtmlFile; var LClient : THTTPClient; LResponse : IHTTPResponse; LUrl: string; begin if TFile.Exists(FHtmlFile) then begin Exit; end; LClient := THTTPClient.Create; try LUrl := Format(sSource, [FChapter, StrToInt(FChapter) + 1, FChapter]); LResponse := LClient.Get(LUrl); ParseImageList(LResponse.ContentAsString); finally LClient.Free; end; end; procedure TLoadThread.ParseImageList(AHtmlDoc: string); var I: Integer; LNodes: IHtmlElement; LlistNodes: IHtmlElementList; LElement: IHtmlElement; LUrlGambar: WideString; LImageSrc: string; LIndex: string; begin LNodes := ParserHTML(AHtmlDoc); LlistNodes := LNodes.SimpleCSSSelector('div[id="manga"] img'); if (LListNodes.Count = 0) then exit; for I := 0 to LlistNodes.Count - 1 do begin LElement := LlistNodes.Items[I]; LUrlGambar := LElement.Attributes['src']; LImageSrc := LImageSrc + Format(sImage, [LUrlGambar]); end; LIndex := Format(sIndex, [LImageSrc]); TFile.WriteAllText(FHtmlFile, LIndex); end; procedure TLoadThread.LoadBrowser; begin if (TFile.Exists(FHtmlFile)) then FBrowser.Navigate('file://' + FHtmlFile); end; procedure TLoadThread.Execute; begin SetHtmlFile; Synchronize(LoadBrowser); end; end.
unit Firebird.Parser.Tests; interface uses System.Generics.Collections, DUnitX.TestFramework, Nathan.Firebird.Validator.Syntax.Keywords.Intf; {$M+} type [TestFixture] TTestFirebird25Parser = class private FCut: IFb25Parser; function CreateStubDomainTokens(): TList<IFb25Token>; function CreateStubInsertIntoTokens(HowMany: Integer; CorrectArgumentList: Boolean): TList<IFb25Token>; function CreateStubInsertIntoTokens2(): TList<IFb25Token>; public [Setup] procedure SetUp(); [TearDown] procedure TearDown(); published [Test] procedure Test_FirstTestWithVisitorPattern(); [Test] procedure Test_CreateDomain_IsCorrect(); [Test] [TestCase('IsCorrect', 'True')] [TestCase('IsIncorrect', 'False')] procedure Test_InsertInto(Value: Boolean); [Test] procedure Test_HasTerminatatorCharacters(); [Test] procedure Test_SimpleTestWithAllVisitors(); [Test] procedure Test_HowToMockAFb25Parser(); end; {$M-} implementation uses System.Rtti, Delphi.Mocks, Nathan.Firebird.Validator.Syntax.Keywords.Parser, Nathan.Firebird.Validator.Syntax.Keywords.Token, Nathan.Firebird.Validator.Syntax.Keywords.Scanner, Nathan.Firebird.Validator.Syntax.Keywords.Types; { TTestFirebird25Scanner } procedure TTestFirebird25Parser.SetUp; begin FCut := TFb25Parser.Create; end; procedure TTestFirebird25Parser.TearDown; begin if (Assigned(FCut) and Assigned(FCut.Tokens)) then FCut.Tokens.Free(); FCut := nil; end; function TTestFirebird25Parser.CreateStubDomainTokens(): TList<IFb25Token>; begin Result := TList<IFb25Token>.Create; Result.Add(TFb25Token.Create('CREATE', fb25Starter)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('DOMAIN', fb25Operator)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('TFLOAT', fb25Variable)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('AS', fb25None)); Result.Add(TFb25Token.Create(' ', fb25Operator)); Result.Add(TFb25Token.Create('DECIMAL', fb25Operator)); Result.Add(TFb25Token.Create('(', fb25BracketOpen)); Result.Add(TFb25Token.Create('15,3', fb25Arguments)); Result.Add(TFb25Token.Create(')', fb25BracketClose)); Result.Add(TFb25Token.Create(';', fb25TerminatorCharacter)); end; function TTestFirebird25Parser.CreateStubInsertIntoTokens(HowMany: Integer; CorrectArgumentList: Boolean): TList<IFb25Token>; var Idx: Integer; begin Result := TList<IFb25Token>.Create; for Idx := 0 to HowMany do begin Result.Add(TFb25Token.Create('INSERT', fb25Operator)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('INTO', fb25Operator)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('DOKGRP', fb25Variable)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('(', fb25BracketOpen)); Result.Add(TFb25Token.Create('DOG_FNR, DOG_FBEZEICH', fb25Arguments)); Result.Add(TFb25Token.Create(')', fb25BracketClose)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('VALUES', fb25Operator)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('(', fb25BracketOpen)); if CorrectArgumentList then Result.Add(TFb25Token.Create('1, ''Werkstatt''', fb25Arguments)) else Result.Add(TFb25Token.Create('1, ''Werkstatt'', ''Werbung''', fb25Arguments)); Result.Add(TFb25Token.Create(')', fb25BracketClose)); Result.Add(TFb25Token.Create(';', fb25TerminatorCharacter)); end; end; function TTestFirebird25Parser.CreateStubInsertIntoTokens2(): TList<IFb25Token>; begin Result := TList<IFb25Token>.Create; Result.Add(TFb25Token.Create('INSERT', fb25Operator)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('INTO', fb25Operator)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('DOKGRP', fb25Variable)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('(', fb25BracketOpen)); Result.Add(TFb25Token.Create('DOG_FNR, DOG_FBEZEICH', fb25Arguments)); Result.Add(TFb25Token.Create(')', fb25BracketClose)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('VALUES', fb25Operator)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('(', fb25BracketOpen)); Result.Add(TFb25Token.Create('1, ''Werkstatt''', fb25Arguments)); Result.Add(TFb25Token.Create(')', fb25BracketClose)); Result.Add(TFb25Token.Create(';', fb25TerminatorCharacter)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('INSERT', fb25Operator)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('INTO', fb25Operator)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('DOKGRP', fb25Variable)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('(', fb25BracketOpen)); Result.Add(TFb25Token.Create('DOG_FNR, DOG_FBEZEICH', fb25Arguments)); Result.Add(TFb25Token.Create(')', fb25BracketClose)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('VALUES', fb25Operator)); Result.Add(TFb25Token.Create(' ', fb25Whitespaces)); Result.Add(TFb25Token.Create('(', fb25BracketOpen)); Result.Add(TFb25Token.Create('2, ''Werkstatt'', ''Werbung''', fb25Arguments)); Result.Add(TFb25Token.Create(')', fb25BracketClose)); Result.Add(TFb25Token.Create(';', fb25TerminatorCharacter)); end; procedure TTestFirebird25Parser.Test_FirstTestWithVisitorPattern(); var ActualOnEventCounter: Integer; begin // Arrange, ActualOnEventCounter := 0; FCut.Tokens := CreateStubInsertIntoTokens2(); FCut.OnNotify := procedure(Item: IFb25Token) begin Inc(ActualOnEventCounter); Assert.AreEqual('2, ''Werkstatt'', ''Werbung''', Item.Value); Assert.AreEqual(fb25Arguments, Item.Token); end; // Act FCut.Accept(TFb25VisitorArguments.Create); // Assert Assert.AreEqual(1, ActualOnEventCounter); end; procedure TTestFirebird25Parser.Test_CreateDomain_IsCorrect(); var ActualOnEventCounter: Integer; begin // Arrange, ActualOnEventCounter := 0; FCut.Tokens := CreateStubDomainTokens(); FCut.OnNotify := procedure(Item: IFb25Token) begin Inc(ActualOnEventCounter); end; // Act FCut.Accept(TFb25VisitorArguments.Create); // Assert Assert.AreEqual(0, ActualOnEventCounter); end; procedure TTestFirebird25Parser.Test_InsertInto(Value: Boolean); var ActualOnEventCounter: Integer; begin // Arrange, ActualOnEventCounter := 0; FCut.Tokens := CreateStubInsertIntoTokens(2, Value); FCut.OnNotify := procedure(Item: IFb25Token) begin Inc(ActualOnEventCounter); end; // Act FCut.Accept(TFb25VisitorArguments.Create); // Assert if Value then Assert.AreEqual(0, ActualOnEventCounter) // Don't find any error... else Assert.AreNotEqual(0, ActualOnEventCounter) // Find any error... end; procedure TTestFirebird25Parser.Test_HasTerminatatorCharacters(); var ActualOnEventCounter: Integer; begin // Arrange, ActualOnEventCounter := 0; FCut.Tokens := CreateStubInsertIntoTokens2(); FCut.OnNotify := procedure(Item: IFb25Token) begin Inc(ActualOnEventCounter); end; // Act FCut.Accept(TFb25TerminatorCharacters.Create); // Assert Assert.AreEqual(2, ActualOnEventCounter); end; procedure TTestFirebird25Parser.Test_SimpleTestWithAllVisitors; var ActualOnEventCounter: Integer; begin // Arrange, ActualOnEventCounter := 0; FCut.Tokens := CreateStubInsertIntoTokens2(); FCut.OnNotify := procedure(Item: IFb25Token) begin Inc(ActualOnEventCounter); end; // Act FCut.Accept(TFb25VisitorArguments.Create); FCut.Accept(TFb25TerminatorCharacters.Create); // Assert // 1 x Argumentserror, 2 x Terminator Characters... Assert.AreEqual(3, ActualOnEventCounter); end; procedure TTestFirebird25Parser.Test_HowToMockAFb25Parser(); var Cut: TMock<IFb25Parser>; Vis: IVisitor; Event: TFb25ParserNotifyEvent; ActualOnEventCounter: Integer; begin Event := procedure(Token: IFb25Token) begin Inc(ActualOnEventCounter); end; ActualOnEventCounter := 0; Cut := TMock<IFb25Parser>.Create; Cut.Setup.WillReturn(CreateStubInsertIntoTokens2()).When.Tokens; Cut.Setup.WillReturn((TValue.From<TFb25ParserNotifyEvent>(Event))).When.OnNotify; // Cut.Instance.OnNotify := Event; Vis := TFb25TerminatorCharacters.Create; Vis.Visit(Cut); Assert.AreEqual(2, ActualOnEventCounter); end; initialization TDUnitX.RegisterTestFixture(TTestFirebird25Parser, 'Parser'); end.
unit oWVPatient; { ================================================================================ * * Application: TDrugs Patch OR*3*377 and WV*1*24 * Developer: doma.user@domain.ext * Site: Salt Lake City ISC * * Description: Object that is created via the WVController to maintain * valid WH data during the update process in * frmWHPregLacStatusUpdate. Only accessible as * IWVPatient interface. * * Notes: * ================================================================================ } interface uses System.Classes, System.SysUtils, iWVInterface; type TWVPatient = class(TInterfacedObject, IWVPatient) private fAbleToConceive: TWVAbleToConceive; fAskForLactationData: boolean; fAskForPregnancyData: boolean; fDFN: string; fHysterectomy: boolean; fLactationStatus: TWVLactationStatus; fLastMenstrualPeriod: TDateTime; fMenopause: boolean; fPregnancyStatus: TWVPregnancyStatus; public constructor Create(aDFN: string); destructor Destroy; override; function getAbleToConceive: TWVAbleToConceive; function getAbleToConceiveAsStr: string; function getAskForLactationData: boolean; function getAskForPregnancyData: boolean; function getDFN: string; function getHysterectomy: boolean; function getLactationStatus: TWVLactationStatus; function getLactationStatusAsStr: string; function getLastMenstrualPeriod: TDateTime; function getLastMenstrualPeriodAsStr: string; function getMenopause: boolean; function getPregnancyStatus: TWVPregnancyStatus; function getPregnancyStatusAsStr: string; function getUnableToConceiveReason: string; procedure setAbleToConceive(const aValue: TWVAbleToConceive); procedure setAskForLactationData(const aValue: boolean); procedure setAskForPregnancyData(const aValue: boolean); procedure setDFN(const aValue: string); procedure setHysterectomy(const aValue: boolean); procedure setLactationStatus(const aValue: TWVLactationStatus); procedure setLastMenstrualPeriod(const aValue: TDateTime); procedure setMenopause(const aValue: boolean); procedure setPregnancyStatus(const aValue: TWVPregnancyStatus); end; implementation { TWVPatient } constructor TWVPatient.Create(aDFN: string); begin inherited Create; fDFN := aDFN; fAbleToConceive := atcUnknown; fPregnancyStatus := psUnknown; fLactationStatus := lsUnknown; fHysterectomy := False; fMenopause := False; fLastMenstrualPeriod := 0; end; destructor TWVPatient.Destroy; begin inherited; end; function TWVPatient.getAbleToConceive: TWVAbleToConceive; begin Result := fAbleToConceive; end; function TWVPatient.getAbleToConceiveAsStr: string; begin Result := WV_ABLE_TO_CONCEIVE[fAbleToConceive]; end; function TWVPatient.getAskForLactationData: boolean; begin Result := fAskForLactationData; end; function TWVPatient.getAskForPregnancyData: boolean; begin Result := fAskForPregnancyData; end; function TWVPatient.getDFN: string; begin Result := fDFN; end; function TWVPatient.getHysterectomy: boolean; begin Result := fHysterectomy; end; function TWVPatient.getLactationStatus: TWVLactationStatus; begin Result := fLactationStatus; end; function TWVPatient.getLactationStatusAsStr: string; begin Result := WV_LACTATION_STATUS[fLactationStatus]; end; function TWVPatient.getLastMenstrualPeriod: TDateTime; begin Result := fLastMenstrualPeriod; end; function TWVPatient.getLastMenstrualPeriodAsStr: string; var y, m, d: Word; begin if fLastMenstrualPeriod > 0 then begin DecodeDate(fLastMenstrualPeriod, y, m, d); Result := Format('%3d%.2d%.2d', [y - 1700, m, d]); end else Result := ''; end; function TWVPatient.getMenopause: boolean; begin Result := fMenopause; end; function TWVPatient.getPregnancyStatus: TWVPregnancyStatus; begin Result := fPregnancyStatus; end; function TWVPatient.getPregnancyStatusAsStr: string; begin Result := WV_PREGNANCY_STATUS[fPregnancyStatus]; end; function TWVPatient.getUnableToConceiveReason: string; begin if fHysterectomy and fMenopause then Result := 'Hysterectomy and Menopause' else if fHysterectomy then Result := 'Hysterectomy' else if fMenopause then Result := 'Menopause' else Result := ''; end; procedure TWVPatient.setAbleToConceive(const aValue: TWVAbleToConceive); begin fAbleToConceive := aValue; end; procedure TWVPatient.setAskForLactationData(const aValue: boolean); begin fAskForLactationData := aValue; end; procedure TWVPatient.setAskForPregnancyData(const aValue: boolean); begin fAskForPregnancyData := aValue; end; procedure TWVPatient.setDFN(const aValue: string); begin fDFN := aValue; end; procedure TWVPatient.setHysterectomy(const aValue: boolean); begin fHysterectomy := aValue; end; procedure TWVPatient.setLactationStatus(const aValue: TWVLactationStatus); begin fLactationStatus := aValue; end; procedure TWVPatient.setLastMenstrualPeriod(const aValue: TDateTime); begin fLastMenstrualPeriod := aValue; end; procedure TWVPatient.setMenopause(const aValue: boolean); begin fMenopause := aValue; end; procedure TWVPatient.setPregnancyStatus(const aValue: TWVPregnancyStatus); begin fPregnancyStatus := aValue; end; end.
unit RadioGroup; interface uses Windows, Classes, Graphics, Canvases, Generics.Collections, RootObject; type TRadioGroup = class private class var Dot: TBitmap; private const // отступы от краёв ClientRect окна HorizMargin = 7; VertMargin = 5; // отступы для точки первого элемента DotLeftMargin = 17; DotTopMargin = 26; // шаг элементов ItemsStep = 23; RadioButtonDot = 'RADIODOT'; // идентификатор ресурса битмапа скина: // точка выбранного элемента private LastPos: TPoint; // позиция при последней отрисовске Location: TPoint; BaseImage: TBitmap; ItemIndex: integer; // индекс текущего выбранного элемента Items: TList<TRootClass>; // итемы - классы потомки TRootObject function ItemAtPos(const Point: TPoint): integer; public const // идентификаторы ресурса битмапов скинов радио-групп CanvasRadioGroup = 'CANVASRG'; WalkerRadioGroup = 'WALKERRG'; public constructor Create(AGroupName: string; RightAnchor: boolean; const AItems: array of TRootClass); destructor Destroy; override; procedure Draw(Canvas: IMyCanvas; const ClientRect: TRect); function GetCurrentItem: TRootClass; function SwitchedByClick(const Point: TPoint): boolean; end; implementation { TRadioGroup } constructor TRadioGroup.Create(AGroupName: string; RightAnchor: boolean; const AItems: array of TRootClass); var c: TRootClass; begin Items := TList<TRootClass>.Create; for c in AItems do Items.Add(c); BaseImage := TBitmap.Create; BaseImage.LoadFromResourceName(HInstance, AGroupName); Location.Y := VertMargin; if not RightAnchor then Location.X := HorizMargin else Location.X := -HorizMargin - BaseImage.Width; end; destructor TRadioGroup.Destroy; begin Items.Free; BaseImage.Free; inherited; end; procedure TRadioGroup.Draw(Canvas: IMyCanvas; const ClientRect: TRect); var x, y: integer; begin if Location.X < 0 then x := ClientRect.Right + Location.X else x := Location.X; y := Location.Y; LastPos := Point(x, y); Canvas.DrawBitmap(BaseImage, x, y); Inc(x, DotLeftMargin); Inc(y, DotTopMargin + ItemIndex * ItemsStep); Canvas.DrawBitmap(Dot, x, y); end; function TRadioGroup.GetCurrentItem: TRootClass; begin Result := Items[ItemIndex]; end; function TRadioGroup.SwitchedByClick(const Point: TPoint): boolean; // обработка клика, возвращает True только если изменён выбранный элемент var item_idx: integer; begin if not PtInRect(Rect(LastPos.X, LastPos.Y, LastPos.X + BaseImage.Width, LastPos.Y + BaseImage.Height), Point) then Exit(False); item_idx := ItemAtPos(Point); Result := (item_idx <> -1) and (item_idx <> ItemIndex); if Result then ItemIndex := item_idx; end; function TRadioGroup.ItemAtPos(const Point: TPoint): integer; // возвращает номер элемента по координате клика, либо -1 const ClickMarginX = DotLeftMargin - 2;// ширина некликабельных полей слева и справа ItemYBgn = -4; // смещение начала кликабельной зоны от верхней грани точки ItemHeight = 16; // высота кликабельной зоны элемента var x, y, i: integer; y_from, y_to: integer; begin Result := -1; x := Point.X - LastPos.X; if (x < ClickMarginX) or (x > BaseImage.Width - ClickMarginX) then Exit; y := Point.Y - LastPos.Y; for i := 0 to Items.Count - 1 do begin y_from := DotTopMargin + i * ItemsStep + ItemYBgn; y_to := y_from + ItemHeight; if (y_from <= y) and (y < y_to) then begin Result := i; break; end; end; end; initialization TRadioGroup.Dot := TBitmap.Create; TRadioGroup.Dot.LoadFromResourceName(HInstance, TRadioGroup.RadioButtonDot); finalization TRadioGroup.Dot.Free; 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 Original Code is: SynExportHTML.pas, released 2000-04-16. The Original Code is partly based on the mwHTMLExport.pas file from the mwEdit component suite by Martin Waldenburg and other developers, the Initial Author of this file is Michael Hieke. Portions created by Michael Hieke are Copyright 2000 Michael Hieke. Portions created by James D. Jacobson are Copyright 1999 Martin Waldenburg. Changes to emit XHTML 1.0 Strict complying code by Maël Hörz. All Rights Reserved. Contributors to the SynEdit project are listed in the Contributors.txt file. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL"), in which case the provisions of the GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. $Id: SynExportHTML.pas,v 1.19 2004/07/29 19:33:58 maelh Exp $ You may retrieve the latest version of this file at the SynEdit home page, located at http://SynEdit.SourceForge.net Known Issues: -------------------------------------------------------------------------------} {$IFNDEF QSYNEXPORTHTML} unit SynExportHTML; {$ENDIF} {$I SynEdit.inc} interface uses {$IFDEF SYN_CLX} Qt, QGraphics, QSynEditExport, QSynEditHighlighter, {$ELSE} Windows, Graphics, SynEditExport, SynEditHighlighter, {$ENDIF} Classes; type TSynExporterHTML = class(TSynCustomExporter) private fLastAttri: TSynHighlighterAttributes; function AttriToCSS(Attri: TSynHighlighterAttributes; UniqueAttriName: string): string; function AttriToCSSCallback(Highlighter: TSynCustomHighlighter; Attri: TSynHighlighterAttributes; UniqueAttriName: string; Params: array of Pointer): Boolean; function ColorToHTML(AColor: TColor): string; function GetStyleName(Highlighter: TSynCustomHighlighter; Attri: TSynHighlighterAttributes): string; function MakeValidName(Name: string): string; function StyleNameCallback(Highlighter: TSynCustomHighlighter; Attri: TSynHighlighterAttributes; UniqueAttriName: string; Params: array of Pointer): Boolean; protected fCreateHTMLFragment: boolean; procedure FormatAfterLastAttribute; override; procedure FormatAttributeDone(BackgroundChanged, ForegroundChanged: boolean; FontStylesChanged: TFontStyles); override; procedure FormatAttributeInit(BackgroundChanged, ForegroundChanged: boolean; FontStylesChanged: TFontStyles); override; procedure FormatBeforeFirstAttribute(BackgroundChanged, ForegroundChanged: boolean; FontStylesChanged: TFontStyles); override; procedure FormatNewLine; override; function GetFooter: string; override; function GetFormatName: string; override; function GetHeader: string; override; procedure SetTokenAttribute(Attri: TSynHighlighterAttributes); override; public constructor Create(AOwner: TComponent); override; published property Color; property CreateHTMLFragment: boolean read fCreateHTMLFragment write fCreateHTMLFragment default FALSE; property DefaultFilter; property Font; property Highlighter; property Title; property UseBackground; end; implementation uses {$IFDEF SYN_CLX} QSynEditMiscProcs, QSynEditStrConst, QSynHighlighterMulti, {$ELSE} SynEditMiscProcs, SynEditStrConst, SynHighlighterMulti, {$ENDIF} SysUtils; { TSynExporterHTML } constructor TSynExporterHTML.Create(AOwner: TComponent); const CF_HTML = 'HTML Format'; begin inherited Create(AOwner); {**************} {$IFNDEF SYN_CLX} fClipboardFormat := RegisterClipboardFormat(CF_HTML); {$ENDIF} fDefaultFilter := SYNS_FilterHTML; // setup array of chars to be replaced fReplaceReserved['&'] := '&amp;'; fReplaceReserved['<'] := '&lt;'; fReplaceReserved['>'] := '&gt;'; fReplaceReserved['"'] := '&quot;'; fReplaceReserved['™'] := '&trade;'; fReplaceReserved['©'] := '&copy;'; fReplaceReserved['®'] := '&reg;'; fReplaceReserved['À'] := '&Agrave;'; fReplaceReserved['Á'] := '&Aacute;'; fReplaceReserved['Â'] := '&Acirc;'; fReplaceReserved['Ã'] := '&Atilde;'; fReplaceReserved['Ä'] := '&Auml;'; fReplaceReserved['Å'] := '&Aring;'; fReplaceReserved['Æ'] := '&AElig;'; fReplaceReserved['Ç'] := '&Ccedil;'; fReplaceReserved['È'] := '&Egrave;'; fReplaceReserved['É'] := '&Eacute;'; fReplaceReserved['Ê'] := '&Ecirc;'; fReplaceReserved['Ë'] := '&Euml;'; fReplaceReserved['Ì'] := '&Igrave;'; fReplaceReserved['Í'] := '&Iacute;'; fReplaceReserved['Î'] := '&Icirc;'; fReplaceReserved['Ï'] := '&Iuml;'; fReplaceReserved['Ð'] := '&ETH;'; fReplaceReserved['Ñ'] := '&Ntilde;'; fReplaceReserved['Ò'] := '&Ograve;'; fReplaceReserved['Ó'] := '&Oacute;'; fReplaceReserved['Ô'] := '&Ocirc;'; fReplaceReserved['Õ'] := '&Otilde;'; fReplaceReserved['Ö'] := '&Ouml;'; fReplaceReserved['Ø'] := '&Oslash;'; fReplaceReserved['Ù'] := '&Ugrave;'; fReplaceReserved['Ú'] := '&Uacute;'; fReplaceReserved['Û'] := '&Ucirc;'; fReplaceReserved['Ü'] := '&Uuml;'; fReplaceReserved['Ý'] := '&Yacute;'; fReplaceReserved['Þ'] := '&THORN;'; fReplaceReserved['ß'] := '&szlig;'; fReplaceReserved['à'] := '&agrave;'; fReplaceReserved['á'] := '&aacute;'; fReplaceReserved['â'] := '&acirc;'; fReplaceReserved['ã'] := '&atilde;'; fReplaceReserved['ä'] := '&auml;'; fReplaceReserved['å'] := '&aring;'; fReplaceReserved['æ'] := '&aelig;'; fReplaceReserved['ç'] := '&ccedil;'; fReplaceReserved['è'] := '&egrave;'; fReplaceReserved['é'] := '&eacute;'; fReplaceReserved['ê'] := '&ecirc;'; fReplaceReserved['ë'] := '&euml;'; fReplaceReserved['ì'] := '&igrave;'; fReplaceReserved['í'] := '&iacute;'; fReplaceReserved['î'] := '&icirc;'; fReplaceReserved['ï'] := '&iuml;'; fReplaceReserved['ð'] := '&eth;'; fReplaceReserved['ñ'] := '&ntilde;'; fReplaceReserved['ò'] := '&ograve;'; fReplaceReserved['ó'] := '&oacute;'; fReplaceReserved['ô'] := '&ocirc;'; fReplaceReserved['õ'] := '&otilde;'; fReplaceReserved['ö'] := '&ouml;'; fReplaceReserved['ø'] := '&oslash;'; fReplaceReserved['ù'] := '&ugrave;'; fReplaceReserved['ú'] := '&uacute;'; fReplaceReserved['û'] := '&ucirc;'; fReplaceReserved['ü'] := '&uuml;'; fReplaceReserved['ý'] := '&yacute;'; fReplaceReserved['þ'] := '&thorn;'; fReplaceReserved['ÿ'] := '&yuml;'; fReplaceReserved['¡'] := '&iexcl;'; fReplaceReserved['¢'] := '&cent;'; fReplaceReserved['£'] := '&pound;'; fReplaceReserved['¤'] := '&curren;'; fReplaceReserved['¥'] := '&yen;'; fReplaceReserved['¦'] := '&brvbar;'; fReplaceReserved['§'] := '&sect;'; fReplaceReserved['¨'] := '&uml;'; fReplaceReserved['ª'] := '&ordf;'; fReplaceReserved['«'] := '&laquo;'; fReplaceReserved['¬'] := '&shy;'; fReplaceReserved['¯'] := '&macr;'; fReplaceReserved['°'] := '&deg;'; fReplaceReserved['±'] := '&plusmn;'; fReplaceReserved['²'] := '&sup2;'; fReplaceReserved['³'] := '&sup3;'; fReplaceReserved['´'] := '&acute;'; fReplaceReserved['µ'] := '&micro;'; fReplaceReserved['·'] := '&middot;'; fReplaceReserved['¸'] := '&cedil;'; fReplaceReserved['¹'] := '&sup1;'; fReplaceReserved['º'] := '&ordm;'; fReplaceReserved['»'] := '&raquo;'; fReplaceReserved['¼'] := '&frac14;'; fReplaceReserved['½'] := '&frac12;'; fReplaceReserved['¾'] := '&frac34;'; fReplaceReserved['¿'] := '&iquest;'; fReplaceReserved['×'] := '&times;'; fReplaceReserved['÷'] := '&divide'; fReplaceReserved['€'] := '&euro;'; end; function TSynExporterHTML.AttriToCSS(Attri: TSynHighlighterAttributes; UniqueAttriName: string): string; var StyleName: string; begin StyleName := MakeValidName(UniqueAttriName); Result := '.' + StyleName + ' { '; if UseBackground and (Attri.Background <> clNone) then Result := Result + 'background-color: ' + ColorToHTML(Attri.Background) + '; '; if Attri.Foreground <> clNone then Result := Result + 'color: ' + ColorToHTML(Attri.Foreground) + '; '; if fsBold in Attri.Style then Result := Result + 'font-weight: bold; '; if fsItalic in Attri.Style then Result := Result + 'font-style: italic; '; if fsUnderline in Attri.Style then Result := Result + 'text-decoration: underline; '; if fsStrikeOut in Attri.Style then Result := Result + 'text-decoration: line-through; '; Result := Result + '}'; end; function TSynExporterHTML.AttriToCSSCallback(Highlighter: TSynCustomHighlighter; Attri: TSynHighlighterAttributes; UniqueAttriName: string; Params: array of Pointer): Boolean; var Styles: ^string; begin Styles := Params[0]; Styles^ := Styles^ + AttriToCSS(Attri, UniqueAttriName) + #13#10; Result := True; // we want all attributes => tell EnumHighlighterAttris to continue end; function TSynExporterHTML.ColorToHTML(AColor: TColor): string; var RGBColor: longint; RGBValue: byte; const Digits: array[0..15] of char = '0123456789ABCDEF'; begin RGBColor := ColorToRGB(AColor); Result := '#000000'; RGBValue := GetRValue(RGBColor); if RGBValue > 0 then begin Result[2] := Digits[RGBValue shr 4]; Result[3] := Digits[RGBValue and 15]; end; RGBValue := GetGValue(RGBColor); if RGBValue > 0 then begin Result[4] := Digits[RGBValue shr 4]; Result[5] := Digits[RGBValue and 15]; end; RGBValue := GetBValue(RGBColor); if RGBValue > 0 then begin Result[6] := Digits[RGBValue shr 4]; Result[7] := Digits[RGBValue and 15]; end; end; procedure TSynExporterHTML.FormatAfterLastAttribute; begin AddData('</span>'); end; procedure TSynExporterHTML.FormatAttributeDone(BackgroundChanged, ForegroundChanged: boolean; FontStylesChanged: TFontStyles); begin AddData('</span>'); end; procedure TSynExporterHTML.FormatAttributeInit(BackgroundChanged, ForegroundChanged: boolean; FontStylesChanged: TFontStyles); var StyleName: string; begin StyleName := GetStyleName(Highlighter, fLastAttri); AddData(Format('<span class="%s">', [StyleName])); end; procedure TSynExporterHTML.FormatBeforeFirstAttribute(BackgroundChanged, ForegroundChanged: boolean; FontStylesChanged: TFontStyles); var StyleName: string; begin StyleName := GetStyleName(Highlighter, fLastAttri); AddData(Format('<span class="%s">', [StyleName])); end; procedure TSynExporterHTML.FormatNewLine; begin AddNewLine; end; function TSynExporterHTML.GetFooter: string; begin Result := ''; if fExportAsText then Result := '</span>'#13#10'</code></pre>'#13#10; if not fCreateHTMLFragment and fExportAsText then Result := Result + '</body>'#13#10'</html>'; end; function TSynExporterHTML.GetFormatName: string; begin Result := SYNS_ExporterFormatHTML; end; function TSynExporterHTML.GetHeader: string; const DescriptionSize = 105; HeaderSize = 47; FooterSize1 = 58; FooterSize2 = 24; NativeHeader = 'Version:0.9'#13#10 + 'StartHTML:%.10d'#13#10 + 'EndHTML:%.10d'#13#10 + 'StartFragment:%.10d'#13#10 + 'EndFragment:%.10d'#13#10; HTMLAsTextHeader = '<?xml version="1.0" encoding="iso-8859-1"?>'#13#10 + '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'#13#10 + '<html xmlns="http://www.w3.org/1999/xhtml">'#13#10 + '<head>'#13#10 + '<title>%s</title>'#13#10 + '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />'#13#10 + '<meta name="generator" content="SynEdit HTML exporter" />'#13#10 + '<style type="text/css">'#13#10 + '<!--'#13#10 + 'body { color: %s; background-color: %s; }'#13#10 + '%s' + '-->'#13#10 + '</style>'#13#10 + '</head>'#13#10 + '<body>'#13#10; var Styles, Header: string; begin EnumHighlighterAttris(Highlighter, True, AttriToCSSCallback, [@Styles]); Header := Format(HTMLAsTextHeader, [Title, ColorToHtml(fFont.Color), ColorToHTML(fBackgroundColor), Styles]); Result := ''; if fExportAsText then begin if not fCreateHTMLFragment then Result := Header; Result := Result + Format('<pre>'#13#10'<code><span style="font: %dpt %s;">', [fFont.Size, fFont.Name]); end else begin // Described in http://msdn.microsoft.com/library/sdkdoc/htmlclip/htmlclipboard.htm Result := Format(NativeHeader, [DescriptionSize, DescriptionSize + Length(Header) + GetBufferSize + FooterSize1, DescriptionSize + Length(Header), DescriptionSize + Length(Header) + GetBufferSize + FooterSize2]); Result := Result + Header; Result := Result + '<!--StartFragment--><pre><code>'; AddData('</code></pre><!--EndFragment-->'); end; end; function TSynExporterHTML.GetStyleName(Highlighter: TSynCustomHighlighter; Attri: TSynHighlighterAttributes): string; begin EnumHighlighterAttris(Highlighter, False, StyleNameCallback, [Attri, @Result]); end; function TSynExporterHTML.MakeValidName(Name: string): string; var i: Integer; begin Result := LowerCase(Name); for i := Length(Result) downto 1 do if Result[i] in ['.', '_'] then Result[i] := '-' else if not(Result[i] in ['a'..'z', '0'..'9', '-']) then Delete(Result, i, 1); end; procedure TSynExporterHTML.SetTokenAttribute(Attri: TSynHighlighterAttributes); begin fLastAttri := Attri; inherited; end; function TSynExporterHTML.StyleNameCallback(Highlighter: TSynCustomHighlighter; Attri: TSynHighlighterAttributes; UniqueAttriName: string; Params: array of Pointer): Boolean; var AttriToFind: TSynHighlighterAttributes; StyleName: ^string; begin AttriToFind := Params[0]; StyleName := Params[1]; if Attri = AttriToFind then begin StyleName^ := MakeValidName(UniqueAttriName); Result := False; // found => inform EnumHighlighterAttris to stop searching end else Result := True; end; end.
unit Financas.Model.Entity.Factory; interface uses Financas.Model.Entity.Interfaces, Financas.Model.Connections.Interfaces, Financas.Model.Entity.Produtos; Type TModelEntityFactory = class(TInterfacedObject, iModelEntityFactory) private public constructor Create; destructor Destroy; override; class function New: iModelEntityFactory; function Produtos(DataSet: iModelDataSet): iModelEntity; function Clientes(DataSet: iModelDataSet): iModelEntity; end; implementation { TModelEntityFactory } uses Financas.Model.Entity.Clientes; function TModelEntityFactory.Clientes(DataSet: iModelDataSet): iModelEntity; begin Result := TModelEntityCliente.New(DataSet); end; constructor TModelEntityFactory.Create; begin end; destructor TModelEntityFactory.Destroy; begin inherited; end; class function TModelEntityFactory.New: iModelEntityFactory; begin Result := Self.Create; end; function TModelEntityFactory.Produtos(DataSet: iModelDataSet): iModelEntity; begin Result := TModelEntityProdutos.New(DataSet); end; end.
{: Properties dialog for the GLScene screensaver sample.<p> Here is some basic interface and animation stuff showcased in other GLScene samples. The selection/hot mechanism is a little different from the approach used in other "interface" samples.<br> Note that the Cadencer is used in "cmManual" mode. Why doing this ? well, on slower systems the PickedObject call in each OnMouseMove may overwhelm the message queue, and since the Cadencer uses the message queue, this will result in animation "stalls" when the user is constantly and swiftly moving its mouse. Using the old "AfterRender" trick sorts this out.<p> Beginners may also be interested in the Registry access. } unit Unit2; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, //GLS GLScene, GLObjects, GLTexture, GLCadencer, GLWin32Viewer, GLSpaceText, GLGeomObjects, GLCoordinates, GLCrossPlatform, GLBaseClasses, GLBehaviours; type TForm2 = class(TForm) GLSceneViewer1: TGLSceneViewer; GLScene1: TGLScene; GLCamera1: TGLCamera; GLLightSource1: TGLLightSource; SpaceText4: TGLSpaceText; Button1: TButton; DummyCube1: TGLDummyCube; Torus1: TGLTorus; Torus2: TGLTorus; GLCadencer1: TGLCadencer; Button2: TButton; procedure FormCreate(Sender: TObject); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Button2Click(Sender: TObject); private { Private declarations } FLastHotNb : Integer; procedure SetSelected(nb : Integer); procedure SetHot(nb : Integer); public { Public declarations } end; var Form2: TForm2; function GetMeshResolutions : Integer; procedure SetMeshResolutions(MeshResolutions : Integer); implementation {$R *.DFM} uses Registry, GLScreenSaver; const cSaverRegistryKey = 'Software\GLScene\Samples\Delphi\Demos\ScreenSaver'; cSaverRegistryMeshResolutions = 'MeshResolutions'; function GetMeshResolutions : Integer; var reg : TRegistry; begin reg:=TRegistry.Create; reg.OpenKey(cSaverRegistryKey, True); // If the value cannot be found, we default to hi-resolution if reg.ValueExists(cSaverRegistryMeshResolutions) then Result:=reg.ReadInteger(cSaverRegistryMeshResolutions) else Result:=1; reg.Free; end; procedure SetMeshResolutions(MeshResolutions : Integer); var reg : TRegistry; begin reg:=TRegistry.Create; reg.OpenKey(cSaverRegistryKey, True); reg.WriteInteger(cSaverRegistryMeshResolutions, MeshResolutions); reg.Free; end; procedure TForm2.FormCreate(Sender: TObject); begin // we highlight the current resolution SetSelected(GetMeshResolutions); SetHot(-1); end; procedure TForm2.SetSelected(nb : Integer); const cSelectionColor : array [False..True] of Integer = (clNavy, clBlue); begin Torus1.Material.FrontProperties.Emission.AsWinColor:=(cSelectionColor[nb=0]); Torus2.Material.FrontProperties.Emission.AsWinColor:=(cSelectionColor[nb=1]); end; procedure TForm2.SetHot(nb : Integer); const cHotColor : array [False..True] of Integer = (clGray, clWhite); begin FLastHotNb:=nb; Torus1.Material.FrontProperties.Diffuse.AsWinColor:=(cHotColor[nb=0]); Torus2.Material.FrontProperties.Diffuse.AsWinColor:=(cHotColor[nb=1]); end; procedure TForm2.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var bso : TGLBaseSceneObject; begin // Here I used the trick of setting Torus1.Tag=1 and Torus.Tag=2 // other objects have a Tag of 0 bso:=GLSceneViewer1.Buffer.GetPickedObject(X, Y); if Assigned(bso) and (bso.Tag>0) then SetHot(bso.Tag-1) else SetHot(-1); end; procedure TForm2.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if FLastHotNb>=0 then begin SetSelected(FLastHotNb); SetMeshResolutions(FLastHotNb); end; end; procedure TForm2.Button2Click(Sender: TObject); begin // a call to "Form1.ScreenSaver1.SetPassword;" would have done the same SetScreenSaverPassword; end; end.
unit settings; interface uses SysUtils, windows, messages, Inifiles, StdCtrls; implementation var host:string; user:string; pass:string; port:string; database:string; f:TIniFile; const namefile = 'config.ini'; procedure ReadIniFile(name:string); begin host:=f.ReadString('db','host','localhost'); user:=f.ReadString('db','user','root'); pass:=f.ReadString('db','pass','admin'); port:=f.ReadString('db','port','3306'); database:=f.ReadString('db','database','shop'); end; procedure CreateIniFile(name:string); begin if FileExists(namefile) then begin ReadIniFile(namefile); end else begin f.Create(namefile); f.WriteString('db','host','localhost'); f.WriteString('db','user','root'); f.WriteString('db','pass','admin'); f.WriteString('db','port','3306'); f.WriteString('db','database','shop'); end; end; procedure ExistFile; begin if FileExists(namefile) then ReadIniFile(namefile) else CreateIniFile(namefile); end; procedure WriteIniFile(host:string;user:string;pass:string;port:string;database:string); begin if FileExists(namefile) then begin f.WriteString('db','host',host); f.WriteString('db','user',user); f.WriteString('db','pass',pass); f.WriteString('db','port',port); f.WriteString('db','database',database); end else CreateIniFile(namefile); end; end.
unit VCLBI.Editor.Split; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, BI.Tools; type TSplitEditor = class(TForm) PanelButtons: TPanel; PanelOk: TPanel; BOk: TButton; BCancel: TButton; PageBy: TPageControl; TabPercent: TTabSheet; TabCount: TTabSheet; Panel1: TPanel; RGMode: TRadioGroup; LPercent: TLabel; TBPercent: TTrackBar; LValue: TLabel; ECount: TEdit; procedure TBPercentChange(Sender: TObject); procedure PageByChange(Sender: TObject); procedure ECountChange(Sender: TObject); private { Private declarations } procedure EnableOkButton; public { Public declarations } class function Edit(const AOwner:TComponent; var ASplit:TSplitOptions):Boolean; static; end; implementation
// Designer : Elisabeth Levana (16518128) // Coder : Elisabeth Levana (16518128) // Tester : Morgen Sudyanto (16518380) unit F09; //tambahBuku interface uses typeList,tools; procedure tambahBuku(var lbuku:listbuku); {Buku baru ditambahkan ke dalam filebuku.csv} implementation procedure tambahBuku(var lbuku:listbuku); begin lbuku.neff:= lbuku.neff+1; writeln('Masukkan Informasi buku yang ditambahkan: '); write('Masukkan id buku: '); readln(lbuku.list[lbuku.neff].id_buku); write('Masukkan judul buku: '); readln(lbuku.list[lbuku.neff].judul_buku); write('Masukkan pengarang buku: '); readln(lbuku.list[lbuku.neff].author); write('Masukkan jumlah buku: '); readln(lbuku.list[lbuku.neff].jumlah_buku); write('Masukkan tahun terbit buku: '); readln(lbuku.list[lbuku.neff].tahun_penerbit); write('Masukkan kategori buku: '); readln(lbuku.list[lbuku.neff].kategori); writeln('Buku berhasil ditambahkan ke dalam sistem!'); end; end.
//****************************************************************************** //*** COMMON DELPHI FUNCTIONS *** //*** *** //*** (c) Massimo Magnano 2004-2005 *** //*** *** //*** *** //****************************************************************************** // File : CopyRoutines.pas // // Description : functions for copy e delete Dirs // //****************************************************************************** unit CopyRoutines; interface uses Windows, SysUtils, Masks, Controls, FileVer, Dialogs; const faOnlyFile =$27; faAnyDir =$1F; EXISTING_DONTCOPY =0; EXISTING_IF_VER_GREATER =1; //Copy if New File have greater version EXISTING_IF_ASK =2; EXISTING_OVERWRITE =3; type TCopyPathProgressRoutine =procedure (Data :Pointer; totalfiles, currentfile :Integer; FileName :String; TotalFileSize, TotalBytesTransferred :LARGE_INTEGER; var cancelled :Boolean ); TCopyProgressRoutine = function ( TotalFileSize, // total file size, in bytes TotalBytesTransferred, // total number of bytes transferred StreamSize, // total number of bytes for this stream StreamBytesTransferred : LARGE_INTEGER; // total number of bytes transferred for this stream dwStreamNumber, // the current stream dwCallbackReason :DWord; // reason for callback hSourceFile, // handle to the source file hDestinationFile :THandle; // handle to the destination file lpData :Pointer // passed by CopyFileEx ) :DWord; stdcall; procedure CopyPath(SourcePath, DestPath, wild :String; OnExistingFile :Integer; Recursive :Boolean =True; Data :Pointer=Nil; CopyProgressRoutine :TCopyPathProgressRoutine=Nil); procedure CopyFile(SourceFile, DestPath:String; OnExistingFile :Integer; DestFileName :String=''; Data :Pointer=Nil; CopyProgressRoutine :TCopyPathProgressRoutine=Nil); procedure DeleteDir(BaseDir:String; SelName :String; Recursive, RemoveDirs :Boolean); function AdjustPath(Path :String) :String; implementation type TCopyPathData =record Data :Pointer; FileName :String; CopyProgressRoutine :TCopyPathProgressRoutine; totalfiles, currentfile :Integer; cancelled :Boolean; Check_Ask :TModalResult; end; function internalProgress( TotalFileSize, // total file size, in bytes TotalBytesTransferred, // total number of bytes transferred StreamSize, // total number of bytes for this stream StreamBytesTransferred : LARGE_INTEGER; // total number of bytes transferred for this stream dwStreamNumber, // the current stream dwCallbackReason :DWord; // reason for callback hSourceFile, // handle to the source file hDestinationFile :THandle; // handle to the destination file lpData :Pointer // passed by CopyFileEx ) :DWord; stdcall; var copyData :^TCopyPathData; begin Result :=PROGRESS_CONTINUE; copyData :=lpData; if (copyData=Nil) then Exit; if assigned(copyData^.CopyProgressRoutine) then begin copyData^.CopyProgressRoutine(copyData^.Data, copyData^.totalfiles, copyData^.currentfile, copyData^.FileName, TotalFileSize, TotalBytesTransferred, copyData^.cancelled); if (copyData^.cancelled) then Result :=PROGRESS_CANCEL; end; end; function CheckExisting(SourceFileName, DestFileName :String; OnExistingFile :Integer; var AskResult :TModalResult) :Boolean; Var SVer, DVer, SLang, DLang, SInfo, DInfo :String; FInfo :TSearchRec; function Ask(MsgSource, MsgDest :String) :TModalResult; begin Result :=MessageDlg('Overwrite EXISTING File :'+#13#10#13#10+ DestFileName+#13#10+MsgDest+#13#10#13#10+ 'With NEW File :'+#13#10#13#10+ SourceFileName+#13#10+MsgSource+#13#10#13#10, mtConfirmation, mbYesAllNoAllCancel, 0); end; begin if FileExists(DestFileName) then begin Result :=True; Case OnExistingFile of EXISTING_DONTCOPY : Result :=False; EXISTING_IF_VER_GREATER : begin SVer :=GetFileVerLang(SourceFileName, SLang); DVer :=GetFileVerLang(DestFileName, DLang); Result := (CompareVer(SVer, DVer)>=0); end; EXISTING_IF_ASK : begin if AskResult=mrYesToAll then begin Result :=True; Exit; end else if AskResult=mrNoToAll then begin Result :=False; Exit; end; SVer :=GetFileVerLang(SourceFileName, SLang); DVer :=GetFileVerLang(DestFileName, DLang); FindFirst(SourceFilename, faAnyFile, FInfo); SInfo :=' Version '+SVer+' Lang '+SLang+#13#10+ ' Date '+DateTimeToStr(FileDateToDateTime(FInfo.Time))+#13#10+ ' Size '+IntToStr(FInfo.Size)+#13#10; FindClose(FInfo); FindFirst(DestFilename, faAnyFile, FInfo); DInfo :=' Version '+DVer+' Lang '+DLang+#13#10+ ' Date '+DateTimeToStr(FileDateToDateTime(FInfo.Time))+#13#10+ ' Size '+IntToStr(FInfo.Size)+#13#10; FindClose(FInfo); AskResult :=Ask(SInfo, DInfo); Result := (AskResult in [mrYes, mrYesToAll]); end; EXISTING_OVERWRITE : Result :=True; end; end else Result :=True; end; procedure CopyPath(SourcePath, DestPath, wild :String; OnExistingFile :Integer; Recursive :Boolean =True; Data :Pointer=Nil; CopyProgressRoutine :TCopyPathProgressRoutine=Nil); var xSourcePath, xDestPath :String; myData :TCopyPathData; int0 :LARGE_INTEGER; CanCopy :Boolean; procedure copyDir(rSource, rDest, wild :String); Var fileInfo :TSearchRec; Error :Integer; begin ForceDirectories(rDest); //find first non entra nelle sotto dir se non è *.* // non posso fare (*.*, faDirectory) perchè mi prende anche i file // Questa si che è un mostro di API... Error := FindFirst(rSource+'*.*', faAnyFile, FileInfo); //+wild While (Error=0) Do begin if (FileInfo.Name[1] <> '.') then //non è [.] o [..] begin if ((FileInfo.Attr and faDirectory) = faDirectory) then begin if Recursive then copyDir(rSource+FileInfo.Name+'\', rDest+FileInfo.Name+'\', wild); end else if MatchesMask(FileInfo.Name, wild) then begin myData.FileName :=rSource+FileInfo.Name; inc(myData.currentfile); CanCopy :=CheckExisting(myData.FileName, rDest+FileInfo.Name, OnExistingFile, myData.Check_Ask); myData.cancelled := myData.cancelled or (myData.Check_Ask = mrCancel); if CanCopy then CopyFileEx(PChar(myData.FileName), PChar(rDest+FileInfo.Name), @internalProgress, @myData, Nil, COPY_FILE_RESTARTABLE); end; end; Error :=FindNext(FileInfo); end; FindClose(FileInfo); end; procedure countDir(rSource, rDest, wild :String); Var fileInfo :TSearchRec; Error :Integer; begin Error := FindFirst(rSource+'*.*', faAnyFile, FileInfo); While (Error=0) Do begin if (FileInfo.Name[1] <> '.') then //non è [.] o [..] begin if ((FileInfo.Attr and faDirectory) = faDirectory) then begin if Recursive then countDir(rSource+FileInfo.Name+'\', rDest+FileInfo.Name+'\', wild); end else if MatchesMask(FileInfo.Name, wild) then inc(myData.totalfiles); end; Error :=FindNext(FileInfo); end; FindClose(FileInfo); end; begin xSourcePath :=AdjustPath(SourcePath); xDestPath :=AdjustPath(DestPath); myData.totalfiles :=0; myData.currentfile :=0; myData.cancelled :=False; myData.Data :=Data; myData.CopyProgressRoutine :=CopyProgressRoutine; myData.Check_Ask :=mrNone; if assigned(CopyProgressRoutine) then begin int0.QuadPart :=0; CopyProgressRoutine(Data, 0, 0, 'Preparing for Copy...', int0, int0, myData.Cancelled); countDir(xSourcePath, xDestPath, wild); CopyProgressRoutine(Data, myData.totalfiles, 0, 'Starting Copy...', int0, int0, myData.Cancelled); end; copyDir(xSourcePath, xDestPath, wild); if assigned(CopyProgressRoutine) then CopyProgressRoutine(Data, myData.totalfiles, 0, 'Copy completed...', int0, int0, myData.Cancelled); end; procedure CopyFile(SourceFile, DestPath :String; OnExistingFile :Integer; DestFileName :String=''; Data :Pointer=Nil; CopyProgressRoutine :TCopyPathProgressRoutine=Nil); var xDestPath, xDestFileName :String; myData :TCopyPathData; int0 :LARGE_INTEGER; begin xDestPath :=AdjustPath(DestPath); if (DestFileName='') then xDestFileName :=ExtractFilename(SourceFile) else xDestFileName :=ExtractFilename(DestFileName); myData.totalfiles :=1; myData.currentfile :=0; myData.cancelled :=False; myData.Data :=Data; myData.CopyProgressRoutine :=CopyProgressRoutine; myData.Check_Ask :=mrNone; if assigned(CopyProgressRoutine) then begin int0.QuadPart :=0; CopyProgressRoutine(Data, myData.totalfiles, 0, 'Starting Copy...', int0, int0, myData.Cancelled); end; myData.FileName :=SourceFile; myData.currentfile :=1; if ForceDirectories(xDestPath) then begin if (CheckExisting(SourceFile, xDestPath+xDestFileName, OnExistingFile, myData.Check_Ask)) then CopyFileEx(PChar(SourceFile), PChar(xDestPath+xDestFileName), @internalProgress, @myData, Nil, COPY_FILE_RESTARTABLE); if assigned(CopyProgressRoutine) then CopyProgressRoutine(Data, myData.totalfiles, 0, 'Copy completed...', int0, int0, myData.Cancelled); end else raise Exception.Create('Cannot copy Files on '+xDestPath); end; procedure DeleteDir(BaseDir:String; SelName :String; Recursive, RemoveDirs :Boolean); procedure _DeleteDir(BaseDir:String; SelName :String; Recursive, RemoveDirs :Boolean); Var SFile, SDir :TSearchRec; Error :Integer; begin //Display('Deleting Dir '+BaseDir+'\'+SelName); if (BaseDir[Length(BaseDir)]<>'\') then BaseDir := BaseDir + '\'; Error :=FindFirst(BaseDir+Selname, faOnlyFile, Sfile); While (Error=0) Do begin if (SFile.Name[1]<>'.') and not(Sfile.Attr in[faDirectory..faAnyDir]) then DeleteFile(BaseDir+SFile.Name); Error :=FindNext(SFile); end; FindClose(SFile); if Recursive then begin Error :=FindFirst(BaseDir+'*.*', faAnyDir, SDir); While (Error=0) Do begin if (SDir.Name[1]<>'.') and (SDir.Attr in[faDirectory..faAnyDir]) then begin DeleteDir(BaseDir+Sdir.Name, SelName, Recursive, RemoveDirs); if RemoveDirs then RemoveDirectory(PChar(BaseDir+Sdir.Name)); end; Error :=FindNext(SDir); end; FindClose(SDir); end; end; begin _DeleteDir(BaseDir, SelName, Recursive, RemoveDirs); if RemoveDirs then RemoveDirectory(PChar(BaseDir)); end; function AdjustPath(Path :String) :String; begin if Path[Length(Path)]<>'\' then Result :=Path+'\' else Result :=Path; end; end.
unit u_xpl_config; {$ifdef fpc} {$mode objfpc}{$H+}{$M+} {$endif} interface uses Classes , SysUtils , u_xpl_common , u_xpl_body , u_xpl_messages ; type TxPLConfigItemType = (config, reconf, option); { TxPLCustomConfig } TxPLCustomConfig = class(TComponent, IxPLCommon) private fConfigList : TConfigListStat; fConfigCurrent : TConfigCurrentStat; function Get_FilterSet: TStringList; function Get_GroupSet: TStringList; function Get_Instance: string; function Get_Interval: integer; procedure SetItemValue(const aItmName : string; const aValue : string); procedure ResetValues; public Constructor Create(aOwner : TComponent); override; function IsValid : boolean; procedure DefineItem(const aName : string; const aType : TxPLConfigItemType; const aMax : integer = 1; const aDefault : string = ''); // : integer; function GetItemValue(const aItmName : string) : string; published property ConfigList : TConfigListStat read fConfigList; property CurrentConfig : TConfigCurrentStat read fConfigCurrent; property Instance : string read Get_Instance stored false; property Interval : integer read Get_Interval stored false; property FilterSet : TStringList read Get_FilterSet stored false; property GroupSet : TStringList read Get_GroupSet stored false; end; implementation {===============================================================} uses uxPLconst , StrUtils , typinfo , u_xpl_address ; { TxPLCustomConfig ============================================================} constructor TxPLCustomConfig.Create(aOwner: TComponent); begin inherited Create(aOwner); include(fComponentStyle,csSubComponent); fConfigList := TConfigListStat.Create(self); fConfigCurrent := TConfigCurrentStat.Create(self); fConfigCurrent.newconf := TxPLAddress.InitInstanceByDefault; fConfigCurrent.interval := K_XPL_DEFAULT_HBEAT; end; function TxPLCustomConfig.Get_FilterSet: TStringList; begin result := fConfigCurrent.filters; end; function TxPLCustomConfig.Get_GroupSet: TStringList; begin result := fConfigCurrent.Groups; end; function TxPLCustomConfig.GetItemValue(const aItmName: string): string; begin result := fConfigCurrent.Body.GetValueByKey(aItmName,''); end; function TxPLCustomConfig.Get_Instance: string; begin result := fConfigCurrent.newconf; end; function TxPLCustomConfig.Get_Interval: integer; begin result := fConfigCurrent.interval; end; function TxPLCustomConfig.IsValid: boolean; var i : integer; s : string; begin result := true; for i:=0 to Pred(fConfigList.Body.ItemCount) do begin if fConfigList.Body.Keys[i]<>'option' then begin s := fConfigList.Body.Values[i]; result := result and (fConfigCurrent.Body.GetValueByKey(s,'')<>''); end; end; end; procedure TxPLCustomConfig.DefineItem(const aName : string; const aType : TxPLConfigItemType; const aMax : integer = 1; const aDefault : string = ''); // : integer; var s : string; begin if aMax <> 1 then s := '[' + IntToStr(aMax) + ']' else s := ''; fConfigList.Body.AddKeyValuePairs([GetEnumName(TypeInfo(TxPLConfigItemType),Ord(aType))],[aName + s]); fConfigCurrent.Body.SetValueByKey(aName,aDefault); end; procedure TxPLCustomConfig.SetItemValue(const aItmName : string; const aValue : string); var s : string; begin case AnsiIndexStr(aItmName,[K_CONF_NEWCONF,K_CONF_INTERVAL]) of // Basic control on some special configuration items 0 : s := AnsiLowerCase(aValue); // instance name can not be in upper case 1 : s := IntToStr(StrToIntDef(aValue,MIN_HBEAT)); else s := aValue; end; fConfigCurrent.Body.SetValueByKey(aItmName,s); end; procedure TxPLCustomConfig.ResetValues; var i : integer; begin fConfigCurrent.Body.ResetValues; for i:=0 to Pred(fConfigList.Body.ItemCount) do fConfigCurrent.Body.AddKeyValue(fConfigList.ItemName(i)+'=') end; initialization Classes.RegisterClass(TxPLCustomConfig); end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit frmMain; interface uses Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls, Dialogs, SysUtils, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private DC : HDC; hrc : HGLRC; procedure InitializeRC; procedure SetDCPixelFormat; end; const GLF_START_LIST = 1000; var frmGL: TfrmGL; implementation {$R *.DFM} {======================================================================= Вывод текста} procedure OutText (Litera : PChar); begin glListBase(GLF_START_LIST); glCallLists(Length (Litera), GL_UNSIGNED_BYTE, Litera); end; {======================================================================= Процедура инициализации источника цвета} procedure TfrmGL.InitializeRC; begin glEnable(GL_DEPTH_TEST);// разрешаем тест глубины glEnable(GL_LIGHTING); // разрешаем работу с освещенностью glEnable(GL_LIGHT0); // включаем источник света 0 end; {======================================================================= Рисование картинки} procedure TfrmGL.FormPaint(Sender: TObject); begin glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); // вывод текста OutText ('Проба'); SwapBuffers(DC); end; {======================================================================= Установка формата пикселей} procedure TfrmGL.SetDCPixelFormat; var nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd), 0); With pfd do begin dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; cDepthBits:= 32; end; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); end; {======================================================================= Создание окна} procedure TfrmGL.FormCreate(Sender: TObject); begin DC := GetDC(Handle); SetDCPixelFormat; hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); glClearColor (0.3, 0.4, 0.6, 1.0); wglUseFontOutlines (Canvas.Handle, 0, 255, GLF_START_LIST, 50, 0.15, WGL_FONT_POLYGONS, nil); InitializeRC; end; {======================================================================= Изменение размеров окна} procedure TfrmGL.FormResize(Sender: TObject); begin glMatrixMode(GL_PROJECTION); glLoadIdentity; gluPerspective(15.0, ClientWidth / ClientHeight, 1.0, 20.0); glViewport(0, 0, ClientWidth, ClientHeight); glMatrixMode(GL_MODELVIEW); glLoadIdentity; glTranslatef(-0.8, -0.7, -9.0); glRotatef(30.0, 1.0, 1.0, 0.0); glRotatef(30.0, 0.0, 1.0, 0.0); // поворот на угол InvalidateRect(Handle, nil, False); end; {======================================================================= Конец работы приложения} procedure TfrmGL.FormDestroy(Sender: TObject); begin glDeleteLists (GLF_START_LIST, 256); wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC(Handle, DC); DeleteDC(DC); end; procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close end; end.
{ This unit is part of the LaKraven Studios Standard Library (LKSL). Copyright (C) 2011, LaKraven Studios Ltd. Copyright Protection Packet(s): LKSL001 -------------------------------------------------------------------- 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. -------------------------------------------------------------------- Unit: LKSL.Strings.Conversion.pas Created: 15th December 2011 Modified: 15th December 2011 Changelog: 15th December 2011 - Added "WideStringToAnsiString" (safe conversion of WideString to AnsiString) } unit LKSL.Strings.Conversion; interface {$I LKSL.inc} {$IFDEF MSWINDOWS} uses {$IFDEF DELPHIXE2} Winapi.Windows; {$ELSE} Windows; {$ENDIF} {$ENDIF} {$IFNDEF DELPHIXE} type PLongBool = ^LongBool; function LocaleCharsFromUnicode(CodePage, Flags: Cardinal; UnicodeStr: PWideChar; UnicodeStrLen: Integer; LocaleStr: PAnsiChar; LocaleStrLen: Integer; DefaultChar: PAnsiChar; UsedDefaultChar: PLongBool): Integer; overload; inline; {$ENDIF} // A SAFE way to convert from WideString to AnsiString (UTF-8 chars preserved) function WideStringToAnsiString(const S: WideString): AnsiString; inline; implementation {$IFNDEF DELPHIXE} function LocaleCharsFromUnicode(CodePage, Flags: Cardinal; UnicodeStr: PWideChar; UnicodeStrLen: Integer; LocaleStr: PAnsiChar; LocaleStrLen: Integer; DefaultChar: PAnsiChar; UsedDefaultChar: PLongBool): Integer; overload; begin Result := WideCharToMultiByte(CodePage, Flags, UnicodeStr, UnicodeStrLen, LocaleStr, LocaleStrLen, DefaultChar, PBOOL(UsedDefaultChar)); end; {$ENDIF} function WideStringToAnsiString(const S: WideString): AnsiString; var BufSize: Integer; begin { NOTE: May need to use "WideCharToMultiByte" on older versions in place of "LocaleCharsFromUnicode" } Result := ''; if Length(S) = 0 then Exit; BufSize := LocaleCharsFromUnicode(CP_UTF8, 0, PWideChar(S), Length(S) , nil, 0, nil, nil); SetLength(result, BufSize); LocaleCharsFromUnicode(CP_UTF8, 0, PWideChar(S), Length(S) , PAnsiChar(Result), BufSize, nil, nil); end; end.
unit MediaProcessing.Transformer.RGB.Impl; interface uses SysUtils,Windows,Classes, Graphics, BitmapStreamMediator, MediaProcessing.Definitions,MediaProcessing.Global,MediaProcessing.Transformer.RGB; type TMediaProcessor_Transformer_Rgb_Impl =class (TMediaProcessor_Transformer_Rgb,IMediaProcessorImpl) private FDibBuffer: TBytes; protected procedure Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal; out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); override; public constructor Create; override; destructor Destroy; override; end; implementation uses uBaseClasses,BitPlane,MediaProcessing.Common.Processor.FPS.ImageSize; constructor TMediaProcessor_Transformer_Rgb_Impl.Create; begin inherited; end; destructor TMediaProcessor_Transformer_Rgb_Impl.Destroy; begin inherited; end; procedure TMediaProcessor_Transformer_Rgb_Impl.Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal; out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); var aBitPlane: TBitPlaneDesc; aBitPlane2: TBitPlaneDesc; aTmpBuffer: TBytes; procedure PrepareDib; begin if aOutData<>FDibBuffer then begin if cardinal(Length(FDibBuffer))<aInDataSize then begin FDibBuffer:=nil; SetLength(FDibBuffer,aInDataSize); end; CopyMemory(@FDibBuffer[0],aInData,aInDataSize); aOutData:=@FDibBuffer[0]; end; end; begin TArgumentValidation.NotNil(aInData); aOutData:=nil; aOutDataSize:=0; aOutInfo:=nil; aOutInfoSize:=0; aOutFormat:=aInFormat; if not Process_Fps(aInFormat) then exit; aOutData:=aInData; aOutDataSize:=aInDataSize; aOutInfo:=aInfo; aOutInfoSize:=aInfoSize; if FImageSizeMode<>cismNone then begin PrepareDib; Process_ImageSizeRGB(@FDibBuffer[0],aOutFormat.VideoWidth,aOutFormat.VideoHeight); aOutDataSize:=GetRGBSize(aOutFormat.VideoWidth,aOutFormat.VideoHeight,aInFormat.VideoBitCount); end; if FVerticalReversePhysical and (aOutData<>nil) then begin PrepareDib; aBitPlane.Init(pointer(FDibBuffer),aOutDataSize,aOutFormat.VideoWidth,aOutFormat.VideoHeight,aOutFormat.VideoBitCount); aBitPlane.Upturn; end; if FVerticalReverseLogical and (aOutData<>nil) then begin aOutFormat.VideoReversedVertical:=not aOutFormat.VideoReversedVertical; end; if FRotate then begin PrepareDib; SetLength(aTmpBuffer,Length(FDibBuffer)); CopyMemory(aTmpBuffer,FDibBuffer, Length(FDibBuffer)); aBitPlane.Init(pointer(aTmpBuffer),aOutDataSize,aOutFormat.VideoWidth,aOutFormat.VideoHeight,aOutFormat.VideoBitCount); aBitPlane2.Init(pointer(FDibBuffer),aOutDataSize,aOutFormat.VideoWidth,aOutFormat.VideoHeight,aOutFormat.VideoBitCount); aBitPlane.RotateToBitPlane(aBitPlane2,-FRotateAngle,false) end; end; initialization MediaProceccorFactory.RegisterMediaProcessorImplementation(TMediaProcessor_Transformer_Rgb_Impl); end.
{**********************************************} { TCustomBoxSeries Editor dialog } { TBoxSeries } { THorizBoxSeries } { } { Copyright (c) 2000-2004 by David Berneda } {**********************************************} unit TeeBoxPlotEditor; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, {$ENDIF} TeCanvas, TeePenDlg, TeeBoxPlot, TeeProcs; type TBoxSeriesEditor = class(TForm) BMedian: TButtonPen; Label1: TLabel; EPos: TEdit; Label2: TLabel; ELength: TEdit; BWhisker: TButtonPen; procedure FormShow(Sender: TObject); procedure ELengthChange(Sender: TObject); procedure EPosChange(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } BoxPointerForm : TCustomForm; ExtrPointerForm : TCustomForm; MildPointerForm : TCustomForm; Box : TCustomBoxSeries; public { Public declarations } end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses TeePoEdi, TeeProCo; procedure TBoxSeriesEditor.FormShow(Sender: TObject); begin Box:=TCustomBoxSeries(Tag); if Assigned(Box) then begin with Box do begin BMedian.LinkPen(MedianPen); BWhisker.LinkPen(WhiskerPen); ELength.Text:=FloatToStr(WhiskerLength); EPos.Text:=FloatToStr(Position); end; if Assigned(Parent) then begin if not Assigned(BoxPointerForm) then BoxPointerForm:=TeeInsertPointerForm(Parent,Box.Pointer,TeeMsg_Box); if not Assigned(ExtrPointerForm) then ExtrPointerForm:=TeeInsertPointerForm(Parent,Box.ExtrOut,TeeMsg_ExtrOut); if not Assigned(MildPointerForm) then MildPointerForm:=TeeInsertPointerForm(Parent,Box.MildOut,TeeMsg_MildOut); end; end; end; procedure TBoxSeriesEditor.ELengthChange(Sender: TObject); begin if Showing and (ELength.Text<>'') then Box.WhiskerLength:=StrToFloat(ELength.Text); end; procedure TBoxSeriesEditor.EPosChange(Sender: TObject); begin if Showing and (EPos.Text<>'') then Box.Position:=StrToFloat(EPos.Text); end; procedure TBoxSeriesEditor.FormCreate(Sender: TObject); begin Align:=alClient; end; initialization RegisterClass(TBoxSeriesEditor); end.
// Copyright 2021 Darian Miller, Licensed under Apache-2.0 // SPDX-License-Identifier: Apache-2.0 // More info: www.radprogrammer.com unit radRTL.ByteArrayUtils.Tests; interface uses TestFramework; type TByteArrayUtilsTest = class(TTestCase) published procedure TestReverseByteArray_Empty; procedure TestReverseByteArray_OneBtye; procedure TestReverseByteArray_TwoBtye; procedure TestReverseByteArray_ThreeBtye; procedure TestConvertInt_Zero; procedure TestConvertInt_One; procedure TestConvertInt_Two; procedure TestConvertInt_256; procedure TestConvertInt64_Zero; procedure TestConvertInt64_One; procedure TestConvertInt64_Two; procedure TestConvertInt64_256; procedure TestConvertIntAndReverseByteArray_Zero; procedure TestConvertIntAndReverseByteArray_One; procedure TestConvertIntAndReverseByteArray_Two; end; implementation uses System.SysUtils, radRTL.ByteArrayUtils; procedure TByteArrayUtilsTest.TestReverseByteArray_Empty; var vInput:TBytes; begin CheckEquals(Length(vInput), Length(ReverseByteArray(vInput))); end; procedure TByteArrayUtilsTest.TestReverseByteArray_OneBtye; var vInput:TBytes; vOutput:TBytes; begin SetLength(vInput, 1); vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); vInput[0] := 0; vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); ChecKTrue(ByteArraysMatch(vInput, vOutput)); ChecKTrue(ByteArraysMatch(vInput, ReverseByteArray(vOutput))); vInput[0] := 1; vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); ChecKTrue(ByteArraysMatch(vInput, vOutput)); ChecKTrue(ByteArraysMatch(vInput, ReverseByteArray(vOutput))); vInput[0] := 255; vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); ChecKTrue(ByteArraysMatch(vInput, vOutput)); ChecKTrue(ByteArraysMatch(vInput, ReverseByteArray(vOutput))); end; procedure TByteArrayUtilsTest.TestReverseByteArray_TwoBtye; var vInput:TBytes; vOutput:TBytes; begin SetLength(vInput, 2); vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); vInput[0] := 0; vInput[1] := 1; vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); ChecKTrue(ByteArraysMatch(vInput, ReverseByteArray(vOutput))); vInput[0] := 1; vInput[1] := 0; vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); ChecKTrue(ByteArraysMatch(vInput, ReverseByteArray(vOutput))); vInput[0] := 0; vInput[1] := 255; vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); ChecKTrue(ByteArraysMatch(vInput, ReverseByteArray(vOutput))); vInput[0] := 255; vInput[1] := 0; vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); ChecKTrue(ByteArraysMatch(vInput, ReverseByteArray(vOutput))); end; procedure TByteArrayUtilsTest.TestReverseByteArray_ThreeBtye; var vInput:TBytes; vOutput:TBytes; begin SetLength(vInput, 3); vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); vInput[0] := 0; vInput[1] := 1; vInput[2] := 255; vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); ChecKTrue(ByteArraysMatch(vInput, ReverseByteArray(vOutput))); vInput[0] := 1; vInput[1] := 0; vInput[2] := 255; vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); ChecKTrue(ByteArraysMatch(vInput, ReverseByteArray(vOutput))); vInput[0] := 255; vInput[1] := 0; vInput[2] := 1; vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); ChecKTrue(ByteArraysMatch(vInput, ReverseByteArray(vOutput))); vInput[0] := 0; vInput[1] := 255; vInput[2] := 1; vOutput := ReverseByteArray(vInput); CheckEquals(Length(vInput), Length(vOutput)); ChecKTrue(ByteArraysMatch(vInput, ReverseByteArray(vOutput))); end; procedure TByteArrayUtilsTest.TestConvertInt_Zero; var vInput:Integer; vConverted:TBytes; begin vInput := 0; vConverted := ConvertToByteArray(vInput); ChecKTrue(Length(vConverted) = SizeOf(Integer)); ChecKTrue(vConverted[0] = 0); ChecKTrue(vConverted[1] = 0); ChecKTrue(vConverted[2] = 0); ChecKTrue(vConverted[3] = 0); end; procedure TByteArrayUtilsTest.TestConvertInt_One; var vInput:Integer; vConverted:TBytes; begin vInput := 1; vConverted := ConvertToByteArray(vInput); ChecKTrue(Length(vConverted) = SizeOf(Integer)); ChecKTrue(vConverted[0] = 1); ChecKTrue(vConverted[1] = 0); ChecKTrue(vConverted[2] = 0); ChecKTrue(vConverted[3] = 0); end; procedure TByteArrayUtilsTest.TestConvertInt_Two; var vInput:Integer; vConverted:TBytes; begin vInput := 2; vConverted := ConvertToByteArray(vInput); ChecKTrue(Length(vConverted) = SizeOf(Integer)); ChecKTrue(vConverted[0] = 2); ChecKTrue(vConverted[1] = 0); ChecKTrue(vConverted[2] = 0); ChecKTrue(vConverted[3] = 0); end; procedure TByteArrayUtilsTest.TestConvertInt_256; var vInput:Integer; vConverted:TBytes; begin vInput := 256; vConverted := ConvertToByteArray(vInput); ChecKTrue(Length(vConverted) = SizeOf(Integer)); ChecKTrue(vConverted[0] = 0); ChecKTrue(vConverted[1] = 1); ChecKTrue(vConverted[2] = 0); ChecKTrue(vConverted[3] = 0); end; procedure TByteArrayUtilsTest.TestConvertInt64_Zero; var vInput:Int64; vConverted:TBytes; begin vInput := 0; vConverted := ConvertToByteArray(vInput); ChecKTrue(Length(vConverted) = SizeOf(Int64)); ChecKTrue(vConverted[0] = 0); ChecKTrue(vConverted[1] = 0); ChecKTrue(vConverted[2] = 0); ChecKTrue(vConverted[3] = 0); ChecKTrue(vConverted[4] = 0); ChecKTrue(vConverted[5] = 0); ChecKTrue(vConverted[6] = 0); ChecKTrue(vConverted[7] = 0); end; procedure TByteArrayUtilsTest.TestConvertInt64_One; var vInput:Int64; vConverted:TBytes; begin vInput := 1; vConverted := ConvertToByteArray(vInput); ChecKTrue(Length(vConverted) = SizeOf(Int64)); ChecKTrue(vConverted[0] = 1); ChecKTrue(vConverted[1] = 0); ChecKTrue(vConverted[2] = 0); ChecKTrue(vConverted[3] = 0); ChecKTrue(vConverted[4] = 0); ChecKTrue(vConverted[5] = 0); ChecKTrue(vConverted[6] = 0); ChecKTrue(vConverted[7] = 0); end; procedure TByteArrayUtilsTest.TestConvertInt64_Two; var vInput:Int64; vConverted:TBytes; begin vInput := 2; vConverted := ConvertToByteArray(vInput); ChecKTrue(Length(vConverted) = SizeOf(Int64)); ChecKTrue(vConverted[0] = 2); ChecKTrue(vConverted[1] = 0); ChecKTrue(vConverted[2] = 0); ChecKTrue(vConverted[3] = 0); ChecKTrue(vConverted[4] = 0); ChecKTrue(vConverted[5] = 0); ChecKTrue(vConverted[6] = 0); ChecKTrue(vConverted[7] = 0); end; procedure TByteArrayUtilsTest.TestConvertInt64_256; var vInput:Int64; vConverted:TBytes; begin vInput := 256; vConverted := ConvertToByteArray(vInput); ChecKTrue(Length(vConverted) = SizeOf(Int64)); ChecKTrue(vConverted[0] = 0); ChecKTrue(vConverted[1] = 1); ChecKTrue(vConverted[2] = 0); ChecKTrue(vConverted[3] = 0); ChecKTrue(vConverted[4] = 0); ChecKTrue(vConverted[5] = 0); ChecKTrue(vConverted[6] = 0); ChecKTrue(vConverted[7] = 0); end; procedure TByteArrayUtilsTest.TestConvertIntAndReverseByteArray_Zero; var vInput:Integer; vConverted:TBytes; vReversed:TBytes; begin vInput := 0; vConverted := ConvertToByteArray(vInput); vReversed := ReverseByteArray(vConverted); CheckEquals(Length(vConverted), Length(vReversed)); ChecKTrue(ByteArraysMatch(vConverted, vReversed)); // true for 0 end; procedure TByteArrayUtilsTest.TestConvertIntAndReverseByteArray_One; var vInput:Integer; vConverted:TBytes; vReversed:TBytes; begin vInput := 1; vConverted := ConvertToByteArray(vInput); vReversed := ReverseByteArray(vConverted); CheckEquals(Length(vConverted), Length(vReversed)); CheckFalse(ByteArraysMatch(vConverted, vReversed)); ChecKTrue(ByteArraysMatch(vConverted, ReverseByteArray(vReversed))); end; procedure TByteArrayUtilsTest.TestConvertIntAndReverseByteArray_Two; var vInput:Integer; vConverted:TBytes; vReversed:TBytes; begin vInput := 2; vConverted := ConvertToByteArray(vInput); vReversed := ReverseByteArray(vConverted); CheckEquals(Length(vConverted), Length(vReversed)); CheckFalse(ByteArraysMatch(vConverted, vReversed)); ChecKTrue(ByteArraysMatch(vConverted, ReverseByteArray(vReversed))); end; initialization RegisterTest(TByteArrayUtilsTest.Suite); end.
{** * @Author: Du xinming * @Contact: QQ<36511179>; Email<lndxm1979@163.com> * @Version: 0.0 * @Date: 2018.10 * @Brief: * Windows Thread API Wrapper *} unit org.utilities.thread; interface uses Winapi.Windows, System.SysUtils; type TThread = class protected FTerminated: Boolean; public procedure DoThreadBegin; virtual; abstract; procedure DoThreadEnd; virtual; abstract; procedure Execute; virtual; abstract; procedure Start; virtual; abstract; procedure Stop; virtual; abstract; end; TSingleThread = class(TThread) private FThreadHandle: THandle; public constructor Create; destructor Destroy; override; procedure DoThreadBegin; override; procedure DoThreadEnd; override; procedure Start; override; procedure Stop; override; end; TThreadPool = class(TThread) private FThreadCount: Integer; FWaitThreadCount: Integer; FThreadHandles: TWOHandleArray; function InnerCreateThread: THandle; public constructor Create(AThreadCount: Integer = 0); destructor Destroy; override; procedure DoThreadBegin; override; procedure DoThreadEnd; override; procedure Start; override; procedure Stop; override; property ThreadCount: Integer read FThreadCount; end; implementation uses Vcl.Forms; procedure ThreadProc(AThread: TThread); begin AThread.DoThreadBegin(); try AThread.Execute(); finally AThread.DoThreadEnd(); end; end; { TThreadPool } constructor TThreadPool.Create(AThreadCount: Integer); var I: Integer; begin FThreadCount := AThreadCount; FWaitThreadCount := AThreadCount; FTerminated := False; // SetLength(FThreadHandles, FThreadCount); for I := 0 to FThreadCount - 1 do FThreadHandles[I] := InnerCreateThread(); end; destructor TThreadPool.Destroy; begin inherited; end; procedure TThreadPool.DoThreadBegin; begin InterlockedDecrement(FWaitThreadCount); end; procedure TThreadPool.DoThreadEnd; begin InterlockedIncrement(FWaitThreadCount); end; function TThreadPool.InnerCreateThread: THandle; var AThreadId: Cardinal; begin Result := System.BeginThread(nil, 0, @ThreadProc, Self, CREATE_SUSPENDED, AThreadId); if Result = 0 then begin raise Exception.CreateFmt('<%s.InnerCreateThread> failed with LastErrCode=%d',[ClassName(), GetLastError()]); end; end; procedure TThreadPool.Start; var I: Integer; begin for I := 0 to FThreadCount - 1 do begin ResumeThread(FThreadHandles[I]); // Sleep(50); end; while FWaitThreadCount > 0 do begin Application.ProcessMessages(); Sleep(10); end; end; procedure TThreadPool.Stop; begin FTerminated := True; while FWaitThreadCount < FThreadCount do begin Application.ProcessMessages(); Sleep(10); end; end; { TSingleThread } constructor TSingleThread.Create; var AThreadId: Cardinal; begin FThreadHandle := 0; FTerminated := False; FThreadHandle := System.BeginThread(nil, 0, @ThreadProc, Self, CREATE_SUSPENDED, AThreadId); if FThreadHandle = 0 then begin raise Exception.CreateFmt('<%s.Create.BeginThread> failed with LastErrCode=%d',[ClassName(), GetLastError()]); end; end; destructor TSingleThread.Destroy; begin CloseHandle(FThreadHandle); inherited; end; procedure TSingleThread.DoThreadBegin; begin end; procedure TSingleThread.DoThreadEnd; begin end; procedure TSingleThread.Start; begin ResumeThread(FThreadHandle); end; procedure TSingleThread.Stop; begin FTerminated := True; end; end.
unit SharedMemoryName_TLB; // ************************************************************************ // // WARNING // ------- // The types declared in this file were generated from data read from a // Type Library. If this type library is explicitly or indirectly (via // another type library referring to this type library) re-imported, or the // 'Refresh' command of the Type Library Editor activated while editing the // Type Library, the contents of this file will be regenerated and all // manual modifications will be lost. // ************************************************************************ // // $Rev: 52393 $ // File generated on 21.12.2013 18:25:30 from Type Library described below. // ************************************************************************ // // Type Lib: D:\Projects\SearchInform\COM\SharedMemoryName (1) // LIBID: {1A11E0F4-1DC4-4F6E-8C8C-E1B226772B58} // LCID: 0 // Helpfile: // HelpString: // DepndLst: // (1) v2.0 stdole, (C:\Windows\System32\stdole2.tlb) // SYS_KIND: SYS_WIN32 // ************************************************************************ // {$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers. {$WARN SYMBOL_PLATFORM OFF} {$WRITEABLECONST ON} {$VARPROPSETTER ON} {$ALIGN 4} interface uses Winapi.Windows, System.Classes, System.Variants, System.Win.StdVCL, Vcl.Graphics, Vcl.OleServer, Winapi.ActiveX; // *********************************************************************// // GUIDS declared in the TypeLibrary. Following prefixes are used: // Type Libraries : LIBID_xxxx // CoClasses : CLASS_xxxx // DISPInterfaces : DIID_xxxx // Non-DISP interfaces: IID_xxxx // *********************************************************************// const // TypeLibrary Major and minor versions SharedMemoryNameMajorVersion = 1; SharedMemoryNameMinorVersion = 0; LIBID_SharedMemoryName: TGUID = '{1A11E0F4-1DC4-4F6E-8C8C-E1B226772B58}'; IID_IUniqueName: TGUID = '{F7CB991F-C6C5-476A-9717-900C4850B4F1}'; CLASS_UniqueName: TGUID = '{1E14AD0B-6293-4BBF-BAF9-B370E53408D9}'; type // *********************************************************************// // Forward declaration of types defined in TypeLibrary // *********************************************************************// IUniqueName = interface; // *********************************************************************// // Declaration of CoClasses defined in Type Library // (NOTE: Here we map each CoClass to its Default Interface) // *********************************************************************// UniqueName = IUniqueName; // *********************************************************************// // Interface: IUniqueName // Flags: (256) OleAutomation // GUID: {F7CB991F-C6C5-476A-9717-900C4850B4F1} // *********************************************************************// IUniqueName = interface(IUnknown) ['{F7CB991F-C6C5-476A-9717-900C4850B4F1}'] function GetSharedMemoryName: WideString; safecall; end; // *********************************************************************// // The Class CoUniqueName provides a Create and CreateRemote method to // create instances of the default interface IUniqueName exposed by // the CoClass UniqueName. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// CoUniqueName = class class function Create: IUniqueName; class function CreateRemote(const MachineName: string): IUniqueName; end; implementation uses System.Win.ComObj; class function CoUniqueName.Create: IUniqueName; begin Result := CreateComObject(CLASS_UniqueName) as IUniqueName; end; class function CoUniqueName.CreateRemote(const MachineName: string): IUniqueName; begin Result := CreateRemoteComObject(MachineName, CLASS_UniqueName) as IUniqueName; end; end.
unit UAnLiteral; interface uses Classes; const { Tokens } TOKEN_FIM = 0; TOKEN_LITERAL = 1; TOKEN_OUTRO = 2; type { TAnLiteral } TAnLiteral = class private FStr: String; FPos: Integer; FTam: Integer; FToken: Integer; FCaractere: Char; FTokenStr: String; function ProximoCaractere: Char; public constructor Cria(Str: String); destructor Destroy; override; function ProximoToken: Integer; property Token: Integer read FToken; property TokenStr: String read FTokenStr; end; implementation { TAnLiteral } constructor TAnLiteral.Cria(Str: String); begin FStr := Str; FPos := 1; FTam := Length(FStr); ProximoCaractere(); ProximoToken(); end; destructor TAnLiteral.Destroy; begin FStr := ''; inherited Destroy; end; function TAnLiteral.ProximoCaractere: Char; begin if FPos > FTam then Result := #0 else begin Result := FStr[FPos]; Inc(FPos); end; FCaractere := Result; end; function TAnLiteral.ProximoToken: Integer; begin FTokenStr := ''; case FCaractere of #0: Result := TOKEN_FIM; '"': begin repeat FTokenStr := FTokenStr + FCaractere; until ProximoCaractere() in ['"', #0, #10]; FTokenStr := FTokenStr + FCaractere; if FCaractere = '"' then Result := TOKEN_LITERAL else Result := TOKEN_OUTRO; if FCaractere in ['"', #10] then ProximoCaractere(); end; else repeat FTokenStr := FTokenStr + FCaractere; until ProximoCaractere() in ['"', #0]; Result := TOKEN_OUTRO; end; FToken := Result; end; end.
unit uDAO.Interfaces; interface uses Data.DB, uModel.Interfaces; type iPessoaDAO = interface ['{2E4931F4-6F1F-4C15-879D-D7F6BA35CF23}'] function Get(pId: Integer): TDataSet; overload; function Get(pId: Integer; pModel: iPessoaModel): iPessoaDAO; overload; function Delete(pId: Integer): Boolean; function Save(pModel: iPessoaModel): Boolean; end; iPessoaContatoDAO = interface ['{7DCA099D-4AA5-4588-9322-5ACB2DAD664A}'] function Get(pIdPessoa: Integer; pList: iPessoaContatoList = nil): TDataSet; function Delete(pId, pIdPessoa: Integer): Boolean; function Save(pModel: iPessoaContatoModel): Boolean; end; implementation end.
{ ****************************************************************************** } { * AI Rasterization Recognition ON Video * } { * by QQ 600585@qq.com * } { ****************************************************************************** } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } unit zAI_VideoRasterDNNThreadQueue; {$INCLUDE zDefine.inc} interface uses CoreClasses, PascalStrings, UnicodeMixedLib, DoStatusIO, MemoryStream64, ListEngine, LinearAction, {$IFDEF FPC} FPCGenericStructlist, {$ENDIF FPC} MemoryRaster, Geometry2DUnit, H264, FFMPEG, FFMPEG_Reader, FFMPEG_Writer, zAI, zAI_Common, zAI_FFMPEG, Learn, LearnTypes, KDTree; type TRasterInputQueue = class; TRasterRecognitionData = class protected FOwner: TRasterInputQueue; FID: SystemString; FRaster: TRaster; FIDLE: Boolean; FNullRec: Boolean; FDNNThread: TAI_DNN_Thread; FInputTime, FDoneTime: TTimeTick; FState: SystemString; FNextLevel: TRasterInputQueue; FUserData: Pointer; function DoGetState(): SystemString; virtual; function DoGetShortName(): SystemString; virtual; public constructor Create(Owner_: TRasterInputQueue); virtual; destructor Destroy; override; property Owner: TRasterInputQueue read FOwner; procedure SetDone; function Busy(): Boolean; overload; function Busy(checkNextLevel_: Boolean): Boolean; overload; function UsageTime: TTimeTick; property Raster: TRaster read FRaster; property ID: SystemString read FID; property NullRec: Boolean read FNullRec; function GetStateInfo: SystemString; property StateInfo: SystemString read GetStateInfo; function GetNextLevel: TRasterInputQueue; property NextLevel: TRasterInputQueue read GetNextLevel; property DirectNextLevel: TRasterInputQueue read FNextLevel; property UserData: Pointer read FUserData write FUserData; property ShortName: SystemString read DoGetShortName; end; TRasterRecognitionDataClass = class of TRasterRecognitionData; TRasterRecognitionData_Passed = class(TRasterRecognitionData) public constructor Create(Owner_: TRasterInputQueue); override; destructor Destroy; override; end; TRasterRecognitionData_SP = class(TRasterRecognitionData) protected function DoGetState(): SystemString; override; function DoGetShortName(): SystemString; override; public Parallel_: TAI_Parallel; SP_Desc: TMatrixVec2; MMOD_Desc: TMMOD_Desc; FaceRasterList: TMemoryRasterList; constructor Create(Owner_: TRasterInputQueue); override; destructor Destroy; override; end; TRasterRecognitionData_Metric = class(TRasterRecognitionData) protected function DoGetState(): SystemString; override; function DoGetShortName(): SystemString; override; public Output: TLVec; L: TLearn; constructor Create(Owner_: TRasterInputQueue); override; destructor Destroy; override; end; TRasterRecognitionData_LMetric = class(TRasterRecognitionData) protected function DoGetState(): SystemString; override; function DoGetShortName(): SystemString; override; public Output: TLVec; L: TLearn; constructor Create(Owner_: TRasterInputQueue); override; destructor Destroy; override; end; TRasterRecognitionData_MMOD6L = class(TRasterRecognitionData) protected function DoGetState(): SystemString; override; function DoGetShortName(): SystemString; override; public Output: TMMOD_Desc; constructor Create(Owner_: TRasterInputQueue); override; destructor Destroy; override; end; TRasterRecognitionData_MMOD3L = class(TRasterRecognitionData) protected function DoGetState(): SystemString; override; function DoGetShortName(): SystemString; override; public Output: TMMOD_Desc; constructor Create(Owner_: TRasterInputQueue); override; destructor Destroy; override; end; TRasterRecognitionData_RNIC = class(TRasterRecognitionData) protected function DoGetState(): SystemString; override; function DoGetShortName(): SystemString; override; public Output: TLVec; ClassifierIndex: TPascalStringList; constructor Create(Owner_: TRasterInputQueue); override; destructor Destroy; override; end; TRasterRecognitionData_LRNIC = class(TRasterRecognitionData) protected function DoGetState(): SystemString; override; function DoGetShortName(): SystemString; override; public Output: TLVec; ClassifierIndex: TPascalStringList; constructor Create(Owner_: TRasterInputQueue); override; destructor Destroy; override; end; TRasterRecognitionData_GDCNIC = class(TRasterRecognitionData) protected function DoGetState(): SystemString; override; function DoGetShortName(): SystemString; override; public Output: TLVec; ClassifierIndex: TPascalStringList; constructor Create(Owner_: TRasterInputQueue); override; destructor Destroy; override; end; TRasterRecognitionData_GNIC = class(TRasterRecognitionData) protected function DoGetState(): SystemString; override; function DoGetShortName(): SystemString; override; public Output: TLVec; ClassifierIndex: TPascalStringList; constructor Create(Owner_: TRasterInputQueue); override; destructor Destroy; override; end; TRasterRecognitionData_SS = class(TRasterRecognitionData) protected function DoGetState(): SystemString; override; function DoGetShortName(): SystemString; override; public Output: TMemoryRaster; SSTokenOutput: TPascalStringList; ColorPool: TSegmentationColorTable; constructor Create(Owner_: TRasterInputQueue); override; destructor Destroy; override; end; TRasterRecognitionData_ZMetric = class(TRasterRecognitionData) protected function DoGetState(): SystemString; override; function DoGetShortName(): SystemString; override; public Output: TLVec; L: TLearn; SS_Width, SS_Height: Integer; constructor Create(Owner_: TRasterInputQueue); override; destructor Destroy; override; end; TRasterRecognitionDataList = {$IFDEF FPC}specialize {$ENDIF FPC} TGenericsList<TRasterRecognitionData>; TOnInput = procedure(Sender: TRasterInputQueue; Raster: TRaster) of object; TOnRecognitionDone = procedure(Sender: TRasterInputQueue; RD: TRasterRecognitionData) of object; TOnQueueDone = procedure(Sender: TRasterInputQueue) of object; TOnCutNullRec = procedure(Sender: TRasterInputQueue; bIndex, eIndex: Integer) of object; TOnCutMaxLimit = procedure(Sender: TRasterInputQueue; bIndex, eIndex: Integer) of object; TRasterInputQueue = class private FRunning: Integer; FOwner: TRasterRecognitionData; FQueue: TRasterRecognitionDataList; FCritical: TCritical; FCutNullQueue: Boolean; FMaxQueue: Integer; FSyncEvent: Boolean; FUserData: Pointer; FOnInput: TOnInput; FOnRecognitionDone: TOnRecognitionDone; FOnQueueDone: TOnQueueDone; FOnCutNullRec: TOnCutNullRec; FOnCutMaxLimit: TOnCutMaxLimit; procedure DoDelayCheckBusyAndFree; function BeforeInput(ID_: SystemString; UserData_: Pointer; Raster: TRaster; instance_: Boolean; dataClass: TRasterRecognitionDataClass): TRasterRecognitionData; procedure Sync_DoFinish(Data1: Pointer; Data2: TCoreClassObject; Data3: Variant); procedure DoCheckDone(RD: TRasterRecognitionData); procedure DoFinish(RD: TRasterRecognitionData; RecSuccessed: Boolean); procedure DoRunSP(thSender: TCompute); procedure Do_Input_Metric_Result(thSender: TAI_DNN_Thread_Metric; UserData: Pointer; Input: TMemoryRaster; Output: TLVec); virtual; procedure Do_Input_LMetric_Result(thSender: TAI_DNN_Thread_LMetric; UserData: Pointer; Input: TMemoryRaster; Output: TLVec); virtual; procedure Do_Input_MMOD3L_Result(thSender: TAI_DNN_Thread_MMOD3L; UserData: Pointer; Input: TMemoryRaster; Output: TMMOD_Desc); virtual; procedure Do_Input_MMOD6L_Result(thSender: TAI_DNN_Thread_MMOD6L; UserData: Pointer; Input: TMemoryRaster; Output: TMMOD_Desc); virtual; procedure Do_Input_RNIC_Result(thSender: TAI_DNN_Thread_RNIC; UserData: Pointer; Input: TMemoryRaster; Output: TLVec); virtual; procedure Do_Input_LRNIC_Result(thSender: TAI_DNN_Thread_LRNIC; UserData: Pointer; Input: TMemoryRaster; Output: TLVec); virtual; procedure Do_Input_GDCNIC_Result(thSender: TAI_DNN_Thread_GDCNIC; UserData: Pointer; Input: TMemoryRaster; Output: TLVec); virtual; procedure Do_Input_GNIC_Result(thSender: TAI_DNN_Thread_GNIC; UserData: Pointer; Input: TMemoryRaster; Output: TLVec); virtual; procedure Do_Input_SS_Result(thSender: TAI_DNN_Thread_SS; UserData: Pointer; Input: TMemoryRaster; SSTokenOutput: TPascalStringList; Output: TMemoryRaster); virtual; procedure Do_Input_ZMetric_Result(thSender: TAI_DNN_Thread_ZMetric; UserData: Pointer; Input: TMemoryRaster; SS_Width, SS_Height: Integer; Output: TLVec); virtual; public constructor Create(Owner_: TRasterRecognitionData); destructor Destroy; override; property Owner: TRasterRecognitionData read FOwner; function Input_Passed(ID_: SystemString; UserData_: Pointer; Raster: TRaster; instance_: Boolean): TRasterRecognitionData_Passed; function Input_SP(ID_: SystemString; UserData_: Pointer; Raster: TRaster; instance_: Boolean; MMOD_Desc: TMMOD_Desc; Parallel_: TAI_Parallel): TRasterRecognitionData_SP; function Input_Metric(ID_: SystemString; UserData_: Pointer; Raster: TRaster; L: TLearn; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_Metric): TRasterRecognitionData_Metric; function Input_LMetric(ID_: SystemString; UserData_: Pointer; Raster: TRaster; L: TLearn; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_LMetric): TRasterRecognitionData_LMetric; function Input_MMOD3L(ID_: SystemString; UserData_: Pointer; Raster: TRaster; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_MMOD3L): TRasterRecognitionData_MMOD3L; function Input_MMOD6L(ID_: SystemString; UserData_: Pointer; Raster: TRaster; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_MMOD6L): TRasterRecognitionData_MMOD6L; function Input_RNIC(ID_: SystemString; UserData_: Pointer; Raster: TRaster; ClassifierIndex: TPascalStringList; num_crops: Integer; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_RNIC): TRasterRecognitionData_RNIC; function Input_LRNIC(ID_: SystemString; UserData_: Pointer; Raster: TRaster; ClassifierIndex: TPascalStringList; num_crops: Integer; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_LRNIC): TRasterRecognitionData_LRNIC; function Input_GDCNIC(ID_: SystemString; UserData_: Pointer; Raster: TRaster; ClassifierIndex: TPascalStringList; SS_Width, SS_Height: Integer; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_GDCNIC): TRasterRecognitionData_GDCNIC; function Input_GNIC(ID_: SystemString; UserData_: Pointer; Raster: TRaster; ClassifierIndex: TPascalStringList; SS_Width, SS_Height: Integer; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_GNIC): TRasterRecognitionData_GNIC; function Input_SS(ID_: SystemString; UserData_: Pointer; Raster: TRaster; ColorPool: TSegmentationColorTable; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_SS): TRasterRecognitionData_SS; function Input_ZMetric(ID_: SystemString; UserData_: Pointer; Raster: TRaster; L: TLearn; SS_Width, SS_Height: Integer; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_ZMetric): TRasterRecognitionData_ZMetric; function FindDNNThread(DNNThread: TAI_DNN_Thread): Integer; function BusyNum: Integer; function Busy: Boolean; overload; function Busy(bIndex, eIndex: Integer): Boolean; overload; function Delete(bIndex, eIndex: Integer): Boolean; procedure RemoveNullOutput; procedure GetQueueState(); function Count: Integer; function LockQueue: TRasterRecognitionDataList; procedure UnLockQueue; procedure Clean; procedure DelayCheckBusyAndFree; property CutNullQueue: Boolean read FCutNullQueue write FCutNullQueue; property MaxQueue: Integer read FMaxQueue write FMaxQueue; property SyncEvent: Boolean read FSyncEvent write FSyncEvent; property UserData: Pointer read FUserData write FUserData; property OnInput: TOnInput read FOnInput write FOnInput; property OnRecognitionDone: TOnRecognitionDone read FOnRecognitionDone write FOnRecognitionDone; property OnQueueDone: TOnQueueDone read FOnQueueDone write FOnQueueDone; property OnCutNullRec: TOnCutNullRec read FOnCutNullRec write FOnCutNullRec; property OnCutMaxLimit: TOnCutMaxLimit read FOnCutMaxLimit write FOnCutMaxLimit; end; implementation type TRasterRecognitionData_ = record Data: TRasterRecognitionData; end; TRasterRecognitionData_Ptr = ^TRasterRecognitionData_; function TRasterRecognitionData.DoGetState: SystemString; begin Result := PFormat('Done %s.', [ClassName]); end; function TRasterRecognitionData.DoGetShortName: SystemString; var n: U_String; begin n := ClassName; if n.Exists('_') then Result := umlGetLastStr(n, '_') else Result := 'Base'; end; constructor TRasterRecognitionData.Create(Owner_: TRasterInputQueue); begin inherited Create; FOwner := Owner_; FID := ''; FRaster := nil; FIDLE := False; FNullRec := True; FDNNThread := nil; FInputTime := 0; FDoneTime := 0; FState := ''; FNextLevel := nil; FUserData := nil; end; destructor TRasterRecognitionData.Destroy; begin if FNextLevel <> nil then FNextLevel.DelayCheckBusyAndFree; DisposeObjectAndNil(FRaster); inherited Destroy; end; procedure TRasterRecognitionData.SetDone; begin FIDLE := True; FDoneTime := GetTimeTick(); end; function TRasterRecognitionData.Busy(): Boolean; begin Result := Busy(True); end; function TRasterRecognitionData.Busy(checkNextLevel_: Boolean): Boolean; begin Result := True; if not FIDLE then exit; Result := (checkNextLevel_) and (FNextLevel <> nil) and (FNextLevel.Busy()); end; function TRasterRecognitionData.UsageTime: TTimeTick; begin if Busy then Result := 0 else Result := FDoneTime - FInputTime; end; function TRasterRecognitionData.GetStateInfo: SystemString; begin if FIDLE then begin if FState = '' then FState := DoGetState; Result := FState; end else Result := 'BUSY.' end; function TRasterRecognitionData.GetNextLevel: TRasterInputQueue; begin if FNextLevel = nil then FNextLevel := TRasterInputQueue.Create(Self); Result := FNextLevel; end; constructor TRasterRecognitionData_Passed.Create(Owner_: TRasterInputQueue); begin inherited Create(Owner_); end; destructor TRasterRecognitionData_Passed.Destroy; begin inherited Destroy; end; function TRasterRecognitionData_SP.DoGetState: SystemString; var i: Integer; begin Result := 'Done SP: '; for i := 0 to Length(SP_Desc) - 1 do Result := Result + PFormat('%s%d', [if_(i > 0, ',', ''), Length(SP_Desc[i])]); end; function TRasterRecognitionData_SP.DoGetShortName: SystemString; begin Result := 'SP'; end; constructor TRasterRecognitionData_SP.Create(Owner_: TRasterInputQueue); begin inherited Create(Owner_); Parallel_ := nil; SetLength(SP_Desc, 0, 0); SetLength(MMOD_Desc, 0); FaceRasterList := TMemoryRasterList.Create; FaceRasterList.AutoFreeRaster := True; end; destructor TRasterRecognitionData_SP.Destroy; begin SetLength(SP_Desc, 0, 0); SetLength(MMOD_Desc, 0); DisposeObject(FaceRasterList); inherited Destroy; end; function TRasterRecognitionData_Metric.DoGetState: SystemString; var i: Integer; k: TLFloat; begin Result := inherited DoGetState; if L = nil then exit; i := L.ProcessMaxIndex(Output); k := LDistance(Output, L[i]^.m_in); Result := PFormat('Done Metric %s:%f', [L[i]^.token.Text, k]); end; function TRasterRecognitionData_Metric.DoGetShortName: SystemString; begin Result := 'Metric'; end; constructor TRasterRecognitionData_Metric.Create(Owner_: TRasterInputQueue); begin inherited Create(Owner_); SetLength(Output, 0); L := nil; end; destructor TRasterRecognitionData_Metric.Destroy; begin SetLength(Output, 0); inherited Destroy; end; function TRasterRecognitionData_LMetric.DoGetState: SystemString; var i: Integer; k: TLFloat; begin Result := inherited DoGetState; if L = nil then exit; i := L.ProcessMaxIndex(Output); k := LDistance(Output, L[i]^.m_in); Result := PFormat('Done LMetric %s:%f', [L[i]^.token.Text, k]); end; function TRasterRecognitionData_LMetric.DoGetShortName: SystemString; begin Result := 'LMetric'; end; constructor TRasterRecognitionData_LMetric.Create(Owner_: TRasterInputQueue); begin inherited Create(Owner_); SetLength(Output, 0); L := nil; end; destructor TRasterRecognitionData_LMetric.Destroy; begin SetLength(Output, 0); inherited Destroy; end; function TRasterRecognitionData_MMOD6L.DoGetState: SystemString; begin Result := PFormat('Done MMOD6L: %d', [Length(Output)]); end; function TRasterRecognitionData_MMOD6L.DoGetShortName: SystemString; begin Result := 'MMOD6L'; end; constructor TRasterRecognitionData_MMOD6L.Create(Owner_: TRasterInputQueue); begin inherited Create(Owner_); SetLength(Output, 0); end; destructor TRasterRecognitionData_MMOD6L.Destroy; begin SetLength(Output, 0); inherited Destroy; end; function TRasterRecognitionData_MMOD3L.DoGetState: SystemString; begin Result := PFormat('Done MMOD3L: %d', [Length(Output)]); end; function TRasterRecognitionData_MMOD3L.DoGetShortName: SystemString; begin Result := 'MMOD3L'; end; constructor TRasterRecognitionData_MMOD3L.Create(Owner_: TRasterInputQueue); begin inherited Create(Owner_); SetLength(Output, 0); end; destructor TRasterRecognitionData_MMOD3L.Destroy; begin SetLength(Output, 0); inherited Destroy; end; function TRasterRecognitionData_RNIC.DoGetState: SystemString; var i, j: Integer; v: TLVec; begin Result := 'Done RNIC.'; v := LVecCopy(Output); for i := 0 to umlMin(ClassifierIndex.Count - 1, 4) do begin j := LMaxVecIndex(v); if j < ClassifierIndex.Count then Result := Result + #13#10 + PFormat('%s=%f', [ClassifierIndex[j].Text, v[j]]); v[j] := 0; end; end; function TRasterRecognitionData_RNIC.DoGetShortName: SystemString; begin Result := 'RNIC'; end; constructor TRasterRecognitionData_RNIC.Create(Owner_: TRasterInputQueue); begin inherited Create(Owner_); SetLength(Output, 0); ClassifierIndex := nil; end; destructor TRasterRecognitionData_RNIC.Destroy; begin SetLength(Output, 0); inherited Destroy; end; function TRasterRecognitionData_LRNIC.DoGetState: SystemString; var i, j: Integer; v: TLVec; begin Result := 'Done LRNIC.'; v := LVecCopy(Output); for i := 0 to umlMin(ClassifierIndex.Count - 1, 4) do begin j := LMaxVecIndex(v); if j < ClassifierIndex.Count then Result := Result + #13#10 + PFormat('%s=%f', [ClassifierIndex[j].Text, v[j]]); v[j] := 0; end; end; function TRasterRecognitionData_LRNIC.DoGetShortName: SystemString; begin Result := 'LRNIC'; end; constructor TRasterRecognitionData_LRNIC.Create(Owner_: TRasterInputQueue); begin inherited Create(Owner_); SetLength(Output, 0); ClassifierIndex := nil; end; destructor TRasterRecognitionData_LRNIC.Destroy; begin SetLength(Output, 0); inherited Destroy; end; function TRasterRecognitionData_GDCNIC.DoGetState: SystemString; var i, j: Integer; v: TLVec; begin Result := 'Done GDCNIC.'; v := LVecCopy(Output); for i := 0 to umlMin(ClassifierIndex.Count - 1, 4) do begin j := LMaxVecIndex(v); if j < ClassifierIndex.Count then Result := Result + #13#10 + PFormat('%s=%f', [ClassifierIndex[j].Text, v[j]]); v[j] := 0; end; end; function TRasterRecognitionData_GDCNIC.DoGetShortName: SystemString; begin Result := 'GDCNIC'; end; constructor TRasterRecognitionData_GDCNIC.Create(Owner_: TRasterInputQueue); begin inherited Create(Owner_); SetLength(Output, 0); ClassifierIndex := nil; end; destructor TRasterRecognitionData_GDCNIC.Destroy; begin SetLength(Output, 0); inherited Destroy; end; function TRasterRecognitionData_GNIC.DoGetState: SystemString; var i, j: Integer; v: TLVec; begin Result := 'Done GNIC.'; v := LVecCopy(Output); for i := 0 to umlMin(ClassifierIndex.Count - 1, 4) do begin j := LMaxVecIndex(v); if j < ClassifierIndex.Count then Result := Result + #13#10 + PFormat('%s=%f', [ClassifierIndex[j].Text, v[j]]); v[j] := 0; end; end; function TRasterRecognitionData_GNIC.DoGetShortName: SystemString; begin Result := 'GNIC'; end; constructor TRasterRecognitionData_GNIC.Create(Owner_: TRasterInputQueue); begin inherited Create(Owner_); SetLength(Output, 0); ClassifierIndex := nil; end; destructor TRasterRecognitionData_GNIC.Destroy; begin SetLength(Output, 0); inherited Destroy; end; function TRasterRecognitionData_SS.DoGetState: SystemString; var i: Integer; begin Result := 'Done SS.'; for i := 0 to umlMin(SSTokenOutput.Count - 1, 4) do Result := Result + #13#10 + PFormat('found: %s', [SSTokenOutput[i].Text]); end; function TRasterRecognitionData_SS.DoGetShortName: SystemString; begin Result := 'SS'; end; constructor TRasterRecognitionData_SS.Create(Owner_: TRasterInputQueue); begin inherited Create(Owner_); Output := NewRaster(); SSTokenOutput := TPascalStringList.Create; ColorPool := nil; end; destructor TRasterRecognitionData_SS.Destroy; begin DisposeObject(Output); DisposeObject(SSTokenOutput); inherited Destroy; end; function TRasterRecognitionData_ZMetric.DoGetState: SystemString; var i: Integer; k: TLFloat; begin Result := inherited DoGetState; if L = nil then exit; i := L.ProcessMaxIndex(Output); k := LDistance(Output, L[i]^.m_in); Result := PFormat('Done Z-Metric %s:%f', [L[i]^.token.Text, k]); end; function TRasterRecognitionData_ZMetric.DoGetShortName: SystemString; begin Result := 'ZMetric'; end; constructor TRasterRecognitionData_ZMetric.Create(Owner_: TRasterInputQueue); begin inherited Create(Owner_); SetLength(Output, 0); L := nil; SS_Width := 0; SS_Height := 0; end; destructor TRasterRecognitionData_ZMetric.Destroy; begin SetLength(Output, 0); inherited Destroy; end; procedure TRasterInputQueue.DoDelayCheckBusyAndFree; begin while (FRunning > 0) or (Busy) do TCompute.Sleep(10); DisposeObject(Self); end; function TRasterInputQueue.BeforeInput(ID_: SystemString; UserData_: Pointer; Raster: TRaster; instance_: Boolean; dataClass: TRasterRecognitionDataClass): TRasterRecognitionData; var RD: TRasterRecognitionData; begin RD := dataClass.Create(Self); if instance_ then RD.FRaster := Raster else RD.FRaster := Raster.Clone; RD.FID := ID_; RD.FInputTime := GetTimeTick(); RD.FDoneTime := RD.FInputTime; RD.UserData := UserData_; FCritical.Lock; FQueue.Add(RD); FCritical.UnLock; try if Assigned(FOnInput) then FOnInput(Self, RD.FRaster); except end; Result := RD; end; procedure TRasterInputQueue.Sync_DoFinish(Data1: Pointer; Data2: TCoreClassObject; Data3: Variant); var RD: TRasterRecognitionData; RecSuccessed: Boolean; begin RD := TRasterRecognitionData(Data2); RecSuccessed := Data3; RD.FNullRec := not RecSuccessed; try if Assigned(FOnRecognitionDone) then FOnRecognitionDone(Self, RD); except end; RD.SetDone; DoCheckDone(RD); AtomDec(FRunning); end; procedure TRasterInputQueue.DoCheckDone(RD: TRasterRecognitionData); var i: Integer; begin if RD.Busy then exit; if (not Busy) then begin if FOwner <> nil then if FOwner.FOwner <> nil then FOwner.FOwner.DoCheckDone(FOwner); try if Assigned(FOnQueueDone) then FOnQueueDone(Self); except end; end; if (FMaxQueue > 0) and (Count > FMaxQueue) then begin if not Busy(0, Count - FMaxQueue) then begin try if Assigned(FOnCutMaxLimit) then FOnCutMaxLimit(Self, 0, Count - FMaxQueue); except end; Delete(0, Count - FMaxQueue); end; end; if (RD.FNullRec) and (FCutNullQueue) then begin FCritical.Lock; i := FQueue.IndexOf(RD); FCritical.UnLock; if i >= 0 then if not Busy(0, i) then begin try if Assigned(FOnCutNullRec) then FOnCutNullRec(Self, 0, i); except end; Delete(0, i); end; end; end; procedure TRasterInputQueue.DoFinish(RD: TRasterRecognitionData; RecSuccessed: Boolean); begin if RD.FOwner <> Self then exit; AtomInc(FRunning); if FSyncEvent then TCompute.PostM3(nil, RD, RecSuccessed, {$IFDEF FPC}@{$ENDIF FPC}Sync_DoFinish) else Sync_DoFinish(nil, RD, RecSuccessed); end; procedure TRasterInputQueue.DoRunSP(thSender: TCompute); var p: TRasterRecognitionData_Ptr; spData: TRasterRecognitionData_SP; AI: TAI; rgbHnd: TRGB_Image_Handle; i: Integer; faceHnd: TFACE_Handle; Successed_: Boolean; begin p := thSender.UserData; spData := TRasterRecognitionData_SP(p^.Data); Successed_ := False; AI := spData.Parallel_.GetAndLockAI(); if spData.Parallel_.InternalFaceSP then begin faceHnd := AI.Face_Detector(p^.Data.Raster, spData.MMOD_Desc, C_Metric_Input_Size); Successed_ := faceHnd <> nil; if Successed_ then for i := 0 to AI.Face_chips_num(faceHnd) - 1 do begin spData.SP_Desc[i] := AI.Face_ShapeV2(faceHnd, i); spData.FaceRasterList.Add(AI.Face_chips(faceHnd, i)); end; end else begin rgbHnd := AI.Prepare_RGB_Image(p^.Data.Raster); for i := 0 to Length(spData.MMOD_Desc) - 1 do spData.SP_Desc[i] := AI.SP_ProcessRGB_Vec2(AI.Parallel_SP_Hnd, rgbHnd, spData.MMOD_Desc[i].R); AI.Close_RGB_Image(rgbHnd); Successed_ := True; end; spData.Parallel_.UnLockAI(AI); DoFinish(p^.Data, Successed_); Dispose(p); end; procedure TRasterInputQueue.Do_Input_Metric_Result(thSender: TAI_DNN_Thread_Metric; UserData: Pointer; Input: TMemoryRaster; Output: TLVec); var p: TRasterRecognitionData_Ptr; begin p := UserData; TRasterRecognitionData_Metric(p^.Data).Output := LVecCopy(Output); DoFinish(p^.Data, True); Dispose(p); end; procedure TRasterInputQueue.Do_Input_LMetric_Result(thSender: TAI_DNN_Thread_LMetric; UserData: Pointer; Input: TMemoryRaster; Output: TLVec); var p: TRasterRecognitionData_Ptr; begin p := UserData; TRasterRecognitionData_LMetric(p^.Data).Output := LVecCopy(Output); DoFinish(p^.Data, True); Dispose(p); end; procedure TRasterInputQueue.Do_Input_MMOD3L_Result(thSender: TAI_DNN_Thread_MMOD3L; UserData: Pointer; Input: TMemoryRaster; Output: TMMOD_Desc); var p: TRasterRecognitionData_Ptr; i: Integer; begin p := UserData; SetLength(TRasterRecognitionData_MMOD3L(p^.Data).Output, Length(Output)); for i := 0 to Length(Output) - 1 do TRasterRecognitionData_MMOD3L(p^.Data).Output[i] := Output[i]; DoFinish(p^.Data, Length(Output) > 0); Dispose(p); end; procedure TRasterInputQueue.Do_Input_MMOD6L_Result(thSender: TAI_DNN_Thread_MMOD6L; UserData: Pointer; Input: TMemoryRaster; Output: TMMOD_Desc); var p: TRasterRecognitionData_Ptr; i: Integer; begin p := UserData; SetLength(TRasterRecognitionData_MMOD6L(p^.Data).Output, Length(Output)); for i := 0 to Length(Output) - 1 do TRasterRecognitionData_MMOD6L(p^.Data).Output[i] := Output[i]; DoFinish(p^.Data, Length(Output) > 0); Dispose(p); end; procedure TRasterInputQueue.Do_Input_RNIC_Result(thSender: TAI_DNN_Thread_RNIC; UserData: Pointer; Input: TMemoryRaster; Output: TLVec); var p: TRasterRecognitionData_Ptr; begin p := UserData; TRasterRecognitionData_RNIC(p^.Data).Output := LVecCopy(Output); DoFinish(p^.Data, True); Dispose(p); end; procedure TRasterInputQueue.Do_Input_LRNIC_Result(thSender: TAI_DNN_Thread_LRNIC; UserData: Pointer; Input: TMemoryRaster; Output: TLVec); var p: TRasterRecognitionData_Ptr; begin p := UserData; TRasterRecognitionData_LRNIC(p^.Data).Output := LVecCopy(Output); DoFinish(p^.Data, True); Dispose(p); end; procedure TRasterInputQueue.Do_Input_GDCNIC_Result(thSender: TAI_DNN_Thread_GDCNIC; UserData: Pointer; Input: TMemoryRaster; Output: TLVec); var p: TRasterRecognitionData_Ptr; begin p := UserData; TRasterRecognitionData_GDCNIC(p^.Data).Output := LVecCopy(Output); DoFinish(p^.Data, True); Dispose(p); end; procedure TRasterInputQueue.Do_Input_GNIC_Result(thSender: TAI_DNN_Thread_GNIC; UserData: Pointer; Input: TMemoryRaster; Output: TLVec); var p: TRasterRecognitionData_Ptr; begin p := UserData; TRasterRecognitionData_GNIC(p^.Data).Output := LVecCopy(Output); DoFinish(p^.Data, True); Dispose(p); end; procedure TRasterInputQueue.Do_Input_SS_Result(thSender: TAI_DNN_Thread_SS; UserData: Pointer; Input: TMemoryRaster; SSTokenOutput: TPascalStringList; Output: TMemoryRaster); var p: TRasterRecognitionData_Ptr; begin p := UserData; TRasterRecognitionData_SS(p^.Data).Output.SwapInstance(Output); TRasterRecognitionData_SS(p^.Data).SSTokenOutput.Assign(SSTokenOutput); DoFinish(p^.Data, SSTokenOutput.Count > 0); Dispose(p); end; procedure TRasterInputQueue.Do_Input_ZMetric_Result(thSender: TAI_DNN_Thread_ZMetric; UserData: Pointer; Input: TMemoryRaster; SS_Width, SS_Height: Integer; Output: TLVec); var p: TRasterRecognitionData_Ptr; begin p := UserData; TRasterRecognitionData_ZMetric(p^.Data).Output := LVecCopy(Output); TRasterRecognitionData_ZMetric(p^.Data).SS_Width := SS_Width; TRasterRecognitionData_ZMetric(p^.Data).SS_Height := SS_Height; DoFinish(p^.Data, True); Dispose(p); end; constructor TRasterInputQueue.Create(Owner_: TRasterRecognitionData); begin inherited Create; FRunning := 0; FOwner := Owner_; FQueue := TRasterRecognitionDataList.Create; FCritical := TCritical.Create; FCutNullQueue := False; FMaxQueue := 0; FSyncEvent := False; FUserData := nil; FOnInput := nil; FOnRecognitionDone := nil; FOnQueueDone := nil; FOnCutNullRec := nil; FOnCutMaxLimit := nil; end; destructor TRasterInputQueue.Destroy; begin Clean; DisposeObject(FQueue); FCritical.Free; inherited Destroy; end; function TRasterInputQueue.Input_Passed(ID_: SystemString; UserData_: Pointer; Raster: TRaster; instance_: Boolean): TRasterRecognitionData_Passed; begin Result := BeforeInput(ID_, UserData_, Raster, instance_, TRasterRecognitionData_Passed) as TRasterRecognitionData_Passed; DoFinish(Result, True); end; function TRasterInputQueue.Input_SP(ID_: SystemString; UserData_: Pointer; Raster: TRaster; instance_: Boolean; MMOD_Desc: TMMOD_Desc; Parallel_: TAI_Parallel): TRasterRecognitionData_SP; var p: TRasterRecognitionData_Ptr; i: Integer; begin if Parallel_ = nil then begin Result := nil; exit; end; Result := BeforeInput(ID_, UserData_, Raster, instance_, TRasterRecognitionData_SP) as TRasterRecognitionData_SP; SetLength(Result.SP_Desc, Length(MMOD_Desc)); SetLength(Result.MMOD_Desc, Length(MMOD_Desc)); for i := 0 to Length(MMOD_Desc) - 1 do Result.MMOD_Desc[i] := MMOD_Desc[i]; Result.Parallel_ := Parallel_; New(p); p^.Data := Result; TCompute.RunM(p, Result, {$IFDEF FPC}@{$ENDIF FPC}DoRunSP); end; function TRasterInputQueue.Input_Metric(ID_: SystemString; UserData_: Pointer; Raster: TRaster; L: TLearn; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_Metric): TRasterRecognitionData_Metric; var p: TRasterRecognitionData_Ptr; begin if NoQueue_ and (FindDNNThread(DNNThread) > 0) then begin // skip this raster if instance_ then DisposeObject(Raster); Result := nil; exit; end; Result := BeforeInput(ID_, UserData_, Raster, instance_, TRasterRecognitionData_Metric) as TRasterRecognitionData_Metric; Result.L := L; New(p); p^.Data := Result; DNNThread.ProcessM(p, Result.Raster, False, {$IFDEF FPC}@{$ENDIF FPC}Do_Input_Metric_Result); end; function TRasterInputQueue.Input_LMetric(ID_: SystemString; UserData_: Pointer; Raster: TRaster; L: TLearn; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_LMetric): TRasterRecognitionData_LMetric; var p: TRasterRecognitionData_Ptr; begin if NoQueue_ and (FindDNNThread(DNNThread) > 0) then begin // skip this raster if instance_ then DisposeObject(Raster); Result := nil; exit; end; Result := BeforeInput(ID_, UserData_, Raster, instance_, TRasterRecognitionData_LMetric) as TRasterRecognitionData_LMetric; Result.L := L; New(p); p^.Data := Result; DNNThread.ProcessM(p, Result.Raster, False, {$IFDEF FPC}@{$ENDIF FPC}Do_Input_LMetric_Result); end; function TRasterInputQueue.Input_MMOD3L(ID_: SystemString; UserData_: Pointer; Raster: TRaster; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_MMOD3L): TRasterRecognitionData_MMOD3L; var p: TRasterRecognitionData_Ptr; begin if NoQueue_ and (FindDNNThread(DNNThread) > 0) then begin // skip this raster if instance_ then DisposeObject(Raster); Result := nil; exit; end; Result := BeforeInput(ID_, UserData_, Raster, instance_, TRasterRecognitionData_MMOD3L) as TRasterRecognitionData_MMOD3L; New(p); p^.Data := Result; DNNThread.ProcessM(p, Result.Raster, False, {$IFDEF FPC}@{$ENDIF FPC}Do_Input_MMOD3L_Result); end; function TRasterInputQueue.Input_MMOD6L(ID_: SystemString; UserData_: Pointer; Raster: TRaster; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_MMOD6L): TRasterRecognitionData_MMOD6L; var p: TRasterRecognitionData_Ptr; begin if NoQueue_ and (FindDNNThread(DNNThread) > 0) then begin // skip this raster if instance_ then DisposeObject(Raster); Result := nil; exit; end; Result := BeforeInput(ID_, UserData_, Raster, instance_, TRasterRecognitionData_MMOD6L) as TRasterRecognitionData_MMOD6L; New(p); p^.Data := Result; DNNThread.ProcessM(p, Result.Raster, False, {$IFDEF FPC}@{$ENDIF FPC}Do_Input_MMOD6L_Result); end; function TRasterInputQueue.Input_RNIC(ID_: SystemString; UserData_: Pointer; Raster: TRaster; ClassifierIndex: TPascalStringList; num_crops: Integer; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_RNIC): TRasterRecognitionData_RNIC; var p: TRasterRecognitionData_Ptr; begin if NoQueue_ and (FindDNNThread(DNNThread) > 0) then begin // skip this raster if instance_ then DisposeObject(Raster); Result := nil; exit; end; Result := BeforeInput(ID_, UserData_, Raster, instance_, TRasterRecognitionData_RNIC) as TRasterRecognitionData_RNIC; Result.ClassifierIndex := ClassifierIndex; New(p); p^.Data := Result; DNNThread.ProcessM(p, Result.Raster, num_crops, False, {$IFDEF FPC}@{$ENDIF FPC}Do_Input_RNIC_Result); end; function TRasterInputQueue.Input_LRNIC(ID_: SystemString; UserData_: Pointer; Raster: TRaster; ClassifierIndex: TPascalStringList; num_crops: Integer; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_LRNIC): TRasterRecognitionData_LRNIC; var p: TRasterRecognitionData_Ptr; begin if NoQueue_ and (FindDNNThread(DNNThread) > 0) then begin // skip this raster if instance_ then DisposeObject(Raster); Result := nil; exit; end; Result := BeforeInput(ID_, UserData_, Raster, instance_, TRasterRecognitionData_LRNIC) as TRasterRecognitionData_LRNIC; Result.ClassifierIndex := ClassifierIndex; New(p); p^.Data := Result; DNNThread.ProcessM(p, Result.Raster, num_crops, False, {$IFDEF FPC}@{$ENDIF FPC}Do_Input_LRNIC_Result); end; function TRasterInputQueue.Input_GDCNIC(ID_: SystemString; UserData_: Pointer; Raster: TRaster; ClassifierIndex: TPascalStringList; SS_Width, SS_Height: Integer; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_GDCNIC): TRasterRecognitionData_GDCNIC; var p: TRasterRecognitionData_Ptr; begin if NoQueue_ and (FindDNNThread(DNNThread) > 0) then begin // skip this raster if instance_ then DisposeObject(Raster); Result := nil; exit; end; Result := BeforeInput(ID_, UserData_, Raster, instance_, TRasterRecognitionData_GDCNIC) as TRasterRecognitionData_GDCNIC; Result.ClassifierIndex := ClassifierIndex; New(p); p^.Data := Result; DNNThread.ProcessM(p, Result.Raster, SS_Width, SS_Height, False, {$IFDEF FPC}@{$ENDIF FPC}Do_Input_GDCNIC_Result); end; function TRasterInputQueue.Input_GNIC(ID_: SystemString; UserData_: Pointer; Raster: TRaster; ClassifierIndex: TPascalStringList; SS_Width, SS_Height: Integer; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_GNIC): TRasterRecognitionData_GNIC; var p: TRasterRecognitionData_Ptr; begin if NoQueue_ and (FindDNNThread(DNNThread) > 0) then begin // skip this raster if instance_ then DisposeObject(Raster); Result := nil; exit; end; Result := BeforeInput(ID_, UserData_, Raster, instance_, TRasterRecognitionData_GNIC) as TRasterRecognitionData_GNIC; Result.ClassifierIndex := ClassifierIndex; New(p); p^.Data := Result; DNNThread.ProcessM(p, Result.Raster, SS_Width, SS_Height, False, {$IFDEF FPC}@{$ENDIF FPC}Do_Input_GNIC_Result); end; function TRasterInputQueue.Input_SS(ID_: SystemString; UserData_: Pointer; Raster: TRaster; ColorPool: TSegmentationColorTable; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_SS): TRasterRecognitionData_SS; var p: TRasterRecognitionData_Ptr; begin if NoQueue_ and (FindDNNThread(DNNThread) > 0) then begin // skip this raster if instance_ then DisposeObject(Raster); Result := nil; exit; end; Result := BeforeInput(ID_, UserData_, Raster, instance_, TRasterRecognitionData_SS) as TRasterRecognitionData_SS; Result.ColorPool := ColorPool; New(p); p^.Data := Result; DNNThread.ProcessM(p, Result.Raster, ColorPool, False, {$IFDEF FPC}@{$ENDIF FPC}Do_Input_SS_Result); end; function TRasterInputQueue.Input_ZMetric(ID_: SystemString; UserData_: Pointer; Raster: TRaster; L: TLearn; SS_Width, SS_Height: Integer; instance_, NoQueue_: Boolean; DNNThread: TAI_DNN_Thread_ZMetric): TRasterRecognitionData_ZMetric; var p: TRasterRecognitionData_Ptr; begin if NoQueue_ and (FindDNNThread(DNNThread) > 0) then begin // skip this raster if instance_ then DisposeObject(Raster); Result := nil; exit; end; Result := BeforeInput(ID_, UserData_, Raster, instance_, TRasterRecognitionData_ZMetric) as TRasterRecognitionData_ZMetric; Result.L := L; New(p); p^.Data := Result; DNNThread.ProcessM(p, Result.Raster, SS_Width, SS_Height, False, {$IFDEF FPC}@{$ENDIF FPC}Do_Input_ZMetric_Result); end; function TRasterInputQueue.FindDNNThread(DNNThread: TAI_DNN_Thread): Integer; var i: Integer; begin FCritical.Lock; Result := 0; for i := 0 to FQueue.Count - 1 do if FQueue[i].FDNNThread = DNNThread then inc(Result); FCritical.UnLock; end; function TRasterInputQueue.BusyNum: Integer; var i: Integer; begin Result := 0; FCritical.Lock; for i := 0 to FQueue.Count - 1 do if FQueue[i].Busy() then inc(Result); FCritical.UnLock; end; function TRasterInputQueue.Busy: Boolean; begin Result := Busy(0, FQueue.Count - 1); end; function TRasterInputQueue.Busy(bIndex, eIndex: Integer): Boolean; var i: Integer; begin FCritical.Lock; Result := False; for i := umlMax(0, bIndex) to umlMin(FQueue.Count - 1, eIndex) do Result := Result or FQueue[i].Busy(); FCritical.UnLock; end; function TRasterInputQueue.Delete(bIndex, eIndex: Integer): Boolean; var i, j: Integer; RD: TRasterRecognitionData; begin Result := False; if not Busy(bIndex, eIndex) then begin FCritical.Lock; for i := umlMax(0, bIndex) to umlMin(FQueue.Count - 1, eIndex) do begin RD := FQueue[bIndex]; DisposeObject(RD); FQueue.Delete(bIndex); end; FCritical.UnLock; Result := True; end; end; procedure TRasterInputQueue.RemoveNullOutput; var i, j: Integer; RD: TRasterRecognitionData; begin FCritical.Lock; i := 0; while i < FQueue.Count do begin RD := FQueue[i]; if (not RD.Busy) then begin DisposeObject(RD); FQueue.Delete(i); end else inc(i); end; FCritical.UnLock; end; procedure TRasterInputQueue.GetQueueState(); var i, j: Integer; RD: TRasterRecognitionData; begin FCritical.Lock; for i := 0 to FQueue.Count - 1 do begin RD := FQueue[i]; if RD.Busy then begin end else begin end; end; FCritical.UnLock; end; function TRasterInputQueue.Count: Integer; begin Result := FQueue.Count; end; function TRasterInputQueue.LockQueue: TRasterRecognitionDataList; begin FCritical.Lock; Result := FQueue; end; procedure TRasterInputQueue.UnLockQueue; begin FCritical.UnLock; end; procedure TRasterInputQueue.Clean; var i, j: Integer; RD: TRasterRecognitionData; begin while Busy do TCompute.Sleep(1); FCritical.Lock; for i := 0 to FQueue.Count - 1 do begin RD := FQueue[i]; DisposeObject(RD); end; FQueue.Clear; FCritical.UnLock; end; procedure TRasterInputQueue.DelayCheckBusyAndFree; begin TCompute.RunM_NP({$IFDEF FPC}@{$ENDIF FPC}DoDelayCheckBusyAndFree); end; end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 16384,0,0} { by Behdad Esfahbod Algorithmic Problems Book April '2000 Problem 170 O(N4) Matching Method FordFulkerson Alg. } program UglyMatrix; const MaxN = 100; type TM = array [1 .. MaxN] of Integer; var N, M : Integer; G : array [1 .. MaxN, 1 .. MaxN] of Integer; Mt : array [1 .. 2] of TM; Ans : array [1 .. MaxN] of TM; Mark : array [0 .. MaxN] of Boolean; I, J, K : Integer; procedure ReadInput; begin Assign(Input, 'input.txt'); Reset(Input); Readln(N, M); for I := 1 to N do begin for J := 1 to M do begin Read(K); Inc(G[J, K]); end; Readln; end; Close(Input); end; procedure WriteOutput; begin Assign(Output, 'output.txt'); Rewrite(Output); for I := 1 to N do begin for J := 1 to M do Write(Ans[I, J], ' '); Writeln; end; Close(Output); end; function Dfs (V : Integer) : Boolean; var I : Integer; begin if V = 0 then begin Dfs := True; Exit; end; Mark[V] := True; for I := 1 to M do if (G[V, I] <> 0) and not Mark[Mt[2, I]] and Dfs(Mt[2, I]) then begin Dfs := True; Mt[2, I] := V; Mt[1, V] := I; Exit; end; Dfs := False; end; procedure Matching; var I : Integer; begin FillChar(Mark, SizeOf(Mark), 0); FillChar(Mt, SizeOf(Mt), 0); for I := 1 to M do if (Mt[1, I] = 0) and Dfs(I) then begin FillChar(Mark, SizeOf(Mark), 0); I := 0; end; end; procedure BipartiteEdgeColor; begin for I := 1 to N do begin Matching; Ans[I] := Mt[1]; for J := 1 to M do Dec(G[J, Mt[1, J]]); end; end; begin ReadInput; BipartiteEdgeColor; WriteOutput; end.
unit cEstoque; interface type Estoque = class (TObject) protected codEstq : integer; qtdPesoEstqAtual : real; qtdPesoEstqAntg : real; qtdUnitEstqAtual : integer; qtdUnitEstqAntg : integer; qtdMinEstq : integer; public Constructor Create (codEstq:integer; qtdPesoEstqAtual:real; qtdPesoEstqAntg:real; qtdUnitEstqAtual:integer; qtdUnitEstqAntg:integer; qtdMinEstq:integer); Procedure setcodestq (codEstq : integer); Function getcodEstq:integer; Procedure setqtdPesoEstqAtual (qtdPesoEstqAtual : real); Function getqtdPesoEstqAtual:real; Procedure setqtdPesoEstqAntg (qtdPesoEstqAntg : real); Function getqtdPesoEstqAntg:real; Procedure setqtdUnitestqAtual (qtdUnitestqAtual : integer); Function getqtdunitEstqAtual:integer; Procedure setqtdUnitEstqAntg (qtdUnitEstqAntg : integer); Function getqtdUnitEstqAntg:integer; Procedure setqtdMinEstq(qtdMinEstq : integer); Function getqtdMinEstq:integer; end; implementation Constructor Estoque.Create(codEstq:integer; qtdPesoEstqAtual:real; qtdPesoEstqAntg:real; qtdUnitEstqAtual:integer; qtdUnitEstqAntg:integer; qtdMinEstq:integer); begin self.codEstq := codestq; self.qtdPesoEstqAtual := qtdPesoEstqAtual; self.qtdPesoEstqAntg := qtdPesoEstqAntg; self.qtdUnitEstqAtual := qtdUnitEstqAtual; self.qtdUnitEstqAntg := qtdUnitEstqAntg; self.qtdMinEstq := qtdMinEstq; end; Procedure Estoque.setcodestq(codestq:integer); begin self.codEstq := codestq; end; Function Estoque.getcodEstq:integer; begin result := codestq; end; Procedure Estoque.setqtdPesoEstqAtual(qtdPesoEstqAtual:real); begin self.qtdPesoEstqAtual := qtdPesoEstqAtual; end; Function Estoque.getqtdPesoEstqAtual:real; begin result := qtdPesoEstqAtual; end; Procedure Estoque.setqtdPesoEstqAntg(qtdPesoEstqAntg:real); begin self.qtdPesoEstqAntg := qtdPesoEstqAntg; end; Function Estoque.getqtdPesoEstqAntg:real; begin result := qtdPesoEstqAntg; end; Procedure Estoque.setqtdUnitEstqAtual(qtdUnitEstqAtual:integer); begin self.qtdUnitEstqAtual := qtdUnitEstqAtual; end; Function Estoque.getqtdunitEstqAtual:integer; begin result := qtdUnitEstqAtual; end; Procedure Estoque.setqtdUnitEstqAntg(qtdUnitEstqAntg:integer); begin self.qtdUnitEstqAntg := qtdUnitEstqAntg; end; Function Estoque.getqtdUnitEstqAntg:integer; begin result := qtdUnitEstqAntg; end; Procedure Estoque.setqtdMinEstq(qtdMinEstq:integer); begin self.qtdMinEstq := qtdMinEstq; end; Function Estoque.getqtdMinEstq:integer; begin result := qtdMinEstq; end; end.
{*********************************************} { TeeGrid Software Library } { FMX TScrollable control } { Copyright (c) 2016 by Steema Software } { All Rights Reserved } {*********************************************} unit FMXTee.Control; {$I Tee.inc} interface uses System.Classes, {$IF CompilerVersion>24} FMX.StdCtrls, {$IFEND} FMX.Types, FMX.Controls; type TScrollBars=class(TPersistent) private FHorizontal: TScrollBar; FVertical: TScrollBar; function Calc(const Horiz:Boolean; const AValue:Single):Single; public Constructor Create(const AParent:TControl); Destructor Destroy; override; procedure Reset(const W,H,AWidth,AHeight:Single); published property Horizontal:TScrollBar read FHorizontal; property Vertical:TScrollBar read FVertical; end; TScrollableControl=class(TStyledControl) private FScrollBars : TScrollBars; procedure DoHorizScroll(Sender:TObject); procedure DoVertScroll(Sender:TObject); protected function GetMaxBottom:Single; virtual; abstract; function GetMaxRight:Single; virtual; abstract; function RemainSize(const Horizontal:Boolean):Single; procedure SetScrollX(const Value:Single); virtual; abstract; procedure SetScrollY(const Value:Single); virtual; abstract; public Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; property ScrollBars:TScrollBars read FScrollBars; end; implementation
program AWSCustomRuntime; {$mode objfpc}{$H+} uses sysutils, classes, fphttpclient, fpjson, jsonparser; var awsHost, awsBaseUrl, awsResponseUrl, awsErrorUrl, awsRequestId, awsEventBody: String; httpClient: TFPHTTPClient; awsEvent, awsError: TJSONObject; const // Current AWS runtime API version APIVERSION = '2018-06-01'; begin awsEvent := TJSONObject.Create; awsError := TJSONObject.Create; httpClient := TFPHttpClient.Create(Nil); try // Get the runtime api awsHost awsHost := GetEnvironmentVariable('AWS_LAMBDA_RUNTIME_API'); // Create the base url awsBaseUrl := 'http://' + awsHost + '/' + APIVERSION + '/runtime/invocation/'; while true do begin try // Get the event awsEventBody := httpClient.get(awsBaseUrl + 'next'); // Get the JSON data and set the TJSONObject awsEvent := TJSONObject(GetJSON(awsEventBody)); // Pretty-print the event (Should be visible in logwatch) WriteLn(awsEvent.FormatJSON); // Get the request id, used when responding awsRequestId := trim(httpClient.ResponseHeaders.Values['Lambda-Runtime-AWS-Request-Id']); // Create the response url awsResponseUrl := awsBaseUrl + awsRequestId + '/response'; // Create error url awsErrorUrl := awsBaseUrl + awsRequestId + '/error'; // Send successful event response TFPHttpClient.SimpleFormPost(awsResponseUrl, awsEventBody); { Error responses should follow the JSON format below, see here for details https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html#runtimes-api-invokeerror Example ------- awsError.Strings['errorMessage'] := 'Something went horribly wrong'; awsError.Strings['errorType'] := 'InvalidEventDataException'; TFPHttpClient.SimpleFormPost(awsErrorUrl, awsError.AsJSON); } except end; end; finally httpClient.Free; awsEvent.Free; awsError.Free; end; end.
{----------------------------------------------------------------------------- Unit Name: fMain This software and source code are distributed on an as is basis, without warranty of any kind, either express or implied. This file can be redistributed, modified if you keep this header. Copyright © Erwien Saputra 2005 All Rights Reserved. Author: Erwien Saputra Purpose: Main form History: 11/22/2004 - Added menu, saving and restoring last position, last tab opened, last selected item. 11/26/2004 - Added the ability to save a custom setting to a file. 11/31/2004 - Updated this file with a bunch of comments, refactored some methods. 02/22/2005 - Bug with the delete button for the BDS1, set Scaled to false. 02/25/2005 - Fixed bug when trying to save .reg file with invalid character. 04/05/2005 - Implemented load/save setting using setting persistent classes. Removed dependency on ConfigPersistent.pas, IMainProperties interface and its methods. 06/18/2005 - Added SettingTemplate. This class is responsible for loading the template file. -----------------------------------------------------------------------------} unit fMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, frmSetting, SettingCollection, Buttons, ActnList, StdActns, Menus, ImgList, SettingPersistent, ExtCtrls; type TSettingManagerForm = class; TfrmMain = class(TForm) Menu: TMainMenu; File1: TMenuItem; Exit1: TMenuItem; mnuCustomSetting: TMenuItem; NewCustomSetting: TMenuItem; DeleteCustomSetting: TMenuItem; RenameCustomSetting: TMenuItem; CopyCustomSetting: TMenuItem; Help1: TMenuItem; About1: TMenuItem; N2: TMenuItem; CreateShortcut1: TMenuItem; RunDelphi1: TMenuItem; pcInstalledIDE: TPageControl; btnCreateShortcut: TButton; btnClose: TButton; dlgSave: TSaveDialog; btnRunDelphi: TButton; ActionList: TActionList; actFileExit: TFileExit; actCreateShortcut: TAction; actRunDelphi: TAction; actNewSetting: TAction; actDeleteSetting: TAction; actRenameSetting: TAction; actCopySetting: TAction; Options1: TMenuItem; RestoreDefaultSize1: TMenuItem; actRestoreSize: TAction; actSaveSetting: TAction; SaveSetting1: TMenuItem; N1: TMenuItem; actAbout: TAction; actEditSetting: TAction; Edit1: TMenuItem; iLst_IDEs: TImageList; pnl_Buttons: TPanel; procedure actEditSettingExecute(Sender: TObject); procedure actAboutExecute(Sender: TObject); procedure actSaveSettingExecute(Sender: TObject); procedure actRestoreSizeExecute(Sender: TObject); procedure actCopySettingExecute(Sender: TObject); procedure actRenameSettingExecute(Sender: TObject); procedure actDeleteSettingExecute(Sender: TObject); procedure actNewSettingExecute(Sender: TObject); procedure actRunDelphiExecute(Sender: TObject); procedure actCreateShortcutExecute(Sender: TObject); private { Private declarations } FSettingManagerForm : TSettingManagerForm; function CurrentFrame : TfrmSettingList; procedure LoadIcons; procedure CreateTabs; procedure LoadTabs; procedure SetTab (const IDE : TIDEVersion; const IDEInstalled : boolean); //IMainFormProperties function GetSelectedTabIndex : integer; function GetSelectedCustomSetting : string; procedure SetSelectedCustomSetting (const AValue : string); procedure SetSelectedTabIndex (const AValue : integer); function CorrectFileName (AFileName : string) : string; public { Public declarations } constructor Create (AOwner: TComponent); override; destructor Destroy; override; end; TSettingManagerForm = class (TFormSetting) private function GetSelectedCustomSetting: string; function GetSelectedTabIndex: integer; procedure SetSelectedCustomSetting(const Value: string); procedure SetSelectedTabIndex(const Value: integer); published property SelectedTabIndex : integer read GetSelectedTabIndex write SetSelectedTabIndex; property SelectedCustomSetting : string read GetSelectedCustomSetting write SetSelectedCustomSetting; end; var frmMain: TfrmMain; implementation uses ShellUtilities, LoadSaveCustomSetting, fAbout, SettingTemplate, dmGlyphs; const //Error message if no IDE is installed in the system. ERR_NO_SUPPORTED_IDE = 'There is no supported Borland IDE installed in this machine. '#13#10'(%s)'; //Default form width and height. FORM_WIDTH = 550; FORM_HEIGHT = 370; //The template file name. It must be in the same location with the executable. GALILEO_TEMPLATE_NAME = 'TEMPLATE.XML'; {$R *.dfm} { TForm1 } // Load IDE icons from resources procedure TfrmMain.LoadIcons; var IDELoop : TIDEVersion; tmpIcon : TIcon; PrevIdx : Integer; begin PrevIdx := 0; for IDELoop := Low(TIDEVersion) to High(TIDEVersion) do if ((PrevIdx = 0) or (PrevIdx <> IDEParams[IDELoop].IconIndex)) then try PrevIdx := IDEParams[IDELoop].IconIndex; tmpIcon := TIcon.Create; tmpIcon.ReleaseHandle; tmpIcon.Handle := LoadIcon(hInstance, PWideChar(PrevIdx)); iLst_IDEs.AddIcon(tmpIcon); finally FreeAndNil(tmpIcon); end; end; // Dynamically creating tabs for all IDEs procedure TfrmMain.CreateTabs; var IDELoop : TIDEVersion; newTab : TTabSheet; newFrame : TfrmSettingList; begin for IDELoop := Low(TIDEVersion) to High(TIDEVersion) do begin try newTab := TTabSheet.Create(Self); newTab.Caption := IDEParams[IDELoop].DisplayName; newTab.Name := 'tab_' + IDEParams[IDELoop].ShortName; newTab.PageControl := pcInstalledIDE; newTab.ImageIndex := IDEParams[IDELoop].IconIndex - 2; newFrame := TfrmSettingList.Create(Self); newFrame.Name := 'frm_' + IDEParams[IDELoop].ShortName; newFrame.Parent := newTab; newFrame.Align := alClient; except FreeAndNil(newTab); end; end; end; //Retrieve a set of installed Delphi IDEs and then for each IDE version, set the //correspoinding Tab Sheet. The TabSheet which has no corresponding IDE will be //hidden. procedure TfrmMain.LoadTabs; var InstalledIDE : TInstalledIDE; Loop : TIDEVersion; TabLoop : integer; ErrorString : string; begin //If there is no supported IDE installed, display an information dialog and //terminate the app. //If there is at least one supported IDE installad, InstalledIDE will not be //an empty set. if GetInstalledIDEVersion (InstalledIDE) = false then begin ErrorString := ''; for Loop := Low (TIDEVersion) to High (TIDEVersion) do begin if (ErrorString <> '') then ErrorString := ErrorString + ', '; ErrorString := ErrorString + IDEParams[Loop].DisplayName; end; ErrorString := Format(ERR_NO_SUPPORTED_IDE, [ErrorString]); MessageDlg (ErrorString, mtInformation, [mbOK], 0); Application.Terminate; end else begin Assert (InstalledIDE <> []); //Iterate through the TIDEVersion constants and based on whether the IDE //is installed or not, set the tab. for Loop := Low (TIDEVersion) to High (TIDEVersion) do SetTab (Loop, (Loop in InstalledIDE)); //At this point, all tabs which have corresponding IDE installed will be //enabled and visible. Set the first tab which is visible and enabled to be //the active tab. for TabLoop := 0 to pcInstalledIDE.PageCount - 1 do if pcInstalledIDE.Pages[TabLoop].TabVisible = true then begin pcInstalledIDE.ActivePageIndex := TabLoop; Break; end; end; end; //SetTab set the tab visible if the corresponding IDE is installed, and //initialize the frame if the IDE is installed. procedure TfrmMain.SetTab(const IDE: TIDEVersion; const IDEInstalled: boolean); var Tab : TTabSheet; Frame : TfrmSettingList; begin //Based on the IDE, get the corresponding Tab and Frame. Tab := TTabSheet(Self.FindComponent('tab_' + IDEParams[IDE].ShortName)); Frame := TfrmSettingList(Self.FindComponent('frm_' + IDEParams[IDE].ShortName)); //Disable or set the tab invisible if corresponding IDE is not installed. Tab.Visible := IDEInstalled; Tab.TabVisible := IDEInstalled; Tab.Enabled := IDEInstalled; if IDEInstalled = true then Frame.SetIDEVersion (IDE); end; //Returns the TfrmSettingList of the active frame. function TfrmMain.CurrentFrame: TfrmSettingList; var frmName: string; begin //Return TfrmSettingLIst based on the index of the current page. frmName := StringReplace(pcInstalledIDE.ActivePage.Name, 'tab_', 'frm_', []); Result := TfrmSettingList(Self.FindComponent(frmName)); end; //If CurrentFrame is a valid Frame and there is a selected item, open the file //save dialog and save a shortcut. procedure TfrmMain.actCreateShortcutExecute(Sender: TObject); begin //If there is no item selected or there is no frame in the current tab, exit. if (CurrentFrame = nil) or (CurrentFrame.ItemSelected = false) then Exit; dlgSave.DefaultExt := 'lnk'; dlgSave.FileName := CorrectFileName (CurrentFrame.SelectedSettingName); //Create the shortcut. Encluse the registry key within double quotes, to //anticipate registry key with space in it. if dlgSave.Execute = true then CreateLink (dlgSave.FileName, GetExecutablePath (CurrentFrame.IDEVersion), '-r"' + CurrentFrame.SelectedRegistryKey + '"' + GetStartParams (CurrentFrame.IDEVersion)); end; //Execute the selected IDE, if CurrentFrame is valid and an item is selected. procedure TfrmMain.actRunDelphiExecute(Sender: TObject); begin if (CurrentFrame = nil) or (CurrentFrame.ItemSelected = true) then begin Screen.Cursor := crHourglass; try RunDelphi (GetExecutablePath (CurrentFrame.IDEVersion), '-r"' + CurrentFrame.SelectedRegistryKey + '"' + GetStartParams (CurrentFrame.IDEVersion)); finally Screen.Cursor := crArrow; end; end; end; procedure TfrmMain.actNewSettingExecute(Sender: TObject); begin CurrentFrame.CreateNewSetting; end; procedure TfrmMain.actDeleteSettingExecute(Sender: TObject); begin CurrentFrame.DeleteSelectedCustomSetting; end; procedure TfrmMain.actRenameSettingExecute(Sender: TObject); begin CurrentFrame.RenameSelectedSetting; end; procedure TfrmMain.actCopySettingExecute(Sender: TObject); begin CurrentFrame.CopySelectedSetting; end; procedure TfrmMain.actEditSettingExecute(Sender: TObject); begin CurrentFrame.EditSetting; end; //Property getter, returns the selected custom setting, if there is one. If no //frame is active, this will return an empty string. function TfrmMain.GetSelectedCustomSetting: string; begin if (CurrentFrame <> nil) then Result := CurrentFrame.SelectedSettingName else Result := EmptyStr; end; //Property getter, Returns the index of the selected tab. function TfrmMain.GetSelectedTabIndex: integer; begin Result := pcInstalledIDE.ActivePageIndex; end; //Property setter, to select a setting on the CurrentFrame. procedure TfrmMain.SetSelectedCustomSetting(const AValue: string); begin if (CurrentFrame <> nil) then CurrentFrame.SelectSettingByName (AValue); end; //Property setter to select a tab index. procedure TfrmMain.SetSelectedTabIndex(const AValue: integer); begin //Make sure that the AValue is a valid tab index value and the tab sheet is //visible. if (AValue < pcInstalledIDE.PageCount) and (pcInstalledIDE.Pages [AValue].TabVisible = true) then pcInstalledIDE.ActivePageIndex := AValue; end; //Restore the form size and position. The default position is in the center of //the screen. procedure TfrmMain.actRestoreSizeExecute(Sender: TObject); begin Width := FORM_WIDTH; Height := FORM_HEIGHT; Left := (Screen.Width - Width) div 2; Top := (Screen.Height - Height) div 2; end; //Action item for saving the selected custom setting to a registry file. procedure TfrmMain.actSaveSettingExecute(Sender: TObject); var SaveSetting : ISaveSetting; begin //Execute only if the current frame is a valid frame and an item is selected. if (CurrentFrame <> nil) and (CurrentFrame.ItemSelected = true) then begin dlgSave.DefaultExt := 'reg'; //Since the exported file will have .reg extension, add the IDE name in //front of the default name. By having the IDE name in front of the registry //file, it will make it easy to recognize for which IDE is the .reg file. dlgSave.FileName := CorrectFileName ( pcInstalledIDE.ActivePage.Caption + ' ' + CurrentFrame.SelectedSettingName + '.reg'); if dlgSave.Execute = true then begin SaveSetting := GetSaveSetting; SaveSetting.FileName := dlgSave.FileName; SaveSetting.CustomSettingPath := CurrentFrame.SelectedRegistryPath; SaveSetting.SaveSettingToFile; end; end; end; constructor TfrmMain.Create(AOwner: TComponent); begin inherited; LoadIcons; CreateTabs; LoadTabs; FSettingManagerForm := TSettingManagerForm.Create (self); SettingPersistent.GetIniPersistentManager.LoadSetting (FSettingManagerForm); SettingTemplate.CreateTemplateCollection ( ExtractFilePath (Application.ExeName) + GALILEO_TEMPLATE_NAME); Self.Icon.Assign(Application.Icon); end; destructor TfrmMain.Destroy; begin if Assigned (FSettingManagerForm) then begin SettingPersistent.GetIniPersistentManager.SaveSetting (FSettingManagerForm); SettingPersistent.GetIniPersistentManager.SaveSetting (FSettingManagerForm); FreeAndNil (FSettingManagerForm); end; inherited; end; procedure TfrmMain.actAboutExecute(Sender: TObject); begin with TfrmAbout.Create (self) do try ShowModal; finally Release; end; end; function TfrmMain.CorrectFileName(AFileName: string): string; const INVALID_CHAR_FILENAME : set of char = ['<', '>', '|', '"', '\', '/']; var Loop : integer; begin for Loop := 1 to Length (AFileName) do if AFileName[Loop] in INVALID_CHAR_FILENAME then AFileName[Loop] := '_'; Result := AFileName; end; { TSettingManagerForm } function TSettingManagerForm.GetSelectedCustomSetting: string; begin Result := (Form as TfrmMain).GetSelectedCustomSetting; end; procedure TSettingManagerForm.SetSelectedCustomSetting(const Value: string); begin (Form as TfrmMain).SetSelectedCustomSetting (Value); end; function TSettingManagerForm.GetSelectedTabIndex: integer; begin Result := (Form as TfrmMain).GetSelectedTabIndex; end; procedure TSettingManagerForm.SetSelectedTabIndex(const Value: integer); begin (Form as TfrmMain).SetSelectedTabIndex (Value); end; end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit frmMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private DC: HDC; hrc: HGLRC; procedure SetDCPixelFormat; protected procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; end; var frmGL: TfrmGL; a, b, c: GLfloat; Angle: GLfloat = 0.0; AngleSystem : GLfloat = 0.0; implementation uses DGLUT; {$R *.DFM} procedure DrawScene (light : Boolean); begin glPushMatrix; If light then begin glEnable (GL_LIGHTING); glEnable (GL_LIGHT0); glColor3f(1, 0.3, 0.5); end; glutsolidTorus(0.1, 0.2, 16, 16); If light then glColor3f(0.5, 0.8, 0.8); glTranslatef(0.05, 0.08,-0.2); glutSolidSphere(0.05, 16, 16); glTranslatef(0.2, 0.2, 0.4); glutsolidSphere(0.1, 16, 16); glTranslatef(0.3, 0.3, -0.2); If light then begin glDisable (GL_LIGHT0); glDisable (GL_LIGHTING); end; glPopMatrix; end; {======================================================================= Рисование картинки} procedure TfrmGL.WMPaint(var Msg: TWMPaint); var ps : TPaintStruct; begin BeginPaint(Handle, ps); glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glPushMatrix; glPushMatrix; glColor3f(0.8, 0.8, 1); glRotatef(Angle, 0, 1, 0); glBegin(GL_POLYGON); glVertex3f(0.5, -0.5, 0.5); glVertex3f(0.5, 0.5, 0.5); glVertex3f(0.5, 0.5, -0.5); glVertex3f(0.5, -0.5, -0.5); glEnd; glPopMatrix; glPushMatrix; glClear(GL_STENCIL_BUFFER_BIT); glEnable(GL_STENCIL_TEST); glColor4f(0, 0, 0, 0.4); glTranslatef(0.5*c, 0, 0.5*a); glScaled(abs(a),1,abs(c)); glDisable(GL_DEPTH_TEST); glRotatef(AngleSystem, 1, 1, 1); DrawScene (False); glEnable(GL_DEPTH_TEST); glDisable(GL_STENCIL_TEST); glPopMatrix; glRotatef(AngleSystem, 1, 1, 1); DrawScene (True); glPopMatrix; SwapBuffers(DC); EndPaint(Handle, ps); Angle := Angle + 5; If Angle >= 360.0 then Angle := 0.0; AngleSystem := AngleSystem + 2.5; If AngleSystem >= 360.0 then AngleSystem := 0.0; a := -sin(Angle * Pi/180); b := 0; c := cos(Angle * Pi/180); InvalidateRect(Handle, nil, False); end; {======================================================================= Создание окна} procedure TfrmGL.FormCreate(Sender: TObject); begin DC := GetDC(Handle); SetDCPixelFormat; hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glClearStencil(0); glStencilOp(GL_INCR, GL_INCR, GL_INCR); glStencilFunc(GL_EQUAL, 0, $FF); end; {======================================================================= Устанавливаем формат пикселей} procedure TfrmGL.SetDCPixelFormat; var nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); end; {======================================================================= Конец работы программы} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC(Handle, DC); DeleteDC (DC); end; procedure TfrmGL.FormResize(Sender: TObject); begin glViewport(0, 0, ClientWidth, ClientHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity; gluPerspective(15, ClientWidth / ClientHeight, 1, 50); glMatrixMode(GL_MODELVIEW); glLoadIdentity; glTranslatef(-0.5, -0.5, -8.0); InvalidateRect(Handle, nil, False); end; procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close end; end.
{*********************************************} { TeeGrid Software Library } { Abstract Painter class } { Copyright (c) 2016 by Steema Software } { All Rights Reserved } {*********************************************} unit VCLTee.Painter; {$I Tee.inc} interface uses {$IFNDEF FPC} {System.}Types, {$ENDIF} {WinAPI.}Windows, {VCL.}Graphics, Tee.Painter, Tee.Format; type TTeeFont=Tee.Format.TFont; TWindowsPainter=class(TPainter) protected ICanvas : TCanvas; IDC : HDC; public Constructor Create(const ACanvas:TCanvas); property Canvas:TCanvas read ICanvas; procedure Init(const DC:HDC); virtual; end; TGDIPainter=class(TWindowsPainter) private type TAlign=record public Horizontal : THorizontalAlign; Vertical : TVerticalAlign; function Flags:Cardinal; end; var IAlign : TAlign; IClipHistory : Array of HRGN; function GraphicOf(const APicture: TPicture):TGraphic; procedure SetTextAlignments; public class procedure ApplyFont(const ASource:TTeeFont; const ADest:Graphics.TFont); static; procedure Clip(const R:TRectF); override; procedure Clip(const R:TRect); overload; procedure UnClip; override; procedure HideBrush; override; procedure SetBrush(const ABrush:TBrush); override; procedure SetFont(const AFont:TFont); override; procedure SetHorizontalAlign(const Value:THorizontalAlign); override; procedure SetStroke(const AStroke:TStroke); override; procedure SetVerticalAlign(const Value:TVerticalAlign); override; procedure Draw(const R:TRectF); override; procedure Draw(const P:TPointsF); override; procedure Draw(const APicture:TPicture; const X,Y:Single); overload; override; procedure Draw(const APicture:TPicture; const R:TRectF); overload; override; procedure DrawEllipse(const R:TRectF); override; procedure Fill(const R:TRectF); override; procedure Fill(const R:TRectF; const AColor:TColor); override; procedure Fill(const P:TPointsF); override; procedure FillEllipse(const R:TRectF); override; procedure HorizontalLine(const Y,X0,X1:Single); override; procedure Line(const X0,Y0,X1,Y1:Single); override; procedure Lines(const P:TPointsF); override; procedure Paint(const AFormat: TFormat; const R: TRectF); override; procedure Paint(const AFormat: TFormat; const P: TPointsF); override; function TextHeight(const AText:String):Single; override; procedure TextOut(const X,Y:Single; const AText:String); override; function TextWidth(const AText:String):Single; override; procedure VerticalLine(const X,Y0,Y1:Single); override; end; implementation
unit dbf_ansistrings; {$I dbf_common.inc} interface uses SysUtils; type {$IFDEF FPC} TdbfStrLen = function(Str: PAnsiChar): SizeInt; TdbfStrCopy = function(Dest: PAnsiChar; Source: PAnsiChar): PChar; TdbfStrLCopy = function(Dest: PAnsiChar; Source: PAnsiChar; MaxLen: SizeInt): PChar; TdbfFloatToText = function(BufferArg: PAnsiChar; Value: Extended; Format: TFloatFormat; Precision: Integer; Digits: Integer): LongInt; {$IFDEF SUPPORT_FORMATSETTINGSTYPE} TdbfFloatToTextFmt = function(BufferArg: PAnsiChar; Value: Extended; Format: TFloatFormat; Precision: Integer; Digits: Integer; const FormatSettings: TFormatSettings): LongInt; {$ENDIF} TdbfStrUpper = function(Str: PAnsiChar): PAnsiChar; TdbfStrLower = function(Str: PAnsiChar): PAnsiChar; TdbfStrIComp = function(S1, S2: PAnsiChar): SizeInt; TdbfStrLIComp = function(S1, S2: PAnsiChar; MaxLen: SizeInt): SizeInt; TdbfStrPos = function(Str, SubStr: PAnsiChar): PAnsiChar; TdbfStrLComp = function(S1, S2: PAnsiChar; MaxLen: SizeInt): SizeInt; TdbfStrComp = function(S1, S2: PAnsiChar): SizeInt; TdbfStrScan = function(Str: PAnsiChar; Chr: AnsiChar): PAnsiChar; TdbfTextToFloat = function(Buffer: PAnsiChar; out Value; ValueType: TFloatValue): Boolean; {$IFDEF SUPPORT_FORMATSETTINGSTYPE} TdbfTextToFloatFmt = function(Buffer: PAnsiChar; out Value; ValueType: TFloatValue; const FormatSettings: TFormatSettings): Boolean; {$ENDIF} TdbfStrPLCopy = function(Dest: PAnsiChar; const Source: string; MaxLen: SizeUInt): PAnsiChar; TdbfTrimLeft = function(const S: string): string; TdbfTrimRight = function(const S: string): string; {$ELSE} TdbfStrLen = function(const Str: PAnsiChar): Cardinal; TdbfStrCopy = function(Dest: PAnsiChar; const Source: PAnsiChar): PAnsiChar; TdbfStrLCopy = function(Dest: PAnsiChar; const Source: PAnsiChar; MaxLen: Cardinal): PAnsiChar; TdbfFloatToText = function(BufferArg: PAnsiChar; const Value; ValueType: TFloatValue; Format: TFloatFormat; Precision, Digits: Integer): Integer; {$IFDEF SUPPORT_FORMATSETTINGSTYPE} TdbfFloatToTextFmt = function(BufferArg: PAnsiChar; const Value; ValueType: TFloatValue; Format: TFloatFormat; Precision, Digits: Integer; const FormatSettings: TFormatSettings): Integer; {$ENDIF} TdbfStrUpper = function(Str: PAnsiChar): PAnsiChar; TdbfStrLower = function(Str: PAnsiChar): PAnsiChar; TdbfStrIComp = function(const S1, S2: PAnsiChar): Integer; TdbfStrLIComp = function(const S1, S2: PAnsiChar; MaxLen: Cardinal): Integer; TdbfStrPos = function(const Str, SubStr: PAnsiChar): PAnsiChar; TdbfStrLComp = function(const S1, S2: PAnsiChar; MaxLen: Cardinal): Integer; TdbfStrComp = function(const S1, S2: PAnsiChar): Integer; TdbfStrScan = function(const Str: PAnsiChar; Chr: AnsiChar): PAnsiChar; TdbfTextToFloat = function(Buffer: PAnsiChar; var Value; ValueType: TFloatValue): Boolean; {$IFDEF SUPPORT_FORMATSETTINGSTYPE} TdbfTextToFloatFmt = function(Buffer: PAnsiChar; var Value; ValueType: TFloatValue; const FormatSettings: TFormatSettings): Boolean; {$ENDIF} TdbfStrPLCopy = function(Dest: PAnsiChar; const Source: AnsiString; MaxLen: Cardinal): PAnsiChar; TdbfTrimLeft = function(const S: AnsiString): AnsiString; TdbfTrimRight = function(const S: AnsiString): AnsiString; {$ENDIF} var dbfStrLen: TdbfStrLen{ = nil}; dbfStrCopy: TdbfStrCopy{ = nil}; dbfStrLCopy: TdbfStrLCopy{ = nil}; dbfFloatToText: TdbfFloatToText{ = nil}; {$IFDEF SUPPORT_FORMATSETTINGSTYPE} dbfFloatToTextFmt: TdbfFloatToTextFmt{ = nil}; {$ENDIF} dbfStrUpper: TdbfStrUpper{ = nil}; dbfStrLower: TdbfStrLower{ = nil}; dbfStrIComp: TdbfStrIComp{ = nil}; dbfStrLIComp: TdbfStrLIComp{ = nil}; dbfStrPos: TdbfStrPos{ = nil}; dbfStrLComp: TdbfStrLComp{ = nil}; dbfStrComp: TdbfStrComp{ = nil}; dbfStrScan: TdbfStrScan{ = nil}; {$IFDEF SUPPORT_FORMATSETTINGSTYPE} dbfTextToFloatFmt: TdbfTextToFloatFmt{ = nil}; {$ENDIF} dbfTextToFloat: TdbfTextToFloat{ = nil}; dbfStrPLCopy: TdbfStrPLCopy{ = nil}; dbfTrimLeft: TdbfTrimLeft{ = nil}; dbfTrimRight: TdbfTrimRight{ = nil}; implementation {$IFDEF SUPPORT_ANSISTRINGS_UNIT} uses AnsiStrings; // For XE4 and up, not for FPC {$ELSE} // XE2 has PAnsiChar versions of TrimLeft/TrimRight in AnsiStrings, // the other string manipulation functions are still in SysUtils. // It is assumed that the same applies for D2009-XE3 (but this is not tested!). {$IFDEF WINAPI_IS_UNICODE} uses AnsiStrings; {$ENDIF} {$ENDIF} {$IFDEF SUPPORT_ANSISTRINGS_UNIT} procedure Init; begin dbfStrLen := AnsiStrings.StrLen; dbfStrCopy := AnsiStrings.StrCopy; dbfStrLCopy := AnsiStrings.StrLCopy; dbfFloatToText := AnsiStrings.FloatToText; {$IFDEF SUPPORT_FORMATSETTINGSTYPE} dbfFloatToTextFmt := AnsiStrings.FloatToText; {$ENDIF} dbfStrUpper := AnsiStrings.StrUpper; dbfStrLower := AnsiStrings.StrLower; dbfStrIComp := AnsiStrings.StrIComp; dbfStrLIComp := AnsiStrings.StrLIComp; dbfStrPos := AnsiStrings.StrPos; dbfStrLComp := AnsiStrings.StrLComp; dbfStrComp := AnsiStrings.StrComp; dbfStrScan := AnsiStrings.StrScan; {$IFDEF SUPPORT_FORMATSETTINGSTYPE} dbfTextToFloatFmt := AnsiStrings.TextToFloat; {$ENDIF} dbfTextToFloat := AnsiStrings.TextToFloat; dbfStrPLCopy := AnsiStrings.StrPLCopy; dbfTrimLeft := AnsiStrings.TrimLeft; dbfTrimRight := AnsiStrings.TrimRight; end; {$ELSE} procedure Init; begin dbfStrLen := SysUtils.StrLen; dbfStrCopy := SysUtils.StrCopy; dbfStrLCopy := SysUtils.StrLCopy; dbfFloatToText := SysUtils.FloatToText; {$IFDEF SUPPORT_FORMATSETTINGSTYPE} dbfFloatToTextFmt := SysUtils.FloatToText; {$ENDIF} dbfStrUpper := SysUtils.StrUpper; dbfStrLower := SysUtils.StrLower; dbfStrIComp := SysUtils.StrIComp; dbfStrLIComp := SysUtils.StrLIComp; dbfStrPos := SysUtils.StrPos; dbfStrLComp := SysUtils.StrLComp; dbfStrComp := SysUtils.StrComp; dbfStrScan := SysUtils.StrScan; {$IFDEF SUPPORT_FORMATSETTINGSTYPE} dbfTextToFloatFmt := SysUtils.TextToFloat; {$ENDIF} dbfTextToFloat := SysUtils.TextToFloat; dbfStrPLCopy := SysUtils.StrPLCopy; {$IFDEF WINAPI_IS_UNICODE} dbfTrimLeft := AnsiStrings.TrimLeft; dbfTrimRight := AnsiStrings.TrimRight; {$ELSE} dbfTrimLeft := SysUtils.TrimLeft; dbfTrimRight := SysUtils.TrimRight; {$ENDIF} end; {$ENDIF} initialization Init; end.
{**********************************************} { TeeChart Pro and TeeTree VCL About Form } { Copyright (c) 1995-2004 by David Berneda } {**********************************************} unit TeeAbout; {$I TeeDefs.inc} interface uses {$IFDEF LINUX} Libc, {$ELSE} Windows, Messages, {$ENDIF} {$IFDEF CLX} Qt, QGraphics, QControls, QForms, QExtCtrls, QStdCtrls, {$ELSE} Graphics, Controls, Forms, ExtCtrls, StdCtrls, {$ENDIF} Classes, SysUtils; type TTeeAboutForm = class(TForm) BClose: TButton; Image2: TImage; LabelCopy: TLabel; LabelVersion: TLabel; Label1: TLabel; Labelwww: TLabel; Image1: TImage; Bevel1: TBevel; LabelEval: TLabel; Timer1: TTimer; procedure LabelwwwClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormPaint(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { Private declarations } StartColor : TColor; EndColor : TColor; Delta : Integer; public { Public declarations } end; TeeWindowHandle={$IFDEF CLX}QOpenScrollViewH{$ELSE}Integer{$ENDIF}; Procedure GotoURL(Handle:TeeWindowHandle; Const URL:String); { Displays the TeeChart about-box dialog } Procedure TeeShowAboutBox(Const ACaption:String=''; Const AVersion:String=''); Var TeeAboutBoxProc:Procedure=nil; TeeIsTrial:Boolean=False; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses {$IFNDEF LINUX} ShellApi, {$ENDIF} {$IFDEF CLR} System.Reflection, {$ENDIF} TeCanvas, TeeProcs, TeeConst; Procedure TeeShowAboutBox(Const ACaption:String=''; Const AVersion:String=''); var tmp : TTeeAboutForm; begin tmp:=TTeeAboutForm.Create(nil); with tmp do try if ACaption<>'' then Caption:=ACaption; if AVersion<>'' then LabelVersion.Caption:=AVersion; if TeeIsTrial then LabelEval.Caption:=LabelEval.Caption+' TRIAL'; TeeTranslateControl(tmp); ShowModal; finally Free; end; end; Procedure GotoURL(Handle: TeeWindowHandle; Const URL:String); {$IFNDEF LINUX} {$IFNDEF CLR} Var St : TeeString256; {$ENDIF} {$ENDIF} begin {$IFNDEF LINUX} ShellExecute({$IFDEF CLX}0{$ELSE}Handle{$ENDIF},'open', {$IFDEF CLR}URL{$ELSE}StrPCopy(St,URL){$ENDIF}, nil, {$IFDEF CLR}''{$ELSE}nil{$ENDIF}, SW_SHOW); { <-- do not translate } {$ENDIF} end; procedure TTeeAboutForm.LabelwwwClick(Sender: TObject); begin GotoURL(Handle,LabelWWW.Caption); end; procedure TTeeAboutForm.FormPaint(Sender: TObject); begin {$IFNDEF CLX} // CLX repaints on top of form ! With TTeeCanvas3D.Create do try ReferenceCanvas:=Self.Canvas; GradientFill(ClientRect,StartColor,EndColor,gdDiagonalUp); finally Free; end; {$ENDIF} end; procedure TTeeAboutForm.FormCreate(Sender: TObject); begin {$IFNDEF CLX} DoubleBuffered:=True; {$ENDIF} StartColor:=$E0E0E0; EndColor:=clDkGray; Delta:=4; Caption:=Caption+' '+TeeMsg_Version; LabelVersion.Caption:=TeeMsg_Version {$IFDEF CLX}+' CLX'{$ENDIF}; {$IFDEF CLR} LabelVersion.Caption:=LabelVersion.Caption+' '+ System.Reflection.Assembly.GetExecutingAssembly.GetName.Version.ToString; LabelVersion.AutoSize:=True; {$ENDIF} LabelCopy.Caption:=TeeMsg_Copyright; BorderStyle:=TeeBorderStyle; end; Procedure TeeShowAboutBox2; begin if Assigned(TeeAboutBoxProc) then begin TeeShowAboutBox; TeeAboutBoxProc:=nil; end; end; procedure TTeeAboutForm.Timer1Timer(Sender: TObject); procedure ChangeColor(var C:TColor; N:Integer); procedure Add(var B:Byte); begin if N>0 then if B+N<256 then B:=B+N else B:=255 else if B+N>0 then B:=B+N else B:=0; end; var tmp : TColor; R,G,B : Byte; begin tmp:=ColorToRGB(C); R:=GetRValue(tmp); G:=GetGValue(tmp); B:=GetBValue(tmp); Add(R); Add(G); Add(B); C:=RGB(R,G,B); end; begin ChangeColor(StartColor,-Delta); ChangeColor(EndColor,Delta); if (StartColor=ColorToRGB(clBlack)) or (EndColor=ColorToRGB(clBlack)) then Delta:=-Delta; Invalidate; end; initialization TeeAboutBoxProc:=TeeShowAboutBox2; finalization TeeAboutBoxProc:=nil; end.