text
stringlengths
14
6.51M
unit Test; { * Copyright 2015 E Spelt for only the test files * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Implemented by E. Spelt for Delphi } interface uses DUnitX.TestFramework, SysUtils, ScanManager, BarcodeFormat, ReadResult, FMX.Types, FMX.Graphics, FMX.Objects; type [TestFixture] TZXingDelphiTest = class(TObject) private public function GetImage(Filename: string): TBitmap; function Decode(Filename: String; CodeFormat: TBarcodeFormat): TReadResult; [Test] procedure AllQRCode; [Test] procedure AllCode128(); [Test] procedure AllCode93(); [Test] procedure AllCodeITF; [Test] procedure AutoTypes(); end; implementation procedure TZXingDelphiTest.AllQRCode(); var result: TReadResult; begin try result := Decode('qrcode.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://google.com'), 'QR code result Text Incorrect: ' + result.Text); // From here a test set from: http://datagenetics.com/blog/november12013/index.html // Please take a look of what QR can do for you // NOTE: some test are expected to fail and are setup as such. // !Cancelled for test. Does not work with zxing.net either. // Rotation does not work. // result := Decode('q3.png', BarcodeFormat.QR_CODE); // Assert.IsNotNull(result, ' Nil result '); // Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), // 'QR code result Text Incorrect: ' + result.Text); result := Decode('q33.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Contains('Never gonna give you up'), 'QR code result Text Incorrect: ' + result.Text); Assert.IsTrue(result.Text.Contains('Never gonna tell a lie and hurt you'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q1.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q2.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q2q.png', BarcodeFormat.QR_CODE); // rotate 90 degrees Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q2m.png', BarcodeFormat.QR_CODE); // rotate 120 degrees Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q4.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q5.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); // fails on example website but does work! Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q6.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q7.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q8.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q9.png', BarcodeFormat.QR_CODE); Assert.IsNull(result, ' Should be nil result. Missing possition block '); result := Decode('q10.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q11.png', BarcodeFormat.QR_CODE); Assert.IsNull(result, ' The code should not scan '); result := Decode('q12.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q13.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q14.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q15.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q16.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q17.png', BarcodeFormat.QR_CODE); Assert.IsNull(result, ' Should not scan '); result := Decode('q18.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q21.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q22.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q23.png', BarcodeFormat.QR_CODE); Assert.IsNull(result, ' to dizzy to scan'); result := Decode('q25.png', BarcodeFormat.QR_CODE); Assert.IsNull(result, 'Should not scan'); result := Decode('q28.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q29.png', BarcodeFormat.QR_CODE); Assert.IsNull(result, 'Should not scan'); result := Decode('q30.png', BarcodeFormat.QR_CODE); Assert.IsNull(result, 'Should not be scanned'); result := Decode('q31.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q32.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('qr-a1.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('a1'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('qr-1a.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('1a'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('qr-12.png', BarcodeFormat.QR_CODE); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('12'), 'QR code result Text Incorrect: ' + result.Text); finally FreeAndNil(result); end; end; procedure TZXingDelphiTest.AllCode128(); var result: TReadResult; begin try result := Decode('Code128.png', BarcodeFormat.CODE_128); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('1234567'), 'Code 128 result Text Incorrect: ' + result.Text); result := Decode('Code128-laser.png', BarcodeFormat.CODE_128); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('1234567'), 'Code 128 (laser) result Text Incorrect: ' + result.Text); result := Decode('Code128-custom.bmp', BarcodeFormat.CODE_128); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('000100101767448'), 'Code 128 result Text Incorrect: ' + result.Text); result := Decode('Code128-custom.bmp', BarcodeFormat.Auto); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('000100101767448'), 'Auto Code 128 result Text Incorrect: ' + result.Text); result := Decode('Code128-custom-laser.bmp', BarcodeFormat.Auto); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('000100101767448'), 'Auto Code 128 (laser) result Text Incorrect: ' + result.Text); finally FreeAndNil(result); end; end; procedure TZXingDelphiTest.AllCode93(); var result: TReadResult; begin try result := Decode('Code93-1.png', BarcodeFormat.CODE_93); Assert.IsNotNull(result, ' nil result '); Assert.IsTrue(result.Text.Equals('THIS IS CODE93'), 'Code 93 - 1 result Text Incorrect: ' + result.Text); result := Decode('Code93-1-laser.png', BarcodeFormat.CODE_93); Assert.IsNotNull(result, ' nil result '); Assert.IsTrue(result.Text.Equals('THIS IS CODE93'), 'Code 93 - 1 (laser) result Text Incorrect: ' + result.Text); result := Decode('Code93-2.png', BarcodeFormat.CODE_93); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('ABC CODE93-2'), 'Code 93 - 2 result Text Incorrect: ' + result.Text); result := Decode('Code93-2-laser.png', BarcodeFormat.CODE_93); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('ABC CODE93-2'), 'Code 93 - 2 (laser) result Text Incorrect: ' + result.Text); result := Decode('Code93-3.png', BarcodeFormat.CODE_93); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('ABC CODE96'), 'Code 93 - 3 result Text Incorrect: ' + result.Text); result := Decode('Code93-3-laser.png', BarcodeFormat.CODE_93); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('ABC CODE96'), 'Code 93 - 3 (laser) result Text Incorrect: ' + result.Text); result := Decode('Code93-3.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('ABC CODE96'), 'Auto Code 93 - 3 result Text Incorrect: ' + result.Text); result := Decode('Code93-3-laser.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('ABC CODE96'), 'Auto Code 93 - 3 (laser) result Text Incorrect: ' + result.Text); finally FreeAndNil(result); end; end; procedure TZXingDelphiTest.AllCodeITF(); var result: TReadResult; begin result := Decode('q4.png', BarcodeFormat.ITF); try Assert.IsNull(result, ' Should be nil result '); result := Decode('ITF-1.png', BarcodeFormat.ITF); Assert.IsNotNull(result, ' nil result '); Assert.IsTrue(result.Text.Equals('55867492279103'), 'Code ITF - 1 result Text Incorrect: ' + result.Text); result := Decode('ITF-2.png', BarcodeFormat.ITF); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('04601234567893'), 'ITF - 2 result Text Incorrect: ' + result.Text); result := Decode('ITF-3.png', BarcodeFormat.ITF); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('12345678900098'), 'ITF - 3 result Text Incorrect: ' + result.Text); result := Decode('ITF-4.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('32145678900098'), 'ITF - 4 result Text Incorrect: ' + result.Text); result := Decode('ITF-5.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('77745678900093'), 'ITF - 5 result Text Incorrect: ' + result.Text); finally FreeAndNil(result); end; end; procedure TZXingDelphiTest.AutoTypes; var result: TReadResult; begin try result := Decode('Code128.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('1234567'), 'Code 128 result Text Incorrect: ' + result.Text); result := Decode('Code93-1.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' nil result '); Assert.IsTrue(result.Text.Equals('THIS IS CODE93'), 'Code 93 - 1 result Text Incorrect: ' + result.Text); result := Decode('Code128.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('1234567'), 'Code 128 result Text Incorrect: ' + result.Text); result := Decode('q4.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('q2.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('Code93-1.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' nil result '); Assert.IsTrue(result.Text.Equals('THIS IS CODE93'), 'Code 93 - 1 result Text Incorrect: ' + result.Text); result := Decode('Code93-1.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' nil result '); Assert.IsTrue(result.Text.Equals('THIS IS CODE93'), 'Code 93 - 1 result Text Incorrect: ' + result.Text); result := Decode('q2.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('http://DataGenetics.com'), 'QR code result Text Incorrect: ' + result.Text); result := Decode('ITF-2.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('04601234567893'), 'ITF - 2 result Text Incorrect: ' + result.Text); result := Decode('ITF-3.png', BarcodeFormat.Auto); Assert.IsNotNull(result, ' Nil result '); Assert.IsTrue(result.Text.Equals('12345678900098'), 'ITF - 3 result Text Incorrect: ' + result.Text); finally FreeAndNil(result); end; end; /// ///////////////////////////////////////////////////////////////////////////// /// / Helpers below ///// /// ///////////////////////////////////////////////////////////////////////////// function TZXingDelphiTest.Decode(Filename: String; CodeFormat: TBarcodeFormat) : TReadResult; var bmp: TBitmap; ScanManager: TScanManager; begin bmp := GetImage(Filename); try ScanManager := TScanManager.Create(CodeFormat, nil); result := ScanManager.Scan(bmp); finally FreeAndNil(bmp); FreeAndNil(ScanManager); end; end; function TZXingDelphiTest.GetImage(Filename: string): TBitmap; var img: TImage; fs: string; begin img := TImage.Create(nil); try fs := ExtractFileDir(ParamStr(0)) + '\..\..\images\' + Filename; img.Bitmap.LoadFromFile(fs); result := TBitmap.Create; result.Assign(img.Bitmap); finally img.Free; end; end; (* TBarcodeFormat.CODE_128 Result Decode(string file, BarcodeFormat? format = null, KeyValuePair<DecodeHintType, object>[] additionalHints = null) { var r = GetReader(format, additionalHints); var i = GetImage(file); var result = r.decode(i); // decode(i); return result; } *) initialization TDUnitX.RegisterTestFixture(TZXingDelphiTest); end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Winapi.ActiveX, Winapi.DirectShow9, SignalGenerator3DVideoFrame, DeckLinkAPI, DeckLinkAPI.Discovery, DeckLinkAPI.Modes; type _OutputSignal = TOleEnum; const kOutputSignalPip = $00000000; kOutputSignalDrop = $00000001; const kAudioWaterlevel = 48000; const // SD 75% Colour Bars gSD75pcColourBars : array[0..7] of cardinal = ($eb80eb80, $a28ea22c, $832c839c, $703a7048, $54c654b8, $41d44164, $237223d4, $10801080); const // HD 75% Colour Bars gHD75pcColourBars : array[0..7] of cardinal = ($eb80eb80, $a888a82c, $912c9193, $8534853f, $3fcc3fc1, $33d4336d, $1c781cd4, $10801080); type TDeckLinkdisplayModeObject = class private fName: string; fvideoDisplayMode : IDeckLinkdisplayMode; public property Name : string read fName; property videoDisplayMode : IDeckLinkdisplayMode read fvideoDisplayMode; constructor Create(const name : string; const videoDisplayMode : IDeckLinkdisplayMode) ; end; type TForm1 = class(TForm, IDeckLinkVideoOutputCallback, IDeckLinkAudioOutputCallback) GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; m_videoFormatCombo: TComboBox; m_outputSignalCombo: TComboBox; m_audioChannelCombo: TComboBox; m_audioSampleDepthCombo: TComboBox; m_startButton: TButton; m_pixelFormatCombo: TComboBox; Label5: TLabel; procedure RefreshDisplayModeMenu(); procedure FormCreate(Sender: TObject); procedure EnableInterface(enable : boolean); procedure m_startButtonClick(Sender: TObject); function GetBytesPerPixel(const pixelFormat: _BMDPixelFormat): integer; Procedure StartRunning(); Procedure StopRunning(); Procedure ScheduleNextFrame(prerolling : boolean); Procedure WriteNextAudioSamples(); function CreateBlackFrame(): TSignalGenerator3DVideoFrame; function CreateBarsFrame(): TSignalGenerator3DVideoFrame; procedure FormClose(Sender: TObject; var Action: TCloseAction); protected function QueryInterface1(const IID: TGUID; out Obj): HRESULT; stdcall; function IDeckLinkVideoOutputCallback.QueryInterface = QueryInterface1; function IDeckLinkAudioOutputCallback.QueryInterface = QueryInterface1; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function RenderAudioSamples(preroll: Integer): HResult; stdcall; function ScheduledFrameCompleted(const completedFrame: IDeckLinkVideoFrame; results: _BMDOutputFrameCompletionResult): HResult; stdcall; function ScheduledPlaybackHasStopped: HResult; stdcall; private { Private declarations } public { Public declarations } end; var Form1: TForm1; m_DeckLink : IDeckLink = nil; m_deckLinkOutput : IDeckLinkOutput = nil; m_running : boolean = false; m_videoFrameBars : TSignalGenerator3DVideoFrame = nil; //IDeckLinkMutableVideoFrame = nil; m_videoFrameBlack : TSignalGenerator3DVideoFrame = nil; //IDeckLinkMutableVideoFrame = nil; m_audioBuffer : Pointer = nil; m_outputSignal : _OutputSignal; m_audioSampleDepth : _BMDAudioSampleType; m_audioSampleRate : word; m_audioChannelCount : integer; m_framesPerSecond : Int64; m_frameDuration : Int64; m_frameTimescale : Int64; m_audioSamplesPerFrame : cardinal; m_audioSamplesLength : cardinal; m_audioBufferSampleLength : int64; m_totalAudioSecondsScheduled : int64; m_totalFramesScheduled : Int64; m_frameWidth : integer; m_frameHeight : integer; implementation {$R *.dfm} (* TVideoFormat *) constructor TDeckLinkdisplayModeObject.Create(const name : string; const videoDisplayMode : IDeckLinkdisplayMode) ; begin fName := name; fvideoDisplayMode := videoDisplayMode; end; Procedure FillSine(audioBuffer: Pointer; sampleToWrite: longint; channels : integer; samleDepth : integer); var sample16 : SmallInt; sample32 : integer; i, ch : longint; begin case samleDepth of 16 : begin for i:=0 to sampleToWrite-1 do begin sample16:=Round(24576.0 * sin((i*2.0*PI) / 48.0)); for ch := 0 to channels-1 do begin PSmallInt(audioBuffer)^:=sample16; inc(PSmallInt(audioBuffer),1); end; end; end; 32 : begin for i:=0 to sampleToWrite-1 do begin sample32:=Round(1610612736.0 * sin((i*2.0*PI) / 48.0)); for ch := 0 to channels-1 do begin PInteger(audioBuffer)^:=sample32; inc(PInteger(audioBuffer),1); end; end; end; end; end; Procedure FillBlack(theFrame : IDeckLinkVideoFrame); var nextword : pDWORD; width : cardinal; height : cardinal; wordsRemaining : cardinal; begin theframe.GetBytes(Pointer(nextword)); width := theFrame.GetWidth(); height := theFrame.GetHeight(); wordsRemaining := (width*2 * height) div 4; while (wordsRemaining > 0) do begin nextword^:= $10801080; inc(nextword, 1); dec(wordsRemaining); end; end; Procedure FillColourBars(theFrame : IDeckLinkVideoFrame; reversed : boolean); var nextword : pDWORD; bars : array[0..7] of cardinal; width : integer; height : integer; x,y : integer; colourBarCount : integer; pos : integer; begin theFrame.GetBytes(Pointer(nextWord)); width := theFrame.GetWidth(); height := theFrame.GetHeight(); if (width > 720) then begin move(gHD75pcColourBars[0], bars[0], sizeof(gHD75pcColourBars)); colourBarCount := sizeof(gHD75pcColourBars) div sizeof(gHD75pcColourBars[0]); end else begin move(gSD75pcColourBars[0], bars[0], sizeof(gSD75pcColourBars)); colourBarCount := sizeof(gSD75pcColourBars) div sizeof(gSD75pcColourBars[0]); end; for y := 0 to height-1 do begin x:=0; while x < width do begin pos := x * colourBarCount div width; if (reversed) then pos := colourBarCount - pos - 1; nextword^:= bars[pos]; inc(nextword, 1); inc(x, 2); end; end; end; function TForm1.GetBytesPerPixel(const pixelFormat: _BMDPixelFormat): integer; var bytesPerPixel : integer; begin case pixelFormat of bmdFormat8BitYUV: bytesPerPixel := 2; bmdFormat10BitYUV: bytesPerPixel := 4; bmdFormat8BitARGB: bytesPerPixel := 4; bmdFormat10BitRGB: bytesPerPixel := 4; else bytesPerPixel := 2; end; result:= bytesPerPixel; end; Procedure TForm1.WriteNextAudioSamples(); var sampleFramesWritten : SYSUINT; begin // Write one second of audio to the DeckLink API. if (m_outputSignal = kOutputSignalPip) then begin // Schedule one-frame of audio tone if (m_deckLinkOutput.ScheduleAudioSamples(m_audioBuffer, m_audioSamplesPerFrame, (m_totalAudioSecondsScheduled * m_audioBufferSampleLength), m_audioSampleRate, sampleFramesWritten) <> S_OK) then exit; end else begin // Schedule one-second (minus one frame) of audio tone if (m_deckLinkOutput.ScheduleAudioSamples(m_audioBuffer, (m_audioBufferSampleLength - m_audioSamplesPerFrame), (m_totalAudioSecondsScheduled * m_audioBufferSampleLength) + m_audioSamplesPerFrame, m_audioSampleRate, sampleFramesWritten) <> S_OK) then exit; end; inc(m_totalAudioSecondsScheduled); end; Procedure TForm1.ScheduleNextFrame(prerolling : boolean); var result : HRESULT; begin if not prerolling then begin // If not prerolling, make sure that playback is still active if not m_running then exit; end; if m_outputSignal = kOutputSignalPip then begin if (m_totalFramesScheduled mod m_framesPerSecond)=0 then begin // On each second, schedule a frame of bars result:=m_deckLinkOutput.ScheduleVideoFrame(m_videoFrameBars, (m_totalFramesScheduled * m_frameDuration), m_frameDuration, m_frameTimescale); if FAILED(result) then exit; end else begin // Schedue frames of black result := m_deckLinkOutput.ScheduleVideoFrame(m_videoFrameBlack, (m_totalFramesScheduled * m_frameDuration), m_frameDuration, m_frameTimescale); if FAILED(result) then exit; end; end else begin if (m_totalFramesScheduled mod m_framesPerSecond)=0 then begin // On each second, schedule a frame of black result := m_deckLinkOutput.ScheduleVideoFrame(m_videoFrameBlack, (m_totalFramesScheduled * m_frameDuration), m_frameDuration, m_frameTimescale); if FAILED(result) then exit; end else begin // Schedue frames of color bars result:=m_deckLinkOutput.ScheduleVideoFrame(m_videoFrameBars, (m_totalFramesScheduled * m_frameDuration), m_frameDuration, m_frameTimescale); if FAILED(result) then exit; end; end; inc(m_totalFramesScheduled); end; function TForm1._AddRef: Integer; begin Result := 1; end; function TForm1._Release: Integer; begin result:=1; end; function TForm1.QueryInterface1(const IID: TGUID; out Obj): HRESULT; begin Result := E_NOINTERFACE; end; function TForm1.RenderAudioSamples(preroll: Integer): HResult; begin // Provide further audio samples to the DeckLink API until our preferred buffer waterlevel is reached WriteNextAudiosamples; // Start audio and video output if preroll > 0 then m_deckLinkOutput.StartScheduledPlayback(0,100,1.0); result:=S_OK; end; function TForm1.ScheduledPlaybackHasStopped: HResult; begin result:=S_OK; end; function TForm1.ScheduledFrameCompleted(const completedFrame: IDeckLinkVideoFrame; results: _BMDOutputFrameCompletionResult): HResult; begin // When a video frame has been ScheduleNextFrame(false); result:=S_OK; end; procedure TForm1.RefreshDisplayModeMenu(); var // Populate the display mode combo with a list of display modes supported by the installed DeckLink card displayModeIterator : IDeckLinkDisplayModeIterator; deckLinkDisplayMode : IDeckLinkDisplayMode; resultDisplayMode : IDeckLinkDisplayMode; pixelFormat : _BMDPixelFormat; i : integer; modeName : widestring; hr : HRESULT; displayModeSupport : _BMDDisplayModeSupport; videoOutputFlags : _BMDVideoOutputFlags; VideoFormat : TDeckLinkdisplayModeObject; begin pixelFormat := _BMDPixelFormat(m_pixelFormatCombo.Items.Objects[m_pixelFormatCombo.ItemIndex]); for i := 0 to m_videoFormatCombo.Items.Count-1 do begin VideoFormat := m_videoFormatCombo.Items.Objects[i] as TDeckLinkdisplayModeObject; VideoFormat.Destroy; end; m_videoFormatCombo.Clear; if m_deckLinkOutput.GetDisplayModeIterator(displayModeIterator) <> S_OK then exit; while (displayModeIterator.Next(deckLinkDisplayMode) = S_OK) do begin videoOutputFlags := bmdVideoOutputDualStream3D; if (deckLinkDisplayMode.GetName(modeName) <> S_OK) then begin deckLinkDisplayMode._Release(); continue; end; m_videoFormatCombo.Items.AddObject(modeName, TDeckLinkdisplayModeObject.Create(modeName, DeckLinkdisplayMode)); hr := m_deckLinkOutput.DoesSupportVideoMode(deckLinkDisplayMode.GetDisplayMode(), pixelFormat, videoOutputFlags, displayModeSupport, resultDisplayMode); if ((hr <> S_OK) or (displayModeSupport = bmdDisplayModeNotSupported)) then continue; m_videoFormatCombo.Items.AddObject(modeName + ' 3D', TDeckLinkdisplayModeObject.Create(modeName, DeckLinkdisplayMode)); deckLinkDisplayMode._AddRef(); end; if assigned(displayModeIterator) then displayModeIterator := nil; m_videoFormatCombo.ItemIndex := 0; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin if m_running then StopRunning(); if Assigned(m_deckLinkOutput) then begin m_deckLinkOutput.SetScheduledFrameCompletionCallback(nil); m_deckLinkOutput.SetAudioCallback(nil); end; end; procedure TForm1.FormCreate(Sender: TObject); label bail; var DisplayModeIterator : IDeckLinkDisplayModeIterator; DeckLinkdisplayMode : IDeckLinkdisplayMode; DeckLinkIterator : IDeckLinkIterator; success : boolean; result : HRESULT; begin // Initialize instance variables m_running := false; m_deckLink := nil; m_deckLinkOutput := nil; m_videoFrameBlack := nil; m_videoFrameBars := nil; m_audioBuffer := nil; DeckLinkdisplayMode := nil; DisplayModeIterator := nil; DeckLinkIterator := nil; success := false; // Initialize the DeckLink API result:= CoInitialize(nil); result := CoCreateInstance(CLASS_CDeckLinkIterator, nil, CLSCTX_ALL, IID_IDeckLinkIterator, DeckLinkIterator); if result <> S_OK then begin showmessage(format('This application requires the DeckLink drivers installed.'+#10#13+'Please install the Blackmagic DeckLink drivers to use the features of this application.'+#10#13+'result = %08x.', [result])); goto bail; end; // Connect to the first DeckLink instance result:=deckLinkIterator.Next(m_deckLink); if result <> S_OK then begin showmessage(format('This application requires a DeckLink PCI card.'+#10#13+'You will not be able to use the features of this application until a DeckLink PCI card is installed.'+#10#13+'result = %08x.', [result])); goto bail; end; // Obtain the audio/video output interface (IDeckLinkOutput) result:=m_DeckLink.QueryInterface(IID_IDeckLinkOutput, m_deckLinkOutput); if result <> S_OK then begin showmessage(format('Could not obtain the IDeckLinkOutput interface.'+#10#13+'result = %08x.', [result])); goto bail; end; // Provide this class as a delegate to the audio and video output interfaces m_deckLinkOutput.SetScheduledFrameCompletionCallback(Form1); m_deckLinkOutput.SetAudioCallback(Form1); m_outputSignalCombo.Clear; m_audioChannelCombo.Clear; m_audioSampleDepthCombo.Clear; m_pixelFormatCombo.Clear; // Set the item data for combo box entries to store audio channel count and sample depth information m_outputSignalCombo.Items.AddObject('Pip', TObject(kOutputSignalPip)); m_outputSignalCombo.Items.AddObject('Drop', TObject(kOutputSignalDrop)); // m_audioChannelCombo.Items.AddObject('2 channels', TObject(2)); // 2 channels m_audioChannelCombo.Items.AddObject('8 channels', TObject(8)); // 8 channels m_audioChannelCombo.Items.AddObject('16 channels', TObject(16)); // 16 channels // m_audioSampleDepthCombo.Items.AddObject('16-bit', TObject(16)); // 16-bit samples m_audioSampleDepthCombo.Items.AddObject('32-bit', TObject(32)); // 32-bit samples m_pixelFormatCombo.Items.AddObject('8Bit YUV', TObject(bmdFormat8BitYUV)); m_pixelFormatCombo.Items.AddObject('10Bit YUV', TObject(bmdFormat10BitYUV)); m_pixelFormatCombo.Items.AddObject('8Bit ARGB', TObject(bmdFormat8BitARGB)); m_pixelFormatCombo.Items.AddObject('10Bit RGB', TObject(bmdFormat10BitRGB)); // Select the first item in each combo box m_outputSignalCombo.ItemIndex := 0; m_audioChannelCombo.ItemIndex := 0; m_audioSampleDepthCombo.ItemIndex := 0; m_pixelFormatCombo.ItemIndex := 0; RefreshDisplayModeMenu(); success:=true; bail: begin if not success then begin if assigned(m_deckLinkOutput) then m_deckLinkOutput:=nil; if assigned(m_deckLink) then m_deckLink:=nil; // Disable the user interface if we could not succsssfully connect to a DeckLink device m_startButton.Enabled:=false; EnableInterface(false); end; if assigned(deckLinkIterator) then deckLinkIterator:=nil; end; end; procedure TForm1.EnableInterface(enable : boolean); begin // Set the enable state of user interface elements m_outputSignalCombo.Enabled:=enable; m_audioChannelCombo.Enabled:=enable; m_audioSampleDepthCombo.Enabled:=enable; m_videoFormatCombo.Enabled:=enable; m_pixelFormatCombo.Enabled:=enable; end; function TForm1.CreateBlackFrame(): TSignalGenerator3DVideoFrame; label bail; var referenceBlack : IDeckLinkMutableVideoFrame; scheduleBlack : IDeckLinkMutableVideoFrame; pixelFormat : _BMDPixelFormat; HR : HRESULT; bytesPerPixel : integer; frameConverter : IDeckLinkVideoConversion; ret : TSignalGenerator3DVideoFrame; begin referenceBlack := nil; scheduleBlack := nil; frameConverter := nil; ret := nil; pixelFormat := _BMDPixelFormat(m_pixelFormatCombo.Items.Objects[m_pixelFormatCombo.ItemIndex]); bytesPerPixel := GetBytesPerPixel(pixelFormat); hr := m_deckLinkOutput.CreateVideoFrame(m_frameWidth, m_frameHeight, m_frameWidth*bytesPerPixel, pixelFormat, bmdFrameFlagDefault, scheduleBlack); if (hr <> S_OK) then goto bail; if (pixelFormat = bmdFormat8BitYUV) then begin FillBlack(scheduleBlack); end else begin hr := m_deckLinkOutput.CreateVideoFrame(m_frameWidth, m_frameHeight, m_frameWidth*2, bmdFormat8BitYUV, bmdFrameFlagDefault, referenceBlack); if (hr <> S_OK) then goto bail; FillBlack(referenceBlack); hr := CoCreateInstance(CLASS_CDeckLinkVideoConversion, nil, CLSCTX_ALL, IID_IDeckLinkVideoConversion, frameConverter); if (hr <> S_OK) then goto bail; hr := frameConverter.ConvertFrame(referenceBlack, scheduleBlack); if (hr <> S_OK) then goto bail; end; ret := TSignalGenerator3DVideoFrame.Create(scheduleBlack); bail: if assigned(referenceBlack) then referenceBlack := nil; if assigned(scheduleBlack) then scheduleBlack := nil; if assigned(frameConverter) then frameConverter := nil; result := ret; end; function TForm1.CreateBarsFrame(): TSignalGenerator3DVideoFrame; label bail; var referenceBarsLeft : IDeckLinkMutableVideoFrame; referenceBarsRight : IDeckLinkMutableVideoFrame; scheduleBarsLeft : IDeckLinkMutableVideoFrame; scheduleBarsRight : IDeckLinkMutableVideoFrame; pixelFormat : _BMDPixelFormat; HR : HRESULT; bytesPerPixel : integer; frameConverter : IDeckLinkVideoConversion; ret : TSignalGenerator3DVideoFrame; begin referenceBarsLeft := nil; referenceBarsRight := nil; scheduleBarsLeft := nil; scheduleBarsRight := nil; frameConverter := nil; ret := nil; pixelFormat := _BMDPixelFormat(m_pixelFormatCombo.Items.Objects[m_pixelFormatCombo.ItemIndex]); bytesPerPixel := GetBytesPerPixel(pixelFormat); hr := m_deckLinkOutput.CreateVideoFrame(m_frameWidth, m_frameHeight, m_frameWidth*bytesPerPixel, pixelFormat, bmdFrameFlagDefault, scheduleBarsLeft); if (hr <> S_OK) then goto bail; hr := m_deckLinkOutput.CreateVideoFrame(m_frameWidth, m_frameHeight, m_frameWidth*bytesPerPixel, pixelFormat, bmdFrameFlagDefault, scheduleBarsRight); if (hr <> S_OK) then goto bail; if (pixelFormat = bmdFormat8BitYUV) then begin FillColourBars(scheduleBarsLeft, false); FillColourBars(scheduleBarsRight, true); end else begin hr := m_deckLinkOutput.CreateVideoFrame(m_frameWidth, m_frameHeight, m_frameWidth*2, bmdFormat8BitYUV, bmdFrameFlagDefault, referenceBarsLeft); if (hr <> S_OK) then goto bail; hr := m_deckLinkOutput.CreateVideoFrame(m_frameWidth, m_frameHeight, m_frameWidth*2, bmdFormat8BitYUV, bmdFrameFlagDefault, referenceBarsRight); if (hr <> S_OK) then goto bail; FillColourBars(referenceBarsLeft, false); FillColourBars(referenceBarsRight, true); hr := CoCreateInstance(CLASS_CDeckLinkVideoConversion, nil, CLSCTX_ALL, IID_IDeckLinkVideoConversion, frameConverter); if (hr <> S_OK) then goto bail; hr := frameConverter.ConvertFrame(referenceBarsLeft, scheduleBarsLeft); if (hr <> S_OK) then goto bail; hr := frameConverter.ConvertFrame(referenceBarsRight, scheduleBarsRight); if (hr <> S_OK) then goto bail; end; ret := TSignalGenerator3DVideoFrame.Create(scheduleBarsLeft, scheduleBarsRight); bail: if assigned(scheduleBarsLeft) then scheduleBarsLeft := nil; if assigned(scheduleBarsRight) then scheduleBarsRight := nil; if assigned(referenceBarsLeft) then scheduleBarsLeft := nil; if assigned(referenceBarsRight) then referenceBarsRight := nil; if assigned(frameConverter) then frameConverter := nil; result := ret; end; procedure TForm1.m_startButtonClick(Sender: TObject); begin if m_running then StopRunning else StartRunning; end; Procedure TForm1.StopRunning(); var actualStopTime: Int64; begin // Stop the audio and video output streams immediately m_deckLinkOutput.StopScheduledPlayback(0,actualStopTime,0); // m_deckLinkOutput.DisableAudioOutput; m_deckLinkOutput.DisableVideoOutput; if assigned(m_videoFrameBlack) then m_videoFrameBlack._Release; m_videoFrameBlack:=nil; if assigned(m_videoFrameBars) then m_videoFrameBars._Release; m_videoFrameBars:=nil; if assigned(m_audioBuffer) then HeapFree(GetProcessHeap,0,m_audioBuffer); // Success; update the UI m_running:=false; m_startButton.Caption:='Start'; // Re-enable the user interface when stopped EnableInterface(true); end; Procedure TForm1.StartRunning(); label bail; var videoDisplayMode : IDeckLinkdisplayMode; DisplayModeIterator : IDeckLinkDisplayModeIterator; videoOutputFlags : _BMDVideoOutputFlags; i : integer; videoFormatName : string; result : HRESULT; VideoFormat : TDeckLinkdisplayModeObject; begin videoDisplayMode := nil; DisplayModeIterator := nil; videoOutputFlags := bmdVideoOutputFlagDefault; videoFormatName:=m_videoFormatCombo.Items.Strings[m_videoFormatCombo.ItemIndex]; if videoFormatName.Contains(' 3D') then videoOutputFlags := bmdVideoOutputDualStream3D; // Determine the audio and video properties for the output stream m_outputSignal := _OutputSignal(m_outputSignalCombo.ItemIndex); m_audioChannelCount:= Integer(m_audioChannelCombo.Items.Objects[m_audioChannelCombo.ItemIndex]); m_audioSampleDepth := _BMDAudioSampleType(m_audioSampleDepthCombo.Items.Objects[m_audioSampleDepthCombo.ItemIndex]); m_audioSampleRate := bmdAudioSampleRate48kHz; // // - Extract the IDeckLinkDisplayMode from the display mode popup menu (stashed in the item's tag) VideoFormat := m_videoFormatCombo.items.Objects[m_videoFormatCombo.ItemIndex] as TDeckLinkdisplayModeObject; videoDisplayMode := VideoFormat.videoDisplayMode; m_frameWidth := videoDisplayMode.GetWidth(); m_frameHeight := videoDisplayMode.GetHeight(); videoDisplayMode.GetFrameRate(m_frameDuration, m_frameTimescale); // Calculate the number of frames per second, rounded up to the nearest integer. For example, for NTSC (29.97 FPS), framesPerSecond == 30. m_framesPerSecond := (m_frameTimeScale + (m_frameDuration-1)) div m_frameDuration; // Set the video output mode result := m_decklinkOutput.EnableVideoOutput(videoDisplayMode.GetDisplayMode, bmdVideoOutputFlagDefault); if result <> S_OK then begin showmessage(format('Could not obtain the IDeckLinkOutput.EnableVideoOutput interface.'+#10#13+'result = %08x.', [result])); goto bail; end; // Set the audio output mode result:=m_decklinkOutput.EnableAudioOutput(m_audioSampleRate, m_audioSampleDepth, m_audioChannelCount, bmdAudioOutputStreamTimestamped); if result <> S_OK then begin showmessage(format('Could not obtain the IDeckLinkOutput.EnableAudioOutput interface.'+#10#13+'result = %08x.', [result])); goto bail; end; // Generate one second of audio tone m_audioSamplesPerFrame:=(m_audioSampleRate * m_frameDuration) div m_frameTimescale; m_audioBufferSampleLength:= (m_framesPerSecond * m_audioSampleRate * m_frameDuration) div m_frameTimescale; m_audioBuffer := HeapAlloc(GetProcessHeap(),0, (m_audioBufferSampleLength * m_audioChannelCount * (m_audioSampleDepth div 8))); if not assigned(m_audioBuffer) then goto bail; FillSine(m_audioBuffer, m_audioBufferSampleLength, m_audioChannelCount, m_audioSampleDepth); // Generate a frame of black m_videoFrameBlack := CreateBlackFrame(); if not assigned(m_videoFrameBlack) then goto bail; {result:=m_decklinkOutput.CreateVideoFrame(m_frameWidth, m_frameHeight, m_frameWidth*4, bmdFormat8bitBGRA, bmdFrameFlagFlipVertical, m_videoFrameBlack); if result <> S_OK then begin showmessage(format('Could not obtain the IDeckLinkOutput.CreateVideoFrame interface.'+#10#13+'result = %08x.', [result])); goto bail; end; FillBlack(m_videoFrameBlack); } {result:=m_decklinkOutput.CreateVideoFrame(m_frameWidth, m_frameHeight, m_frameWidth*4, bmdFormat8bitBGRA, bmdFrameFlagDefault, m_videoFrameBars); if result <> S_OK then begin showmessage(format('Could not obtain the IDeckLinkOutput.CreateVideoFrame interface.'+#10#13+'result = %08x.', [result])); goto bail; end; FillColourBars(m_videoFrameBars);} // Generate a frame of colour bars m_videoFrameBars := CreateBarsFrame(); if not assigned(m_videoFrameBars) then goto bail; // Begin video preroll by scheduling a second of frames in hardware m_totalFramesScheduled :=1; for I := 0 to m_framesPerSecond-1 do ScheduleNextFrame(true); // Begin audio preroll. This will begin calling our audio callback, which will start the DeckLink output stream. m_totalAudioSecondsScheduled :=0; result:=m_deckLinkOutput.BeginAudioPreroll; if result <> S_OK then begin showmessage(format('Could not obtain the IDeckLinkOutput.BeginAudioPreroll interface.'+#10#13+'result = %08x.', [result])); goto bail; end; // Success; update the UI m_running := true; m_startButton.Caption:='Stop'; // Disable the user interface while running (prevent the user from making changes to the output signal) enableInterface(false); exit; bail : begin // *** Error-handling code. Cleanup any resources that were allocated. *** // StopRunning; end; end; end.
unit ViewMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, System.ImageList, Vcl.ImgList, System.Actions, Vcl.ActnList, Vcl.CheckLst, Vcl.Grids, IOUtils, StrUtils, MyUtils, Install, Vcl.ComCtrls, WinSvc, Vcl.ExtCtrls; type TWindowMain = class(TForm) Images: TImageList; OpenFilePath: TFileOpenDialog; OpenDllPath: TFileOpenDialog; Page: TPageControl; TabSetup: TTabSheet; BtnPath: TSpeedButton; LblPort: TLabel; LblVersion: TLabel; LblPath: TLabel; LblServiceName: TLabel; LblDll: TLabel; CheckAll: TCheckBox; TxtPort: TEdit; BoxVersion: TComboBox; TxtPath: TEdit; BtnCopyDll: TSpeedButton; BtnDeleteDll: TSpeedButton; BtnAdd: TSpeedButton; BtnRemove: TSpeedButton; BtnExecute: TSpeedButton; BtnLoadFolders: TSpeedButton; Actions: TActionList; ActPath: TAction; ActAdd: TAction; ActRemove: TAction; ActLoadFolders: TAction; ActCopyDll: TAction; DeleteDll: TAction; ActInstall: TAction; ActUninstall: TAction; ActEsc: TAction; BtnAddFirewall: TSpeedButton; ActAddFirewall: TAction; ActRemoveFirewall: TAction; BtnRemoveFirewall: TSpeedButton; BtnServices: TSpeedButton; ActServices: TAction; MemoLog: TMemo; BtnOpenDir: TSpeedButton; ActOpenDir: TAction; LblDefaultInstance: TLabel; ListDll: TCheckListBox; TxtServiceName: TEdit; RadioGroupMethod: TRadioGroup; ActStart: TAction; ShapeStatusService: TShape; TimerStatus: TTimer; ShapeStatusPath: TShape; BtnRemoveService: TSpeedButton; BtnStopService: TSpeedButton; BtnStartService: TSpeedButton; ActRemoveService: TAction; ActStopService: TAction; ActStartService: TAction; ActChangeToInstall: TAction; ActChangeToUninstall: TAction; procedure ActPathExecute(Sender: TObject); procedure ActAddExecute(Sender: TObject); procedure ActRemoveExecute(Sender: TObject); procedure ActUninstallExecute(Sender: TObject); procedure ActInstallExecute(Sender: TObject); procedure ActEscExecute(Sender: TObject); procedure ActLoadFoldersExecute(Sender: TObject); procedure ActCopyDllExecute(Sender: TObject); procedure DeleteDllExecute(Sender: TObject); procedure FormActivate(Sender: TObject); procedure BoxVersionChange(Sender: TObject); procedure CheckAllClick(Sender: TObject); procedure ListDllClickCheck(Sender: TObject); procedure ActAddFirewallExecute(Sender: TObject); procedure ActRemoveFirewallExecute(Sender: TObject); procedure ActServicesExecute(Sender: TObject); procedure ActOpenDirExecute(Sender: TObject); procedure ActStartExecute(Sender: TObject); procedure RadioGroupMethodClick(Sender: TObject); procedure TimerStatusTimer(Sender: TObject); procedure ActRemoveServiceExecute(Sender: TObject); procedure ActStopServiceExecute(Sender: TObject); procedure ActStartServiceExecute(Sender: TObject); procedure ActChangeToInstallExecute(Sender: TObject); procedure ActChangeToUninstallExecute(Sender: TObject); private function GetInstallation: TInstall; procedure UpdateButtons; end; var WindowMain: TWindowMain; implementation {$R *.dfm} procedure TWindowMain.FormActivate(Sender: TObject); begin BoxVersionChange(BoxVersion); ActLoadFolders.Execute; UpdateButtons; //CheckAll.Checked := true; end; procedure TWindowMain.TimerStatusTimer(Sender: TObject); var ServiceStatus: Cardinal; begin if TDirectory.Exists(TxtPath.Text) then begin ShapeStatusPath.Brush.Color := clGreen; ShapeStatusPath.Hint := 'Diretório Existente'; end else begin ShapeStatusPath.Brush.Color := clRed; ShapeStatusPath.Hint := 'Diretório Não Existente'; end; ServiceStatus := TUtils.GetServiceStatus('', 'FirebirdServer' + TUtils.IfEmpty(TxtServiceName.Text, 'DefaultInstance')); case TStatusService(ServiceStatus) of csNotInstalled: begin ShapeStatusService.Brush.Color := clRed; ShapeStatusService.Hint := 'Serviço Não Instalado'; end; csPaused: begin ShapeStatusService.Brush.Color := clYellow; ShapeStatusService.Hint := 'Serviço Pausado'; end; csStopped: begin ShapeStatusService.Brush.Color := clYellow; ShapeStatusService.Hint := 'Serviço Parado'; end; csRunning: begin ShapeStatusService.Brush.Color := clGreen; ShapeStatusService.Hint := 'Serviço Rodando'; end; end; end; procedure TWindowMain.ActAddExecute(Sender: TObject); begin if OpenDllPath.Execute then begin ListDll.Items.Add(OpenDllPath.FileName); end; end; procedure TWindowMain.ActRemoveExecute(Sender: TObject); var Index: integer; begin Index := ListDll.ItemIndex; ListDll.DeleteSelected; if Index = 0 then begin ListDll.ItemIndex := 0; end else begin ListDll.ItemIndex := Index - 1; end; end; procedure TWindowMain.ActLoadFoldersExecute(Sender: TObject); var Path: string; begin for Path in TDirectory.GetDirectories('C:\') do begin if ContainsText(Path, 'NETSide') then begin ListDll.Items.Add(Path); end; end; end; procedure TWindowMain.ActCopyDllExecute(Sender: TObject); var Installation: TInstall; begin try Installation := GetInstallation; Installation.CopyDll; ShowMessage('Dlls Copiadas!'); finally FreeAndNil(Installation); end; end; procedure TWindowMain.DeleteDllExecute(Sender: TObject); var Installation: TInstall; begin try Installation := GetInstallation; Installation.DeleteDll; ShowMessage('Dlls Deletadas!'); finally FreeAndNil(Installation); end; end; procedure TWindowMain.ActAddFirewallExecute(Sender: TObject); begin TUtils.AddFirewallPort('Firebird' + TUtils.IfEmpty(TxtServiceName.Text, 'DefaultInstance'), TxtPort.Text); ShowMessage('Porta e serviço adicionados no firewall!'); end; procedure TWindowMain.ActRemoveFirewallExecute(Sender: TObject); begin TUtils.DeleteFirewallPort('Firebird' + TUtils.IfEmpty(TxtServiceName.Text, 'DefaultInstance')); ShowMessage('Porta e serviço removidos do firewall!'); end; procedure TWindowMain.ActServicesExecute(Sender: TObject); begin TUtils.ExecCmd('/C services.msc', 0); end; procedure TWindowMain.ActRemoveServiceExecute(Sender: TObject); begin TUtils.RemoveService('FirebirdServer' + TxtServiceName.Text); end; procedure TWindowMain.ActStopServiceExecute(Sender: TObject); begin TUtils.StopService('FirebirdServer' + TxtServiceName.Text); end; procedure TWindowMain.ActStartServiceExecute(Sender: TObject); begin TUtils.StartService('FirebirdServer' + TxtServiceName.Text); end; procedure TWindowMain.ActOpenDirExecute(Sender: TObject); begin TUtils.OpenOnExplorer(TxtPath.Text); end; procedure TWindowMain.RadioGroupMethodClick(Sender: TObject); var IsInstall: boolean; begin IsInstall := RadioGroupMethod.ItemIndex = 0; TxtPath.Enabled := IsInstall; BtnPath.Enabled := IsInstall; TxtPort.Enabled := IsInstall; end; procedure TWindowMain.ActStartExecute(Sender: TObject); begin case RadioGroupMethod.ItemIndex of 0: ActInstall.Execute; 1: ActUninstall.Execute; end; end; procedure TWindowMain.ActInstallExecute(Sender: TObject); var Installation: TInstall; begin try Screen.Cursor := crHourGlass; Application.ProcessMessages; Installation := GetInstallation; Installation.Install; finally Screen.Cursor := crDefault; FreeAndNil(Installation); end; end; procedure TWindowMain.ActUninstallExecute(Sender: TObject); var Installation: TInstall; begin try screen.Cursor := crHourGlass; Application.ProcessMessages; Installation := GetInstallation; Installation.Uninstall; finally Screen.Cursor := crDefault; FreeAndNil(Installation); end; end; procedure TWindowMain.ActPathExecute(Sender: TObject); begin if OpenFilePath.Execute then begin TxtPath.Text := OpenFilePath.FileName; end; end; procedure TWindowMain.ActEscExecute(Sender: TObject); begin Close; end; function TWindowMain.GetInstallation: TInstall; var Configs: TInstallConfig; I: integer; begin Configs := TInstallConfig.Create; with Configs do begin Version := TVersion(BoxVersion.ItemIndex); Path := TUtils.IfEmpty(TxtPath.Text, 'C:\Program Files (x86)\Firebird'); ServiceName := TxtServiceName.Text; Port := TUtils.IfEmpty(TxtPort.Text, '3050'); DllPaths := TStringList.Create; Log := MemoLog; for I := 0 to ListDll.Count - 1 do begin if ListDll.Checked[I] then begin DllPaths.Add(ListDll.Items[I]); end; end; end; Result := TInstall.Create(Configs); end; procedure TWindowMain.BoxVersionChange(Sender: TObject); begin case TVersion(BoxVersion.ItemIndex) of vrFb21: begin TxtPath.Text := 'C:\Program Files (x86)\Firebird\Firebird_2_1'; TxtServiceName.Text := 'NETSide2.1'; TxtPort.Text := '3050'; end; vrFb25: begin TxtPath.Text := 'C:\Program Files (x86)\Firebird\Firebird_2_5'; TxtServiceName.Text := 'NETSide2.5'; TxtPort.Text := '3060'; end; vrFb30: begin TxtPath.Text := 'C:\Program Files (x86)\Firebird\Firebird_3_0'; TxtServiceName.Text := 'NETSide3.0'; TxtPort.Text := '3070'; end; vrFb40: begin TxtPath.Text := 'C:\Program Files (x86)\Firebird\Firebird_4_0'; TxtServiceName.Text := 'NETSide4.0'; TxtPort.Text := '3080'; end; end; end; procedure TWindowMain.CheckAllClick(Sender: TObject); begin if CheckAll.Checked then begin ListDll.CheckAll(cbChecked); end else begin ListDll.CheckAll(cbUnchecked); end; UpdateButtons; end; procedure TWindowMain.ListDllClickCheck(Sender: TObject); begin UpdateButtons; end; procedure TWindowMain.UpdateButtons; var I: integer; Checked: boolean; begin Checked := false; for I := 0 to ListDll.Count - 1 do begin Checked := Checked or ListDll.Checked[I]; end; BtnCopyDll.Enabled := Checked; BtnDeleteDll.Enabled := Checked; end; procedure TWindowMain.ActChangeToInstallExecute(Sender: TObject); begin RadioGroupMethod.ItemIndex := 0; end; procedure TWindowMain.ActChangeToUninstallExecute(Sender: TObject); begin RadioGroupMethod.ItemIndex := 1; end; end.
unit datamodel.turndata.standard; interface uses cwCollections , datamodel , datamodel.gamedataobject.custom ; type TTurnData = class( TGameDataObject, ITurnData ) fQuestion: string; fSelection: ICardData; fAnswers: IList<ICardData>; fCards: IList<ICardData>; strict private function getQuestion: string; function getSelection: ICardData; function getAnswers: IList<ICardData>; function getCards: IList<ICardData>; procedure setQuestion( const value: string ); protected function ToJSON: string; override; public constructor Create; destructor Destroy; override; end; implementation uses System.JSON , cwCollections.Standard , datamodel.carddata.standard ; { TTurnData } constructor TTurnData.Create; begin inherited; fAnswers := TList<ICardData>.Create; fCards := TList<ICardData>.Create; fSelection := TCardData.Create; end; destructor TTurnData.Destroy; begin fAnswers := nil; fCards := nil; fSelection := nil; inherited; end; function TTurnData.getAnswers: IList<ICardData>; begin Result := fAnswers; end; function TTurnData.getCards: IList<ICardData>; begin Result := fCards; end; function TTurnData.getQuestion: string; begin Result := fQuestion; end; function TTurnData.getSelection: ICardData; begin Result := fSelection; end; procedure TTurnData.setQuestion(const value: string); begin fQuestion := Value; end; function TTurnData.ToJSON: string; var TurnData: TJSONObject; Selection: TJSONObject; Answer: TJSONObject; Card: TJSONObject; Answers: TJSONArray; Cards: TJSONArray; begin TurnData := TJSONObject.Create; try TurnData.AddPair(TJSONPair.Create('question',fQuestion)); Selection := TJSONObject.Create; Selection.AddPair('cardid',fSelection.CardID); Selection.AddPair('title',fSelection.Title); TurnData.AddPair('selection',Selection); Answers := TJSONArray.Create; TurnData.AddPair('answers',Answers); fAnswers.ForEach( procedure ( const item: ICardData ) begin Answer := TJSONObject.Create; Answer.AddPair('cardid',Item.CardID); Answer.AddPair('title',Item.Title); Answers.Add(Answer); end ); Cards := TJSONArray.Create; TurnData.AddPair('cards',Cards); fCards.ForEach( procedure ( const item: ICardData ) begin Card := TJSONObject.Create; Card.AddPair('cardid',Item.CardID); Card.AddPair('title',Item.Title); Cards.Add(Answer); end ); Result := TurnData.ToJSON; finally TurnData.DisposeOf; end; end; end.
unit UCommon; interface uses UDefinitions; function Elapsed(const AStartTick: Cardinal): string; overload; function Elapsed(const AStart: TDateTime): string; overload; procedure WaitFor(const AInterval: Cardinal; AWaitCondition: TConditionFunc); implementation uses System.SysUtils, Winapi.Windows, Vcl.Forms, UConstants; function Elapsed(const AStartTick: Cardinal): string; begin Result := FormatDateTime(cTimeStr, (GetTickCount - AStartTick) * c1MsecDate); end; function Elapsed(const AStart: TDateTime): string; overload; begin Result := FormatDateTime(cTimeStr, (Now - AStart)); end; procedure WaitFor(const AInterval: Cardinal; AWaitCondition: TConditionFunc); var crdStart: Cardinal; begin crdStart := GetTickCount; while ((GetTickCount - crdStart) < AInterval) and AWaitCondition do Application.ProcessMessages; end; end.
(*----------------------------------------------------------*) (* Übung 3 ; Beispiel 1 Vertauschungsprozedur *) (* Entwickler: Neuhold Michael *) (* Datum: 24.10.2018 *) (* Lösungsidee: 2 Real und 2 Int Werte eingeben *) (* 2 Prozeduren mit jeweils zwei call by *) (* reference Parametern, jeweils Werte der *) (* Parameter tauschen. Im Main-Teil Ausgeben. *) (*----------------------------------------------------------*) PROGRAM Vertauschungsprozedur; (* Vertausche REAL *) PROCEDURE SwapReal (VAR r1: REAL; VAR r2: REAL); VAR h : REAL; (* Hilfsvariable *) BEGIN h := r1; r1 := r2; r2 := h; END; (* Vertausche REAL *) (* Vertausche INT *) PROCEDURE SwapInt (VAR i1: INTEGER; VAR i2: INTEGER); VAR h : INTEGER; (* Hilfsvariable *) BEGIN h := i1; i1 := i2; i2 := h; END; (* Vertausche INT *) (* Main *) VAR i1,i2 : INTEGER; r1,r2 : REAL; BEGIN (* Eingaben *) WriteLn('Geben Sie zwei Zahlen vom Typ REAL ein:'); Write('Real1: '); ReadLn(r1); Write('Real2: '); ReadLn(r2); WriteLn('Geben Sie zwei Zahlen vom Typ INTEGER ein:'); Write('Int1: '); ReadLn(i1); Write('Int2: '); ReadLn(i2); (* Tauschen + Ausgabe *) SwapReal(r1,r2); SwapInt(i1,i2); WriteLn('Hier die Vertauschten Real-Werte:', r1,' ',r2); WriteLn('Hier die Vertauschten INT-Werte:', i1,' ',i2); END. (* Vertauschungsprozedur *)
unit RelatorioResumoCaixa; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, RelatorioTemplate, DB, RxQuery, DBTables, Placemnt, StdCtrls, Mask, ToolEdit, RxLookup, ExtCtrls, Buttons, jpeg, ComCtrls, ppDB, ppDBPipe, ppDBBDE, ppModule, ppVar, ppCtrls, ppBands, ppReport, ppStrtch, ppSubRpt, ppPrnabl, ppClass, ppCache, ppComm, ppRelatv, ppProd, ppViewr, UCrpe32, AdvOfficeStatusBar, AdvOfficeStatusBarStylers; type TFormRelatorioResumoCaixa = class(TFormRelatorioTEMPLATE) SQLTotaNumerario: TRxQuery; DSSQLTotaNumrario: TDataSource; SQLTotalOperacao: TRxQuery; SQLTotalOperacaoOPCXICOD: TIntegerField; SQLTotalOperacaoOPCXA60DESCR: TStringField; SQLTotalOperacaoCREDITOS: TBCDField; SQLTotalOperacaoDEBITOS: TBCDField; DSSQLTotalOperacao: TDataSource; SQLTerminal: TRxQuery; DSSQLTerminal: TDataSource; GroupBox3: TGroupBox; ComboTerminal: TRxDBLookupCombo; SQLTotaNumerarioNUMEICOD: TIntegerField; SQLTotaNumerarioNUMEA30DESCR: TStringField; SQLTotaNumerarioVLRCREDITO: TBCDField; SQLTotaNumerarioVLRDEBITO: TBCDField; SQLTotaNumerarioSALDO: TFloatField; GroupBox2: TGroupBox; ComboTerminal2: TRxDBLookupCombo; HoraInicial: TEdit; HoraFinal: TEdit; SQLTotalOperacaoSALDO: TFloatField; SQLOperador: TRxQuery; DSSQLOperador: TDataSource; GroupBox4: TGroupBox; ComboOperador: TRxDBLookupCombo; CKImpVendaCartoes: TCheckBox; ckImpProdutosVendidos: TCheckBox; ckImpEncerrantes: TCheckBox; SQLVendaCartoesCheques: TRxQuery; dsSQLVendaCartoesCheques: TDataSource; SQLVendaCartoesChequesCTRCN2VLR: TBCDField; SQLVendaCartoesChequesCTRCDVENC: TDateTimeField; SQLVendaCartoesChequesNUMEICOD: TIntegerField; SQLVendaCartoesChequesNUMEA30DESCR: TStringField; SQLVendaCartoesChequesTEF: TStringField; SQLVendaCartoesChequesBANCA5CODCHQ: TStringField; SQLVendaCartoesChequesCTRCA10AGENCIACHQ: TStringField; SQLVendaCartoesChequesCTRCA15NROCHQ: TStringField; PipeOperacao: TppBDEPipeline; PipeOperacaoppField1: TppField; PipeOperacaoppField2: TppField; PipeOperacaoppField3: TppField; PipeOperacaoppField4: TppField; PipeOperacaoppField5: TppField; PipeNumerario: TppBDEPipeline; PipeNumerarioppField1: TppField; PipeNumerarioppField2: TppField; PipeNumerarioppField3: TppField; PipeNumerarioppField4: TppField; PipeNumerarioppField5: TppField; PipeVendasCartoesCheques: TppBDEPipeline; PipeVendasCartoesChequesppField1: TppField; PipeVendasCartoesChequesppField2: TppField; PipeVendasCartoesChequesppField3: TppField; PipeVendasCartoesChequesppField4: TppField; PipeVendasCartoesChequesppField5: TppField; PipeVendasCartoesChequesppField6: TppField; PipeVendasCartoesChequesppField7: TppField; PipeVendasCartoesChequesppField8: TppField; ReportTotais: TppReport; ppTitleBand1: TppTitleBand; ppLabel1: TppLabel; ppLabel2: TppLabel; ppLabel3: TppLabel; LbPeriodo: TppLabel; LbTerminal: TppLabel; ppLabel9: TppLabel; ppSystemVariable1: TppSystemVariable; ppLabel14: TppLabel; ppHeaderBand1: TppHeaderBand; ppLabel10: TppLabel; ppLabel11: TppLabel; ppLabel12: TppLabel; ppLabel13: TppLabel; ppDetailBand1: TppDetailBand; ppDBText1: TppDBText; ppDBText2: TppDBText; ppDBText3: TppDBText; ppDBText4: TppDBText; ppSummaryBand2: TppSummaryBand; ppSubReport1: TppSubReport; ppChildReport1: TppChildReport; ppTitleBand5: TppTitleBand; ppLabel15: TppLabel; ppLabel23: TppLabel; ppLabel24: TppLabel; ppLabel32: TppLabel; ppDetailBand2: TppDetailBand; ppDBText5: TppDBText; ppDBText6: TppDBText; ppDBText7: TppDBText; ppDBText8: TppDBText; SumarioNumerarios: TppSummaryBand; ppDBCalc1: TppDBCalc; ppLabel33: TppLabel; ppLine4: TppLine; ppLine13: TppLine; SubProdutosVendidos: TppSubReport; ppChildReport5: TppChildReport; TituloProdutosVendidos: TppTitleBand; ppLabel41: TppLabel; ppLabel42: TppLabel; ppLabel43: TppLabel; ppLabel30: TppLabel; DetalheProdutosVendidos: TppDetailBand; ppDBText26: TppDBText; ppDBText27: TppDBText; ppDBText28: TppDBText; Produto: TppLabel; ppDBText20: TppDBText; SumarioProdutosVendidos: TppSummaryBand; ppLine5: TppLine; SubVendasCartoesCheque: TppSubReport; ppChildReport6: TppChildReport; TituloVendaCartoes: TppTitleBand; ppLabel7: TppLabel; ppLabel8: TppLabel; ppLabel46: TppLabel; ppLabel48: TppLabel; ppLabel47: TppLabel; ppLabel49: TppLabel; ppLabel50: TppLabel; DetalheVendaCartoes: TppDetailBand; ppDBText29: TppDBText; ppDBText30: TppDBText; ppDBText31: TppDBText; ppDBText32: TppDBText; ppDBText33: TppDBText; ppDBText34: TppDBText; TEF: TppLabel; SumarioVendaCartoes: TppSummaryBand; ppLine2: TppLine; ppDBCalc3: TppDBCalc; ppDBCalc7: TppDBCalc; ppLine11: TppLine; ppLabel45: TppLabel; ppLine12: TppLine; ppDBCalc8: TppDBCalc; dsSQLItensVendidos: TDataSource; SQLItensVendidos: TRxQuery; SQLItensVendidosPRODICOD: TIntegerField; SQLItensVendidosCPITN3VLRUNIT: TBCDField; SQLItensVendidosQTDE: TFloatField; SQLItensVendidosVLRTOTALITEM: TFloatField; ppLabel31: TppLabel; ppGroup1: TppGroup; ppGroupHeaderBand1: TppGroupHeaderBand; TotalProdutosVendidos: TppGroupFooterBand; ppDBCalc2: TppDBCalc; ppDBCalc4: TppDBCalc; ppOperador: TppLabel; ppReducaoZ: TppReport; ckLayout: TCheckBox; ppHeaderBand2: TppHeaderBand; ppDetailBand4: TppDetailBand; ppLabel39: TppLabel; ppLabel44: TppLabel; ppLabel51: TppLabel; ppLabel52: TppLabel; ppLabel53: TppLabel; ppLabel95: TppLabel; ppLabel96: TppLabel; ppCancelamentos: TppLabel; ppSangrias: TppLabel; ppVendaBruta: TppLabel; ppSuprimentos: TppLabel; ppVendaLiq: TppLabel; ppDescontos: TppLabel; ppLabel55: TppLabel; ppRecebimentos: TppLabel; LbTerminal2: TppLabel; LbPeriodo2: TppLabel; ppLabel58: TppLabel; ppLabel59: TppLabel; lbOperador2: TppLabel; ppLabel61: TppLabel; ppSubRepNumerarios: TppSubReport; ppReportNumerarios: TppChildReport; ppDetailBand5: TppDetailBand; ppSummaryBand1: TppSummaryBand; ppDBText63: TppDBText; ppDBText66: TppDBText; ppDBCalc10: TppDBCalc; ppDBCalc5: TppDBCalc; ppDBCalc6: TppDBCalc; ppLine9: TppLine; ppLabel54: TppLabel; ppTitleBand3: TppTitleBand; ppLabel56: TppLabel; ppLabel57: TppLabel; ppLabel60: TppLabel; ppSummaryBand3: TppSummaryBand; ppDBText21: TppDBText; ppDBText35: TppDBText; ppLabel62: TppLabel; LbEmpresa2: TppLabel; SQLTotalOperacaoDESCONTOS: TBCDField; ppLabel63: TppLabel; ppEstornoVenda: TppLabel; ppLabel64: TppLabel; ppLabel65: TppLabel; SQLItensVendidosCPITTOBS: TStringField; PipeItensVendidos: TppBDEPipeline; ppDBText36: TppDBText; procedure ExecutarBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ReportTotaisPreviewFormCreate(Sender: TObject); procedure SumarioProdutosVendidosBeforePrint(Sender: TObject); procedure DetalheProdutosVendidosBeforePrint(Sender: TObject); procedure SumarioNumerariosBeforePrint(Sender: TObject); procedure ppTitleBand1BeforePrint(Sender: TObject); procedure ppHeaderBand2BeforePrint(Sender: TObject); procedure ppReducaoZPreviewFormCreate(Sender: TObject); private { Private declarations } Sigla : String; VendaBruta, Cancelamentos_Operador, Estorno_VendasRealizadas, Descontos, VendaLiq, Sangrias, Suprimentos, Recebimentos : Double; public { Public declarations } end; var FormRelatorioResumoCaixa: TFormRelatorioResumoCaixa; implementation uses DataModulo, DataModuloTemplate; {$R *.dfm} procedure TFormRelatorioResumoCaixa.ExecutarBtnClick(Sender: TObject); begin inherited; SQLTotaNumerario.Close ; SQLTotaNumerario.MacrobyName('MEmpresa').Value := SQLDeLista(ComboEmpresa, ListaEmpresas, '', 'MOVIMENTOCAIXA',''); SQLTotaNumerario.MacroByName('MTerminal').Value := '0=0'; if (HoraInicial.Text = '') and (HoraInicial.Text = '') then SQLTotaNumerario.MacroByName('MData').Value := 'MOVIMENTOCAIXA.MVCXDMOV >= "' + FormatDateTime('mm/dd/yyyy', De.Date) + '" and ' + 'MOVIMENTOCAIXA.MVCXDMOV <= "' + FormatDateTime('mm/dd/yyyy', Ate.Date) + '"' else SQLTotaNumerario.MacroByName('MData').Value := 'MOVIMENTOCAIXA.REGISTRO >= "' + FormatDateTime('mm/dd/yyyy ', De.Date) + HoraInicial.Text + '" and ' + 'MOVIMENTOCAIXA.REGISTRO <= "' + FormatDateTime('mm/dd/yyyy ', Ate.Date)+ HoraFinal.Text + '"'; SQLTotaNumerario.MacroByName('MTerminal').Value := '0=0'; if ComboTerminal.Value <> '' then SQLTotaNumerario.MacroByName('MTerminal').Value := 'MOVIMENTOCAIXA.TERMICOD = ' + ComboTerminal.Value; if ComboTerminal2.Value <> '' then SQLTotaNumerario.MacroByName('MTerminal').Value := SQLTotaNumerario.MacroByName('MTerminal').Value + ' or ' + 'MOVIMENTOCAIXA.TERMICOD = ' + ComboTerminal2.Value; if ComboOperador.Value <> '' then SQLTotaNumerario.MacroByName('MOperador').Value := 'MOVIMENTOCAIXA.USUAICOD = ' + ComboOperador.Value else SQLTotaNumerario.MacroByName('MOperador').Value := '0=0'; SQLTotaNumerario.Open; SQLTotalOperacao.Close; SQLTotalOperacao.MacrobyName('MEmpresa').Value := SQLDeLista(ComboEmpresa, ListaEmpresas, '', 'MOVIMENTOCAIXA',''); SQLTotalOperacao.MacroByName('MTerminal').Value := '0=0'; if (HoraInicial.Text = '') and (HoraInicial.Text = '') then SQLTotalOperacao.MacroByName('MData').Value := 'MOVIMENTOCAIXA.MVCXDMOV >= "' + FormatDateTime('mm/dd/yyyy', De.Date) + '" and ' + 'MOVIMENTOCAIXA.MVCXDMOV <= "' + FormatDateTime('mm/dd/yyyy', Ate.Date) + '"' else SQLTotalOperacao.MacroByName('MData').Value := 'MOVIMENTOCAIXA.REGISTRO >= "' + FormatDateTime('mm/dd/yyyy ', De.Date) + HoraInicial.Text + '" and ' + 'MOVIMENTOCAIXA.REGISTRO <= "' + FormatDateTime('mm/dd/yyyy ', Ate.Date)+ HoraFinal.Text + '"'; if ComboTerminal.Value <> '' then SQLTotalOperacao.MacroByName('MTerminal').Value := 'MOVIMENTOCAIXA.TERMICOD = ' + ComboTerminal.Value; if ComboTerminal2.Value <> '' then SQLTotalOperacao.MacroByName('MTerminal').Value := SQLTotalOperacao.MacroByName('MTerminal').Value + ' or ' + 'MOVIMENTOCAIXA.TERMICOD = ' + ComboTerminal2.Value; if ComboOperador.Value <> '' then SQLTotalOperacao.MacroByName('MOperador').Value := 'MOVIMENTOCAIXA.USUAICOD = ' + ComboOperador.Value else SQLTotalOperacao.MacroByName('MOperador').Value := '0=0'; SQLTotalOperacao.Open ; // Produtos Vendidos SQLItensVendidos.Close; SQLItensVendidos.MacrobyName('MEmpresa').Value := SQLDeLista(ComboEmpresa, ListaEmpresas, '', 'CUPOM',''); if (HoraInicial.Text = '') and (HoraInicial.Text = '') then SQLItensVendidos.MacroByName('MData').Value := 'CUPOM.CUPODEMIS >= "' + FormatDateTime('mm/dd/yyyy', De.Date) + '" and ' + 'CUPOM.CUPODEMIS <= "' + FormatDateTime('mm/dd/yyyy', Ate.Date) + '"' else SQLItensVendidos.MacroByName('MData').Value := 'CUPOM.CUPODEMIS >= "' + FormatDateTime('mm/dd/yyyy ', De.Date) + HoraInicial.Text + '" and ' + 'CUPOM.CUPODEMIS <= "' + FormatDateTime('mm/dd/yyyy ', Ate.Date)+ HoraFinal.Text + '"'; SQLItensVendidos.MacroByName('MTerminal').Value := '0=0'; if ComboTerminal.Value <> '' then SQLItensVendidos.MacroByName('MTerminal').Value := 'CUPOM.TERMICOD = ' + ComboTerminal.Value; if ComboTerminal2.Value <> '' then SQLItensVendidos.MacroByName('MTerminal').Value := SQLItensVendidos.MacroByName('MTerminal').Value + ' or ' + 'CUPOM.TERMICOD = ' + ComboTerminal2.Value; if ComboOperador.Value <> '' then SQLItensVendidos.MacroByName('MOperador').Value := 'CUPOM.USUAICODVENDA = ' + ComboOperador.Value else SQLItensVendidos.MacroByName('MOperador').Value := '0=0'; SQLItensVendidos.Open ; // Venda Cartoes , Cheques e Crediario SQLVendaCartoesCheques.Close; SQLVendaCartoesCheques.MacrobyName('MEmpresa').Value := SQLDeLista(ComboEmpresa, ListaEmpresas, '', 'CUPOM',''); if (HoraInicial.Text = '') and (HoraInicial.Text = '') then SQLVendaCartoesCheques.MacroByName('MData').Value := 'CUPOM.CUPODEMIS >= "' + FormatDateTime('mm/dd/yyyy', De.Date) + '" and ' + 'CUPOM.CUPODEMIS <= "' + FormatDateTime('mm/dd/yyyy', Ate.Date) + '"' else SQLVendaCartoesCheques.MacroByName('MData').Value := 'CUPOM.CUPODEMIS >= "' + FormatDateTime('mm/dd/yyyy ', De.Date) + HoraInicial.Text + '" and ' + 'CUPOM.CUPODEMIS <= "' + FormatDateTime('mm/dd/yyyy ', Ate.Date)+ HoraFinal.Text + '"'; SQLVendaCartoesCheques.MacroByName('MTerminal').Value := '0=0'; if ComboTerminal.Value <> '' then SQLVendaCartoesCheques.MacroByName('MTerminal').Value := 'CUPOM.TERMICOD = ' + ComboTerminal.Value; if ComboTerminal2.Value <> '' then SQLVendaCartoesCheques.MacroByName('MTerminal').Value := SQLItensVendidos.MacroByName('MTerminal').Value + ' or ' + 'CUPOM.TERMICOD = ' + ComboTerminal2.Value; if ComboOperador.Value <> '' then SQLVendaCartoesCheques.MacroByName('MOperador').Value := 'CUPOM.USUAICODVENDA = ' + ComboOperador.Value else SQLVendaCartoesCheques.MacroByName('MOperador').Value := '0=0'; SQLVendaCartoesCheques.Open ; if not ckLayout.Checked then ReportTotais.Print else begin Sangrias := 0; Suprimentos := 0; Recebimentos := 0; VendaBruta := 0; VendaLiq := 0; Cancelamentos_Operador := 0; Descontos := 0; Estorno_VendasRealizadas := 0; SQLTotalOperacao.First; while not SQLTotalOperacao.eof do begin Sigla := dm.SQLLocate('OPERACAOCAIXA ','OPCXICOD','OPCXA5SIGLA',SQLTotalOperacaoOPCXICOD.AsString); // Cancelamentos if (Sigla = 'CANVV') or (Sigla = 'CANVP') or (Sigla = 'CANCO') then Cancelamentos_Operador := Cancelamentos_Operador + SQLTotalOperacaoDEBITOS.Value; // Descontos if SQLTotalOperacaoDESCONTOS.Value > 0 then Descontos := Descontos + SQLTotalOperacaoDESCONTOS.Value; // Sangria if Sigla = 'SANGR' then Sangrias := Sangrias + SQLTotalOperacaoDEBITOS.Value; // Suprimento if Sigla = 'SUPRI' then Suprimentos := Suprimentos + SQLTotalOperacaoCREDITOS.Value; // Recebimentos Crediario if Sigla = 'RCCRD' then Recebimentos := Recebimentos + SQLTotalOperacaoCREDITOS.Value; // Venda Bruta if (Sigla = 'VDVIS') or (Sigla = 'VDCRD') or (Sigla = 'VDCHQ') or (Sigla = 'VDCRT') or (Sigla = 'EVPRZ') or (Sigla = 'EVCHP') or (Sigla = 'EVCRT') then begin VendaBruta := VendaBruta + SQLTotalOperacaoCREDITOS.Value; Estorno_VendasRealizadas := Estorno_VendasRealizadas + SQLTotalOperacaoDEBITOS.Value; end; SQLTotalOperacao.Next; end; VendaBruta := VendaBruta + Descontos; ppReducaoZ.Print; end; end; procedure TFormRelatorioResumoCaixa.FormCreate(Sender: TObject); begin inherited; SQLOperador.Open; SQLTerminal.Open; if dm.SQLUsuarioUSUACPERMVMOVCX.Value <> 'S' then begin de.Enabled := False; ate.Enabled := False; end; end; procedure TFormRelatorioResumoCaixa.ReportTotaisPreviewFormCreate( Sender: TObject); begin inherited; ReportTotais.PreviewForm.WindowState := wsMaximized; TppViewer(ReportTotais.PreviewForm.Viewer).ZoomPercentage := 100; end; procedure TFormRelatorioResumoCaixa.SumarioProdutosVendidosBeforePrint( Sender: TObject); begin inherited; if not CKImpVendaCartoes.Checked then begin TituloVendaCartoes.Visible := False; DetalheVendaCartoes.Visible := False; TotalProdutosVendidos.Visible := False; end else begin TituloVendaCartoes.Visible := True; DetalheVendaCartoes.Visible := True; TotalProdutosVendidos.Visible := True; end; end; procedure TFormRelatorioResumoCaixa.DetalheProdutosVendidosBeforePrint( Sender: TObject); begin inherited; PRODUTO.Caption := DM.SQLLocate('PRODUTO','PRODICOD','PRODA60DESCR',SQLItensVendidosPRODICOD.AsString); end; procedure TFormRelatorioResumoCaixa.SumarioNumerariosBeforePrint( Sender: TObject); begin inherited; if not ckImpProdutosVendidos.Checked then begin TituloProdutosVendidos.Visible := False; TotalProdutosVendidos.Visible := False; end else begin TituloProdutosVendidos.Visible := True; TotalProdutosVendidos.Visible := True; end; end; procedure TFormRelatorioResumoCaixa.ppTitleBand1BeforePrint( Sender: TObject); begin inherited; LbPeriodo.Caption := de.Text + ' até ' + Ate.Text; LbTerminal.Caption := ComboTerminal.Text + ' - ' + ComboTerminal2.Text; ppOperador.Caption := 'Operador: ' + ComboOperador.Text; end; procedure TFormRelatorioResumoCaixa.ppHeaderBand2BeforePrint( Sender: TObject); begin inherited; LbEmpresa2.Caption := ComboEmpresa.Text; LbPeriodo2.Caption := de.Text + ' até ' + Ate.Text; LbTerminal2.Caption := ComboTerminal.Text + ' - ' + ComboTerminal2.Text; lbOperador2.Caption := 'Operador: ' + ComboOperador.Text; ppVendaBruta.Caption := FormatFloat('##0.00',VendaBruta); ppCancelamentos.Caption := FormatFloat('##0.00',Cancelamentos_Operador); ppEstornoVenda.Caption := FormatFloat('##0.00',Estorno_VendasRealizadas); ppDescontos.Caption := FormatFloat('##0.00',Descontos); ppVendaLiq.Caption := FormatFloat('##0.00',VendaBruta- Cancelamentos_Operador- Estorno_VendasRealizadas- Descontos); ppSangrias.Caption := FormatFloat('##0.00',Sangrias); ppSuprimentos.Caption := FormatFloat('##0.00',Suprimentos); ppRecebimentos.Caption := FormatFloat('##0.00',Recebimentos); end; procedure TFormRelatorioResumoCaixa.ppReducaoZPreviewFormCreate( Sender: TObject); begin inherited; ppReducaoZ.PreviewForm.WindowState := wsMaximized; TppViewer(ppReducaoZ.PreviewForm.Viewer).ZoomPercentage := 100; end; end.
unit uBookClasses; interface uses Aurelius.Mapping.Attributes, Aurelius.Types.Proxy, System.Generics.Collections, Aurelius.Types.Blob; type TThreadListArray<T> = class(TThreadList<T>) public function ToArray: TArray<T>; end; type TBook = class; TAuthor = class; TPublisher = class; [Entity,Automapping] TAuthorBook = class private FId: Integer; [Association([TAssociationProp.Lazy], CascadeTypeAllButRemove)] FAuthor: Proxy<TAuthor>; [Association([TAssociationProp.Lazy], CascadeTypeAllButRemove)] FBook: Proxy<TBook>; function GetAuthor: TAuthor; function GetBook: TBook; procedure SetAuthor(const Value: TAuthor); procedure SetBook(const Value: TBook); public property Id: Integer read FId write FId; property Book: TBook read GetBook write SetBook; property Author: TAuthor read GetAuthor write SetAuthor; end; [Entity] [Automapping] TPublisherBook = class private FID: Integer; [Association([TAssociationProp.Lazy], CascadeTypeAllButRemove )] FPublisher: Proxy<TPublisher>; [Association([TAssociationProp.Lazy], CascadeTypeAllButRemove )] FBook: Proxy<TBook>; function GetBook: TBook; function GetPublisher: TPublisher; procedure SetBook(const Value: TBook); procedure SetPublisher(const Value: TPublisher); public property Book: TBook read GetBook write SetBook; property Publisher: TPublisher read GetPublisher write SetPublisher; end; [Entity,Automapping] TAuthor = class private FId: Integer; FName: String; FExtId: Integer; [ManyValuedAssociation( [TAssociationProp.Lazy],CascadeTypeAll, 'FAuthor' )] FBooks: Proxy<TList<TAuthorBook>>; function GetBooks: TList<TAuthorBook>; public constructor Create; destructor Destroy; override; property Id: Integer read FId write FId; property ExtId: Integer read FExtId write FExtId; property Name: String read FName write FName; property Books: TList<TAuthorBook> read GetBooks; end; [Entity,Automapping] TPublisher = class private FId: Integer; FName: String; FExtId: Integer; [ManyValuedAssociation([TAssociationProp.Lazy], CascadeTypeAll, 'FPublisher' )] FBooks: Proxy<TList<TPublisherBook>>; function GetBooks: TList<TPublisherBook>; public constructor Create; destructor Destroy; override; property Id: Integer read FId write FId; property ExtId: Integer read FExtId write FExtId; property Name: String read FName write FName; property Books: TList<TPublisherBook> read GetBooks; end; [Entity] [Automapping] TBook = class private FId: Integer; FTitle: String; FThumbUrl: String; FLang: String; FPubDate: String; FIsbn10: String; FIsbn13: String; [ManyValuedAssociation( [TAssociationProp.Lazy],CascadeTypeAll, 'FBook' )] FAuthors: Proxy<TList<TAuthorBook>>; [ManyValuedAssociation( [TAssociationProp.Lazy],CascadeTypeAll, 'FBook' )] FPublishers: Proxy<TList<TPublisherBook>>; FExtId: Integer; FThumb: TBlob; function GetAuthors: TList<TAuthorBook>; function GetPublishers: TList<TPublisherBook>; public constructor Create; destructor Destroy; override; property Id: Integer read FId write FId; property ExtId: Integer read FExtId write FExtId; property Title: String read FTitle write FTitle; property ThumbUrl: String read FThumbUrl write FThumbUrl; property Isbn10: String read FIsbn10 write FIsbn10; property Isbn13: String read FIsbn13 write FIsbn13; property Lang: String read FLang write FLang; property PubDate: String read FPubDate write FPubDate; property Thumb: TBlob read FThumb write FThumb; property Authors: TList<TAuthorBook> read GetAuthors; property Publishers: TList<TPublisherBook> read GetPublishers; end; TBookList = TList<TBook>; TAuthorList = TList<TAuthor>; TPublisherList = TList<TPublisher>; implementation { TAuthor } constructor TAuthor.Create; begin inherited; FBooks.SetInitialValue(TList<TAuthorBook>.Create); end; destructor TAuthor.Destroy; begin FBooks.DestroyValue; inherited; end; function TAuthor.GetBooks: TList<TAuthorBook>; begin Result := FBooks.Value; end; { TBook } constructor TBook.Create; begin inherited; FAuthors.SetInitialValue(TList<TAuthorBook>.Create); FPublishers.SetInitialValue(TList<TPublisherBook>.Create); end; destructor TBook.Destroy; begin FPublishers.DestroyValue; FAuthors.DestroyValue; inherited; end; function TBook.GetAuthors: TList<TAuthorBook>; begin Result := FAuthors.Value; end; function TBook.GetPublishers: TList<TPublisherBook>; begin Result := FPublishers.Value; end; { TAuthorBook } function TAuthorBook.GetAuthor: TAuthor; begin Result := FAuthor.Value; end; function TAuthorBook.GetBook: TBook; begin Result := FBook.Value; end; procedure TAuthorBook.SetAuthor(const Value: TAuthor); begin FAuthor.Value := Value; end; procedure TAuthorBook.SetBook(const Value: TBook); begin FBook.Value := Value; end; { TPublisherBook } function TPublisherBook.GetBook: TBook; begin Result := FBook.Value; end; function TPublisherBook.GetPublisher: TPublisher; begin Result := FPublisher.Value; end; procedure TPublisherBook.SetBook(const Value: TBook); begin FBook.Value := Value; end; procedure TPublisherBook.SetPublisher(const Value: TPublisher); begin FPublisher.Value := Value; end; { TPublisher } constructor TPublisher.Create; begin inherited; FBooks.SetInitialValue(TList<TPublisherBook>.Create); end; destructor TPublisher.Destroy; begin FBooks.DestroyValue; inherited; end; function TPublisher.GetBooks: TList<TPublisherBook>; begin Result := FBooks.Value; end; { TThreadListArray } function TThreadListArray<T>.ToArray: TArray<T>; var I: Integer; LList: TList<T>; begin LList := LockList; try SetLength(Result, LList.Count); for I := 0 to LList.Count - 1 do begin Result[I] := LList[I]; end; finally UnlockList; end; end; end.
{*******************************************************} { } { Delphi FireMonkey Notification Service } { } { Helpers for MacOS implementations } { } { Copyright(c) 2013 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.MediaLibrary.Android; interface procedure RegisterMediaLibraryServices; implementation uses System.Classes, System.SysUtils, System.IOUtils, System.Types, System.Math, FMX.MediaLibrary, FMX.Platform, FMX.Platform.Android, FMX.Controls, FMX.Helpers.Android, FMX.Graphics, FMX.Consts, FMX.Surfaces, FMX.Messages, FMX.Forms, FMX.Types3D, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.App, Androidapi.JNI.JavaTypes, Androidapi.JNI.Net, Androidapi.IOUtils, Androidapi.JNIBridge, Androidapi.JNI, Androidapi.Bitmap, Androidapi.JNI.Os, Androidapi.JNI.Embarcadero; type TImageManagerAndroid = class sealed (TInterfacedObject, IFMXCameraService, IFMXTakenImageService) strict private { Message Subscriptions } FSubscriptionReceivedBitmapID: Integer; FSubscriptionCancelReceivedBitmapID: Integer; { Events } FOnDidFinishTaking: TOnDidFinishTaking; FOnDidCancelTaking: TOnDidCancelTaking; { FMX Messages System } procedure DidReceiveBitmap(const Sender: TObject; const M: TMessage); procedure DidCancelReceiveBitmap(const Sender: TObject; const M: TMessage); { The returned size is a frame in which the size of the resultant photo will be adjusted } function ApproximateAdmissibleImageSize(const ASize: TSize): TSize; public constructor Create; destructor Destroy; override; { IFMXCameraService } procedure TakePhoto(const AControl: TControl; const ARequiredResolution: TSize; const AOnDidDinishTaking: TOnDidFinishTaking; const AOnDidCancelTaking: TOnDidCancelTaking); { IFMXTakenImageService } procedure TakeImageFromLibrary(const AControl: TControl; const ARequiredResolution: TSize; const AOnDidFinishTaking: TOnDidFinishTaking; const AOnDidCancelTaking: TOnDidCancelTaking); end; TSharingManagerAndroid = class sealed (TInterfacedObject, IFMXShareSheetActionsService) strict private type TSharingDataType = (sdtImage, sdtText); TSharingDataTypes = set of TSharingDataType; strict private function GetSharingMIMETypes(const DataTypes: TSharingDataTypes): string; function GetChooserCaption(const DataTypes: TSharingDataTypes): string; { IFMXShareSheetActionsService } procedure Share(const AControl: TControl; const AText: string; const AImage: TBitmap); end; var ImageManager: TImageManagerAndroid; SharingManager: TSharingManagerAndroid; procedure RegisterMediaLibraryServices; begin ImageManager := TImageManagerAndroid.Create; SharingManager := TSharingManagerAndroid.Create; if HasSystemService(TJPackageManager.JavaClass.FEATURE_CAMERA) or (HasSystemService(TJPackageManager.JavaClass.FEATURE_CAMERA_FRONT) ) then TPlatformServices.Current.AddPlatformService(IFMXCameraService, IInterface(ImageManager)); TPlatformServices.Current.AddPlatformService(IFMXTakenImageService, IInterface(ImageManager)); TPlatformServices.Current.AddPlatformService(IFMXShareSheetActionsService, IInterface(SharingManager)); end; { TImageManagerAndroid } constructor TImageManagerAndroid.Create; begin { Subscription } FSubscriptionReceivedBitmapID := TMessageManager.DefaultManager.SubscribeToMessage(TMessageReceivedImage, DidReceiveBitmap); FSubscriptionCancelReceivedBitmapID := TMessageManager.DefaultManager.SubscribeToMessage(TMessageCancelReceivingImage, DidCancelReceiveBitmap); end; destructor TImageManagerAndroid.Destroy; begin { Unsibscribe } TMessageManager.DefaultManager.Unsubscribe(TMessageReceivedImage, FSubscriptionReceivedBitmapID); TMessageManager.DefaultManager.Unsubscribe(TMessageCancelReceivingImage, FSubscriptionCancelReceivedBitmapID); inherited Destroy; end; procedure TImageManagerAndroid.DidCancelReceiveBitmap(const Sender: TObject; const M: TMessage); begin if Assigned(FOnDidCancelTaking) then FOnDidCancelTaking; end; procedure TImageManagerAndroid.DidReceiveBitmap(const Sender: TObject; const M: TMessage); var BitmapSurface: TBitmapSurface; NativeBitmap: JBitmap; RequestCode: Integer; Photo: TBitmap; begin if M is TMessageReceivedImage then begin NativeBitmap := (M as TMessageReceivedImage).Value; RequestCode := (M as TMessageReceivedImage).RequestCode; if Assigned(NativeBitmap) then begin BitmapSurface := TBitmapSurface.Create; try BitmapSurface.SetSize(NativeBitmap.getWidth, NativeBitmap.getHeight); JBitmapToSurface(NativeBitmap, BitmapSurface); Photo := TBitmap.Create(0, 0); try Photo.Assign(BitmapSurface); if Assigned(FOnDidFinishTaking) then FOnDidFinishTaking(Photo) else begin if RequestCode = TJFMXMediaLibrary.JavaClass.ACTION_TAKE_IMAGE_FROM_CAMERA then TMessageManager.DefaultManager.SendMessage(Self, TMessageDidFinishTakingImageFromCamera.Create(Photo)); if RequestCode = TJFMXMediaLibrary.JavaClass.ACTION_TAKE_IMAGE_FROM_LIBRARY then TMessageManager.DefaultManager.SendMessage(Self, TMessageDidFinishTakingImageFromLibrary.Create(Photo)); end; finally Photo.Free; end; finally BitmapSurface.Free; end; end; end; end; function TImageManagerAndroid.ApproximateAdmissibleImageSize(const ASize: TSize): TSize; begin Result.cx := Min(TContext3D.MaxTextureSize, ASize.Width); Result.cy := Min(TContext3D.MaxTextureSize, ASize.Height); end; procedure TImageManagerAndroid.TakeImageFromLibrary(const AControl: TControl; const ARequiredResolution: TSize; const AOnDidFinishTaking: TOnDidFinishTaking; const AOnDidCancelTaking: TOnDidCancelTaking); var ApproximatedResolution: TSize; begin FOnDidFinishTaking := AOnDidFinishTaking; FOnDidCancelTaking := AOnDidCancelTaking; ApproximatedResolution := ApproximateAdmissibleImageSize(ARequiredResolution); MainActivity.getFMXMediaLibrary.takeImageFromLibrary(ApproximatedResolution.Width, ApproximatedResolution.Height); end; procedure TImageManagerAndroid.TakePhoto(const AControl: TControl; const ARequiredResolution: TSize; const AOnDidDinishTaking: TOnDidFinishTaking; const AOnDidCancelTaking: TOnDidCancelTaking); var ApproximatedResolution: TSize; begin FOnDidFinishTaking := AOnDidDinishTaking; FOnDidCancelTaking := AOnDidCancelTaking; ApproximatedResolution := ApproximateAdmissibleImageSize(ARequiredResolution); MainActivity.getFMXMediaLibrary.takeImageFromCamera(ApproximatedResolution.Width, ApproximatedResolution.Height); end; { TSharingAndroid } function TSharingManagerAndroid.GetChooserCaption(const DataTypes: TSharingDataTypes): string; begin if (TSharingDataType.sdtImage in DataTypes) and (TSharingDataType.sdtText in DataTypes) then Result := SMediaLibraryOpenTextAndImageWith else if TSharingDataType.sdtText in DataTypes then Result := SMediaLibraryOpenTextWith else if TSharingDataType.sdtImage in DataTypes then Result := SMediaLibraryOpenImageWith; end; function TSharingManagerAndroid.GetSharingMIMETypes(const DataTypes: TSharingDataTypes): string; begin if TSharingDataType.sdtImage in DataTypes then Result := 'image/jpeg;'; if TSharingDataType.sdtText in DataTypes then Result := Result + 'text/plain;'; end; procedure TSharingManagerAndroid.Share(const AControl: TControl; const AText: string; const AImage: TBitmap); function DefineDataTypes: TSharingDataTypes; var DataTypes: TSharingDataTypes; begin DataTypes := []; if AText.Length > 0 then Include(DataTypes, TSharingDataType.sdtText); if Assigned(AImage) and not AImage.IsEmpty then Include(DataTypes, TSharingDataType.sdtImage); Result := DataTypes; end; procedure SetImage(AIntent: JIntent); var ImageFile: JFile; ImageUri: Jnet_Uri; FileNameTemp: JString; begin FileNameTemp := StringToJString('attachment.jpg'); SharedActivity.openFileOutput(FileNameTemp, TJActivity.JavaClass.MODE_WORLD_READABLE); ImageFile := SharedActivity.getFileStreamPath(FileNameTemp); ImageUri := TJnet_Uri.JavaClass.fromFile(ImageFile); AImage.SaveToFile(JStringToString(ImageFile.getAbsolutePath)); AIntent.putExtra(TJIntent.JavaClass.EXTRA_STREAM, TJParcelable.Wrap((ImageUri as ILocalObject).GetObjectID)); end; var Intent: JIntent; IntentChooser: JIntent; MIMETypes: string; ChooserCaption: string; DataTypes: TSharingDataTypes; begin Intent := TJIntent.Create; DataTypes := DefineDataTypes; if DataTypes <> [] then begin MIMETypes := GetSharingMIMETypes(DataTypes); ChooserCaption := GetChooserCaption(DataTypes); { Create chooser of activity } Intent.setAction(TJIntent.JavaClass.ACTION_SEND); Intent.setType(StringToJString(MIMETypes)); Intent.addFlags(TJIntent.JavaClass.FLAG_GRANT_READ_URI_PERMISSION); if TSharingDataType.sdtText in DataTypes then Intent.putExtra(TJIntent.JavaClass.EXTRA_TEXT, StringToJString(AText)); if TSharingDataType.sdtImage in DataTypes then SetImage(Intent); Intent.setFlags(TJIntent.JavaClass.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); IntentChooser := TJIntent.JavaClass.createChooser(Intent, StrToJCharSequence(ChooserCaption)); SharedActivity.startActivity(IntentChooser); end; end; end.
unit Oven; interface uses System.SysUtils, System.Classes, WinTypes, WinProcs, Modlink; type TMU110 = class private FModbusConnection: TModbusConnection; FModbusClient: TModbusClient; constructor ActualCreate(AOwner: TComponent); constructor Create(AOwner: TComponent = nil); public function SetPort(APort: string): boolean; function SetAddress(AAddress: byte): boolean; function SetFlashTime(ATime: word): boolean; function OutOn(AOutNumber: byte): boolean; function OutOff(AOutNumber: byte): boolean; function OutFlash(AOutNumber: byte): boolean; class function GetInstance(AOwner: TComponent = nil): TMU110; destructor Destroy; override; end; implementation var MU110: TMU110; constructor TMU110.ActualCreate(AOwner: TComponent); begin inherited Create; FModbusConnection:= TModbusConnection.Create(AOwner); FModbusClient:= TModbusClient.Create(AOwner); FModbusConnection.BaudRate:= br9600; FModbusConnection.Parity:= psNone; FModbusClient.ServerAddress:= 16; FModbusClient.Connection:= FModbusConnection; end; constructor TMU110.Create(AOwner: TComponent = nil); begin raise Exception.Create('Attempt to create an instance of TSingleton'); end; class function TMU110.GetInstance(AOwner: TComponent = nil): TMU110; begin if MU110 = nil then MU110:= TMU110.ActualCreate(AOwner); Result := MU110; end; destructor TMU110.Destroy; begin FModbusClient.Free; FModbusConnection.Free; MU110:= nil; inherited Destroy; end; function TMU110.SetPort(APort: string): boolean; begin try FModbusConnection.Active:= false; FModbusConnection.Port:= APort; Result:= true; except Result:= false; end; end; function TMU110.SetAddress(AAddress: byte): boolean; begin try FModbusConnection.Active:= false; FModbusClient.ServerAddress:= AAddress; Result:= true; except Result:= false; end; end; function TMU110.SetFlashTime(ATime: word): boolean; var StartReg, i: Word; RegValues: TRegValues; begin // if MU110 <> nil then MessageDlg('MU110 exist '+MU110.FModbusConnection.Port+' Address '+ // IntToStr(MU110.FModbusClient.ServerAddress) , mtInformation, // [mbOk], 0, mbOk); try FModbusConnection.Active:= true; StartReg:= 32; SetLength(RegValues, 8); for i:=0 to 7 do RegValues[i]:= ATime; FModbusClient.WriteMultipleRegisters(StartReg, RegValues); Result:= true; except Result:= false; end; end; function TMU110.OutOn(AOutNumber: byte): boolean; var StartReg: Word; RegValues: TRegValues; begin // if MU110 <> nil then MessageDlg('MU110 exist '+MU110.FModbusConnection.Port+' Address '+ // IntToStr(MU110.FModbusClient.ServerAddress) , mtInformation, // [mbOk], 0, mbOk); try FModbusConnection.Active:= true; StartReg:= AOutNumber - 1; SetLength(RegValues, 1); RegValues[0]:= 1000; FModbusClient.WriteMultipleRegisters(StartReg, RegValues); Result:= true; except Result:= false; end; end; function TMU110.OutOff(AOutNumber: byte): boolean; var StartReg: Word; RegValues: TRegValues; begin // if MU110 <> nil then MessageDlg('MU110 exist '+MU110.FModbusConnection.Port+' Address '+ // IntToStr(MU110.FModbusClient.ServerAddress) , mtInformation, // [mbOk], 0, mbOk); try FModbusConnection.Active:= true; StartReg:= AOutNumber - 1; SetLength(RegValues, 1); RegValues[0]:= 0; FModbusClient.WriteMultipleRegisters(StartReg, RegValues); Result:= true; except Result:= false; end; end; function TMU110.OutFlash(AOutNumber: byte): boolean; var StartReg: Word; RegValues: TRegValues; begin // if MU110 <> nil then MessageDlg('MU110 exist '+MU110.FModbusConnection.Port+' Address '+ // IntToStr(MU110.FModbusClient.ServerAddress) , mtInformation, // [mbOk], 0, mbOk); try FModbusConnection.Active:= true; StartReg:= AOutNumber - 1; SetLength(RegValues, 1); RegValues[0]:= 500; FModbusClient.WriteMultipleRegisters(StartReg, RegValues); Result:= true; except Result:= false; end; end; end.
function IntToChar(getal: integer): char; // declare your variables here begin if (getal = 0) then begin InttoChar := ' '; end else begin InttoChar := CHR(getal + 96); end; end;
unit DW.Macapi.IOKit; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses Macapi.CoreFoundation, Macapi.IOKit; // Backfills for Macapi.IOKit // Info gleaned from: // https://github.com/hans/universal-remote/blob/master/IOKit.framework/Versions/A/Headers/ps/IOPowerSources.h // https://github.com/hans/universal-remote/blob/master/IOKit.framework/Versions/A/Headers/ps/IOPSKeys.h // https://github.com/nanotech/iphoneheaders/blob/master/IOKit/IOKitKeys.h function IOPSCopyPowerSourcesInfo: CFTypeRef; cdecl; external libIOKit name _PU + 'IOPSCopyPowerSourcesInfo'; function IOPSCopyPowerSourcesList(blob: CFTypeRef): CFArrayRef; cdecl; external libIOKit name _PU + 'IOPSCopyPowerSourcesList'; function IOPSGetPowerSourceDescription(blob: CFTypeRef; ps: CFTypeRef): CFDictionaryRef; cdecl; external libIOKit name _PU + 'IOPSGetPowerSourceDescription'; // Used to obtain a CFStringRef value function kIOPSNameKey: CFStringRef; // Used to obtain a CFString, value is kIOPSACPowerValue, kIOPSBatteryPowerValue, or kIOPSOffLineValue function kIOPSPowerSourceStateKey: CFStringRef; // Used to obtain a CFNumber (signed integer), units are relative to "Max Capacity" function kIOPSCurrentCapacityKey: CFStringRef; // Used to obtain a CFNumber (signed integer), units are % function kIOPSMaxCapacityKey: CFStringRef; // Only valid if the power source is running off its own power. That's when the kIOPSPowerSourceStateKey has value kIOPSBatteryPowerValue, // and the value of kIOPSIsChargingKey is kCFBooleanFalse. // Used to obtain a CFNumber (signed integer), units are minutes // A value of -1 indicates "Still Calculating the Time", otherwise estimated minutes left on the battery function kIOPSTimeToEmptyKey: CFStringRef; // Only valid if the value of kIOPSIsChargingKey is kCFBooleanTrue. // Used to obtain a CFNumber (signed integer), units are minutes // A value of -1 indicates "Still Calculating the Time", otherwise estimated minutes until fully charged. function kIOPSTimeToFullChargeKey: CFStringRef; // Used to obtain a CFBoolean - kCFBooleanTrue or kCFBooleanFalse function kIOPSIsChargingKey: CFStringRef; // Used to obtain a CFStringRef function kIOPSBatteryHealthKey: CFStringRef; // Used to obtain a CFStringRef function kIOPlatformSerialNumberKey: CFStringRef; implementation uses Macapi.Foundation; function kIOPSNameKey: CFStringRef; begin Result := CFSTR('Name'); end; function kIOPSPowerSourceStateKey: CFStringRef; begin Result := CFSTR('Power Source State'); end; function kIOPSCurrentCapacityKey: CFStringRef; begin Result := CFSTR('Current Capacity'); end; function kIOPSMaxCapacityKey: CFStringRef; begin Result := CFSTR('Max Capacity'); end; function kIOPSTimeToEmptyKey: CFStringRef; begin Result := CFSTR('Time to Empty'); end; function kIOPSTimeToFullChargeKey: CFStringRef; begin Result := CFSTR('Time to Full Charge'); end; function kIOPSIsChargingKey: CFStringRef; begin Result := CFSTR('Is Charging'); end; function kIOPSBatteryHealthKey: CFStringRef; begin Result := CFSTR('BatteryHealth'); end; function kIOPlatformSerialNumberKey: CFStringRef; begin Result := CFSTR('IOPlatformSerialNumber'); end; end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Ported to Delphi by Michal Wojcik. // unit CountsTest; interface uses StrUtils, SysUtils, TestFramework; type TCountsTest=class(TTestCase) published procedure testEquality(); end; implementation uses Counts; { TCountsTest } procedure TCountsTest.testEquality(); begin CheckFalse(TCounts.Create().equals(nil)); CheckFalse(TCounts.Create().equals(TObject.Create){''}); //TODO CheckEquals(TCounts.Create(), TCounts.Create()); CheckEquals(TCounts.Create().toString, TCounts.Create().toString); CheckEquals(TCounts.Create(0, 0, 0, 0).toString, TCounts.Create(0, 0, 0, 0).toString); CheckEquals(TCounts.Create(1, 1, 1, 1).toString, TCounts.Create(1, 1, 1, 1).toString); CheckEquals(TCounts.Create(5, 0, 1, 3).toString, TCounts.Create(5, 0, 1, 3).toString); CheckFalse(TCounts.Create(1, 0, 0, 0).equals(TCounts.Create(0, 0, 0, 0))); end; initialization TestFramework.RegisterTest(TCountsTest.Suite); end.
unit HTTPPoolForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Mask, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Samples.Spin, ThreadPool, HTTPThreadPool; type TMainForm = class(TForm) Panel1: TPanel; LogMemo: TMemo; URLMemo: TMemo; Label1: TLabel; AddTasksButton: TButton; CancelTasksButton: TButton; Label2: TLabel; Label3: TLabel; ProgressBar: TProgressBar; ConcurrentWorkersEdit: TSpinEdit; SpareWorkersEdit: TSpinEdit; procedure FormCreate(Sender: TObject); procedure ConcurrentWorkersEditChange(Sender: TObject); procedure SpareWorkersEditChange(Sender: TObject); procedure AddTasksButtonClick(Sender: TObject); procedure CancelTasksButtonClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private procedure TaskStart(Sender: TObject); procedure TaskCanceled(Sender: TObject); procedure TaskDone(Sender: TObject); procedure TaskDownloadStatus(Sender: TObject; Progress, MaxProgress: Int64); procedure TasksStatus(Sender: TObject; Progress: Single); procedure TasksComplete(Sender: TObject); end; var MainForm: TMainForm; implementation {$R *.dfm} { TMainForm } procedure TMainForm.AddTasksButtonClick(Sender: TObject); var cc: Integer; HTTPTask: THTTPTask; begin LogMemo.Clear; // Create once, assign needed event handlers and make later only clones with some customizing's HTTPTask := THTTPTask.Create(Self); HTTPTask.OnDone := TaskDone; HTTPTask.OnStart := TaskStart; HTTPTask.OnCancel := TaskCanceled; HTTPTask.OnDownloadStatus := TaskDownloadStatus; for cc:=0 to URLMemo.Lines.Count - 1 do begin HTTPTask.URL := URLMemo.Lines[cc]; if cc >= (URLMemo.Lines.Count - 3) then HTTPTask.Priority := tpHighest else HTTPTask.Priority := tpLowest; HTTPManager.AddTask(HTTPTask); HTTPTask := THTTPTask(HTTPTask.Clone); end; end; procedure TMainForm.CancelTasksButtonClick(Sender: TObject); begin if THTTPManager.HasSingleton then HTTPManager.CancelTasksByOwner(Self); end; procedure TMainForm.ConcurrentWorkersEditChange(Sender: TObject); begin if THTTPManager.HasSingleton then HTTPManager.ConcurrentWorkersCount := Trunc(ConcurrentWorkersEdit.Value); end; procedure TMainForm.FormCreate(Sender: TObject); begin THTTPManager.RegisterSingletonOnDemandProc( procedure(Manager: TPoolManager) begin Manager.ConcurrentWorkersCount := Trunc(ConcurrentWorkersEdit.Value); Manager.SpareWorkersCount := Trunc(SpareWorkersEdit.Value); if not Manager.RestoreOwners then Manager.RegisterOwner(MainForm, MainForm.TasksStatus, MainForm.TasksComplete); end); end; procedure TMainForm.FormDestroy(Sender: TObject); begin TPoolManager.TerminateSingletonInstances; end; procedure TMainForm.SpareWorkersEditChange(Sender: TObject); begin if THTTPManager.HasSingleton then HTTPManager.SpareWorkersCount := Trunc(SpareWorkersEdit.Value); end; procedure TMainForm.TaskCanceled(Sender: TObject); var HTTPTask: THTTPTask; begin if not (Assigned(Sender) and (Sender is THTTPTask)) then Exit; HTTPTask := THTTPTask(Sender); LogMemo.Lines.Add(Format('Task canceled for "%s"', [HTTPTask.URL])); end; procedure TMainForm.TaskDone(Sender: TObject); var HTTPTask: THTTPTask; ThreadID: Cardinal; begin if not (Assigned(Sender) and (Sender is THTTPTask)) then Exit; HTTPTask := THTTPTask(Sender); if Assigned(HTTPTask.Owner) and (HTTPTask.Owner is TPoolWorker) then ThreadID := TPoolWorker(HTTPTask.Owner).ThreadID else ThreadID := 0; LogMemo.Lines.Add(Format('Task done for "%s". [HTTP-Code: %d], [Response-Size: %d Bytes], [ThreadID: %d]', [HTTPTask.URL, HTTPTask.ResponseCode, HTTPTask.ResponseSize, ThreadID])); end; procedure TMainForm.TaskDownloadStatus(Sender: TObject; Progress, MaxProgress: Int64); var HTTPTask: THTTPTask; begin if not (Assigned(Sender) and (Sender is THTTPTask)) then Exit; HTTPTask := THTTPTask(Sender); LogMemo.Lines.Add(Format('%d %% (%d of %d Bytes) downloaded of "%s"', [Round(Progress / MaxProgress * 100), Progress, MaxProgress, HTTPTask.URL])); end; procedure TMainForm.TasksComplete(Sender: TObject); begin end; procedure TMainForm.TasksStatus(Sender: TObject; Progress: Single); begin ProgressBar.Position := Round(Progress * 100); end; procedure TMainForm.TaskStart(Sender:TObject); begin end; end.
unit FileSearcherExtUnit; interface uses Classes, SysUtils, StrUtils, FileSearcherUnit; type TFileSearcherExt = class(TFileSearcher) strict protected // допустимые расширения, которые могут иметь искомые файлы FExtensions: TStrings; // Проверяет, является ли расширение Ext файла допустимым function IsExtensionValid(const FileExt: string): Boolean; function AllowToGetFileInfoIfExtensionIsValid( const FileName: String; var AllowToGetFileInfo: Boolean ): Boolean; function ProcessFileInfo( const DirPathOfFile: String; const FileInfo: TSearchRec; var AllowToGetFileInfo: Boolean ): Pointer; override; public constructor Create(BeginDirectory: string); destructor Destroy; override; // Поиск с учётом расширений файлов (например, .pdf, .txt, .doc и т.д.) procedure AddExtension(const FileExt: string); procedure AddExtensions(const FileExts: array of string); overload; procedure AddExtensions(const FileExts: TStrings); overload; procedure ClearExtensions; procedure RemoveExtension(const FileExt: string); procedure RemoveExtensions(const FileExts: TStrings); overload; procedure RemoveExtensions(const FileExts: array of String); overload; end; implementation { TFileSearcher } { TFileSearcherExt } procedure TFileSearcherExt.AddExtension(const FileExt: string); var LowerFileExt: String; begin LowerFileExt := AnsiLowerCase(FileExt); if FExtensions.IndexOf(LowerFileExt) < 0 then FExtensions.Add(LowerFileExt); end; procedure TFileSearcherExt.AddExtensions(const FileExts: array of string); var CurrFileExt: String; begin for CurrFileExt in FileExts do AddExtension(CurrFileExt); end; procedure TFileSearcherExt.AddExtensions(const FileExts: TStrings); var CurrFileExt: string; begin for CurrFileExt in FileExts do AddExtension(CurrFileExt); end; function TFileSearcherExt.AllowToGetFileInfoIfExtensionIsValid( const FileName: String; var AllowToGetFileInfo: Boolean): Boolean; begin AllowToGetFileInfo := IsExtensionValid(ExtractFileExt(FileName)); Result := AllowToGetFileInfo; end; procedure TFileSearcherExt.ClearExtensions; begin FExtensions.Clear; end; constructor TFileSearcherExt.Create(BeginDirectory: string); begin inherited; FExtensions := TStringList.Create; end; destructor TFileSearcherExt.Destroy; begin FreeAndNil(FExtensions); inherited; end; function TFileSearcherExt.IsExtensionValid(const FileExt: string): Boolean; begin Result := FExtensions.IndexOf(AnsiLowerCase(PChar(FileExt))) >= 0; end; function TFileSearcherExt.ProcessFileInfo(const DirPathOfFile: String; const FileInfo: TSearchRec; var AllowToGetFileInfo: Boolean): Pointer; begin if AllowToGetFileInfoIfExtensionIsValid( FileInfo.Name, AllowToGetFileInfo ) then Result := inherited ProcessFileInfo(DirPathOfFile, FileInfo, AllowToGetFileInfo); end; procedure TFileSearcherExt.RemoveExtension(const FileExt: string); var RemovedFileExtIndex: Integer; begin RemovedFileExtIndex := FExtensions.IndexOf(FileExt); if RemovedFileExtIndex >= 0 then FExtensions.Delete(RemovedFileExtIndex); end; procedure TFileSearcherExt.RemoveExtensions(const FileExts: TStrings); var CurrFileExt: string; begin for CurrFileExt in FileExts do RemoveExtension(CurrFileExt); end; procedure TFileSearcherExt.RemoveExtensions(const FileExts: array of String); var CurrFileExt: String; begin for CurrFileExt in FileExts do RemoveExtension(CurrFileExt); end; end.
// ################################################################### // #### This file is part of the mathematics library project, and is // #### offered under the licence agreement described on // #### http://www.mrsoft.org/ // #### // #### Copyright:(c) 2011, Michael R. . All rights reserved. // #### // #### Unless required by applicable law or agreed to in writing, software // #### distributed under the License is distributed on an "AS IS" BASIS, // #### WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // #### See the License for the specific language governing permissions and // #### limitations under the License. // ################################################################### unit LinearAlgebraicEquations; // ############################################ // #### Functions to solve linear algebraic equations // ############################################ interface uses SysUtils, Types, MatrixConst, OptimizedFuncs; // solves the matrix A*X = B where A*x1=b1, A*x2=b2, ... A*xm=bm // The function stores in A the inverse of A and B stores the result vectors // A must be a square matrix (width*width) and B must be m*width. function MatrixGaussJordanInPlace(A : PDouble; const LineWidthA : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; width : TASMNativeInt; m : TASMNativeInt; const epsilon : double = 1e-20; progress : TLinEquProgress = nil) : TLinEquResult; function MatrixGaussJordan(A : PDouble; const LineWidthA : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; invA : PDouble; const LineWidthInvA : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt; width : TASMNativeInt; m : TASMNativeInt; const epsilon : double = 1e-20; progress : TLinEquProgress = nil) : TLinEquResult; // interface functions (used in different parts - don't call them directly) procedure LUSwap(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; k1, k2 : TASMNativeInt; indx : PIntegerArray; var parity : TASMNativeInt); procedure LUBacksup(A : PDouble; width, height : TASMNativeInt; B : PDouble; const LineWidth : TASMNativeInt); // inplace LU decomposition of the matrix A. Diagonal elements of the lower triangular matrix are set to one // thus the diagonal elements of the resulting matrix A are composed from the upper diagonal elements only. // The index records the row permutation effected by the partial pivoting. function MatrixLUDecompInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; indx : PIntegerArray; progress : TLinEquProgress = nil) : TLinEquResult; function MatrixLUDecomp(A : PDouble; const LineWidthA : TASMNativeInt; LUDecomp : PDouble; const LineWidthLU : TASMNativeInt; width : TASMNativeInt; indx : PIntegerArray; progress : TLinEquProgress = nil) : TLinEquResult; overload; function MatrixLUDecomp(A : PDouble; const LineWidthA : TASMNativeInt; LUDecomp : PDouble; const LineWidthLU : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress = nil) : TLinEquResult; overload; procedure MatrixLUBackSubst(LUDecomp : PDouble; const LineWidthLU : TASMNativeInt; width : TASMNativeInt; const indx : PIntegerArray; B : PDouble; const LineWidthB : TASMNativeInt; progress : TLinEquProgress = nil); // inverse of a matrix by using the LU decomposition function MatrixInverseInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress = nil) : TLinEquResult; // Matrix determinant calculated from the LU decomposition. Returns zero in case of a singular matrix. Drawback is a double // memory usage since the LU decomposition must be stored in a temporary matrix. function MatrixDeterminant(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress = nil) : double; // Matrix Line Equation Solver routines which are based on LU decomposition. // note these functions use temporarily double the size of A memory. // The result is stored in X. B and X must have the same size, also B may have // more than one column. function MatrixLinEQSolve(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt; Width2 : TASMNativeInt; const NumRefinments : TASMNativeInt = 0; progress : TLinEquProgress = nil) : TLinEquResult; // Inplace svd decomposition of a Matrix A // The output is the computation of A= U*W*V' whereas U is stored in A, and W is a vector 0..Width-1. The matrix V (not V') must be as large as Width*Width! function MatrixSVDInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; Height : TASMNativeInt; W : PDouble; const LineWidthW : TASMNativeInt; V : PDouble; const LineWidthV : TASMNativeInt; progress : TLinEquProgress = nil) : TSVDResult; function MatrixSVD(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; Height : TASMNativeInt; U : PDouble; const LineWidthU : TASMNativeInt; W : PDouble; const LineWidthW : TASMNativeInt; V : PDouble; const LineWidthV : TASMNativeInt; progress : TLinEquProgress = nil) : TSVDResult; // Inplace Cholesky decomposition of the matrix A (A=L*L'). A must be a positive-definite symmetric matrix. // The cholesky factor L is returned in the lower triangle of a, except for its diagonal elements which are returned in p function MatrixCholeskyInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; P : PDouble; LineWidthP : TASMNativeInt; progress : TLinEquProgress = nil) : TCholeskyResult; function MatrixCholesky(dest : PDouble; const LineWidthDest : TASMNativeInt; A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; P : PDouble; const LineWidthP : TASMNativeInt; progress : TLinEquProgress = nil) : TCholeskyResult; // solves the set of linear equations Ax = b where A is a positive-definite symmetric matrix. A and P are input as the output of // MatrixCholeskyInPlace. Only the lower triangle is accessed. The result is stored in X, thus the routine can be called multiple // times. B and X can point to the same memory! procedure MatrixCholeskySolveLinEq(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; P : PDouble; const LineWidthP : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt; progress : TLinEquProgress = nil); // Linpack version of cholesky decomposition function MatrixCholeskyInPlace2(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress = nil) : TCholeskyResult; function MatrixCholeskyInPlace3(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress = nil) : TCholeskyResult; function MatrixCholeskyInPlace4(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; pnlSize : TASMNativeInt; progress : TLinEquProgress = nil) : TCholeskyResult; // original functions from Numerical Recipies: // In place QR decomposition. Constructs the QR decomposition of A (n*n). The upper triangle matrix R is returned // in the upper triangle of a, except for the diagonal elements of R which are returned in // d. The orthogonal matrix Q is represented as a product of n-1 Householder matrices Q1...Qn-1, where // Qj = 1 - uj*(uj/cj). The ith component of uj is zero for i = 1..j-1 while the nonzero components are returned // in a[i][j] for i = j...n . False is returned if no singularity was detected function MatrixQRDecompInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; C : PDouble; const LineWidthC : TASMNativeInt; D : PDouble; const LineWidthD : TASMNativeInt; progress : TLinEquProgress = nil) : TQRResult; function MatrixQRDecomp(dest : PDouble; const LineWidthDest : TASMNativeInt; A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; C : PDouble; const LineWidthC : TASMNativeInt; D : PDouble; const LineWidthD : TASMNativeInt; progress : TLinEquProgress = nil) : TQRResult; // solves the System A*x = b. The input paramaters are the output parameters from the QR decomposition. // b is the matrix right hand side and will be overwritten by the result x. procedure MatrixQRSolveLinEq(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; C : PDouble; const LineWidthC : TASMNativeInt; D : PDouble; const LineWidthD : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; progress : TLinEquProgress = nil); // implementation of Lapack's blocked QR decomposition // the upper triangle matrix R is returned in the upper triangle of A. The elements below the // diagonal with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors. // further details: The matrix Q is represented as a product of elementary reflectors // Q = H(1) H(2) . . . H(k), where k = min(m,n). // Each H(i) has the form // H(i) = I - tau * v * v**T // where tau is a real scalar, and v is a real vector with // v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), // and tau in TAU(i). // note the matrix above starts with index 1 instead of 0. // the output is the same as the matlab economy size output on a QR decomposition e.g. dcmp = qr(A, 0); function MatrixQRDecompInPlace2(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; progress : TLinEquProgress = nil) : TQRResult; overload; function MatrixQRDecompInPlace2(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; work : PDouble; pnlSize : TASMNativeInt; progress : TLinEquProgress = nil) : TQRResult; overload; // implementation of Lapacks dorgqr function: On start the matrix A and Tau contains the result of // the MatrixQRDecompInPlace2 function (economy size QR Decomposition). On output A is replaced by the full Q // matrix with orthonormal columns. procedure MatrixQFromQRDecomp(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; progress : TLinEquProgress = nil); overload; procedure MatrixQFromQRDecomp(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; BlockSize : TASMNativeInt; work : PDouble; progress : TLinEquProgress = nil); overload; // Pseudoinversion - implementation taken from matlab // X = pinv(A) produces a matrix X of the same dimensions // as A' so that A*X*A = A, X*A*X = X and A*X and X*A // are Hermitian. The computation is based on SVD(A) and any // singular values less than a tolerance are treated as zero. // The default tolerance is MAX(SIZE(A)) * NORM(A) * EPS(class(A)) // Note the Matrix in X is also used in the calculations, thus it's content is destroyed! // dest must be at least as big as the transposed of X function MatrixPseudoinverse(dest : PDouble; const LineWidthDest : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt; width, height : TASMNativeInt; progress : TLinEquProgress = nil) : TSVDResult; // ###################################################### // #### internaly used objects and definitions type TLinearEQProgress = class(TObject) public refProgress : TLinEquProgress; numRefinenmentSteps : TASMNativeInt; procedure LUDecompSolveProgress(Progress : integer); procedure RefinementProgress(Progress : integer); end; // ########################################### // #### only for internal use // ########################################### type TRecMtxQRDecompData = record pWorkMem : PByte; work : PDouble; LineWidthWork : TASMNativeInt; BlkMultMem : PDouble; Progress : TLinEquProgress; qrWidth, qrHeight : TASMNativeInt; actIdx : TASMNativeInt; pnlSize : TASMNativeInt; MatrixMultT1 : TMatrixBlockedMultfunc; MatrixMultT2 : TMatrixBlockedMultfunc; end; function InternalMatrixQRDecompInPlace2(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; qrData : TRecMtxQRDecompData) : boolean; procedure InternalBlkMatrixQFromQRDecomp(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; qrData : TRecMtxQRDecompData); function InternalBlkCholeskyInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; pnlSize : TASMNativeInt; aMatrixMultT2Ex : TMatrixBlockedMultfunc; multMem : PDouble; progress : TLinEquProgress = nil) : TCholeskyResult; implementation uses Math, MathUtilFunc, ASMMatrixOperations, SimpleMatrixOperations, BlockSizeSetup; function MatrixPseudoinverse(dest : PDouble; const LineWidthDest : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt; width, height : TASMNativeInt; progress : TLinEquProgress) : TSVDResult; var doTranspose : boolean; data : TDoubleDynArray; UTranspose : TDoubleDynArray; pData : PDouble; lineWidthData : TASMNativeInt; S, V : TDoubleDynArray; lineWidthV : TASMNativeInt; tolerance : double; r : TASMNativeInt; i : TASMNativeInt; k, l : TASMNativeInt; pUTranspose : PDouble; res : TDoubleDynArray; pRes : PDouble; destOffset : TASMNativeInt; begin // pseudo inversion of a matrix: pinv(x) = x'*(x*x')^-1 // based on the matlab implementation: // [u s v] = svd(x, 0) // s = diag(S); // tol = max(m,n) * eps(max(s)); // r = sum(s > tol); // s = diag(ones(r,1)./s(1:r)); // X = V(:,1:r)*s*U(:,1:r)'; assert((width > 0) and (height > 0) and (lineWidthDest >= height*sizeof(double)), 'Dimension error'); doTranspose := width > height; if doTranspose then begin data := MatrixTranspose(X, LineWidthX, width, height); pData := @data[0]; lineWidthData := height*sizeof(double); Result := MatrixPseudoinverse(X, LineWidthX, pData, lineWidthData, height, width); MatrixTranspose(dest, LineWidthDest, x, LineWidthX, width, height); exit; end; SetLength(S, width); SetLength(V, sqr(width)); lineWidthV := width*sizeof(double); Result := MatrixSVDInPlace(X, lineWidthX, width, height, @S[0], sizeof(double), @V[0], lineWidthV, progress); if Result = srNoConvergence then exit; tolerance := height*eps(MatrixMax(@S[0], width, 1, width*sizeof(double))); r := 0; for i := 0 to width - 1 do begin if s[i] > tolerance then inc(r) end; if r = 0 then begin // set all to zero destOffset := LineWidthDest - height*sizeof(double); for k := 0 to width - 1 do begin for l := 0 to height - 1 do begin dest^ := 0; inc(dest); end; inc(PByte(dest), destOffset); end; end else begin // invert for i := 0 to width - 1 do begin if s[i] > tolerance then s[i] := 1/s[i] else s[i] := 0; end; UTranspose := MatrixTranspose(X, LineWidthX, width, height); pUTranspose := @UTranspose[0]; for k := 0 to width - 1 do begin for l := 0 to height - 1 do begin pUTranspose^ := pUTranspose^*s[k]; inc(pUTranspose); end; end; res := MatrixMult(@V[0], @UTranspose[0], width, width, height, width, width*sizeof(double), height*sizeof(double)); V := nil; UTranspose := nil; s := nil; // copy pRes := @res[0]; for k := 0 to width - 1 do begin Move(pRes^, dest^, sizeof(double)*height); inc(PByte(dest), LineWidthDest); inc(PByte(pRes), sizeof(double)*height); end; end; end; function MatrixGaussJordan(A : PDouble; const LineWidthA : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; invA : PDouble; const LineWidthInvA : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt; width : TASMNativeInt; m : TASMNativeInt; const epsilon : double; progress : TLinEquProgress) : TLinEquResult; var i: TASMNativeInt; pInvA : PDouble; PX : PDouble; begin Assert(width > 0, 'Dimension Error'); Assert(lineWidthInvA >= width*sizeof(double), 'Dimension error'); Assert(lineWidthX >= sizeof(double), 'Dimension error'); // copy data -> now we can perform an inline gauss elimination procedure PInvA := invA; PX := X; for i := 0 to width - 1 do begin Move(A^, PInvA^, sizeof(double)*width); inc(PByte(PInvA), LineWidthInvA); inc(PByte(A), LineWidthA); Move(B^, PX^, sizeof(double)*m); inc(PByte(B), LineWidthB); inc(PByte(PX), LineWidthX); end; Result := MatrixGaussJordaninPlace(invA, lineWidthInvA, X, LineWidthX, width, m, epsilon, progress); end; function MatrixGaussJordanInPlace(A : PDouble; const LineWidthA : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; width : TASMNativeInt; m : TASMNativeInt; const epsilon : double; progress : TLinEquProgress) : TLinEquResult; var i, icol, irow, j, k, l, ll : TASMNativeInt; big, dum, pivinv : double; indxc, indxr, ipiv : Array of integer; pVal1 : PDouble; pVal2 : PDouble; begin assert(LineWidthA >= width*sizeof(double), 'Dimension error'); assert(LineWidthB >= m*sizeof(double), 'Dimension error'); Result := leOk; SetLength(indxc, width); SetLength(indxr, width); SetLength(ipiv, width); icol := 0; irow := 0; if Assigned(progress) then progress(0); for j := 0 to width - 1 do ipiv[j] := 0; // main loop over the columns to be reduced for i := 0 to width - 1 do begin big := 0; for j := 0 to width - 1 do begin if ipiv[j] <> 1 then begin for k := 0 to width - 1 do begin if ipiv[k] = 0 then begin pVal1 := PDouble(PAnsiChar(A) + j*LineWidthA); inc(pVal1, k); if abs(pVal1^) >= big then begin big := abs(pVal1^); irow := j; icol := k; end; end else if ipiv[k] > 1 then begin Result := leSingular; exit; end; end; end; end; inc(ipiv[icol]); // we now have the pivot element, so we interchange rows, if needed, to put the pivot // element on the dagonal. if irow <> icol then begin pVal1 := PDouble(PAnsiChar(A) + irow*LineWidthA); pVal2 := PDouble(PAnsiChar(A) + icol*LineWidthA); for l := 0 to width - 1 do begin DoubleSwap(pVal1^, pVal2^); inc(pVal1); inc(pVal2); end; pVal1 := PDouble(PAnsiChar(B) + irow*LineWidthB); pVal2 := PDouble(PAnsiChar(B) + icol*LineWidthB); for l := 0 to m - 1 do begin DoubleSwap(pVal1^, pVal2^); inc(pVal1); inc(pVal2); end; end; // we are now ready to divide the pivot row by the pivot element, located in irow and icol indxr[i] := irow; indxc[i] := icol; pVal1 := PDouble(PAnsiChar(A) + icol*LineWidthA); inc(pVal1, icol); if abs(pVal1^) < epsilon then begin Result := leSingular; exit; end; pivinv := 1/pVal1^; pVal1^ := 1; pVal1 := PDouble(PAnsiChar(A) + icol*LineWidthA); for l := 0 to width - 1 do begin pVal1^ := pVal1^*pivinv; inc(pVal1); end; pVal1 := PDouble(PAnsiChar(B) + icol*LineWidthB); for l := 0 to m - 1 do begin pVal1^ := Pivinv*pVal1^; inc(pVal1); end; for ll := 0 to width - 1 do begin if ll <> icol then begin pVal1 := PDouble(PAnsiChar(A) + ll*LineWidthA); inc(pVal1, icol); dum := pVal1^; pVal1^ := 0; pVal1 := PDouble(PAnsiChar(A) + ll*LineWidthA); pVal2 := PDouble(PAnsiChar(A) + icol*LineWidthA); for l := 0 to width - 1 do begin pVal1^ := pVal1^ - pVal2^*dum; inc(pVal1); inc(pVal2); end; pVal1 := PDouble(PAnsiChar(B) + ll*LineWidthB); pVal2 := PDouble(PAnsiChar(B) + icol*LineWidthB); for l := 0 to m - 1 do begin pVal1^ := pVal1^ - pVal2^*dum; inc(pVal1); inc(pVal2); end; end; end; if Assigned(progress) then progress(100*i div width); end; for l := width - 1 downto 0 do begin if indxr[l] <> indxc[l] then begin for k := 0 to width - 1 do begin pVal1 := PDouble(PAnsiChar(A) + k*LineWidthA); pVal2 := pVal1; inc(pval1, indxr[l]); inc(pval2, indxc[l]); DoubleSwap(pVal1^, pVal2^); end; end; end; if Assigned(progress) then progress(100); end; // LUSWAP performs a series of row interchanges on the matrix A. // One row interchange is initiated for each of rows K1 through K2 of A. procedure LUSwap(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; k1, k2 : TASMNativeInt; indx : PIntegerArray; var parity : TASMNativeInt); var i : TASMNativeInt; pA1, pA2 : PDouble; begin for i := k1 to k2 do begin if indx^[i] <> i then begin // interchange rows pA1 := A; inc(PByte(pA1), i*LineWidthA); pA2 := A; inc(PByte(pA2), indx^[i]*LineWidthA); // swap a complete row at once MatrixRowSwap(pA1, pA2, width); parity := -parity; end; end; end; procedure LUBacksup(A : PDouble; width, height : TASMNativeInt; B : PDouble; const LineWidth : TASMNativeInt); var j, i, k : TASMNativeInt; pA, pAi : PDouble; pB, pBj : PDouble; pBDest, pBDestj, pBDesti : PDouble; begin pA := A; inc(PByte(pA), LineWidth); pB := B; pBDest := B; inc(PByte(pBDest), LineWidth); for k := 0 to height - 1 do begin pAi := pA; pBDesti := pBDest; for i := k + 1 to height - 1 do begin pBj := pB; pBDestj := pBDesti; for j := 0 to width - 1 do begin pBDestj^ := pBDestj^ - pBj^*pAi^; inc(pBj); inc(pBDestj); end; inc(PByte(pAi), LineWidth); inc(PByte(pBDesti), LineWidth); end; inc(pA); inc(PByte(pA), LineWidth); inc(PByte(pB), LineWidth); inc(PByte(pBDest), LineWidth); end; end; const cBlkMultSize = 48; type TRecMtxLUDecompData = record progress : TLinEquProgress; numCols, numCalc : TASMNativeInt; blkMultMem : Pdouble; LineWidth : TASMNativeInt; end; function InternalRecursiveMatrixLUDecompInPlace(A : PDouble; width, height : TASMNativeInt; indx : PIntegerArray; var parity : TASMNativeInt; var data : TRecMtxLUDecompData) : TLinEquResult; var mn : TASMNativeInt; pA : PDouble; idx : TASMNativeInt; maxVal : double; nleft, nright : TASMNativeInt; i : TASMNativeInt; pB, a12, a21 : PDouble; absMaxVal : double; begin mn := min(width, height); if mn > 1 then begin nleft := mn div 2; nright := width - nleft; Result := InternalRecursiveMatrixLUDecompInPlace(A, nLeft, height, indx, parity, data); if Result <> leOk then exit; pA := A; inc(pA, nLeft); LUSwap(pA, data.LineWidth, nright, 0, nleft - 1, indx, parity); // lu backsup A12 = L - one*A12 if nRight > 1 then LUBacksup(A, nRight, nLeft, pA, data.LineWidth); // matrix mult sub // A22 = A22 - A21*A12 pB := A; inc(pB, nleft); a12 := pB; inc(PByte(pB), nLeft*data.LineWidth); a21 := A; inc(PByte(a21), nleft*data.LineWidth); // in this case it's faster to have a small block size! if (nright > cBlkMultSize) or (height - nleft > cBlkMultSize) then BlockedMatrixMultiplication(pB, data.LineWidth, a21, a12, nleft, height - nleft, nright, nleft, data.LineWidth, data.LineWidth, cBlkMultSize, doSub, data.blkMultMem) else begin MatrixMult(data.blkMultMem, (nright + nright and $01)*sizeof(double), a21, a12, nleft, height - nleft, nright, nleft, data.LineWidth, data.LineWidth); MatrixSub(pB, data.LineWidth, pB, data.blkMultMem, nright, height - nleft, data.LineWidth, (nright + nright and $01)*sizeof(double)); end; // apply recursive LU to A(nleft + 1, nleft + 1); Result := InternalRecursiveMatrixLUDecompInPlace(pB, nright, height - nleft, @(indx^[nleft]), parity, data); if Result <> leok then exit; for i := nLeft to width - 1 do indx^[i] := indx^[i] + nLeft; // dlswap LUSwap(A, data.LineWidth, nleft, nleft, mn - 1, indx, parity); end else begin // find maximum element of this column maxVal := 0; absMaxVal := 0; idx := -1; pA := A; for i := 0 to Height - 1 do begin if Abs(pA^) > absMaxVal then begin idx := i; maxVal := pA^; absMaxVal := abs(maxVal); end; inc(PByte(pA), data.LineWidth); end; // now it's time to apply the gauss elimination indx^[0] := idx; // check for save invertion of maxVal if Abs(maxVal) > 10/MaxDouble then begin MatrixScaleAndAdd(A, data.LineWidth, 1, Height, 0, 1/maxVal); pA := A; inc(PByte(pA), data.LineWidth*idx); pA^ := A^; A^ := maxVal; Result := leOk; if Assigned(data.progress) then begin inc(data.numCalc); data.progress(data.numCalc*100 div data.numCols); end; end else Result := leSingular; end; end; function MatrixLUDecompInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; indx : PIntegerArray; progress : TLinEquProgress) : TLinEquResult; var parity : TASMNativeInt; mem : Array[0..(4+4*cBlkMultSize*cBlkMultSize)] of double; rc : TRecMtxLUDecompData; begin FillChar(indx^, width*sizeof(integer), 0); parity := 1; rc.progress := progress; rc.numCols := width; rc.numCalc := 0; rc.blkMultMem := PDouble(TASMNativeUInt(@mem[0]) + 16 - (TASMNativeUInt(@mem[0]) and $0F)); rc.LineWidth := LineWidthA; Result := InternalRecursiveMatrixLUDecompInPlace(A, width, width, indx, parity, rc); end; function MatrixLUDecomp(A : PDouble; const LineWidthA : TASMNativeInt; LUDecomp : PDouble; const LineWidthLU : TASMNativeInt; width : TASMNativeInt; indx : PIntegerArray; progress : TLinEquProgress) : TLinEquResult; begin Assert(width > 0, 'Dimension Error'); // copy data -> now we can perform an inline LU decomposition MatrixCopy(LUDecomp, LineWidthLU, A, LineWidthA, width, width); Result := MatrixLUDecompInPlace(LUDecomp, lineWidthLU, width, indx, progress); end; function MatrixLUDecomp(A : PDouble; const LineWidthA : TASMNativeInt; LUDecomp : PDouble; const LineWidthLU : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress) : TLinEquResult; var indx : array of integer; begin Assert(width > 0, 'Dimension Error'); setLength(indx, width); Result := MatrixLUDecomp(A, LineWidthA, LUDecomp, LineWidthLU, width, @indx[0], progress); end; procedure MatrixLUBackSubst(LUDecomp : PDouble; const LineWidthLU : TASMNativeInt; width : TASMNativeInt; const indx : PIntegerArray; B : PDouble; const LineWidthB : TASMNativeInt; progress : TLinEquProgress); var i : TASMNativeInt; ii : TASMNativeInt; ip : TASMNativeInt; j : TASMNativeInt; sum : double; pB : PDouble; pB2 : PDouble; pVal : PDouble; pVal2 : PDouble; begin assert(width*sizeof(double) <= LineWidthLU, 'Dimension Error'); if Assigned(progress) then progress(0); ii := -1; pB2 := B; for i := 0 to width - 1 do begin ip := indx^[i]; pB := B; inc(PByte(pB), ip*LineWidthB); sum := pB^; pB^ := pB2^; if ii >= 0 then begin pVal := PDouble(PAnsiChar(LUDecomp) + i*LineWidthLU); inc(pVal, ii); pB := B; inc(PByte(pB), LineWidthB*ii); for j := ii to i - 1 do begin sum := sum - pVal^*pB^; inc(pVal); inc(PByte(pB), LineWidthB); end; end else if sum <> 0 then ii := i; pB2^ := sum; inc(PByte(pB2), LineWidthB); end; if Assigned(progress) then progress(50); pB := B; inc(PByte(pB), LineWidthB*(width - 1)); pVal := PDouble(PAnsiChar(LUDecomp) + (width - 1)*LineWidthLU); inc(pVal, width - 1); for i := width - 1 downto 0 do begin sum := pB^; pB2 := pB; inc(PByte(pB2), LineWidthB); pVal2 := pVal; inc(pVal2); for j := i + 1 to width - 1 do begin sum := sum - pVal2^*pB2^; inc(PByte(pB2), LineWidthB); inc(pVal2); end; pB^ := sum/pVal^; dec(pVal); dec(PByte(pVal), LineWidthLU); dec(PByte(pB), LineWidthB); end; if Assigned(progress) then progress(100); end; function MatrixInverseInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress) : TLinEquResult; var Y : PDouble; indx : array of integer; i, j : TASMNativeInt; pVal : PDouble; col : TDoubleDynArray; w : TASMNativeInt; begin Assert(lineWidthA >= width*sizeof(double), 'Dimension Error'); Assert(width > 0, 'Dimension error'); w := width + width and $01; Y := GetMemory(w*w*sizeof(double)); SetLength(indx, width); SetLength(col, width); MatrixCopy(Y, sizeof(double)*w, A, LineWidthA, width, width); Result := MatrixLUDecompInPlace(Y, w*sizeof(double), width, @indx[0], progress); if Result = leSingular then begin FreeMem(Y); exit; end; for j := 0 to width - 1 do begin pVal := A; inc(pVal, j); for i := 0 to width - 1 do col[i] := 0; col[j] := 1; MatrixLUBackSubst(Y, w*sizeof(double), width, @indx[0], @col[0], sizeof(double)); for i := 0 to width - 1 do begin pVal^ := col[i]; inc(PByte(pVal), LineWidthA); end; end; FreeMem(Y); end; function MatrixDeterminant(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress) : double; var LUDecomp : PDouble; indx : Array of Integer; i : TASMNativeInt; pVal : PDouble; parity : TASMNativeInt; rc : TRecMtxLUDecompData; w : TASMNativeInt; mem : Array[0..(4+4*cBlkMultSize*cBlkMultSize)] of double; begin assert(width > 0, 'Dimension error'); assert(LineWidthA >= width*sizeof(double), 'Dimension error'); w := width + width and $01; LUDecomp := GetMemory(w*w*sizeof(double)); SetLength(indx, width); MatrixCopy(LUDecomp, w*sizeof(double), A, LineWidthA, width, width); rc.progress := progress; rc.numCols := width; rc.numCalc := 0; rc.blkMultMem := PDouble(TASMNativeUInt(@mem[0]) + 16 - TASMNativeUInt(@mem[0]) and $0F); rc.LineWidth := w*sizeof(double); parity := 1; if InternalRecursiveMatrixLUDecompInPlace(LUDecomp, width, width, @indx[0], parity, rc) = leSingular then begin Result := 0; FreeMem(LUDecomp); exit; end; pVal := LUDecomp; Result := parity; for i := 0 to width - 1 do begin Result := Result * pVal^; inc(pVal); inc(PByte(pVal), w*sizeof(double)); end; FreeMem(LUDecomp); end; { TLinearEQProgress } procedure TLinearEQProgress.LUDecompSolveProgress(Progress: integer); begin if numRefinenmentSteps > 0 then refProgress(progress*8 div 10) else refProgress(progress); end; procedure TLinearEQProgress.RefinementProgress(Progress: integer); begin refProgress(80 + 2*progress div 10); end; function MatrixLinEQSolve(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt; Width2 : TASMNativeInt; const NumRefinments : TASMNativeInt; progress : TLinEquProgress) : TLinEquResult; var indx : Array of Integer; LUDecomp : TDoubleDynArray; sdp : double; row : TDoubleDynArray; pB : PDouble; i : TASMNativeInt; pA : PDouble; j, k : TASMNativeInt; pX : PDouble; pVal : PDouble; refinementCounter : TASMNativeInt; progObj : TLinearEQProgress; progRef : TLinEquProgress; begin progRef := nil; progObj := nil; if Assigned(progress) then begin progObj := TLinearEQProgress.Create; progObj.refProgress := progress; progObj.numRefinenmentSteps := NumRefinments; progRef := {$IFDEF FPC}@{$ENDIF}progObj.LUDecompSolveProgress; end; // ########################################### // #### Standard LU Decomposition SetLength(LUDecomp, width*width); SetLength(indx, width); Result := MatrixLUDecomp(A, LineWidthA, @LUDecomp[0], width*sizeof(double), width, @indx[0], progRef); if Result = leSingular then begin progObj.Free; exit; end; for i := 0 to width2 - 1 do begin // copy one column pX := X; inc(pX, i); pVal := B; inc(pVal, i); for j := 0 to width - 1 do begin pX^ := pVal^; inc(PByte(pX), LineWidthX); inc(PByte(pVal), LineWidthB); end; pX := X; inc(pX, i); // calculate vector X MatrixLUBackSubst(@LUDecomp[0], width*sizeof(double), width, @indx[0], pX, LineWidthX); end; // ########################################### // #### Iterative refinements if NumRefinments > 0 then begin SetLength(row, width); // for each solution do a separate refinement: for k := 0 to width2 - 1 do begin if Assigned(progobj) then progObj.RefinementProgress(Int64(k)*100 div Int64(width2)); for refinementCounter := 0 to NumRefinments - 1 do begin pb := B; pA := A; for i := 0 to width - 1 do begin pVal := pA; sdp := -pB^; inc(PByte(pB), LineWidthB); pX := X; for j := 0 to width - 1 do begin sdp := sdp + pX^*pVal^; inc(pVal); inc(pX); end; inc(PByte(pA), LineWidthA); row[i] := sdp; end; MatrixLUBackSubst(@LUDecomp[0], sizeof(double)*width, width, @indx[0], @row[0], sizeof(double)); pX := X; for i := 0 to width - 1 do begin pX^ := pX^ - row[i]; inc(PByte(pX), LineWidthX); end; end; inc(B); inc(X); end; end; if Assigned(progObj) then progObj.Free; if Assigned(progress) then progress(100); end; function MatrixSVDInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; Height : TASMNativeInt; W : PDouble; const LineWidthW : TASMNativeInt; V : PDouble; const LineWidthV : TASMNativeInt; progress : TLinEquProgress) : TSVDResult; const cMaxNumSVDIter = 75; var flag : boolean; i, j, jj, k, l : TASMNativeInt; its : TASMNativeInt; nm : TASMNativeInt; anorm : double; c, f, g, h : double; s, scale, x, y, z : double; rv1 : Array of double; pA : PDouble; pAi : PDouble; pAj : PDouble; pV : PDouble; pVj : PDouble; invScale : double; invh : double; val : double; pWi : PDouble; begin assert(LineWidthA >= width*sizeof(double), 'Dimension error'); assert(LineWidthV >= width*sizeof(double), 'Dimension error'); if Assigned(progress) then progress(0); SetLength(rv1, width); g := 0; scale := 0; anorm := 0; l := 1; nm := 0; Result := srNoConvergence; pWi := W; // Householder reduction to bidiagonal form pAi := A; for i := 0 to width - 1 do begin if Assigned(progress) then progress(0 + Round(10*(i/width))); l := i + 1; rv1[i] := scale*g; g := 0; s := 0; scale := 0; if i < height then begin pA := pAi; inc(pA, i); for k := i to height - 1 do begin scale := scale + abs(pA^); inc(PByte(pA), LineWidthA); end; if scale <> 0 then begin pA := pAi; inc(pA, i); invScale := 1/scale; for k := i to height - 1 do begin pA^ := pA^*invScale; s := s + sqr(pA^); inc(PByte(pA), LineWidthA); end; pA := pAi; inc(pA, i); f := pA^; g := -sign(sqrt(s), f); h := f*g - s; pA^ := f - g; invh := 1/h; for j := l to width - 1 do begin s := 0; pA := pAi; pAj := pA; inc(pA, i); inc(pAj, j); for k := i to height - 1 do begin s := s + pA^*pAj^; inc(PByte(pA), LineWidthA); inc(PByte(pAj), LineWidthA); end; f := s*invh; pA := pAi; pAj := pA; inc(pA, i); inc(pAj, j); for k := i to height - 1 do begin pAj^ := pAj^ + f*pA^; inc(PByte(pAj), LineWidthA); inc(PByte(pA), LineWidthA); end; end; pA := pAi; inc(pA, i); for k := i to height - 1 do begin pA^ := scale*pA^; inc(PByte(pA), LineWidthA); end; end; // end if scale end; // end if i < height pWi^ := scale*g; g := 0; scale := 0; s := 0; if (i < width) and (i <> width - 1) then begin pA := pAi; inc(pA, l); for k := l to width - 1 do begin scale := scale + abs(pA^); inc(pA); end; if scale <> 0 then begin pA := pAi; inc(pA, l); invScale := 1/scale; for k := l to width - 1 do begin pA^ := pA^*invScale; s := s + sqr(pA^); inc(pA); end; pA := pAi; inc(pA, l); f := pA^; g := -sign(sqrt(s), f); h := f*g - s; pA^ := f - g; invh := 1/h; for k := l to width - 1 do begin rv1[k] := pA^*invh; inc(pA); end; for j := l to height - 1 do begin s := 0; pAj := A; inc(pAj, l); pA := pAi; inc(pA, l); inc(PByte(pAj), LineWidthA*j); for k := l to width - 1 do begin s := s + pAj^*pA^; inc(pAj); inc(pA); end; pA := A; inc(PByte(pA), LineWidthA*j); inc(pA, l); for k := l to width - 1 do begin pA^ := pA^ + s*rv1[k]; inc(pA); end; end; pA := pAi; inc(pA, l); for k := l to width - 1 do begin pA^ := pA^*scale; inc(pA); end; end; end; anorm := max(anorm, abs(pWi^) + abs(rv1[i])); inc(PByte(pWi), LineWidthW); inc(PByte(pAi), LineWidthA); end; // accumulation of right-hand transformations pAi := A; inc(PByte(pAi), (width - 1)*LineWidthA); for i := width - 1 downto 0 do begin if Assigned(progress) then progress(Round(10 + 10*((width - 1 - i)/(width)))); if i < width - 1 then begin if g <> 0 then begin pV := V; inc(pV, i); inc(PByte(pV), LineWidthV*l); pA := pAi; inc(pA, l); val := pA^; val := 1/(val*g); for j := l to width - 1 do begin pV^ := pA^*val; inc(pA); inc(PByte(pV), LineWidthV); end; for j := l to width - 1 do begin s := 0; pA := pAi; inc(pA, l); pV := V; inc(pV, j); inc(PByte(pV), LineWidthV*l); for k := l to width - 1 do begin s := s + pA^*pV^; inc(pA); inc(PByte(pV), LineWidthV); end; pV := V; inc(pV, i); inc(PByte(pV), LineWidthV*l); pVj := V; inc(pVj, j); inc(PByte(pVj), LineWidthV*l); for k := l to width - 1 do begin pVj^ := pVj^ + s*pV^; inc(PByte(pVj), LineWidthV); inc(PByte(pV), LineWidthV); end; end; end; // end if g <> 0 pV := V; inc(pV, l); inc(PByte(pV), LineWidthV*i); pVj := V; inc(pVj, i); inc(PByte(pVj), LineWidthV*l); for j := l to width - 1 do begin pV^ := 0; pVj^ := 0; inc(pV); inc(PByte(pVj), LineWidthV); end; end; // end if i < width -1 pV := V; inc(pV, i); inc(PByte(pV), LineWidthV*i); pV^ := 1; g := rv1[i]; l := i; dec(PByte(pAi), LineWidthA); end; pWi := W; inc(PByte(pWi), (min(width, height) - 1)*LineWidthW); pAi := A; inc(PByte(pAi), (min(width, height) - 1)*LineWidthA); // accumulation of left-hand transformations for i := min(width, height) - 1 downto 0 do begin if Assigned(progress) then progress(Round(20 + 10*((Min(width, height) - 1 - i)/(Min(width, height))))); l := i + 1; g := pWi^; pA := pAi; inc(pA, l); for j := l to width - 1 do begin pA^ := 0; inc(pA); end; if g <> 0 then begin g := 1/g; for j := l to width - 1 do begin s := 0; pA := A; inc(pA, i); inc(PByte(pA), l*LineWidthA); pAj := A; inc(pAj, j); inc(PByte(pAj), l*LineWidthA); for k := l to height - 1 do begin s := s + pA^*pAj^; inc(PByte(pA), LineWidthA); inc(PByte(pAj), LineWidthA); end; pA := pAi; inc(pA, i); f := (s/pA^)*g; pAj := pAi; inc(pAj, j); for k := i to height - 1 do begin pAj^ := pAj^ + f*pA^; inc(PByte(pAj), LineWidthA); inc(PByte(pA), LineWidthA); end; end; pA := pAi; inc(pA, i); for j := i to height - 1 do begin pA^ := pA^*g; inc(PByte(pA), LineWidthA); end; end else begin pA := pAi; inc(pA, i); for j := i to height - 1 do begin pA^ := 0; inc(PByte(pA), LineWidthA); end; end; pA := pAi; inc(pA, i); pA^ := pA^ + 1; dec(PByte(pWi), LineWidthW); dec(PByte(pAi), LineWidthA); end; // Diagonalization of the bidiagonal form: loop over singular values and over // allowed iterations for k := width - 1 downto 0 do begin if Assigned(progress) then progress(Round(30 + 70*((Min(width, height) - 1 - k)/(Min(width, height))))); for its := 0 to cMaxNumSVDIter - 1 do begin flag := true; // test for splitting for l := k downto 0 do begin nm := l - 1; if abs(rv1[l]) + anorm = anorm then begin flag := False; break; end; if abs(PDouble(PAnsiChar(W) + nm*LineWidthW)^) + anorm = anorm then break; end; // Cancellation of rv1[o] if l > 1 if flag then begin c := 0; s := 1; for i := l to k do begin f := s*rv1[i]; rv1[i] := c*rv1[i]; if abs(f) + anorm <> anorm then // check if the value is lower than the precission in contrast to anorm begin g := PDouble(PAnsiChar(W) + i*LineWidthW)^; h := pythag(f, g); PDouble(PAnsiChar(W) + i*LineWidthW)^ := h; h := 1/h; c := g*h; s := -f*h; pA := A; inc(pA, nm); pAj := A; inc(pAj, i); for j := 0 to height - 1 do begin y := pA^; z := pAj^; pA^ := y*c + z*s; pAj^ := z*c - y*s; inc(PByte(pA), LineWidthA); inc(PByte(pAj), LineWidthA); end; end; end; end; z := PDouble(PAnsiChar(W) + k*LineWidthW)^; // convergence if l = k then begin if z < 0 then begin PDouble(PAnsiChar(W) + k*LineWidthW)^ := -z; pV := V; inc(pV, k); for j := 0 to width - 1 do begin pV^ := -pV^; inc(PByte(pV), LineWidthV); end; end; break; end; if its = cMaxNumSVDIter - 1 then exit; x := PDouble(PAnsiChar(W) + l*LineWidthW)^; nm := k - 1; y := PDouble(PAnsiChar(W) + nm*LineWidthW)^; g := rv1[nm]; h := rv1[k]; f := ((y - z)*(y + z) + (g - h)*(g + h))/(2*h*y); g := pythag(f, 1); val := g; if f < 0 then val := -val; f := ((x - z)*(x + z) + h*((y/(f + val)) - h))/x; c := 1; s := 1; // next QR transformation for j := l to nm do begin i := j + 1; g := rv1[i]; y := PDouble(PAnsiChar(W) + i*LineWidthW)^; h := s*g; g := c*g; z := pythag(f, h); rv1[j] := z; c := f/z; s := h/z; f := x*c + g*s; g := g*c - x*s; h := y*s; y := y*c; pVj := V; inc(pVj, j); pV := V; inc(pV, i); for jj := 0 to width - 1 do begin x := pVj^; z := pV^; pVj^ := x*c + z*s; pV^ := z*c - x*s; inc(PByte(pV), LineWidthV); inc(PByte(pVj), LineWidthV); end; z := pythag(f, h); PDouble(PAnsiChar(W) + j*LineWidthW)^ := z; // rotation can be arbitrary if z = 0 if z <> 0 then begin z := 1/z; c := f*z; s := h*z; end; f := c*g + s*y; x := c*y - s*g; pA := A; inc(pA, i); pAj := A; inc(pAj, j); for jj := 0 to height - 1 do begin y := pAj^; z := pA^; pAj^ := y*c + z*s; pA^ := z*c - y*s; inc(PByte(pAj), LineWidthA); inc(PByte(pA), LineWidthA); end; end; rv1[l] := 0; rv1[k] := f; PDouble(PAnsiChar(W) + k*LineWidthW)^ := x; end; end; Result := srOk; end; function MatrixSVD(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; Height : TASMNativeInt; U : PDouble; const LineWidthU : TASMNativeInt; W : PDouble; const LineWidthW : TASMNativeInt; V : PDouble; const LineWidthV : TASMNativeInt; progress : TLinEquProgress) : TSVDResult; begin assert(LineWidthA >= width*sizeof(double), 'Dimension error'); assert(LineWidthV >= width*sizeof(double), 'Dimension error'); MatrixCopy(U, LineWidthU, A, LineWidthA, width, Height); Result := MatrixSVDInPlace(U, LineWidthU, width, Height, W, LineWidthW, V, LineWidthV, progress); end; function MatrixCholeskyInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; P : PDouble; LineWidthP : TASMNativeInt; progress : TLinEquProgress) : TCholeskyResult; var i, j, k : TASMNativeInt; sum : double; pA : PDouble; pA1 : PDouble; pAj : PDouble; pAj1 : PDouble; begin assert(LineWidthA >= width*sizeof(double), 'Dimension error'); if Assigned(progress) then progress(0); Result := crNoPositiveDefinite; pA := A; for i := 0 to width - 1 do begin if Assigned(progress) then progress(int64(i)*100 div width); pAj := pA; for j := i to width - 1 do begin sum := PDouble(PAnsiChar(pA) + j*sizeof(double))^; pAj1 := pAj; pA1 := pA; if i > 0 then begin inc(pAj1, i - 1); inc(pA1, i - 1); for k := i - 1 downto 0 do begin sum := sum - pA1^*pAj1^; dec(pA1); dec(pAj1); end; end; if i = j then begin // check for Positive definite matrix if sum <= 0 then exit; PDouble(PAnsiChar(P) + i*LineWidthP)^ := sqrt(sum); end else begin pAj1 := pAj; inc(pAj1, i); pAj1^ := sum/PDouble(PAnsiChar(P) + i*LineWidthP)^; end; inc(PByte(pAj), LineWidthA); end; inc(PByte(pA), LineWidthA); end; if Assigned(progress) then progress(100); Result := crOk; end; function MatrixCholesky(dest : PDouble; const LineWidthDest : TASMNativeInt; A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; P : PDouble; const LineWidthP : TASMNativeInt; progress : TLinEquProgress) : TCholeskyResult; var pDest : PDouble; pA : PDouble; i : TASMNativeInt; begin // copy A to dest pA := A; pDest := Dest; for i := 0 to width - 1 do begin Move(pA^, pDest^, sizeof(double)*width); inc(PByte(pDest), LineWidthDest); inc(PByte(pA), LineWidthA); end; Result := MatrixCholeskyInPlace(dest, LineWidthDest, width, P, LineWidthP, progress); end; procedure MatrixCholeskySolveLinEq(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; P : PDouble; const LineWidthP : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt; progress : TLinEquProgress); var i, k : TASMNativeInt; sum : double; pX : PDouble; pXi : PDouble; pA : PDouble; pB : PDouble; pP : PDouble; begin pB := B; pP := P; pXi := X; if Assigned(progress) then progress(0); // Solve L*y = b for i := 0 to width - 1 do begin sum := pB^; if i > 0 then begin pX := pXi; dec(PByte(pX), LineWidthX); pA := A; inc(PByte(pA), i*LineWidthA); inc(pA, i - 1); for k := i - 1 downto 0 do begin sum := sum - pA^*pX^; dec(pA); dec(PByte(pX), LineWidthX); end; end; pXi^ := sum/pP^; inc(PByte(pB), LineWidthB); inc(PByte(pP), LineWidthP); inc(PByte(pXi), LineWidthX); end; if Assigned(progress) then progress(50); // Solve L' * x = y pP := P; inc(PByte(pP), (width - 1)*LineWidthP); pXi := X; inc(PByte(pXi), (width - 1)*LineWidthX); for i := width - 1 downto 0 do begin sum := pXi^; pX := pXi; if i < width - 1 then begin inc(PByte(pX), LineWidthX); pA := A; inc(pA, i); inc(PByte(pA), (i + 1)*LineWidthA); for k := i + 1 to width - 1 do begin sum := sum - pA^*pX^; inc(PByte(pX), LineWidthX); inc(PByte(pA), LineWidthA); end; end; pXi^ := sum/pP^; dec(PByte(pP), LineWidthP); dec(PByte(pXi), LineWidthX); end; if Assigned(progress) then progress(100); end; // ########################################################## // #### Cholesky routines // ########################################################## function InternalBlkCholeskyInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; pnlSize : TASMNativeInt; aMatrixMultT2Ex : TMatrixBlockedMultfunc; multMem : PDouble; progress : TLinEquProgress = nil) : TCholeskyResult; var j : integer; jb : integer; pAjj : PDouble; pA1 : PDouble; pAjb, pAj, pAjjb : PDouble; begin Result := crOk; j := 0; pAjj := A; pA1 := A; while j < width do begin jb := min(pnlSize, width - j); GenericSymRankKUpd(pAjj, LineWidthA, pA1, LineWidthA, j, jb, -1, 1); Result := MatrixCholeskyInPlace2(pAjj, LineWidthA, jb, nil); if result <> crOk then exit; // compute the current block column if j + jb < width then begin pAjb := A; inc(PByte(pAjb), (j + jb)*LineWidthA); pAj := A; inc(PByte(pAj), j*LineWidthA); pAjjb := pAjb; inc(pAjjb, j); aMatrixMultT2Ex(pAjjb, LineWidthA, pAjb, pAj, j, width - j - jb, j, jb, LineWidthA, LineWidthA, jb, doSub, multMem); GenericSolveLoTriMtxTranspNoUnit(pAjj, LineWidthA, pAjjb, LineWidthA, jb, width - j - jb); end; inc(pAjj, pnlSize); inc(PByte(pAjj), pnlSize*LineWidthA); inc(PByte(pA1), pnlSize*LineWidthA); inc(j, pnlSize); if assigned(progress) then progress(Int64(j)*100 div Int64(width)); end; end; function MatrixCholeskyInPlace4(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; pnlSize : TASMNativeInt; progress : TLinEquProgress = nil) : TCholeskyResult; var multMem : PDouble; begin if pnlSize = 0 then pnlSize := CholBlockSize; // single line version if width <= pnlSize then begin Result := MatrixCholeskyInPlace2(A, LineWidthA, width, progress); exit; end; // ########################################### // #### Blocked code // ########################################### multMem := GetMemory(BlockMultMemSize(pnlSize)); Result := InternalBlkCholeskyInPlace(A, LineWidthA, width, pnlSize, {$IFDEF FPC}@{$ENDIF}MatrixMultT2Ex, multMem, progress); FreeMem(multMem); end; // recursive cholesky decomposition: // This is the recursive version of the algorithm. It divides // the matrix into four submatrices: // // [ A11 | A12 ] where A11 is n1 by n1 and A22 is n2 by n2 // A = [ -----|----- ] with n1 = n/2 // [ A21 | A22 ] n2 = n-n1 // // The subroutine calls itself to factor A11. Update and scale A21 // or A12, update A22 then call itself to factor A22. function InternaRecursivelCholeskyInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt) : TCholeskyResult; var n1, n2 : TASMNativeInt; A21, A22 : PDouble; begin Result := crNoPositiveDefinite; if width = 1 then begin if (A^ <= 0) or IsNan(A^) then exit; A^ := Sqrt(A^); end else begin n1 := width div 2; n2 := width - n1; if n1 > 0 then begin Result := InternaRecursivelCholeskyInPlace(A, LineWidthA, n1); if Result <> crOk then exit; end; // lower triangualar cholesky: A21 := A; inc(PByte(A21), n1*LineWidthA); GenericSolveLoTriMtxTranspNoUnit(A, LineWidthA, A21, LineWidthA, n1, n2); // Update and factor A22 A22 := A; inc(PByte(A22), n1*LineWidthA); inc(A22, n1); GenericSymRankKUpd(A22, LineWidthA, A21, LineWidthA, n1, n2, -1, 1); Result := InternaRecursivelCholeskyInPlace(A22, LineWidthA, n2); if Result <> crOk then exit; end; Result := crOk; end; function MatrixCholeskyInPlace3(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress = nil) : TCholeskyResult; begin Result := InternaRecursivelCholeskyInPlace(A, LineWidthA, width) end; // single line but memory access optimal version of the cholesky decomposition function MatrixCholeskyInPlace2(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress = nil) : TCholeskyResult; var i : TASMNativeInt; j, k : TASMNativeInt; pAi : PDouble; sum : double; pAij : PDouble; pAik, pAjk : PDouble; pAjj : PDouble; begin Result := crNoPositiveDefinite; // lower triangular cholesky decomposition for i := 0 to width - 1 do begin pAi := A; inc(PByte(pAi), i*LineWidthA); pAij := PAi; pAjj := A; for j := 0 to i do begin sum := pAij^; pAik := pAi; pAjk := A; inc(PByte(pAjk), j*LineWidthA); for k := 0 to j - 1 do begin sum := sum - pAik^*pAjk^; inc(pAik); inc(pAjk); end; if i > j then pAij^ := sum/pAjj^ else if sum > 0 then begin pAik := pAi; inc(pAik, i); pAik^ := sqrt(sum); end else exit; // not positive definite inc(pAij); inc(pAjj); inc(PByte(pAjj), LineWidthA); end; if Assigned(progress) then Progress(i*100 div (width - 1)); end; Result := crOk; end; function MatrixQRDecompInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; C : PDouble; const LineWidthC : TASMNativeInt; D : PDouble; const LineWidthD : TASMNativeInt; progress : TLinEquProgress) : TQRResult; var i, j, k : TASMNativeInt; scale, sigma, sum, tau : double; pA, pAj : PDouble; pC : PDouble; pD : PDouble; pAk : PDouble; begin assert(LineWidthA >= width*sizeof(double), 'Dimension error'); assert(LineWidthC >= sizeof(double), 'Dimension error'); assert(LineWidthD >= sizeof(double), 'Dimension error'); Result := qrOK; if Assigned(progress) then progress(0); pC := C; pD := D; pAk := A; for k := 0 to width - 2 do begin if Assigned(progress) then progress(Int64(k)*100 div width); scale := 0; pA := pAk; for i := k to width - 1 do begin scale := Max(scale, abs(pA^)); inc(PByte(pA), LineWidthA); end; if scale = 0 then begin Result := qrSingular; pC^ := 0; pD^ := 0; end else begin pA := pAk; for i := k to width - 1 do begin pA^ := pA^/scale; inc(PByte(pA), LineWidthA); end; sum := 0; pA := pAk; for i := k to width - 1 do begin sum := sum + sqr(pA^); inc(PByte(pA), LineWidthA); end; sigma := sign(sqrt(sum), pAk^); pAk^ := pAk^ + sigma; pC^ := sigma*pAk^; pD^ := -scale*sigma; for j := k + 1 to width - 1 do begin sum := 0; pA := pAk; pAj := pAk; inc(pA, j - k); for i := k to width - 1 do begin sum := sum + pA^*pAj^; inc(PByte(pA), LineWidthA); inc(PByte(pAj), LineWidthA); end; tau := sum/pC^; pA := pAk; pAj := pAk; inc(pAj, j - k); for i := k to width - 1 do begin pAj^ := pAj^ - tau*pA^; inc(PByte(pA), LineWidthA); inc(PByte(pAj), LineWidthA); end; end; end; inc(PByte(pC), LineWidthC); inc(PByte(pD), LineWidthD); inc(pAk); inc(PByte(pAk), LineWidthA); end; pD := D; inc(PByte(pD), (width - 1)*LineWidthD); pA := A; inc(pA, width - 1); inc(PByte(pA), (width - 1)*LineWidthA); pD^ := pA^; if pD^ = 0 then Result := qrSingular; if Assigned(Progress) then progress(100); end; function MatrixQRDecomp(dest : PDouble; const LineWidthDest : TASMNativeInt; A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; C : PDouble; const LineWidthC : TASMNativeInt; D : PDouble; const LineWidthD : TASMNativeInt; progress : TLinEquProgress) : TQRResult; var pDest : PDouble; pA : PDouble; i : TASMNativeInt; begin assert(LineWidthA >= width*sizeof(double), 'Dimension error'); assert(LineWidthDest >= width*sizeof(double), 'Dimension error'); assert(LineWidthC >= sizeof(double), 'Dimension error'); assert(LineWidthD >= sizeof(double), 'Dimension error'); // copy A to dest pA := A; pDest := Dest; for i := 0 to width - 1 do begin Move(pA^, pDest^, sizeof(double)*width); inc(PByte(pDest), LineWidthDest); inc(PByte(pA), LineWidthA); end; Result := MatrixQRDecompInPlace(dest, LineWidthDest, width, C, LineWidthC, D, LineWidthD, progress); end; procedure MatrixRSolve(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; C : PDouble; const LineWidthC; D : PDouble; const LineWidthD : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; progress : TLinEquProgress); var i, j : TASMNativeInt; pA : PDouble; pAj : PDouble; pB : PDouble; pBj : PDOuble; pD : PDouble; sum : double; begin pBj := B; inc(PByte(pBj), LineWidthB*(width - 1)); pD := D; inc(PByte(pD), LineWidthD*(width - 1)); pBj^ := pBj^/pD^; pAj := A; inc(PByte(pAj), (width - 2)*LineWidthA); inc(pAj, (width - 1)); if Assigned(progress) then progress(0); for i := width - 2 downto 0 do begin sum := 0; pA := pAj; pB := pBj; for j := i + 1 to width - 1 do begin sum := sum + pA^*pB^; inc(pA); inc(PByte(pB), LineWidthB); end; dec(PByte(pBj), LineWidthB); dec(PByte(pD), LineWidthD); pBj^ := (pBj^ - sum)/pD^; dec(pAj); dec(PByte(pAj), LineWidthA); end; if Assigned(progress) then progress(100); end; procedure MatrixQRSolveLinEq(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; C : PDouble; const LineWidthC : TASMNativeInt; D : PDouble; const LineWidthD : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; progress : TLinEquProgress); var i, j : TASMNativeInt; sum, tau : double; pA : PDouble; pAj : PDouble; pB : PDouble; pBj : PDOuble; pC : PDouble; begin assert(LineWidthA >= width*sizeof(double), 'Dimension error'); assert(LineWidthB >= sizeof(double), 'Dimension error'); assert(LineWidthC >= sizeof(double), 'Dimension error'); assert(LineWidthD >= sizeof(double), 'Dimension error'); pAj := A; pBj := B; pC := C; for j := 0 to width - 2 do begin sum := 0; pA := pAj; pB := pBj; for i := j to width - 1 do begin sum := sum + pA^*pB^; inc(PByte(pA), LineWidthA); inc(PByte(pB), LineWidthB); end; tau := sum/pC^; pA := pAj; pB := pBj; for i := j to width - 1 do begin pB^ := pB^ - tau*pA^; inc(PByte(pB), LineWidthB); inc(PByte(pA), LineWidthA); end; inc(pAj); inc(PByte(pAj), LineWidthA); inc(PByte(pC), LineWidthC); inc(PByte(pBj), LineWidthB); end; MatrixRSolve(A, LineWidthA, width, C, LineWidthC, D, LineWidthD, B, LineWidthB, progress); end; // ########################################################## // #### Blocked QR Decomposition methods // ########################################################## // apply householder transformation to A (one column) // original DLARFG in Lapack function GenElemHousholderRefl(A : PDouble; LineWidthA : TASMNativeInt; Height : TASMNativeInt; var Alpha : double; Tau : PDouble) : boolean; var beta : double; xNorm : double; //saveMin : double; begin Result := False; if height < 1 then begin Tau^ := 0; Result := True; exit; end; xNorm := MatrixElementwiseNorm2(A, LineWidthA, 1, height); if xNorm = 0 then begin // H = I Tau^ := 0; exit; end; beta := -sign( pythag(alpha, xnorm), alpha); // todo: apply under/overflow code here as lapack does // check for possible under/overflow -> rescale //saveMin := cMinDblDivEps; // // note this is not the original code // if Abs(beta) < saveMin then // begin // // todo: // end; Tau^ := (beta - alpha)/beta; MatrixScaleAndAdd(A, LineWidthA, 1, Height, 0, 1/(alpha - beta)); alpha := beta; Result := True; end; // original Dlarf in lapack procedure ApplyElemHousholderRefl(A : PDouble; LineWidthA : TASMNativeInt; width, height : TASMNativeInt; Tau : PDouble; Work : PDouble); var pA1 : PDouble; x, y : TASMNativeInt; pDest : PDouble; pWork : PDouble; pA : PDouble; tmp : double; begin // work = A(1:m, 2:n)T*A(1:m, 1) if tau^ <> 0 then begin pA1 := A; inc(pA1); // todo: there is some other scanning going on for non zero columns... // do the basic operation here... GenericTranspMtxMult(work, sizeof(double), pA1, A, width - 1, height, 1, height, LineWidthA, LineWidthA); // dger: A - tau*A(1:m,1)*work -> do not touch first column pA := A; for y := 0 to height - 1 do begin pDest := pA1; pWork := work; tmp := tau^*pA^; for x := 1 to width - 1 do begin pDest^ := pDest^ - tmp*pwork^; inc(pDest); inc(pWork); end; inc(PByte(pA1), LineWidthA); inc(PByte(pA), LineWidthA); end; end; end; // implementation of lapack's DGEQR2 function MtxQRUnblocked(A : PDouble; LineWidthA : TASMNativeInt; width, height : TASMNativeInt; Tau : PDouble; const qrData : TRecMtxQRDecompData) : boolean; var k : TASMNativeInt; i : TASMNativeInt; pA : PDouble; pTau : PDouble; aii : double; pAlpha : PDouble; lineRes : boolean; begin Result := true; k := min(width, height); pA := A; pTau := Tau; for i := 0 to k - 1 do begin // Generate elemetary reflector H(i) to annihilate A(1+i:height-1,i); pAlpha := pA; if i < height - 1 then inc(PByte(pA), LineWidthA); lineRes := GenElemHousholderRefl(pA, LineWidthA, height - i - 1, pAlpha^, pTau); Result := Result and lineRes; // Apply H(i) to A(i:m,i+1:n) from the left if i < width - 1 then begin aii := pAlpha^; pAlpha^ := 1; ApplyElemHousholderRefl(pAlpha, LineWidthA, width - i, height - i, pTau, qrData.work); pAlpha^ := aii; end; if Assigned(qrData.Progress) then qrData.Progress((qrData.actIdx + i)*100 div qrData.qrWidth); inc(pTau); inc(pA); end; end; // original DLARFT in Lapack procedure CreateTMtx(n, k : TASMNativeInt; A : PDouble; LineWidthA : TASMNativeInt; Tau : PDouble; const qrData : TRecMtxQRDecompData); var i, j : TASMNativeInt; pT, pA : PDouble; pA1 : PDouble; pDest : PDouble; pT1, pt2 : PDouble; x, y : TASMNativeInt; tmp : Double; pMem : PDouble; pResVec : PDouble; T : PDouble; begin assert(k <= n, 'Error k needs to be smaller than n'); // it is assumed that mem is a memory block of at least (n, k) where the first (k, k) elements are reserved for T T := qrData.work; pMem := T; inc(PByte(pMem), k*qrData.LineWidthWork); for i := 0 to k - 1 do begin if Tau^ = 0 then begin // H = I pT := T; for j := 0 to i do begin pT^ := 0; inc(PByte(pT), qrData.LineWidthWork); end; end else begin // general case // T(1:i-1,i) := - tau(i) * A(i:j,1:i-1)**T * A(i:j,i) **T = Transposed // T(1:i-1,i) := - tau(i) * V(i:n,1:i-1)' * V(i:n,i) */ pA1 := A; inc(PByte(pA1), LineWidthA*i); // i + 1); // precalculate -tau*v for the vector T pA := A; inc(pA, i); inc(PByte(pA), (i+1)*LineWidthA); pResVec := pMem; pResVec^ := -Tau^; // first element of V is 1! inc(pResVec); for j := i + 1 to n - 1 do // do not calculate the rest they are gona be multiplied with 0 begin pResVec^ := -Tau^*pA^; inc(pResVec); inc(PByte(pA), LineWidthA); end; pT := T; inc(pT, i); // final -tau * Y' * v -> // todo: Implement an optimized matrix vector operator for mt1'mt2 GenericTranspMtxMult(pT, qrData.LineWidthWork, pA1, pMem, k, n - i, 1, n - i, LineWidthA, sizeof(double)); end; // dtrmv: upper triangle matrix mult T(1:i-1,i) := T(1:i-1, 1:i-1)*T(1:i-1,i) if i > 0 then begin pDest := T; inc(pDest, i); for y := 0 to i - 1 do begin pT1 := T; inc(pT1, y); inc(PByte(pT1), y*qrData.LineWidthWork); pT2 := pDest; tmp := 0; for x := y to i - 1 do begin tmp := tmp + pT1^*pT2^; inc(pT1); inc(PByte(pT2), qrData.LineWidthWork); end; pDest^ := tmp; inc(PByte(pDest), qrData.LineWidthWork); end; end; pT := T; inc(pT, i); inc(PByte(pT), i*qrData.LineWidthWork); pT^ := Tau^; // fill in last Tau inc(Tau); end; end; procedure MatrixSubT(A : PDouble; LineWidthA : TASMNativeInt; B : PDouble; LineWidthB : TASMNativeInt; width, height : TASMNativeInt); var x, y : TASMNativeInt; pA, pB : PDouble; begin // calculate A = A - B' for y := 0 to height - 1 do begin pA := A; pB := B; for x := 0 to width - 1 do begin pA^ := pA^ - pB^; inc(pA); inc(PByte(pB), LineWidthB); end; inc(PByte(A), LineWidthA); inc(B); end; end; // apply block reflector to a matrix // original DLARFB in Lapack procedure ApplyBlockReflector(A : PDouble; LineWidthA : TASMNativeInt; const qrData : TRecMtxQRDecompData; width, height : TASMNativeInt; widthT : TASMNativeInt; Transposed : boolean); var pC1, pC2 : PDouble; pY1, pY2 : PDouble; T : PDouble; LineWidthT : TASMNativeInt; mem : PDouble; LineWidthMem : TASMNativeInt; heightW : TASMNativeInt; begin mem := qrData.work; inc(PByte(mem), widthT*qrData.LineWidthWork); // upper part (nb x nb) is dedicated to T, lower part to W in dlarfb LineWidthMem := qrData.LineWidthWork; T := qrData.work; LineWidthT := qrData.LineWidthWork; // (I - Y*T*Y')xA_trailing pY1 := A; pY2 := A; inc(PByte(pY2), widthT*LineWidthA); pC1 := A; inc(pC1, widthT); pC2 := pC1; inc(PByte(pC2), widthT*LineWidthA); // W = C1'*Y1 MatrixMultTria2T1(mem, LineWidthMem, pC1, LineWidthA, pY1, LineWidthA, width - widthT, widthT, widthT, widthT); heightW := width - widthT; // W = W + C2'*Y2 qrData.MatrixMultT1(mem, LineWidthMem, pC2, pY2, Width - WidthT, height - widthT, WidthT, height - widthT, LineWidthA, LineWidthA, QRMultBlockSize, doAdd, qrData.BlkMultMem); // W = W * T (using dtrm) or W = W*T' if height > widthT then begin if transposed then GenericMtxMultTria2T1StoreT1(mem, LineWidthMem, T, LineWidthT, widthT, heightW, WidthT, WidthT) else GenericMtxMultTria2Store1(mem, LineWidthMem, T, LineWidthT, widthT, heightW, WidthT, WidthT); // C2 = C2 - Y2*W' qrData.MatrixMultT2(pC2, LineWidthA, pY2, mem, widthT, height - widthT, widthT, heightW, LineWidthA, LineWidthMem, QRMultBlockSize, doSub, qrData.BlkMultMem); // W = W*Y1' (lower left part of Y1! -> V1) GenericMtxMultLowTria2T2Store1(mem, LineWidthMem, A, LineWidthA, WidthT, heightW, widthT, widthT); end; // C1 = C1 - W' MatrixSubT(pC1, LineWidthA, mem, LineWidthMem, width - widthT, widthT); end; function InternalMatrixQRDecompInPlace2(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; qrData : TRecMtxQRDecompData) : boolean; var k : TASMNativeInt; idx : TASMNativeInt; ib : TASMNativeInt; pA : PDouble; pnlRes : boolean; begin // ###################################################### // #### original linpack DGEQRF routine k := Min(width, height); // check if the panel size fits the width/heigth -> if not adjust the panel size if (qrdata.pnlSize > 1) and (qrdata.pnlSize > k) then qrdata.pnlSize := max(2, k div 2); Result := True; qrData.LineWidthWork := sizeof(double)*qrdata.pnlSize; idx := 0; pA := A; if (qrdata.pnlSize >= 2) and (qrdata.pnlSize < k) then begin // calculate the qr decomposition for the current panel while idx < k - qrdata.pnlSize - 2 do begin ib := min(width - idx, qrdata.pnlSize); pnlRes := MtxQRUnblocked(pA, LineWidthA, ib, height - idx, Tau, qrData); Result := Result and pnlRes; // calculate T matrix if idx + ib <= height then begin CreateTMtx(height - idx, ib, pA, LineWidthA, Tau, qrData); // apply H to A from the left ApplyBlockReflector(pA, LineWidthA, qrData, width - idx, height - idx, ib, False); end; inc(qrData.actIdx, ib); inc(pA, ib); inc(PByte(pA),ib*LineWidthA); inc(idx, ib); inc(Tau, ib); end; end; // calculate the last panel pnlRes := MtxQRUnblocked(pA, LineWidthA, width - idx, height - idx, Tau, qrData); Result := Result and pnlRes; end; function MatrixQRDecompInPlace2(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; progress : TLinEquProgress = nil) : TQRResult; overload; begin Result := MatrixQRDecompInPlace2(A, LineWidthA, width, height, tau, nil, QRBlockSize, Progress); end; function MatrixQRDecompInPlace2(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; work : PDouble; pnlSize : TASMNativeInt; progress : TLinEquProgress = nil) : TQRResult; overload; var res : boolean; qrData : TRecMtxQRDecompData; begin qrData.pWorkMem := nil; qrData.work := work; qrData.BlkMultMem := nil; qrData.Progress := progress; qrData.qrWidth := width; qrData.qrHeight := height; qrData.actIdx := 0; qrData.pnlSize := pnlSize; qrData.MatrixMultT1 := {$IFDEF FPC}@{$ENDIF}MatrixMultT1Ex; qrData.MatrixMultT2 := {$IFDEF FPC}@{$ENDIF}MatrixMultT2Ex; if work = nil then begin qrData.pWorkMem := GetMemory(pnlSize*sizeof(double)*height + 64 + BlockMultMemSize(QRMultBlockSize) ); qrData.work := PDouble(qrData.pWorkMem); if (NativeUInt(qrData.pWorkMem) and $0000000F) <> 0 then qrData.work := PDouble(NativeUInt(qrData.pWorkMem) + 16 - NativeUInt(qrData.pWorkMem) and $0F); end; // it's assumed that the work memory block may also be used // as blocked multiplication memory storage! qrData.BlkMultMem := qrData.work; inc(qrData.BlkMultMem, pnlSize*height); res := InternalMatrixQRDecompInPlace2(A, LineWidthA, width, height, tau, qrData); if work = nil then FreeMem(qrData.pWorkMem); if res then Result := qrOK else Result := qrSingular; end; // generates an m by n real matrix Q with orthonormal columns, // which is defined as the first n columns of a product of k elementary // reflectors of order m // k: the number of elemetary reflectors whose product defines the matrix Q. width >= K >= 0. // original dorg2r from netlib procedure InternalMatrixQFromQRDecomp(A : PDouble; const LineWidthA : TASMNativeInt; width, height, k : TASMNativeInt; tau : PDouble; const qrData : TRecMtxQRDecompData); var pA : PDouble; pAii : PDouble; i, j : TASMNativeInt; begin if width <= 0 then exit; // Initialise columns k+1:n to columns of the unit matrix for j := k to width - 1 do begin pA := A; inc(pA, j); for i := 0 to height - 1 do begin pA^ := 0; inc(PByte(pA), LineWidthA); end; pA := A; inc(pA, j); inc(PByte(pA), j*LineWidthA); pA^ := 1; end; // Apply H(i) to A(i:m,i:n) from the left inc(tau, k - 1); for i := k - 1 downto 0 do begin if i < width - 1 then begin pAii := A; inc(pAii, i); inc(PByte(pAii), i*LineWidthA); pAii^ := 1; ApplyElemHousholderRefl(pAii, LineWidthA, width - i, height - i, tau, qrData.work); end; // unscaling if i < height - 1 then begin pAii := A; inc(pAii, i); inc(PByte(pAii), (i+1)*LineWidthA); MatrixScaleAndAdd(pAii, LineWidthA, 1, height - i - 1, 0, -tau^); end; pAii := A; inc(pAii, i); inc(PByte(pAii), i*LineWidthA); pAii^ := 1 - tau^; // Set A(1:i-1,i) to zero pA := A; inc(pA, i); for j := 0 to i - 1 do begin pA^ := 0; inc(PByte(pA), LineWidthA); end; dec(tau); // ########################################### // #### Progress if Assigned(qrData.Progress) then qrData.Progress((qrData.actIdx + i)*100 div qrData.qrWidth); end; end; procedure InternalBlkMatrixQFromQRDecomp(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; qrData : TRecMtxQRDecompData); var pA : PDouble; x, y : TASMNativeInt; numIter : TASMNativeInt; pTau : PDouble; counter: TASMNativeInt; idx : TASMNativeInt; begin // check for quick return ??? if width <= 0 then begin qrData.work^ := 1; exit; end; // restrict block size... qrData.pnlSize := min(height, min(width, qrData.pnlSize)); // zero out block not used by Q if height < width then begin for y := 0 to height - 1 do begin pA := A; inc(pA, height); inc(PByte(pA), y*LineWidthA); for x := height to width - 1 do begin pA^ := 0; inc(pA); end; end; // from here on we can do a normal q factorization width := height; end; if qrData.pnlSize = width then begin // unblocked code InternalMatrixQFromQRDecomp(A, LineWidthA, width, height, width, tau, qrData); end else begin numIter := (width div qrData.pnlSize); // apply unblocked code to the last block if numIter*qrData.pnlSize < width then begin idx := numIter*qrData.pnlSize; pA := A; inc(pA, idx); inc(PByte(pA), LineWidthA*idx); pTau := tau; inc(pTau, idx); InternalMatrixQFromQRDecomp(pA, LineWidthA, width - idx, height - idx, width - idx, pTau, qrData); // Set upper rows of current block to zero for y := 0 to idx - 1 do begin pA := A; inc(pA, idx); inc(PByte(pA), LineWidthA*y); for x := 0 to width - idx - 1 do begin pA^ := 0; inc(pA); end; end; end; // blocked code: for counter := numIter - 1 downto 0 do begin idx := counter*qrdata.pnlSize; pA := A; inc(pA, idx); inc(PByte(pA), idx*LineWidthA); pTau := tau; inc(pTau, idx); if (counter + 1)*qrdata.pnlSize < width then begin // form triangular factor of the block reflector // H = H(i) H(i+1) . . . H(i+ib-1) // calculate T matrix CreateTMtx(height - idx, qrData.pnlSize, pA, LineWidthA, pTau, qrData); // apply H to A from the left ApplyBlockReflector(pA, LineWidthA, qrData, width - idx, height - idx, qrdata.pnlSize, True); end; InternalMatrixQFromQRDecomp(pA, LineWidthA, qrData.pnlSize, height - idx, qrData.pnlSize, pTau, qrData); // Set upper rows of current block to zero for y := 0 to idx - 1 do begin pA := A; inc(pA, idx); inc(PByte(pA), LineWidthA*y); for x := 0 to qrData.pnlSize - 1 do begin pA^ := 0; inc(pA); end; end; end; end; end; procedure MatrixQFromQRDecomp(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; progress : TLinEquProgress = nil); overload; begin MatrixQFromQRDecomp(A, LineWidthA, width, height, tau, QRBlockSize, nil, progress); end; procedure MatrixQFromQRDecomp(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; BlockSize : TASMNativeInt; work : PDouble; progress : TLinEquProgress = nil); var qrData : TRecMtxQRDecompData; begin qrData.pWorkMem := nil; qrData.work := work; qrData.BlkMultMem := nil; qrData.Progress := progress; qrData.qrWidth := width; qrData.qrHeight := height; qrData.actIdx := 0; qrData.pnlSize := BlockSize; qrData.LineWidthWork := sizeof(double)*qrdata.pnlSize; qrData.MatrixMultT1 := {$IFDEF FPC}@{$ENDIF}MatrixMultT1Ex; qrData.MatrixMultT2 := {$IFDEF FPC}@{$ENDIF}MatrixMultT2Ex; if work = nil then begin qrData.pWorkMem := GetMemory(qrData.pnlSize*sizeof(double)*height + 64 + BlockMultMemSize(QRMultBlockSize) ); qrData.work := PDouble(qrData.pWorkMem); if (NativeUInt(qrData.pWorkMem) and $0000000F) <> 0 then qrData.work := PDouble(NativeUInt(qrData.pWorkMem) + 16 - NativeUInt(qrData.pWorkMem) and $0F); end; // it's assumed that the work memory block may also be used // as blocked multiplication memory storage! qrData.BlkMultMem := qrData.work; inc(qrData.BlkMultMem, qrData.pnlSize*height); InternalBlkMatrixQFromQRDecomp(A, LineWidthA, width, height, tau, qrData); if not Assigned(work) then freeMem(qrData.pWorkMem); end; end.
unit win.iobuffer; interface uses Types; const SizeMode_0 = 1; SizeMode_1 = 2; SizeMode_2 = 3; SizeMode_4 = 4; SizeMode_8 = 5; SizeMode_16 = 6; SizeMode_32 = 7; SizeMode_64 = 8; SizeMode_128 = 9; SizeMode_256 = 10; SizeMode_512 = 11; SizeMode_1k = 12; SizeMode_2k = 13; SizeMode_4k = 14; SizeMode_8k = 15; SizeMode_16k = 16; SizeMode_32k = 17; SizeMode_64k = 18; SizeMode_128k = 19; SizeMode_256k = 20; SizeMode_512k = 21; SizeMode_1m = 22; SizeMode_2m = 23; SizeMode_4m = 24; SizeMode_8m = 25; SizeMode_16m = 26; SizeMode_32m = 27; SizeMode_64m = 28; SizeMode_128m = 29; SizeMode_256m = 30; SizeMode_512m = 31; SizeMode_1g = 32; SizeMode_2g = 33; SizeMode_4g = 34; SizeMode_8g = 35; SizeMode_16g = 36; SizeMode_32g = 37; SizeMode_64g = 38; SizeMode_128g = 39; SizeMode_256g = 40; SizeMode_512g = 41; SizeMode_1t = 42; SizeMode_2t = 43; SizeMode_4t = 44; SizeMode_8t = 45; SizeMode_16t = 46; SizeMode_32t = 47; SizeMode_64t = 48; SizeMode_128t = 39; SizeMode_256t = 50; SizeMode_512t = 51; SizeMode_1p = 52; type PIOBufferExNode = ^TIOBufferExNode; PIOBufferHead = ^TIOBufferHead; TIOBufferHead = packed record FirstExNode : PIOBufferExNode; LastExNode : PIOBufferExNode; ExNodeCount : Integer; Size : DWORD; TotalLength : DWORD; BufDataLength : DWORD; DataPointer : Pointer; end; PIOBuffer = ^TIOBuffer; TIOBuffer = packed record BufferHead : TIOBufferHead; Data : array[0..0] of AnsiChar; end; PIOBuffer4k = ^TIOBuffer4k; TIOBuffer4k = packed record BufferHead : TIOBufferHead; Data : array[0..4 * 1024 - 1] of AnsiChar; end; PIOBuffer8k = ^TIOBuffer8k; TIOBuffer8k = packed record BufferHead : TIOBufferHead; Data : array[0..8 * 1024 - 1] of AnsiChar; end; PIOBuffer16k = ^TIOBuffer16k; TIOBuffer16k = packed record BufferHead : TIOBufferHead; Data : array[0..16 * 1024 - 1] of AnsiChar; end; PIOBuffer32k = ^TIOBuffer32k; TIOBuffer32k = packed record BufferHead : TIOBufferHead; Data : array[0..32 * 1024 - 1] of AnsiChar; end; PIOBuffer64k = ^TIOBuffer32k; TIOBuffer64k = packed record BufferHead : TIOBufferHead; Data : array[0..64 * 1024 - 1] of AnsiChar; end; PIOBuffer128k = ^TIOBuffer128k; TIOBuffer128k = packed record BufferHead : TIOBufferHead; Data : array[0..128 * 1024 - 1] of AnsiChar; end; PIOBuffer256k = ^TIOBuffer256k; TIOBuffer256k = packed record BufferHead : TIOBufferHead; Data : array[0..256 * 1024 - 1] of AnsiChar; end; PIOBuffer512k = ^TIOBuffer512k; TIOBuffer512k = packed record BufferHead : TIOBufferHead; Data : array[0..512 * 1024 - 1] of AnsiChar; end; PIOBuffer1m = ^TIOBuffer1m; TIOBuffer1m = packed record BufferHead : TIOBufferHead; Data : array[0..1024 * 1024 - 1] of AnsiChar; end; PIOBufferX = ^TIOBufferX; TIOBufferX = packed record BufferHead : TIOBufferHead; Data : array[0..MaxInt - SizeOf(TIOBufferHead) - 1] of AnsiChar; end; TIOBufferExNode = record Buffer : PIOBufferHead; PrevSibling : PIOBufferExNode; NextSibling : PIOBufferExNode; Size : Word; Length : Word; Data : array[0..16 * 1024 - 1] of AnsiChar; end; function CheckOutIOBuffer(ASizeMode: Integer = SizeMode_16k): PIOBuffer; procedure CheckInIOBuffer(var AIOBuffer: PIOBuffer); function CheckOutIOBufferExNode(AIOBuffer: PIOBuffer): PIOBufferExNode; procedure CheckInIOBufferExNode(AIOBufferExNode: PIOBufferExNode); function RepackIOBuffer(AIOBuffer: PIOBuffer): PIOBuffer; procedure ClearIOBuffer(AIOBuffer: PIOBuffer); function GetSizeMode(ASize: Integer): Integer; implementation uses math, Windows; function CheckOutIOBuffer(ASizeMode: Integer = SizeMode_16k): PIOBuffer; var // tmpBuffer256k: PIOBuffer256k; // tmpBuffer16k: PIOBuffer16k; tmpSize: integer; begin // tmpBuffer256k := System.New(PIOBuffer256k); // FillChar(tmpBuffer256k^, SizeOf(TIOBuffer256k), 0); // tmpBuffer256k.BufferHead.Size := SizeOf(tmpBuffer256k.Data); // Result := PIOBuffer(tmpBuffer16k); if 2 < ASizeMode then begin tmpSize := Trunc(math.power(2, (ASizeMode - 2))) + SizeOf(TIOBufferHead); GetMem(Result, tmpSize); FillChar(Result^, tmpSize, 0); Result.BufferHead.Size := tmpSize - SizeOf(TIOBufferHead); end else begin Result := System.New(PIOBuffer); FillChar(Result, SizeOf(TIOBuffer), 0); end; end; procedure CheckInIOBuffer(var AIOBuffer: PIOBuffer); var tmpNode: PIOBufferExNode; tmpNextNode: PIOBufferExNode; begin if nil = AIOBuffer then exit; tmpNode := AIOBuffer.BufferHead.FirstExNode; while nil <> tmpNode do begin tmpNextNode := tmpNode.NextSibling; CheckInIOBufferExNode(tmpNode); tmpNode := tmpNextNode; end; FreeMem(AIOBuffer); AIOBuffer := nil; end; procedure ClearIOBuffer(AIOBuffer: PIOBuffer); var tmpExNode: PIOBufferExNode; tmpNextExNode: PIOBufferExNode; begin tmpExNode := AIOBuffer.BufferHead.FirstExNode; while nil <> tmpExNode do begin tmpNextExNode := tmpExNode.NextSibling; CheckInIOBufferExNode(tmpExNode); tmpExNode := tmpNextExNode; end; AIOBuffer.BufferHead.FirstExNode := nil; AIOBuffer.BufferHead.LastExNode := nil; FillChar(PIOBufferX(AIOBuffer).Data, AIOBuffer.BufferHead.Size, 0); end; function GetSizeMode(ASize: Integer): Integer; var tmpSize: Integer; begin Result := 2; tmpSize := 1; while tmpSize < ASize do begin Result := Result + 1; tmpSize := tmpSize + tmpSize; end; end; function RepackIOBuffer(AIOBuffer: PIOBuffer): PIOBuffer; var tmpSizeMode: integer; tmpBeginPos: integer; tmpNode: PIOBufferExNode; begin tmpSizeMode := GetSizeMode(AIOBuffer.BufferHead.TotalLength); Result := CheckOutIOBuffer(tmpSizeMode); tmpBeginPos := 0; CopyMemory(@PIOBufferX(Result).Data[tmpBeginPos], @AIOBuffer.Data[0], AIOBuffer.BufferHead.BufDataLength); Result.BufferHead.TotalLength := Result.BufferHead.TotalLength + AIOBuffer.BufferHead.BufDataLength; tmpBeginPos := tmpBeginPos + AIOBuffer.BufferHead.BufDataLength; tmpNode := AIOBuffer.BufferHead.FirstExNode; while nil <> tmpNode do begin CopyMemory(@PIOBufferX(Result).Data[tmpBeginPos], @tmpNode.Data[0], tmpNode.Length); Result.BufferHead.TotalLength := Result.BufferHead.TotalLength + tmpNode.Length; tmpBeginPos := tmpBeginPos + tmpNode.Length; tmpNode := tmpNode.NextSibling; end; Result.BufferHead.BufDataLength := Result.BufferHead.TotalLength; end; function CheckOutIOBufferExNode(AIOBuffer: PIOBuffer): PIOBufferExNode; var tmpNode: PIOBufferExNode; begin tmpNode := System.New(PIOBufferExNode); FillChar(tmpNode^, SizeOf(TIOBufferExNode), 0); tmpNode.Buffer := @AIOBuffer.BufferHead; tmpNode.Size := SizeOf(tmpNode.Data); if nil = AIOBuffer.BufferHead.FirstExNode then AIOBuffer.BufferHead.FirstExNode := tmpNode; if nil <> AIOBuffer.BufferHead.LastExNode then begin tmpNode.PrevSibling := AIOBuffer.BufferHead.LastExNode; AIOBuffer.BufferHead.LastExNode.NextSibling := tmpNode; end; AIOBuffer.BufferHead.LastExNode := tmpNode; AIOBuffer.BufferHead.ExNodeCount := AIOBuffer.BufferHead.ExNodeCount + 1; Result := tmpNode; end; procedure CheckInIOBufferExNode(AIOBufferExNode: PIOBufferExNode); begin if nil <> AIOBufferExNode then begin FreeMem(AIOBufferExNode); AIOBufferExNode := nil; end; end; end.
unit DatosGrafico; interface uses Tipos, Controls; const SIN_FECHA : TDate = 0; SIN_CAMBIO : integer = Low(integer); SIN_CAMBIO_TRANSFORMADO: integer = Low(integer); type TDatosGrafico = class private FPCambios: PArrayCurrency; FPFechas: PArrayDate; FXTransformados, FYTransformados: TArrayInteger; FIsSinCambios: TArrayBoolean; FIsDataNulls: TArrayBoolean; FIsCambios: TArrayBoolean; FAncho: integer; FAlto: integer; FTop: integer; FDataCount: integer; FLeft: Integer; FPixelSize: byte; FDataSinCambio: integer; FDataNull: integer; FMaximoManual: currency; FMinimoManual: currency; function GetPXTransformados: PArrayInteger; inline; function GetCambio(index: integer): currency; inline; function GetFechas(index: integer): TDate; inline; function GetIsCambio(index: integer): boolean; inline; function GetIsDataNull(index: integer): boolean; inline; function GetIsSinCambio(index: integer): boolean; inline; function GetXTransformados(index: integer): integer; inline; function GetYTransformados(index: integer): integer; inline; function GetPYTransformados: PArrayInteger; inline; procedure SetDataSinCambio(const Value: integer); protected FMax, FMin: currency; public constructor Create; procedure RecalculateMaxMin(const fromPos, toPos: integer); virtual; procedure SetData(const PCambios: PArrayCurrency; const PFechas: PArrayDate); virtual; procedure RecalculateTransformados(const fromPos, toPos: integer); overload; virtual; procedure RecalculateTransformados; overload; procedure Recalculate(const fromPos, toPos: integer); overload; procedure Recalculate; overload; procedure Clear; property DataCount: integer read FDataCount; property PCambios: PArrayCurrency read FPCambios; property PFechas: PArrayDate read FPFechas; property PXTransformados: PArrayInteger read GetPXTransformados; property PYTransformados: PArrayInteger read GetPYTransformados; property Cambio[index: integer]: currency read GetCambio; property Fechas[index: integer]: TDate read GetFechas; property IsDataNull[index: integer]: boolean read GetIsDataNull; property IsSinCambio[index: integer]: boolean read GetIsSinCambio; property IsCambio[index: integer]: boolean read GetIsCambio; property XTransformados[index: integer]: integer read GetXTransformados; property YTransformados[index: integer]: integer read GetYTransformados; property DataNull: integer read FDataNull write FDataNull; property DataSinCambio: integer read FDataSinCambio write SetDataSinCambio; property Maximo: currency read FMax; property Minimo: currency read FMin; property MaximoManual: currency read FMaximoManual write FMaximoManual; property MinimoManual: currency read FMinimoManual write FMinimoManual; property Ancho: integer read FAncho write FAncho; property Alto: integer read FAlto write FAlto; property Left: Integer read FLeft write FLeft; property Top: integer read FTop write FTop; property PixelSize: byte read FPixelSize write FPixelSize default 1; end; implementation { TDatosGrafico } procedure TDatosGrafico.Clear; begin FPCambios := nil; FPFechas := nil; FDataCount := 0; SetLength(FXTransformados, 0); SetLength(FYTransformados, 0); SetLength(FIsSinCambios, 0); SetLength(FIsDataNulls, 0); SetLength(FIsCambios, 0); end; constructor TDatosGrafico.Create; begin inherited; FPixelSize := 1; FDataNull := 0; FDataCount := 0; FPCambios := nil; FDataSinCambio := SIN_CAMBIO; FMaximoManual := SIN_CAMBIO; FMinimoManual := SIN_CAMBIO; end; function TDatosGrafico.GetCambio(index: integer): currency; begin result := FPCambios^[index]; end; function TDatosGrafico.GetFechas(index: integer): TDate; begin result := FPFechas^[index]; end; function TDatosGrafico.GetIsCambio(index: integer): boolean; begin result := FIsCambios[index]; end; function TDatosGrafico.GetIsDataNull(index: integer): boolean; begin result := FIsDataNulls[index]; end; function TDatosGrafico.GetIsSinCambio(index: integer): boolean; begin result := FIsSinCambios[index]; end; function TDatosGrafico.GetPXTransformados: PArrayInteger; begin result := @FXTransformados; end; function TDatosGrafico.GetPYTransformados: PArrayInteger; begin Result := @FYTransformados; end; function TDatosGrafico.GetXTransformados(index: integer): integer; begin result := FXTransformados[index]; end; function TDatosGrafico.GetYTransformados(index: integer): integer; begin result := FYTransformados[index]; end; procedure TDatosGrafico.Recalculate(const fromPos, toPos: integer); begin RecalculateMaxMin(fromPos, toPos); RecalculateTransformados(fromPos, toPos); end; procedure TDatosGrafico.Recalculate; begin Recalculate(0, DataCount - 1); end; procedure TDatosGrafico.RecalculateMaxMin(const fromPos, toPos: integer); var i: integer; dato: currency; begin if MaximoManual <> FDataSinCambio then begin FMax := FMaximoManual; FMin := FMinimoManual; end else begin FMax := FDataSinCambio; FMin := FDataSinCambio; for i := fromPos to toPos do begin dato := FPCambios^[i]; if (dato = FDataNull) or (dato = FDataSinCambio) then begin // No creamos un and para que vaya más rápido end else begin if FMin = FDataSinCambio then FMin := dato else begin if dato < FMin then FMin := dato; end; if FMax < dato then FMax := dato; end; end; end; end; procedure TDatosGrafico.RecalculateTransformados; begin RecalculateTransformados(0, DataCount - 1); end; procedure TDatosGrafico.RecalculateTransformados(const fromPos, toPos: integer); var i, lon: integer; den, min, dato: currency; anchoDivLon, altoDivDen: Double; altoMasPaddingTop, auxTo: integer; begin min := Minimo; den := Maximo - min; lon := toPos - fromPos + 1; anchoDivLon := (Ancho div PixelSize) / lon; altoDivDen := Alto / den; // + 4 porque sino cuando estás posicionado en el máximo, el cursor se ve cortado, // ya que sale del gráfico, al igual que el indicador de la derecha del cambio altoMasPaddingTop := Alto + Top + 4; auxTo := toPos; if toPos < DataCount - 1 then inc(auxTo); if auxTo >= DataCount then auxTo := DataCount - 1; for i := fromPos to auxTo do begin FXTransformados[i] := Round((i - fromPos) * anchoDivLon) * PixelSize + left; dato := PCambios^[i]; if dato = FDataNull then FYTransformados[i] := FDataNull else begin if dato = FDataSinCambio then FYTransformados[i] := FDataSinCambio else begin if den = 0 then FYTransformados[i] := 0 else begin // Si Maximo - Minimo --> alto // valor - Minimo --> ? FYTransformados[i] := altoMasPaddingTop - Round((dato - min) * altoDivDen); end; end; end; end; end; procedure TDatosGrafico.SetData(const PCambios: PArrayCurrency; const PFechas: PArrayDate); var i: integer; begin FPCambios := PCambios; FPFechas := PFechas; FDataCount := length(FPCambios^); SetLength(FXTransformados, FDataCount); SetLength(FYTransformados, FDataCount); SetLength(FIsSinCambios, FDataCount); SetLength(FIsDataNulls, FDataCount); SetLength(FIsCambios, FDataCount); for i := FDataCount - 1 downto 0 do begin FIsSinCambios[i] := FPCambios^[i] = FDataSinCambio; FIsDataNulls[i] := FPCambios^[i] = FDataNull; FIsCambios[i] := (not FIsDataNulls[i]) and (not FIsSinCambios[i]); end; end; procedure TDatosGrafico.SetDataSinCambio(const Value: integer); begin FDataSinCambio := Value; if FMaximoManual = SIN_CAMBIO then FMaximoManual := FDataSinCambio; if FMinimoManual = SIN_CAMBIO then FMinimoManual := FDataSinCambio; end; end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2015 Vincent Parrett & Contributors } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DUnitX.Expert.ProjectWizardEx; interface {$I DUnitX.inc} uses ToolsApi, {$IFDEF USE_NS} VCL.Graphics, {$ELSE} Graphics, {$ENDIF} {$IFDEF DELPHI_XE103_UP} PlatformConst {$ELSE} PlatformAPI {$ENDIF} ; type TDUnitXNewProjectWizard = class public class procedure RegisterDUnitXProjectWizard(const APersonality: string); end; implementation uses DccStrs, {$IFDEF USE_NS} Vcl.Controls, Vcl.Forms, WinApi.Windows, System.SysUtils, {$ELSE} Controls, Forms, Windows, SysUtils, {$ENDIF} DUnitX.Expert.Forms.NewProjectWizard, DUnitX.Expert.CodeGen.NewTestProject, DUnitX.Expert.CodeGen.NewTestUnit, ExpertsRepository; resourcestring sNewTestProjectCaption = 'DUnitX Project'; sNewTestProjectHint = 'Create New DUnitX Test Project'; { TDUnitXNewProjectWizard } class procedure TDUnitXNewProjectWizard.RegisterDUnitXProjectWizard(const APersonality: string); begin RegisterPackageWizard(TExpertsRepositoryProjectWizardWithProc.Create(APersonality, sNewTestProjectHint, sNewTestProjectCaption, 'DunitX.Wizard.NewProjectWizard', // do not localize 'DUnitX', 'DUnitX Team - https://github.com/VSoftTechnologies/DUnitX', // do not localize procedure var WizardForm : TfrmDunitXNewProject; ModuleServices : IOTAModuleServices; Project : IOTAProject; Config : IOTABuildConfiguration; TestUnit : IOTAModule; begin WizardForm := TfrmDunitXNewProject.Create(Application); try if WizardForm.ShowModal = mrOk then begin if not WizardForm.AddToProjectGroup then begin (BorlandIDEServices as IOTAModuleServices).CloseAll; end; ModuleServices := (BorlandIDEServices as IOTAModuleServices); // Create Project Source ModuleServices.CreateModule(TTestProjectFile.Create(APersonality, WizardForm.ReportLeakOption)); Project := GetActiveProject; Config := (Project.ProjectOptions as IOTAProjectOptionsConfigurations).BaseConfiguration; Config.SetValue(sUnitSearchPath,'$(DUnitX)'); // Create Test Unit if WizardForm.CreateTestUnit then begin TestUnit := ModuleServices.CreateModule( TNewTestUnit.Create(WizardForm.CreateSetupTearDownMethods, WizardForm.CreateSampleMethods, WizardForm.TestFixtureClasaName, APersonality)); if Project <> nil then Project.AddFile(TestUnit.FileName,true); end; end; finally WizardForm.Free; end; end, function: Cardinal begin Result := LoadIcon(HInstance,'DUnitXNewProjectIcon'); end, {$IFDEF DELPHI_XE103_UP} GetAllPlatforms, {$ELSE} TArray<string>.Create(cWin32Platform, cWin64Platform, cOSX32Platform, cAndroidPlatform, ciOSSimulatorPlatform, ciOSDevice32Platform, ciOSDevice64Platform), {$ENDIF} nil)); end; end.
{$MODESWITCH RESULT+} {$GOTO ON} (************************************************************************* Copyright (c) 2007, Sergey Bochkanov (ALGLIB project). >>> SOURCE LICENSE >>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (www.fsf.org); either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************) unit studentttests; interface uses Math, Sysutils, Ap, gammafunc, normaldistr, ibetaf, studenttdistr; procedure StudentTTest1(const X : TReal1DArray; N : AlglibInteger; Mean : Double; var BothTails : Double; var LeftTail : Double; var RightTail : Double); procedure StudentTTest2(const X : TReal1DArray; N : AlglibInteger; const Y : TReal1DArray; M : AlglibInteger; var BothTails : Double; var LeftTail : Double; var RightTail : Double); procedure UnequalVarianceTTest(const X : TReal1DArray; N : AlglibInteger; const Y : TReal1DArray; M : AlglibInteger; var BothTails : Double; var LeftTail : Double; var RightTail : Double); implementation (************************************************************************* One-sample t-test This test checks three hypotheses about the mean of the given sample. The following tests are performed: * two-tailed test (null hypothesis - the mean is equal to the given value) * left-tailed test (null hypothesis - the mean is greater than or equal to the given value) * right-tailed test (null hypothesis - the mean is less than or equal to the given value). The test is based on the assumption that a given sample has a normal distribution and an unknown dispersion. If the distribution sharply differs from normal, the test will work incorrectly. Input parameters: X - sample. Array whose index goes from 0 to N-1. N - size of sample. Mean - assumed value of the mean. Output parameters: BothTails - p-value for two-tailed test. If BothTails is less than the given significance level the null hypothesis is rejected. LeftTail - p-value for left-tailed test. If LeftTail is less than the given significance level, the null hypothesis is rejected. RightTail - p-value for right-tailed test. If RightTail is less than the given significance level the null hypothesis is rejected. -- ALGLIB -- Copyright 08.09.2006 by Bochkanov Sergey *************************************************************************) procedure StudentTTest1(const X : TReal1DArray; N : AlglibInteger; Mean : Double; var BothTails : Double; var LeftTail : Double; var RightTail : Double); var I : AlglibInteger; XMean : Double; XVariance : Double; XStdDev : Double; V1 : Double; V2 : Double; Stat : Double; S : Double; begin if N<=1 then begin BothTails := Double(1.0); LeftTail := Double(1.0); RightTail := Double(1.0); Exit; end; // // Mean // XMean := 0; I:=0; while I<=N-1 do begin XMean := XMean+X[I]; Inc(I); end; XMean := XMean/N; // // Variance (using corrected two-pass algorithm) // XVariance := 0; XStdDev := 0; if N<>1 then begin V1 := 0; I:=0; while I<=N-1 do begin V1 := V1+AP_Sqr(X[I]-XMean); Inc(I); end; V2 := 0; I:=0; while I<=N-1 do begin V2 := V2+(X[I]-XMean); Inc(I); end; V2 := AP_Sqr(V2)/N; XVariance := (V1-V2)/(N-1); if AP_FP_Less(XVariance,0) then begin XVariance := 0; end; XStdDev := Sqrt(XVariance); end; if AP_FP_Eq(XStdDev,0) then begin BothTails := Double(1.0); LeftTail := Double(1.0); RightTail := Double(1.0); Exit; end; // // Statistic // Stat := (XMean-Mean)/(XStdDev/Sqrt(N)); S := StudentTDistribution(N-1, Stat); BothTails := 2*Min(S, 1-S); LeftTail := S; RightTail := 1-S; end; (************************************************************************* Two-sample pooled test This test checks three hypotheses about the mean of the given samples. The following tests are performed: * two-tailed test (null hypothesis - the means are equal) * left-tailed test (null hypothesis - the mean of the first sample is greater than or equal to the mean of the second sample) * right-tailed test (null hypothesis - the mean of the first sample is less than or equal to the mean of the second sample). Test is based on the following assumptions: * given samples have normal distributions * dispersions are equal * samples are independent. Input parameters: X - sample 1. Array whose index goes from 0 to N-1. N - size of sample. Y - sample 2. Array whose index goes from 0 to M-1. M - size of sample. Output parameters: BothTails - p-value for two-tailed test. If BothTails is less than the given significance level the null hypothesis is rejected. LeftTail - p-value for left-tailed test. If LeftTail is less than the given significance level, the null hypothesis is rejected. RightTail - p-value for right-tailed test. If RightTail is less than the given significance level the null hypothesis is rejected. -- ALGLIB -- Copyright 18.09.2006 by Bochkanov Sergey *************************************************************************) procedure StudentTTest2(const X : TReal1DArray; N : AlglibInteger; const Y : TReal1DArray; M : AlglibInteger; var BothTails : Double; var LeftTail : Double; var RightTail : Double); var I : AlglibInteger; XMean : Double; YMean : Double; Stat : Double; S : Double; P : Double; begin if (N<=1) or (M<=1) then begin BothTails := Double(1.0); LeftTail := Double(1.0); RightTail := Double(1.0); Exit; end; // // Mean // XMean := 0; I:=0; while I<=N-1 do begin XMean := XMean+X[I]; Inc(I); end; XMean := XMean/N; YMean := 0; I:=0; while I<=M-1 do begin YMean := YMean+Y[I]; Inc(I); end; YMean := YMean/M; // // S // S := 0; I:=0; while I<=N-1 do begin S := S+AP_Sqr(X[I]-XMean); Inc(I); end; I:=0; while I<=M-1 do begin S := S+AP_Sqr(Y[I]-YMean); Inc(I); end; S := Sqrt(S*(AP_Double(1)/N+AP_Double(1)/M)/(N+M-2)); if AP_FP_Eq(S,0) then begin BothTails := Double(1.0); LeftTail := Double(1.0); RightTail := Double(1.0); Exit; end; // // Statistic // Stat := (XMean-YMean)/S; P := StudentTDistribution(N+M-2, Stat); BothTails := 2*Min(P, 1-P); LeftTail := P; RightTail := 1-P; end; (************************************************************************* Two-sample unpooled test This test checks three hypotheses about the mean of the given samples. The following tests are performed: * two-tailed test (null hypothesis - the means are equal) * left-tailed test (null hypothesis - the mean of the first sample is greater than or equal to the mean of the second sample) * right-tailed test (null hypothesis - the mean of the first sample is less than or equal to the mean of the second sample). Test is based on the following assumptions: * given samples have normal distributions * samples are independent. Dispersion equality is not required Input parameters: X - sample 1. Array whose index goes from 0 to N-1. N - size of the sample. Y - sample 2. Array whose index goes from 0 to M-1. M - size of the sample. Output parameters: BothTails - p-value for two-tailed test. If BothTails is less than the given significance level the null hypothesis is rejected. LeftTail - p-value for left-tailed test. If LeftTail is less than the given significance level, the null hypothesis is rejected. RightTail - p-value for right-tailed test. If RightTail is less than the given significance level the null hypothesis is rejected. -- ALGLIB -- Copyright 18.09.2006 by Bochkanov Sergey *************************************************************************) procedure UnequalVarianceTTest(const X : TReal1DArray; N : AlglibInteger; const Y : TReal1DArray; M : AlglibInteger; var BothTails : Double; var LeftTail : Double; var RightTail : Double); var I : AlglibInteger; XMean : Double; YMean : Double; XVar : Double; YVar : Double; DF : Double; P : Double; Stat : Double; C : Double; begin if (N<=1) or (M<=1) then begin BothTails := Double(1.0); LeftTail := Double(1.0); RightTail := Double(1.0); Exit; end; // // Mean // XMean := 0; I:=0; while I<=N-1 do begin XMean := XMean+X[I]; Inc(I); end; XMean := XMean/N; YMean := 0; I:=0; while I<=M-1 do begin YMean := YMean+Y[I]; Inc(I); end; YMean := YMean/M; // // Variance (using corrected two-pass algorithm) // XVar := 0; I:=0; while I<=N-1 do begin XVar := XVar+AP_Sqr(X[I]-XMean); Inc(I); end; XVar := XVar/(N-1); YVar := 0; I:=0; while I<=M-1 do begin YVar := YVar+AP_Sqr(Y[I]-YMean); Inc(I); end; YVar := YVar/(M-1); if AP_FP_Eq(XVar,0) or AP_FP_Eq(YVar,0) then begin BothTails := Double(1.0); LeftTail := Double(1.0); RightTail := Double(1.0); Exit; end; // // Statistic // Stat := (XMean-YMean)/Sqrt(XVar/N+YVar/M); C := XVar/N/(XVar/N+YVar/M); DF := (N-1)*(M-1)/((M-1)*AP_Sqr(C)+(N-1)*(1-AP_Sqr(C))); if AP_FP_Greater(Stat,0) then begin P := 1-Double(0.5)*IncompleteBeta(DF/2, Double(0.5), DF/(DF+AP_Sqr(Stat))); end else begin P := Double(0.5)*IncompleteBeta(DF/2, Double(0.5), DF/(DF+AP_Sqr(Stat))); end; BothTails := 2*Min(P, 1-P); LeftTail := P; RightTail := 1-P; end; end.
unit UUADEffectiveAge; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2019 by Bradford Technologies, Inc. } interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, DateUtils, Dialogs, UCell, UUADUtils, UContainer, UEditor, UGlobals, UStatus, UForms; type TdlgUADEffectiveAge = class(TAdvancedForm) bbtnCancel: TBitBtn; bbtnOK: TBitBtn; lblYrBuilt: TLabel; bbtnClear: TBitBtn; Label1: TLabel; edtEffAge: TEdit; edtEconLife: TEdit; procedure FormShow(Sender: TObject); procedure bbtnOKClick(Sender: TObject); procedure edtEffAgeKeyPress(Sender: TObject; var Key: Char); procedure edtEconLifeKeyPress(Sender: TObject; var Key: Char); procedure bbtnClearClick(Sender: TObject); private { Private declarations } FClearData : Boolean; DlgType: Integer; function GetAgeText: String; function GetDescriptionText: String; function GetYearBuiltText: String; public { Public declarations } FCell: TBaseCell; FDoc: TContainer; procedure Clear; procedure LoadForm; procedure SaveToCell; end; implementation {$R *.dfm} uses UAppraisalIDs, UStrings, uUtil1; const EstFlag = '~'; procedure TdlgUADEffectiveAge.FormShow(Sender: TObject); begin LoadForm; end; procedure TdlgUADEffectiveAge.bbtnOKClick(Sender: TObject); begin bbtnOK.SetFocus; SaveToCell; ModalResult := mrOK; end; procedure TdlgUADEffectiveAge.edtEffAgeKeyPress(Sender: TObject; var Key: Char); begin // Key := PositiveNumKey(Key); end; procedure TdlgUADEffectiveAge.edtEconLifeKeyPress(Sender: TObject; var Key: Char); begin // Key := PositiveNumKey(Key); end; function TdlgUADEffectiveAge.GetAgeText: String; begin end; function TdlgUADEffectiveAge.GetDescriptionText: String; begin if (DlgType = 0) then // eff age Result := edtEffAge.Text else if (DlgType = 1) then // age Result := GetAgeText else Result := ''; end; /// summary: Gets text for expressing the year built of the property. function TdlgUADEffectiveAge.GetYearBuiltText: String; begin end; procedure TdlgUADEffectiveAge.Clear; begin edtEffAge.Text := ''; edtEconLife.Text := ''; end; procedure TdlgUADEffectiveAge.LoadForm; begin Clear; FClearData := False; FCell := FDoc.GetCellByID(499); if FCell <> nil then edtEffAge.Text := FCell.GetText; FCell := FDoc.GetCellByID(875); if FCell <> nil then edtEconLife.Text := FCell.GetText; end; procedure TdlgUADEffectiveAge.SaveToCell; begin // Remove any legacy data - no longer used FCell.GSEData := ''; // Save the cleared or formatted text if FClearData then // clear ALL GSE data and blank the cell begin FCell := FDoc.GetCellByID(499); if FCell <> nil then FCell.SetText(''); FCell := FDoc.GetCellByID(875); if FCell <> nil then FCell.SetText(''); end else begin FCell := FDoc.GetCellByID(499); if FCell <> nil then FCell.SetText(edtEffAge.Text); FCell := FDoc.GetCellByID(875); if FCell <> nil then FCell.SetText(edtEconLife.Text); end; end; procedure TdlgUADEffectiveAge.bbtnClearClick(Sender: TObject); begin if WarnOK2Continue(msgUAGClearDialog) then begin Clear; FClearData := True; SaveToCell; ModalResult := mrOK; end; end; end.
unit un_utl; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Dialogs, StdCtrls, WinTypes, WinProcs, FORMS, Menus, inifiles; // CPU ID 专用变量================================== const ID_BIT = $200000; // EFLAGS ID bit type TCPUID = array[1..4] of Longint; TVendor = array [0..11] of char; //=================================================== // UN_UTL 专用变量================================== //=================================================== // 日期--------------------------------------------- //英日期转中日期 FUNCTION EDATETOCDATE(EDATE:STRING):STRING; //检查英文日期格式是否正确 FUNCTION EDATECHECK(EDATE:STRING):BOOLEAN; //英日期转中日期 FUNCTION EDATE_TO_CDATE(EDATE:STRING):STRING; //中日期转英日期 FUNCTION CDATE_TO_EDATE(CDATE:STRING):STRING; //中日期 -> 取年份 FUNCTION CDATE_GET_YEAR(T_DATE:STRING):STRING; //中日期 -> 取月份 FUNCTION CDATE_GET_MONTH(T_DATE:STRING):STRING; //中日期 -> 取日期 FUNCTION CDATE_GET_DAY(T_DATE:STRING):STRING; //英日期 -> 取年份 FUNCTION DATE_GET_YEAR(T_DATE:STRING):STRING; //英日期 -> 取月份 FUNCTION DATE_GET_MONTH(T_DATE:STRING):STRING; //英日期 -> 取日期 FUNCTION DATE_GET_DAY(T_DATE:STRING):STRING; //时间 -> 取时间 24H FUNCTION TIME_GET_24H(T_TIME:TTIME):STRING; //时间 -> 检查是否在时间范围内 FUNCTION TIME_CHECK_RANGE(TIME1,TIME2 :STRING; T_RANGE :INTEGER):BOOLEAN; //检查英文日期格式是否正确 FUNCTION CHECK_EDATE(EDATE:STRING;WARNING:BOOLEAN):BOOLEAN; //检查中文日期格式是否正确 FUNCTION CHECK_CDATE(CDATE:STRING;WARNING:BOOLEAN):BOOLEAN; //检查 月份 日期数 格式是否正确 FUNCTION CHECK_DAY(MONTH,DAY:INTEGER;WARNING:BOOLEAN):BOOLEAN; //检查 时间 格式是否正确 FUNCTION CHECK_TIME(TIME:STRING;WARNING:BOOLEAN):BOOLEAN; //检查 时间 格式是否正确(可超过 24H ) FUNCTION CHECK_LONGTIME(TIME:STRING;WARNING:BOOLEAN):BOOLEAN; // 计算 当月 日数 FUNCTION CYEARMONTH_DAYS(CYEARMONTH:STRING):INTEGER; // 计算 当月 日数 FUNCTION EYEARMONTH_DAYS(EYEARMONTH:STRING):INTEGER; // 英文 日期 - 日期 减法 FUNCTION EDATE_SUB_EDATE(DAT1, DAT2 : TDATETIME):INTEGER; // 英文 年份 减法 FUNCTION EYEAR_SUB(CYEAR:STRING;T_SUB:INTEGER):STRING; // 中文 月份 减法 FUNCTION CYEARMONTH_SUB(CYEARMONTH:STRING;T_SUB:INTEGER):STRING; // 密码--------------------------------------------- FUNCTION Encrypt(const InSTRING:STRING; StartKey,MultKey,AddKey:INTEGER): STRING; FUNCTION Decrypt(const InSTRING:STRING; StartKey,MultKey,AddKey:INTEGER): STRING; //edit2.text := Encrypt(edit1.text,123456,13579,24680); //edit3.text := Decrypt(edit2.text,123456,13579,24680); // 文件相关功能 ================================================================ FUNCTION TEST_OPEN_FILE(FILENAME:STRING):BOOLEAN; // 测试文件是否可以打开 FUNCTION FILE_CREATE(FILENAME:STRING):BOOLEAN; // 建立新文件 FUNCTION FILE_REWRITE(FILENAME:STRING):BOOLEAN; // 清除文件 FUNCTION TEXTFILE_RECCNT(FILENAME:STRING):INTEGER; // TEXT读出文件 行数 FUNCTION FILE_APPEND_LOG(FILENAME,TITLE,TXT:STRING):BOOLEAN; // 写入文件 FUNCTION FILE_WRITELN_REC(FILENAME,TITLE,TXT:STRING):STRING; // 写入文件单行 FUNCTION FILE_READLN_REC(FILENAME,TITLE:STRING):STRING; // 读出文件单行 // 文件相关功能 ================================================================ //字符串处理 ======================================================================= //copy 由右至左 FUNCTION Copy_R(S: STRING; Index, Count: INTEGER): STRING; //产生空白 FUNCTION SPACE(Count: INTEGER): STRING; { 字符串复制 } FUNCTION REPLICATE(VSTR1:STRING;VLEN:SMALLINT):STRING; { 字符串填满 } FUNCTION FILL_STR(FILL_STR, STR, KIND:STRING; TOTAL_LENGTH:INTEGER):STRING; { 字符串累加 } FUNCTION STR_INC(FILL_STR, STR:STRING; T_START, T_END, T_CNT:INTEGER):STRING; { 字符串转浮点 } FUNCTION STRTOFLOATDEF(STR:STRING;FDEFAULT:REAL):REAL; { 字符串替换 } FUNCTION STR_REPLACE(STR, SUBSTR1,SUBSTR2:STRING):STRING; { 字符串插入 } FUNCTION STR_INSERT(STR, S1, S2:STRING; FB:BOOLEAN):STRING; { 数据字符串找寻 } FUNCTION STR_DB_FIELDBYNO(STR, RAIL:STRING;FIELD_NO:INTEGER):STRING; { 删除数据字符串 } FUNCTION TRIM_STR(STR, TRIMSTR:STRING):STRING; { 整数 转 字符串 再补零 } FUNCTION INTTOSTR_REP(TINT,REP:INTEGER):STRING; { BOOLEAN TRUE FALSE 转 01 } FUNCTION BOOLEANTOSTR(TB : BOOLEAN):STRING; { 检查是否为整数 } FUNCTION CHECK_INT(T_STR:STRING):BOOLEAN; { 检查是否为浮点数 } FUNCTION CHECK_FLOAT(T_STR:STRING):BOOLEAN; { 检查是否为浮点数 和 整数} FUNCTION CHECK_FLOATINT(T_STR:STRING):BOOLEAN; { 取 浮点数 , 小数点位数 } FUNCTION FLOAT_LENGTH(T_STR:STRING;T_LENGTH:INTEGER):STRING; { 浮点数 转 整数 } FUNCTION FLOATTOINT(T_FLOAT:REAL):INTEGER; { 浮点数 转 整数 PS: 无条件小数第一位进位} FUNCTION FLOATTOINT_ROUND(T_FLOAT:REAL):INTEGER; { 整数 个位数 四舍五入 } FUNCTION ROUND_1(T_INT:INTEGER):INTEGER; { 整数 次方 } FUNCTION INT_CUBE(T_INT,T_CUBE:INTEGER):INTEGER; { 16 进位 转 整数 } FUNCTION HEXTOINT(THEX:STRING):INTEGER; //其它{ Delay program execution by n milliseconds } procedure Delay(n: INTEGER); //汇率计算 FUNCTION EXCHANGE_CAL(T_EXCHG:STRING;T_LENGTH:INTEGER):STRING; //打印机 输出入 ================================================================ procedure Out32(PortAddress:smallint;Value:smallint);stdcall;export; FUNCTION Inp32(PortAddress:smallint):smallint;stdcall;export; FUNCTION COMPORT_OUT (PortNAME,EXPRESS:STRING):BOOLEAN; FUNCTION COMPORT_OUTLN(PortNAME,EXPRESS:STRING):BOOLEAN; //打印机 输出入 ================================================================ //CPU ID 及信息 FUNCTION IsCPUID_Available : BOOLEAN; register; FUNCTION GetCPUID : TCPUID; assembler; register; FUNCTION GetCPUVendor : TVendor; assembler; register; //条形码类 FUNCTION EAN13_ENCODE(T_STR:STRING):STRING; FUNCTION EAN13_AUTOADD(T_STR:STRING):STRING; //发票类 ======================================================================= FUNCTION INVOICE_NO_CHECK(T_STR:STRING):BOOLEAN; //检查发票号码 //发票类 ======================================================================= //检查信用卡号 FUNCTION ValidateCreditCardNo(value: STRING; WARNING:BOOLEAN): BOOLEAN; //对象 储存相关信息值 INI FILE ================================================ FUNCTION INI_SAVE_OBJECT(INIFILENAME, OBJECT_NAME :STRING; T_LEFT, T_TOP :INTEGER; T_TEXT:STRING):BOOLEAN; FUNCTION INI_SAVE_INT (INIFILENAME, OBJECT_NAME :STRING; T_INTEGER :INTEGER):BOOLEAN; FUNCTION INI_SAVE_STR (INIFILENAME, OBJECT_NAME :STRING; T_STR :STRING):BOOLEAN; FUNCTION INI_SAVE_STR2 (INIFILENAME, OBJECT_NAME, OBJECT_KIND :STRING; T_STR :STRING):BOOLEAN; FUNCTION INI_SAVE_BOOL (INIFILENAME, OBJECT_NAME :STRING; T_BOOL :BOOLEAN):BOOLEAN; //对象 取回相关信息值 INI FILE ================================================ FUNCTION INI_LOAD_OBJECT(INIFILENAME, OBJECT_NAME, OBJECT_KIND, T_DEFAULT :STRING):STRING; FUNCTION INI_LOAD_INT (INIFILENAME, OBJECT_NAME :STRING; T_DEFAULT:INTEGER ):INTEGER; FUNCTION INI_LOAD_STR (INIFILENAME, OBJECT_NAME :STRING; T_DEFAULT:STRING ):STRING; FUNCTION INI_LOAD_STR2 (INIFILENAME, OBJECT_NAME , OBJECT_KIND:STRING; T_DEFAULT:STRING ):STRING; FUNCTION INI_LOAD_BOOL (INIFILENAME, OBJECT_NAME :STRING; T_DEFAULT:BOOLEAN ):BOOLEAN; // ============================================================================= { Input dialog } FUNCTION JInputBox(const ACaption, APrompt, ADefault: STRING): STRING; FUNCTION JInputQuery(const ACaption, APrompt: STRING; VAR Value: STRING): BOOLEAN; FUNCTION JMSGFORM(const ACaption, ADefault: STRING;T_FONTSIZE:INTEGER): BOOLEAN; FUNCTION JSHOWMESSAGE(const ACaption, APROMPT: STRING): BOOLEAN; //FUNCTION JInputIntQuery(const ACaption, APrompt: STRING; Value: INTEGER):INTEGER; implementation // 日期--------------------------------------------- //英日期转中日期 FUNCTION EDATETOCDATE(EDATE:STRING):STRING; VAR T_DATE :STRING; T_YEAR, T_MONTH, T_DAY :STRING; BEGIN IF EDATECHECK(EDATE) = FALSE THEN EXIT; T_DATE := EDATE; T_YEAR := COPY(T_DATE,1,POS('/',T_DATE)-1 ); T_DATE := TRIM( COPY(T_DATE,POS('/',T_DATE)+1 ,10) ); T_MONTH := COPY(T_DATE,1,POS('/',T_DATE)-1 ); T_DATE := TRIM( COPY(T_DATE,POS('/',T_DATE)+1 ,10) ); T_DAY := T_DATE; T_YEAR := INTTOSTR( STRTOINT(T_YEAR)-1911 ); T_MONTH := REPLICATE('0',2 - LENGTH(T_MONTH)) + T_MONTH; //加'0' T_DAY := REPLICATE('0',2 - LENGTH(T_DAY )) + T_DAY ; //加'0' Result := T_YEAR+T_MONTH+T_DAY; END; //检查英文日期格式是否正确 FUNCTION EDATECHECK(EDATE:STRING):BOOLEAN; VAR T_DATE :STRING; T_YEAR, T_MONTH, T_DAY :STRING; BEGIN T_DATE := EDATE; T_YEAR := COPY(T_DATE,1,POS('/',T_DATE)-1 ); T_DATE := TRIM( COPY(T_DATE,POS('/',T_DATE)+1 ,10) ); T_MONTH := COPY(T_DATE,1,POS('/',T_DATE)-1 ); T_DATE := TRIM( COPY(T_DATE,POS('/',T_DATE)+1 ,10) ); T_DAY := T_DATE; IF (T_YEAR = '') OR (T_MONTH = '') OR (T_DAY = '') OR ( STRTOINTDEF(T_YEAR ,-1)<= 0 ) OR ( STRTOINTDEF(T_MONTH ,-1)<= 0 ) OR ( STRTOINTDEF(T_DAY ,-1)<= 0 ) OR ( STRTOINTDEF(T_YEAR ,-1)> 2100) OR ( STRTOINTDEF(T_MONTH ,-1)> 12 ) OR ( STRTOINTDEF(T_DAY ,-1)> 31 ) THEN BEGIN SHOWMESSAGE('日期格式不正确'); Result := FALSE; END ELSE BEGIN Result := TRUE; END; END; FUNCTION EDATE_TO_CDATE(EDATE:STRING):STRING; VAR T_YEAR,T_MONTH,T_DAY, T_STR :STRING; BASE_YEAR :INTEGER; BEGIN IF CHECK_EDATE(EDATE,FALSE) = FALSE THEN EXIT; T_YEAR := COPY(EDATE,1,4); T_STR := TRIM(COPY(EDATE,POS('/',EDATE)+1,10)); T_MONTH := COPY(T_STR,1,POS('/',T_STR)-1); T_STR := TRIM(COPY(T_STR,POS('/',T_STR)+1,10)); T_DAY := COPY(T_STR,POS('/',T_STR)+1,2); IF LENGTH(T_MONTH) < 2 THEN T_MONTH := '0' + T_MONTH; IF LENGTH(T_DAY) < 2 THEN T_DAY := '0' + T_DAY; BASE_YEAR := 1911; //RESULT := INTTOSTR(STRTOINT(T_YEAR)-BASE_YEAR) + T_MONTH + T_DAY ; RESULT := T_YEAR + '-' + T_MONTH + '-' + T_DAY ; END; FUNCTION CDATE_TO_EDATE(CDATE:STRING):STRING; VAR T_YEAR,T_MONTH,T_DAY :STRING; BASE_YEAR :INTEGER; BEGIN IF CHECK_CDATE(CDATE,TRUE) = FALSE THEN EXIT; //ds IF LENGTH(CDATE) = 10 THEN BEGIN T_YEAR := COPY(CDATE,1,4); T_MONTH := COPY(CDATE,6,2); T_DAY := COPY(CDATE,9,2); END; //ds {ds IF LENGTH(CDATE) = 7 THEN BEGIN T_YEAR := COPY(CDATE,1,3); T_MONTH := COPY(CDATE,4,2); T_DAY := COPY(CDATE,6,2); END; IF LENGTH(CDATE) = 6 THEN BEGIN T_YEAR := COPY(CDATE,1,2); T_MONTH := COPY(CDATE,3,2); T_DAY := COPY(CDATE,5,2); END;} BASE_YEAR := 1911; //RESULT := INTTOSTR(STRTOINT(T_YEAR)+BASE_YEAR)+'/'+T_MONTH+'/'+T_DAY ; RESULT := T_YEAR+'/'+T_MONTH+'/'+T_DAY ; END; //中日期 -> 取年份 FUNCTION CDATE_GET_YEAR(T_DATE:STRING):STRING; BEGIN RESULT := ''; IF LENGTH(T_DATE) = 10 THEN RESULT := TRIM(COPY(T_DATE,1,4)); //IF LENGTH(T_DATE) = 6 THEN RESULT := TRIM(COPY(T_DATE,1,2)); //IF LENGTH(T_DATE) = 7 THEN RESULT := TRIM(COPY(T_DATE,1,3)); END; //中日期 -> 取月份 FUNCTION CDATE_GET_MONTH(T_DATE:STRING):STRING; BEGIN RESULT := ''; IF LENGTH(T_DATE) = 10 THEN RESULT := TRIM(COPY(T_DATE,6,2)); //IF LENGTH(T_DATE) = 6 THEN RESULT := TRIM(COPY(T_DATE,3,2)); //IF LENGTH(T_DATE) = 7 THEN RESULT := TRIM(COPY(T_DATE,4,2)); END; //中日期 -> 取日期 FUNCTION CDATE_GET_DAY(T_DATE:STRING):STRING; BEGIN RESULT := ''; IF LENGTH(T_DATE) = 10 THEN RESULT := TRIM(COPY(T_DATE,9,3)); //IF LENGTH(T_DATE) = 6 THEN RESULT := TRIM(COPY(T_DATE,5,2)); //IF LENGTH(T_DATE) = 7 THEN RESULT := TRIM(COPY(T_DATE,6,3)); END; //英日期 -> 取年份 FUNCTION DATE_GET_YEAR(T_DATE:STRING):STRING; BEGIN RESULT := TRIM(COPY(T_DATE,1,POS('/',T_DATE)-1)); END; //英日期 -> 取月份 FUNCTION DATE_GET_MONTH(T_DATE:STRING):STRING; VAR T1:STRING; BEGIN T1 := TRIM(COPY(T_DATE,POS('/',T_DATE)+1,LENGTH(T_DATE))); RESULT := TRIM(COPY(T1,1,POS('/',T1)-1)); END; //英日期 -> 取日期 FUNCTION DATE_GET_DAY(T_DATE:STRING):STRING; VAR T1:STRING; BEGIN T1 := T_DATE; T1 := TRIM(COPY(T1,POS('/',T1)+1,LENGTH(T1))); T1 := TRIM(COPY(T1,POS('/',T1)+1,LENGTH(T1))); RESULT := REPLICATE('0',2-LENGTH(T1)) + TRIM(COPY(T1,1,LENGTH(T1))); END; //时间 -> 取时间 24H FUNCTION TIME_GET_24H(T_TIME:TTIME):STRING; VAR RET_TIME, T_APM, T_HOUR, T_MIN :STRING; X_HOUR : INTEGER; BEGIN RET_TIME := COPY(TIMETOSTR(T_TIME),4,5); T_APM := COPY(TIMETOSTR(T_TIME),1,2); T_HOUR := COPY(TIMETOSTR(T_TIME),4,2); T_MIN := COPY(TIMETOSTR(T_TIME),7,2); X_HOUR := STRTOINTDEF(T_HOUR,0); IF T_APM = 'PM' THEN BEGIN IF X_HOUR <12 THEN T_HOUR := INTTOSTR(STRTOINTDEF(T_HOUR,0)+12); RET_TIME := REPLICATE('0',2-LENGTH(T_HOUR)) + T_HOUR+':'+ T_MIN; //加'0' END; IF T_APM = 'AM' THEN BEGIN IF X_HOUR =12 THEN T_HOUR := INTTOSTR(STRTOINTDEF(T_HOUR,0)+12); RET_TIME := REPLICATE('0',2-LENGTH(T_HOUR)) + T_HOUR+':'+ T_MIN; //加'0' END; RESULT := RET_TIME; END; //时间 -> 检查是否在时间范围内 FUNCTION TIME_CHECK_RANGE(TIME1,TIME2 :STRING; T_RANGE :INTEGER):BOOLEAN; VAR T11, T12, T21, T22, T1, T2: INTEGER; BEGIN RESULT := FALSE; IF (CHECK_TIME(TIME1,FALSE) = FALSE) OR (CHECK_TIME(TIME2,FALSE) = FALSE) THEN EXIT; T11 := STRTOINTDEF( COPY(TIME1,1,2) ,0); T12 := STRTOINTDEF( COPY(TIME1,4,2) ,0); T21 := STRTOINTDEF( COPY(TIME2,1,2) ,0); T22 := STRTOINTDEF( COPY(TIME2,4,2) ,0); T1 := T11 * 60 + T12; T2 := T21 * 60 + T22; //SHOWMESSAGE(INTTOSTR(T1)+'='+INTTOSTR(T2)); IF T1 > T2 THEN IF (T1 - T2) <= T_RANGE THEN RESULT := TRUE; IF T2 > T1 THEN IF (T2 - T1) <= T_RANGE THEN RESULT := TRUE; IF T1 = T2 THEN RESULT := TRUE; { IF T12 = T22 THEN RESULT := TRUE; IF T12 > T22 THEN IF (T12 - T22) <= T_RANGE THEN RESULT := TRUE; IF T22 > T12 THEN IF (T22 - T12) <= T_RANGE THEN RESULT := TRUE; } END; FUNCTION CHECK_EDATE(EDATE:STRING;WARNING:BOOLEAN):BOOLEAN; VAR T_YEAR,T_MONTH,T_DAY, T_STR :STRING; BEGIN T_YEAR := COPY(EDATE,1,4); T_STR := TRIM(COPY(EDATE,POS('/',EDATE)+1,10)); T_MONTH := COPY(T_STR,1,POS('/',T_STR)-1); T_STR := TRIM(COPY(T_STR,POS('/',T_STR)+1,10)); T_DAY := COPY(T_STR,POS('/',T_STR)+1,2); IF (STRTOINTDEF(T_YEAR ,-1) < 0 ) OR (STRTOINTDEF(T_MONTH,-1) < 0 ) OR (STRTOINTDEF(T_DAY ,-1) < 0 ) OR (STRTOINTDEF(T_YEAR ,-1) > 9999 ) OR (STRTOINTDEF(T_MONTH,-1) > 12 ) OR (STRTOINTDEF(T_DAY ,-1) > 31 ) THEN BEGIN IF WARNING = TRUE THEN showmessage('日期格式不正确!'); RESULT := FALSE; END ELSE RESULT := TRUE; END; FUNCTION CHECK_CDATE(CDATE:STRING;WARNING:BOOLEAN):BOOLEAN; VAR T_YEAR,T_MONTH,T_DAY,T_STR :STRING; BEGIN T_YEAR := COPY(CDATE,1,4); T_STR := TRIM(COPY(CDATE,POS('-',CDATE)+1,10)); T_MONTH := COPY(T_STR,1,POS('-',T_STR)-1); T_STR := TRIM(COPY(T_STR,POS('-',T_STR)+1,10)); T_DAY := COPY(T_STR,POS('-',T_STR)+1,2); IF (STRTOINTDEF(T_YEAR ,-1) < 0 ) OR (STRTOINTDEF(T_MONTH,-1) < 0 ) OR (STRTOINTDEF(T_DAY ,-1) < 0 ) OR (STRTOINTDEF(T_YEAR ,-1) > 9999 ) OR (STRTOINTDEF(T_MONTH,-1) > 12 ) OR (STRTOINTDEF(T_DAY ,-1) > 31 ) or (Length(CDATE) < 10) or //check length (CHECK_DAY(STRTOINT(T_MONTH),STRTOINT(T_DAY) ,TRUE)=FALSE)//check day THEN//ds BEGIN IF WARNING = TRUE THEN showmessage('日期格式不正确!'); RESULT := FALSE; END ELSE RESULT := TRUE; {IF (STRTOINTDEF(CDATE,-1) < 0 ) then BEGIN IF WARNING = TRUE THEN showmessage('日期格式不正确!'); RESULT := FALSE; EXIT; END; IF (LENGTH(CDATE) > 7 ) then BEGIN IF WARNING = TRUE THEN showmessage('日期长度不能超过7个!'); RESULT := FALSE; EXIT; END; IF (LENGTH(CDATE) < 6 ) then BEGIN IF WARNING = TRUE THEN showmessage('日期长度不能小于6个!'); RESULT := FALSE; EXIT; END; //========================================================== IF (LENGTH(CDATE) = 7 ) AND (CHECK_DAY( STRTOINT(COPY(CDATE,4,2)),STRTOINT(COPY(CDATE,6,2)) ,TRUE)=FALSE )then BEGIN RESULT := FALSE; EXIT; END; //========================================================== IF (LENGTH(CDATE) = 6 ) AND (CHECK_DAY( STRTOINT(COPY(CDATE,3,2)),STRTOINT(COPY(CDATE,5,2)) ,TRUE)=FALSE )then BEGIN RESULT := FALSE; EXIT; END; //========================================================== RESULT := TRUE;} END; FUNCTION CHECK_DAY(MONTH,DAY:INTEGER;WARNING:BOOLEAN):BOOLEAN; BEGIN IF (MONTH > 12 ) OR (MONTH < 1 ) THEN BEGIN IF WARNING = TRUE THEN showmessage('月份格式不正确!'); RESULT := FALSE; EXIT; END; CASE MONTH OF 1,3,5,7,8,10,12 :BEGIN IF (DAY > 31 ) OR (DAY < 1 ) THEN BEGIN IF WARNING = TRUE THEN showmessage('日期格式不正确!'); RESULT := FALSE; EXIT; END; END; 4,6,9,11 :BEGIN IF (DAY > 30 ) OR (DAY < 1 ) THEN BEGIN IF WARNING = TRUE THEN showmessage('日期格式不正确!'); RESULT := FALSE; EXIT; END; END; 2 :BEGIN IF (DAY > 29 ) OR (DAY < 1 ) THEN BEGIN IF WARNING = TRUE THEN showmessage('2月份日期格式不正确!'); RESULT := FALSE; EXIT; END; END; END; RESULT := TRUE; END; FUNCTION CHECK_TIME(TIME:STRING;WARNING:BOOLEAN):BOOLEAN; BEGIN IF (STRTOINTDEF(COPY(TIME,1,2),-1) < 0 ) OR (STRTOINTDEF(COPY(TIME,1,2),-1) >= 24 ) OR (STRTOINTDEF(COPY(TIME,4,2),-1) < 0 ) OR (STRTOINTDEF(COPY(TIME,4,2),-1) >= 60 ) OR (COPY(TIME,3,1) <> ':' ) THEN BEGIN IF WARNING = TRUE THEN showmessage('时间格式不正确!'); RESULT := FALSE; EXIT; END; IF (LENGTH(TIME) > 5 ) then BEGIN IF WARNING = TRUE THEN showmessage('时间长度不能超过5个!'); RESULT := FALSE; EXIT; END; IF (LENGTH(TIME) < 5 ) then BEGIN IF WARNING = TRUE THEN showmessage('时间长度不能小于5个!'); RESULT := FALSE; EXIT; END; RESULT := TRUE; END; FUNCTION CHECK_LONGTIME(TIME:STRING;WARNING:BOOLEAN):BOOLEAN; BEGIN IF (STRTOINTDEF(COPY(TIME,1,2),-1) < 0 ) OR (STRTOINTDEF(COPY(TIME,1,2),-1) >= 29 ) OR (STRTOINTDEF(COPY(TIME,4,2),-1) < 0 ) OR (STRTOINTDEF(COPY(TIME,4,2),-1) >= 60 ) OR (COPY(TIME,3,1) <> ':' ) THEN BEGIN IF WARNING = TRUE THEN showmessage('时间格式不正确!'); RESULT := FALSE; EXIT; END; IF (LENGTH(TIME) > 5 ) then BEGIN IF WARNING = TRUE THEN showmessage('时间长度不能超过5个!'); RESULT := FALSE; EXIT; END; IF (LENGTH(TIME) < 5 ) then BEGIN IF WARNING = TRUE THEN showmessage('时间长度不能小于5个!'); RESULT := FALSE; EXIT; END; RESULT := TRUE; END; // 计算 当月 日数 FUNCTION CYEARMONTH_DAYS(CYEARMONTH:STRING):INTEGER; VAR T_D1, THIS_MONTH:STRING; T_MONTHDAYS:INTEGER; BEGIN T_MONTHDAYS := 30; T_D1 := CDATE_TO_EDATE(CYEARMONTH+'01'); THIS_MONTH := DATE_GET_MONTH(T_D1); IF DATE_GET_MONTH(DATETOSTR(STRTODATE(T_D1)+27)) = TRIM_STR(THIS_MONTH,'0') THEN T_MONTHDAYS := 28; IF DATE_GET_MONTH(DATETOSTR(STRTODATE(T_D1)+28)) = TRIM_STR(THIS_MONTH,'0') THEN T_MONTHDAYS := 29; IF DATE_GET_MONTH(DATETOSTR(STRTODATE(T_D1)+29)) = TRIM_STR(THIS_MONTH,'0') THEN T_MONTHDAYS := 30; IF DATE_GET_MONTH(DATETOSTR(STRTODATE(T_D1)+30)) = TRIM_STR(THIS_MONTH,'0') THEN T_MONTHDAYS := 31; RESULT := T_MONTHDAYS; END; // 计算 当月 日数 FUNCTION EYEARMONTH_DAYS(EYEARMONTH:STRING):INTEGER; VAR T_D1, THIS_MONTH:STRING; T_MONTHDAYS:INTEGER; BEGIN T_MONTHDAYS := 30; T_D1 := DATE_GET_YEAR(EYEARMONTH)+'/'+DATE_GET_MONTH(EYEARMONTH)+'/'+'01'; THIS_MONTH := DATE_GET_MONTH(T_D1); IF DATE_GET_MONTH(DATETOSTR(STRTODATE(T_D1)+27)) = TRIM_STR(THIS_MONTH,'0') THEN T_MONTHDAYS := 28; IF DATE_GET_MONTH(DATETOSTR(STRTODATE(T_D1)+28)) = TRIM_STR(THIS_MONTH,'0') THEN T_MONTHDAYS := 29; IF DATE_GET_MONTH(DATETOSTR(STRTODATE(T_D1)+29)) = TRIM_STR(THIS_MONTH,'0') THEN T_MONTHDAYS := 30; IF DATE_GET_MONTH(DATETOSTR(STRTODATE(T_D1)+30)) = TRIM_STR(THIS_MONTH,'0') THEN T_MONTHDAYS := 31; RESULT := T_MONTHDAYS; END; // 英文 日期 - 日期 减法 FUNCTION EDATE_SUB_EDATE(DAT1, DAT2 : TDATETIME):INTEGER; VAR DAT3 : TDATETIME; Y1, M1, D1: Word; R : INTEGER; BEGIN R := 0; IF DAT2 = DAT1 THEN BEGIN R := 0; END; IF DAT2 > DAT1 THEN BEGIN DAT3 := DAT2 - DAT1 + 1; DecodeDate(DAT3 , Y1, M1, D1); //加上年 R := R + ( (Y1-1900)*365 ); //加上月 IF M1 = 1 THEN R := R + 0 ; IF M1 = 2 THEN R := R + 31 ; IF M1 = 3 THEN R := R + 31 +28 ; IF M1 = 4 THEN R := R + 31 +28 +31 ; IF M1 = 5 THEN R := R + 31 +28 +31 +30 ; IF M1 = 6 THEN R := R + 31 +28 +31 +30 +31 ; IF M1 = 7 THEN R := R + 31 +28 +31 +30 +31 +30 ; IF M1 = 8 THEN R := R + 31 +28 +31 +30 +31 +30 +31 ; IF M1 = 9 THEN R := R + 31 +28 +31 +30 +31 +30 +31 +31 ; IF M1 =10 THEN R := R + 31 +28 +31 +30 +31 +30 +31 +31 +30 ; IF M1 =11 THEN R := R + 31 +28 +31 +30 +31 +30 +31 +31 +30 +31 ; IF M1 =12 THEN R := R + 31 +28 +31 +30 +31 +30 +31 +31 +30 +31 +30 ; //加上日 R := R + D1; END; IF DAT2 < DAT1 THEN BEGIN DAT3 := DAT1 - DAT2 + 1; DecodeDate(DAT3 , Y1, M1, D1); //加上年 R := R + ( (Y1-1900)*365 ); //加上月 IF M1 = 1 THEN R := R + 0 ; IF M1 = 2 THEN R := R + 31 ; IF M1 = 3 THEN R := R + 31 +28 ; IF M1 = 4 THEN R := R + 31 +28 +31 ; IF M1 = 5 THEN R := R + 31 +28 +31 +30 ; IF M1 = 6 THEN R := R + 31 +28 +31 +30 +31 ; IF M1 = 7 THEN R := R + 31 +28 +31 +30 +31 +30 ; IF M1 = 8 THEN R := R + 31 +28 +31 +30 +31 +30 +31 ; IF M1 = 9 THEN R := R + 31 +28 +31 +30 +31 +30 +31 +31 ; IF M1 =10 THEN R := R + 31 +28 +31 +30 +31 +30 +31 +31 +30 ; IF M1 =11 THEN R := R + 31 +28 +31 +30 +31 +30 +31 +31 +30 +31 ; IF M1 =12 THEN R := R + 31 +28 +31 +30 +31 +30 +31 +31 +30 +31 +30 ; //加上日 R := R + D1; R := 0 - R ; END; RESULT := R ; END; // 英文 年份 减法 FUNCTION EYEAR_SUB(CYEAR:STRING;T_SUB:INTEGER):STRING; VAR T_D1 :INTEGER; T_DX2 :STRING; BEGIN RESULT := CYEAR; T_D1 := STRTOINTDEF(TRIM( COPY(CYEAR,1,POS('/',CYEAR)-1) ),1); T_DX2 := TRIM( COPY(CYEAR,POS('/',CYEAR), 10) ) ; T_D1 := T_D1 - T_SUB; RESULT := INTTOSTR(T_D1) + T_DX2; END; // 中文 月份 减一 FUNCTION CYEARMONTH_SUB(CYEARMONTH:STRING;T_SUB:INTEGER):STRING; VAR T_D1, T_D2 : INTEGER; T_DX2 :STRING; BEGIN RESULT := CYEARMONTH; IF STRTOINTDEF(CYEARMONTH,-1) < 0 THEN EXIT; T_D1 := STRTOINTDEF(COPY(CYEARMONTH,1,2),1); T_D2 := STRTOINTDEF(COPY(CYEARMONTH,3,2),1); IF T_D2 > T_SUB THEN BEGIN T_D2 := T_D2 - T_SUB; END ELSE BEGIN T_D1 := T_D1 - 1; T_D2 := T_D2 + 12 - T_SUB; END; T_DX2 := INTTOSTR(T_D2); IF LENGTH(T_DX2) < 2 THEN T_DX2 := '0' + T_DX2; IF LENGTH(T_DX2) < 2 THEN T_DX2 := '0' + T_DX2; RESULT := INTTOSTR(T_D1) + T_DX2; END; //==================================================================================== // 密码--------------------------------------------- {******************************************************* * Standard Encryption algorithm - Copied from Borland * *******************************************************} FUNCTION Encrypt(const InSTRING:STRING; StartKey,MultKey,AddKey:INTEGER): STRING; var I : Byte; BEGIN Result := ''; for I := 1 to Length(InSTRING) do BEGIN Result := Result + CHAR(Byte(InSTRING[I]) xor (StartKey shr 8)); StartKey := (Byte(Result[I]) + StartKey) * MultKey + AddKey; END; END; {******************************************************* * Standard Decryption algorithm - Copied from Borland * *******************************************************} FUNCTION Decrypt(const InSTRING:STRING; StartKey,MultKey,AddKey:INTEGER): STRING; var I : Byte; BEGIN Result := ''; for I := 1 to Length(InSTRING) do BEGIN Result := Result + CHAR(Byte(InSTRING[I]) xor (StartKey shr 8)); StartKey := (Byte(InSTRING[I]) + StartKey) * MultKey + AddKey; END; END; // 文件相关功能 ================================================================ //测试文件是否可以打开 FUNCTION TEST_OPEN_FILE(FILENAME:STRING):BOOLEAN; VAR FileHandle : INTEGER; BEGIN FileHandle := FileOpen(FILENAME, fmOpenWrite); FileClose(FileHandle); IF FileHandle < 0 then BEGIN TEST_OPEN_FILE:= FALSE; // SHOWMESSAGE(FILENAME+'路径文件名设定错误, 文件无法打开!'); END ELSE BEGIN TEST_OPEN_FILE:= TRUE; END; END; //建立新文件 FUNCTION FILE_CREATE(FILENAME:STRING):BOOLEAN; var FileHandle : INTEGER; BEGIN FileHandle := FileOpen(FILENAME, fmOpenWrite); FileClose(FileHandle); IF FileHandle < 0 then BEGIN FileHandle := FileCREATE(FILENAME); FileClose(FileHandle); END; RESULT:= TRUE; END; //清除文件 FUNCTION FILE_REWRITE(FILENAME:STRING):BOOLEAN; VAR TF :TEXTFILE; BEGIN RESULT:= FALSE; IF FileExists(FILENAME) = FALSE THEN BEGIN FILE_CREATE(FILENAME); RESULT:= FALSE; END; IF FileExists(FILENAME) = TRUE THEN BEGIN AssignFile(TF,FILENAME); Rewrite(TF); CloseFile(TF); RESULT:= TRUE; END; END; //写入文件 FUNCTION FILE_APPEND_LOG(FILENAME,TITLE,TXT:STRING):BOOLEAN; VAR TF :TEXTFILE; BEGIN RESULT:= FALSE; IF FileExists(FILENAME) = FALSE THEN BEGIN FILE_CREATE(FILENAME); RESULT:= FALSE; END; IF FileExists(FILENAME) = TRUE THEN BEGIN AssignFile(TF,FILENAME); Append(TF); Writeln(TF,TITLE +'~'+CHR(1)+CHR(2)+CHR(3)+'~'+ TXT); CloseFile(TF); RESULT:= TRUE; END; END; //写入文件单行 FUNCTION FILE_WRITELN_REC(FILENAME,TITLE,TXT:STRING):STRING; VAR TF1, TF2 : TEXTFILE; STR :STRING; BEGIN IF FileExists(FILENAME) = TRUE THEN BEGIN AssignFile(TF1,FILENAME); RESET(TF1); FILE_Rewrite('~LOG.TMP'); AssignFile(TF2,'~LOG.TMP'); Rewrite(TF2); WHILE NOT EOF(TF1) DO BEGIN Readln (TF1,STR); Writeln(TF2,STR); END; CloseFile(TF1); CloseFile(TF2); AssignFile(TF1,FILENAME); Rewrite(TF1); AssignFile(TF2,'~LOG.TMP'); Reset(TF2); WHILE NOT EOF(TF2) DO BEGIN READLN(TF2,STR); IF TITLE = COPY(STR,1,POS('~'+CHR(1)+CHR(2)+CHR(3)+'~',STR)-1) THEN BEGIN Writeln(TF1,TITLE+'~'+CHR(1)+CHR(2)+CHR(3)+'~'+TXT); Break; END; END; CloseFile(TF1); CloseFile(TF2); END; END; //读出文件单行 FUNCTION FILE_READLN_REC(FILENAME,TITLE:STRING):STRING; VAR TF :TEXTFILE; STR :STRING; BEGIN IF FileExists(FILENAME) = TRUE THEN BEGIN AssignFile(TF,FILENAME); Reset(TF); WHILE NOT EOF(TF) DO BEGIN READLN(TF,STR); IF TITLE = COPY(STR,1,POS('~'+CHR(1)+CHR(2)+CHR(3)+'~',STR)-1) THEN BEGIN RESULT := TRIM(COPY(STR,POS('~'+CHR(1)+CHR(2)+CHR(3)+'~',STR)+5,100 ) ); Break; END; END; CloseFile(TF); END; END; // TEXT读出文件 行数 FUNCTION TEXTFILE_RECCNT(FILENAME:STRING):INTEGER; VAR TF :TEXTFILE; STR: STRING; I :INTEGER; BEGIN I := 0; IF FileExists(FILENAME) = TRUE THEN BEGIN AssignFile(TF,FILENAME); Reset(TF); WHILE NOT EOF(TF) DO BEGIN Readln(TF,STR); INC(I); END; CloseFile(TF); END; RESULT := I; END; // 文件相关功能 ================================================================ //copy 由右至左 FUNCTION Copy_R(S: STRING; Index, Count: INTEGER): STRING; BEGIN COPY_R := COPY(S, LENGTH(S) - COUNT + 1 - (INDEX-1) , COUNT); END; //产生空白 FUNCTION SPACE(Count: INTEGER): STRING; VAR I :INTEGER; S , RETURN_S :STRING; BEGIN S := ' '; RETURN_S := ''; for I := 1 to COUNT do RETURN_S := RETURN_S + S; SPACE := RETURN_S ; END; { 字符串复制 } FUNCTION REPLICATE(VSTR1:STRING;VLEN:SMALLINT):STRING; VAR VI:INTEGER ; VSTR2:STRING; BEGIN VSTR2:=''; FOR VI:=1 TO VLEN DO VSTR2:=VSTR2+VSTR1; REPLICATE:=VSTR2; END; {REPLICATE} { 字符串填满 } FUNCTION FILL_STR(FILL_STR, STR, KIND:STRING; TOTAL_LENGTH:INTEGER):STRING; VAR T_STR:STRING; L_LENGTH, R_LENGTH :INTEGER; BEGIN IF KIND = 'L' THEN BEGIN T_STR := REPLICATE( FILL_STR,TOTAL_LENGTH-LENGTH(STR) ) + STR; IF (LENGTH(T_STR)>TOTAL_LENGTH) THEN T_STR := COPY_R(T_STR,1,TOTAL_LENGTH); END ELSE IF KIND = 'R' THEN BEGIN T_STR := STR + REPLICATE( FILL_STR,TOTAL_LENGTH-LENGTH(STR) ); IF (LENGTH(T_STR)>TOTAL_LENGTH) THEN T_STR := COPY(T_STR,1,TOTAL_LENGTH); END; IF KIND = 'C' THEN BEGIN L_LENGTH := (TOTAL_LENGTH - LENGTH(STR)) DIV 2; R_LENGTH := TOTAL_LENGTH - L_LENGTH - LENGTH(STR); T_STR := REPLICATE( FILL_STR,R_LENGTH) + STR + REPLICATE( FILL_STR,R_LENGTH); IF (LENGTH(T_STR)>TOTAL_LENGTH) THEN T_STR := COPY(T_STR,1,TOTAL_LENGTH); END; RESULT := T_STR; END; { 字符串累加 } FUNCTION STR_INC(FILL_STR, STR:STRING; T_START, T_END, T_CNT:INTEGER):STRING; VAR L_STR, M_STR, R_STR :STRING; TOTAL_LENGTH, M_LENGTH :INTEGER; BEGIN RESULT := ''; IF STRTOINTDEF(COPY(STR,T_START,T_END),-1) < 0 THEN EXIT; TOTAL_LENGTH := LENGTH(STR); L_STR := COPY(STR,1,T_START-1); M_STR := COPY(STR,T_START,T_END-T_START+1); R_STR := COPY(STR,T_END+1,TOTAL_LENGTH-T_END); M_LENGTH := LENGTH(M_STR); M_STR := INTTOSTR(STRTOINTDEF(M_STR,0) + T_CNT); M_STR := REPLICATE(FILL_STR,M_LENGTH - LENGTH(M_STR) ) + M_STR; RESULT := L_STR+M_STR+R_STR; END; { 字符串转浮点 } FUNCTION STRTOFLOATDEF(STR:STRING;FDEFAULT:REAL):REAL; BEGIN IF CHECK_FLOATINT(STR) = TRUE THEN BEGIN RESULT := STRTOFLOAT(TRIM(STR)); END ELSE BEGIN RESULT := FDEFAULT; END; END; { 字符串替换 } FUNCTION STR_REPLACE(STR, SUBSTR1,SUBSTR2:STRING):STRING; VAR A, B:STRING; BEGIN WHILE POS(SUBSTR1,STR) > 0 DO BEGIN A := COPY(STR,1, POS(SUBSTR1,STR)-1 ); B := COPY(STR,POS(SUBSTR1,STR)+LENGTH(SUBSTR1), LENGTH(STR) ); STR := A + SUBSTR2 + B; END; RESULT := STR; END; { 字符串插入 } FUNCTION STR_INSERT(STR, S1, S2:STRING; FB:BOOLEAN):STRING; VAR A, B, T_RETURN:STRING; BEGIN IF POS(S1,STR) <= 0 THEN BEGIN IF FB = TRUE THEN RESULT := S2 + STR; IF FB = FALSE THEN RESULT := STR + S2; END ELSE BEGIN A := COPY(STR,1, POS(S1,STR)-1 ); B := COPY(STR,POS(S1,STR)+LENGTH(S1), LENGTH(STR) ); IF FB = TRUE THEN BEGIN RESULT := A + S2 + S1 + B; END; IF FB = FALSE THEN BEGIN RESULT := A + S1 + S2 + B; END; END; END; { 数据字符串找寻 } FUNCTION STR_DB_FIELDBYNO(STR, RAIL:STRING;FIELD_NO:INTEGER):STRING; VAR T, T_RETURN:STRING; I : INTEGER; BEGIN FOR I := 1 TO FIELD_NO DO BEGIN T := COPY(STR,1,POS(RAIL,STR)-1); IF POS(RAIL,STR) <= 0 THEN T_RETURN := STR ELSE T_RETURN := T; STR := COPY(STR,POS(RAIL,STR)+1,LENGTH(STR)-POS(RAIL,STR)); END; RESULT := T_RETURN; END; { 删除数据字符串 } FUNCTION TRIM_STR(STR, TRIMSTR:STRING):STRING; BEGIN WHILE COPY(STR,1,1) = TRIMSTR DO STR := COPY(STR,2,LENGTH(STR)-1); RESULT := STR; END; { 整数 转 字符串 再补零 } FUNCTION INTTOSTR_REP(TINT,REP:INTEGER):STRING; VAR S:STRING; BEGIN S := INTTOSTR(TINT); RESULT := REPLICATE('0',REP-LENGTH(S) ) + S; END; { BOOLEAN TRUE FALSE 转 01 } FUNCTION BOOLEANTOSTR(TB : BOOLEAN):STRING; BEGIN RESULT := '0'; IF TB= TRUE THEN RESULT := '1' ELSE RESULT := '0'; END; { 检查是否为整数 } FUNCTION CHECK_INT(T_STR:STRING):BOOLEAN; BEGIN RESULT := FALSE; IF POS('-',T_STR) <= 0 THEN BEGIN IF (STRTOINTDEF(T_STR,-1) >= 0) THEN RESULT := TRUE; END ELSE BEGIN IF (STRTOINTDEF(COPY(T_STR,2,LENGTH(T_STR)),-1) >= 0) THEN RESULT := TRUE; END; END; { 检查是否为浮点数 } FUNCTION CHECK_FLOAT(T_STR:STRING):BOOLEAN; VAR T_A,T_B:STRING; BEGIN T_A := TRIM(COPY(T_STR,1,POS('.',T_STR)-1) ); T_B := TRIM(COPY(T_STR,POS('.',T_STR)+1,LENGTH(T_STR)) ); IF (STRTOINTDEF(T_A,-1) >= 0) AND (STRTOINTDEF(T_B,-1) >= 0) THEN RESULT := TRUE ELSE RESULT := FALSE; END; { 检查是否为浮点数 和 整数} FUNCTION CHECK_FLOATINT(T_STR:STRING):BOOLEAN; VAR T_A,T_B:STRING; BEGIN IF POS('.',T_STR) >0 THEN BEGIN T_A := TRIM(COPY(T_STR,1,POS('.',T_STR)-1) ); T_B := TRIM(COPY(T_STR,POS('.',T_STR)+1,LENGTH(T_STR)) ); IF (STRTOINTDEF(T_A,-99999999) >= -99999998) AND (STRTOINTDEF(T_B,-99999999) >= -99999998) THEN RESULT := TRUE ELSE RESULT := FALSE; END ELSE BEGIN IF (STRTOINTDEF(T_STR,-99999999) >= -99999998) THEN RESULT := TRUE ELSE RESULT := FALSE; END; END; { 取 浮点数 , 小数点位数 } FUNCTION FLOAT_LENGTH(T_STR:STRING;T_LENGTH:INTEGER):STRING; VAR T_A,T_B:STRING; BEGIN IF POS('.',T_STR) > 0 THEN BEGIN IF T_LENGTH <= 0 THEN RESULT := TRIM(COPY(T_STR,1,POS('.',T_STR)-1) ); IF T_LENGTH > 0 THEN BEGIN T_A := TRIM(COPY(T_STR,1,POS('.',T_STR)-1) ); T_B := TRIM(COPY(T_STR,POS('.',T_STR)+1,T_LENGTH) ); IF (T_A = '') AND (T_B = '') THEN RESULT := '0' +'.'+ REPLICATE('0',T_LENGTH); IF (T_A <> '') AND (T_B = '') THEN RESULT := T_A +'.'+ REPLICATE('0',T_LENGTH); IF (T_A = '') AND (T_B <> '') THEN RESULT := '0' +'.'+T_B+REPLICATE('0',T_LENGTH-LENGTH(T_B)); IF (T_A <> '') AND (T_B <> '') THEN RESULT := T_A +'.'+T_B+REPLICATE('0',T_LENGTH-LENGTH(T_B)); END; END ELSE BEGIN IF T_LENGTH <= 0 THEN RESULT := T_STR; IF T_LENGTH > 0 THEN RESULT := T_STR +'.'+ REPLICATE('0',T_LENGTH); END; END; { 浮点数 转 整数 } FUNCTION FLOATTOINT(T_FLOAT:REAL):INTEGER; VAR A,B : INTEGER; STR : STRING; BEGIN A := 0; B := 0; STR := FLOATTOSTR(T_FLOAT); IF POS('.',STR) > 0 THEN //有小数点 BEGIN A := STRTOINT(COPY(STR,1,POS('.',STR)-1)); B := STRTOINT(COPY(STR,POS('.',STR)+1,2)); IF A >=0 THEN IF B >=5 THEN A := A + 1; IF A < 0 THEN IF B >=5 THEN A := A - 1; // T := COPY(T,1,POS('.',T)-1) END ELSE BEGIN //无小数点 A := STRTOINT(STR); END; RESULT := A; END; { 浮点数 转 整数 PS: 无条件小数第一位进位} FUNCTION FLOATTOINT_ROUND(T_FLOAT:REAL):INTEGER; VAR A,B : INTEGER; STR : STRING; BEGIN A := 0; B := 0; STR := FLOATTOSTR(T_FLOAT); IF POS('.',STR) > 0 THEN //有小数点 BEGIN A := STRTOINT(COPY(STR,1,POS('.',STR)-1)); B := STRTOINT(COPY(STR,POS('.',STR)+1,2)); IF A >=0 THEN IF B >=1 THEN A := A + 1; IF A < 0 THEN IF B >=1 THEN A := A - 1; // T := COPY(T,1,POS('.',T)-1) END ELSE BEGIN //无小数点 A := STRTOINT(STR); END; RESULT := A; END; { 整数 个位数 四舍五入 } FUNCTION ROUND_1(T_INT:INTEGER):INTEGER; VAR T, T1, T2 : STRING; BEGIN RESULT := 0; T := INTTOSTR(T_INT); IF T_INT >= 0 THEN BEGIN IF LENGTH(T) =0 THEN RESULT := 0; IF LENGTH(T) =1 THEN BEGIN IF T_INT >=5 THEN RESULT := 10; IF T_INT <=4 THEN RESULT := 0; END; IF LENGTH(T) >1 THEN BEGIN T1 := COPY_R(T,1,1); T2 := COPY(T,1,LENGTH(T)-1); // SHOWMESSAGE(T1+'='+T2); IF STRTOINT(T1) >= 5 THEN RESULT := (STRTOINT(T2)+1)*10; IF STRTOINT(T1) <= 4 THEN RESULT := (STRTOINT(T2) )*10; END; END ELSE BEGIN IF LENGTH(T) =2 THEN BEGIN IF T_INT <=-5 THEN RESULT := -10; IF T_INT >=-4 THEN RESULT := 0; END; IF LENGTH(T) >2 THEN BEGIN T1 := COPY_R(T,1,1); T2 := COPY(T,1,LENGTH(T)-1); // SHOWMESSAGE(T1+'='+T2); IF STRTOINT(T1) >= 5 THEN RESULT := (STRTOINT(T2)-1)*10; IF STRTOINT(T1) <= 4 THEN RESULT := (STRTOINT(T2) )*10; END; { IF LENGTH(T) <-1 THEN BEGIN T1 := COPY_R(T,1,1); T2 := COPY(T,1,LENGTH(T)-1); IF STRTOINT(T1) <= -5 THEN RESULT := (STRTOINT(T2)+1)*10; IF STRTOINT(T1) >= -4 THEN RESULT := (STRTOINT(T2) )*10; END; } END; END; { 整数 次方 } FUNCTION INT_CUBE(T_INT,T_CUBE:INTEGER):INTEGER; VAR R, I : INTEGER; BEGIN R := T_INT; FOR I := 1 TO T_CUBE-1 DO R := R * T_INT; IF T_CUBE >=1 THEN RESULT := R ELSE RESULT := 1; END; { 16 进位 转 整数 } FUNCTION HEXTOINT(THEX:STRING):INTEGER; VAR TLEN, TINT, T1, I : INTEGER; TX: STRING; BEGIN TLEN := LENGTH(THEX); TINT := 0; FOR I := 1 TO TLEN DO BEGIN TX := COPY_R(THEX,I,1); T1 := 0; IF TX = '0' THEN T1 := 0; IF TX = '1' THEN T1 := 1; IF TX = '2' THEN T1 := 2; IF TX = '3' THEN T1 := 3; IF TX = '4' THEN T1 := 4; IF TX = '5' THEN T1 := 5; IF TX = '6' THEN T1 := 6; IF TX = '7' THEN T1 := 7; IF TX = '8' THEN T1 := 8; IF TX = '9' THEN T1 := 9; IF TX = 'A' THEN T1 :=10; IF TX = 'B' THEN T1 :=11; IF TX = 'C' THEN T1 :=12; IF TX = 'D' THEN T1 :=13; IF TX = 'E' THEN T1 :=14; IF TX = 'F' THEN T1 :=15; TINT := TINT + ( T1 * ( INT_CUBE(16,(I-1)) )); END; RESULT := TINT; END; procedure Delay(n: INTEGER); VAR start: LongInt; BEGIN start := GetTickCount; repeat Application.ProcessMessages; until (GetTickCount - start) >= n; END; FUNCTION EXCHANGE_CAL(T_EXCHG:STRING;T_LENGTH:INTEGER):STRING; VAR T1, T2: STRING; BEGIN T1 := TRIM(COPY(T_EXCHG,1 ,POS(':',T_EXCHG)-1) ); T2 := TRIM(COPY(T_EXCHG,POS(':',T_EXCHG)+1, 10) ); IF ( (CHECK_FLOAT(T1) = TRUE) AND (CHECK_FLOAT(T2) = TRUE) ) OR ( (CHECK_FLOAT(T1) = TRUE) AND (CHECK_INT (T2) = TRUE) ) OR ( (CHECK_INT (T1) = TRUE) AND (CHECK_FLOAT(T2) = TRUE) ) OR ( (CHECK_INT (T1) = TRUE) AND (CHECK_INT (T2) = TRUE) ) THEN BEGIN //台币 / 外币 RESULT := FLOAT_LENGTH( FLOATTOSTR( STRTOFLOAT(T2) / STRTOFLOAT(T1) ),T_LENGTH ); END ELSE BEGIN RESULT := '1'; END; END; //打印机 输出入 ================================================================ procedure Out32(PortAddress:smallint;Value:smallint);stdcall;export; VAR ByteValue:Byte; BEGIN ByteValue:=Byte(Value); asm push dx mov dx,PortAddress mov al, ByteValue out dx,al pop dx END; END; FUNCTION Inp32(PortAddress:smallint):smallint;stdcall;export; VAR ByteValue:byte; BEGIN asm push dx mov dx, PortAddress //////////////in al,dx mov ByteValue,al pop dx END; Inp32:=smallint(ByteValue) and $00FF; END; FUNCTION COMPORT_OUT(PortNAME,EXPRESS:STRING):BOOLEAN; VAR TF :TEXTFILE; BEGIN RESULT := FALSE; IF TEST_OPEN_FILE(PortNAME) = TRUE THEN BEGIN TRY AssignFile(TF,PortNAME); Rewrite(TF); WRITE(TF,EXPRESS); CloseFile(TF); RESULT := TRUE; EXCEPT SHOWMESSAGE('无法送出资料!'); RESULT := FALSE; END; END; END; FUNCTION COMPORT_OUTLN(PortNAME,EXPRESS:STRING):BOOLEAN; VAR TF :TEXTFILE; BEGIN RESULT := FALSE; IF TEST_OPEN_FILE(PortNAME) = TRUE THEN BEGIN TRY AssignFile(TF,PortNAME); Rewrite(TF); Writeln(TF,EXPRESS); CloseFile(TF); RESULT := TRUE; EXCEPT SHOWMESSAGE('无法送出资料!'); RESULT := FALSE; END; END; END; //打印机 输出入 ================================================================ // CPU ID ================================================== FUNCTION IsCPUID_Available : BOOLEAN; register; asm PUSHFD {direct access to flags no possible, only via stack} POP EAX {flags to EAX} MOV EDX,EAX {save current flags} XOR EAX,ID_BIT {not ID bit} PUSH EAX {onto stack} POPFD {from stack to flags, WITH not ID bit} PUSHFD {back to stack} POP EAX {get back to EAX} XOR EAX,EDX {check IF ID bit affected} JZ @exit {no, CPUID not availavle} MOV AL,TRUE {Result=TRUE} @exit: END; FUNCTION GetCPUID : TCPUID; assembler; register; asm PUSH EBX {Save affected register} PUSH EDI MOV EDI,EAX {@Resukt} MOV EAX,1 DW $A20F {CPUID Command} STOSD {CPUID[1]} MOV EAX,EBX STOSD {CPUID[2]} MOV EAX,ECX STOSD {CPUID[3]} MOV EAX,EDX STOSD {CPUID[4]} POP EDI {Restore registers} POP EBX END; FUNCTION GetCPUVendor : TVendor; assembler; register; asm PUSH EBX {Save affected register} PUSH EDI MOV EDI,EAX {@Result (TVendor)} MOV EAX,0 DW $A20F {CPUID Command} MOV EAX,EBX XCHG EBX,ECX {save ECX result} MOV ECX,4 @1: STOSB SHR EAX,8 LOOP @1 MOV EAX,EDX MOV ECX,4 @2: STOSB SHR EAX,8 LOOP @2 MOV EAX,EBX MOV ECX,4 @3: STOSB SHR EAX,8 LOOP @3 POP EDI {Restore registers} POP EBX END; FUNCTION EAN13_ENCODE(T_STR:STRING):STRING; VAR S : ARRAY [2..13] OF INTEGER; ANSWER : STRING; BEGIN T_STR := TRIM(T_STR); RESULT := ''; //空白跳出 IF LENGTH(T_STR) < 12 THEN EXIT; S[13] := STRTOINTDEF( T_STR[ 1] ,-1); S[12] := STRTOINTDEF( T_STR[ 2] ,-1); S[11] := STRTOINTDEF( T_STR[ 3] ,-1); S[10] := STRTOINTDEF( T_STR[ 4] ,-1); S[ 9] := STRTOINTDEF( T_STR[ 5] ,-1); S[ 8] := STRTOINTDEF( T_STR[ 6] ,-1); S[ 7] := STRTOINTDEF( T_STR[ 7] ,-1); S[ 6] := STRTOINTDEF( T_STR[ 8] ,-1); S[ 5] := STRTOINTDEF( T_STR[ 9] ,-1); S[ 4] := STRTOINTDEF( T_STR[10] ,-1); S[ 3] := STRTOINTDEF( T_STR[11] ,-1); S[ 2] := STRTOINTDEF( T_STR[12] ,-1); IF S[13] < 0 THEN EXIT; IF S[12] < 0 THEN EXIT; IF S[11] < 0 THEN EXIT; IF S[10] < 0 THEN EXIT; IF S[ 9] < 0 THEN EXIT; IF S[ 8] < 0 THEN EXIT; IF S[ 7] < 0 THEN EXIT; IF S[ 6] < 0 THEN EXIT; IF S[ 5] < 0 THEN EXIT; IF S[ 4] < 0 THEN EXIT; IF S[ 3] < 0 THEN EXIT; IF S[ 2] < 0 THEN EXIT; ANSWER := INTTOSTR( (S[2] + S[4] + S[6] + S[8] + S[10] + S[12])*3 + S[3] + S[5] + S[7] + S[9] + S[11] + S[13] ); ANSWER := INTTOSTR(10 - (STRTOINT(ANSWER)MOD 10) ); RESULT := T_STR+COPY_R(ANSWER,1,1); END; FUNCTION EAN13_AUTOADD(T_STR:STRING):STRING; BEGIN IF LENGTH(T_STR) < 13 THEN BEGIN T_STR := REPLICATE('0',12 - LENGTH(T_STR) ) + T_STR; T_STR := EAN13_ENCODE(T_STR); END; RESULT := T_STR; END; //发票类 ======================================================================= FUNCTION INVOICE_NO_CHECK(T_STR:STRING):BOOLEAN; BEGIN RESULT := FALSE; IF T_STR <> '' THEN BEGIN IF (LENGTH(T_STR)=10 ) THEN IF STRTOINTDEF(COPY(T_STR,3,8),-1) >= 0 THEN RESULT := TRUE; IF (LENGTH(T_STR)= 8 ) THEN IF STRTOINTDEF(T_STR,-1) >= 0 THEN RESULT := TRUE; END; END; //发票类 ======================================================================= //检查信用卡号 FUNCTION ValidateCreditCardNo(value: STRING; WARNING:BOOLEAN): BOOLEAN; VAR idx, Sum, leng, Weight: INTEGER; Digital: array of INTEGER; DigitalNumberIsOdd: BOOLEAN; BEGIN Result := FALSE; leng := length(value); IF leng=0 then EXIT; SetLength(Digital, leng); Sum := 0; IF Odd(leng) then DigitalNumberIsOdd := TRUE else DigitalNumberIsOdd := FALSE; for idx := 1 to leng do BEGIN Digital[idx - 1] := Ord(Value[idx]) - Ord('0'); IF (Digital[idx - 1] > 9) or (Digital[idx - 1] < 0) then EXIT; IF (DigitalNumberIsOdd) then IF odd(idx) then Weight := 1 else Weight := 2 else IF odd(idx) then Weight := 2 else Weight := 1; Digital[idx - 1] := Digital[idx - 1] * Weight; IF (Digital[idx - 1] > 9) then Digital[idx - 1] := Digital[idx - 1] - 9; Sum := Sum + Digital[idx - 1]; END; IF (Sum mod 10 = 0) then Result := TRUE else Result := FALSE; IF (WARNING = TRUE) AND (RESULT = FALSE) THEN SHOWMESSAGE('信用卡号码错误!'); END; //对象 储存相关信息值 INI FILE ================================================ FUNCTION INI_SAVE_OBJECT(INIFILENAME, OBJECT_NAME :STRING; T_LEFT, T_TOP :INTEGER; T_TEXT:STRING):BOOLEAN; VAR T : TINIFILE; //暂存对象 BEGIN TRY T := TINIFILE.Create(INIFILENAME); T.WriteINTEGER(OBJECT_NAME,'LEFT', T_LEFT); T.WriteINTEGER(OBJECT_NAME,'TOP' , T_TOP ); T.WriteSTRING (OBJECT_NAME,'TEXT', T_TEXT); RESULT := TRUE; FINALLY T.FREE; END; END; //对象 储存相关信息值 INI FILE ================================================ FUNCTION INI_SAVE_INT(INIFILENAME, OBJECT_NAME :STRING; T_INTEGER :INTEGER):BOOLEAN; VAR T : TINIFILE; //暂存对象 BEGIN TRY T := TINIFILE.Create(INIFILENAME); T.WriteINTEGER(OBJECT_NAME,'INTEGER', T_INTEGER); RESULT := TRUE; FINALLY T.FREE; END; END; //对象 储存相关信息值 INI FILE ================================================ FUNCTION INI_SAVE_STR(INIFILENAME, OBJECT_NAME :STRING; T_STR :STRING):BOOLEAN; VAR T : TINIFILE; //暂存对象 BEGIN TRY T := TINIFILE.Create(INIFILENAME); T.WriteSTRING(OBJECT_NAME,'STRING', T_STR); RESULT := TRUE; FINALLY T.FREE; END; END; //对象 储存相关信息值 INI FILE ================================================ FUNCTION INI_SAVE_STR2(INIFILENAME, OBJECT_NAME, OBJECT_KIND :STRING; T_STR :STRING):BOOLEAN; VAR T : TINIFILE; //暂存对象 BEGIN TRY T := TINIFILE.Create(INIFILENAME); T.WriteSTRING(OBJECT_NAME,OBJECT_KIND, T_STR); RESULT := TRUE; FINALLY T.FREE; END; END; //对象 储存相关信息值 INI FILE ================================================ FUNCTION INI_SAVE_BOOL(INIFILENAME, OBJECT_NAME :STRING; T_BOOL :BOOLEAN):BOOLEAN; VAR T : TINIFILE; //暂存对象 BEGIN TRY T := TINIFILE.Create(INIFILENAME); T.WriteBool(OBJECT_NAME,'BOOL', T_BOOL); RESULT := TRUE; FINALLY T.FREE; END; END; //对象 取回相关信息值 INI FILE ================================================ FUNCTION INI_LOAD_OBJECT(INIFILENAME, OBJECT_NAME, OBJECT_KIND, T_DEFAULT :STRING):STRING; VAR T : TINIFILE; //暂存对象 BEGIN TRY T := TINIFILE.Create(INIFILENAME); RESULT := T.ReadSTRING(OBJECT_NAME,OBJECT_KIND, T_DEFAULT); FINALLY T.FREE; END; END; //对象 取回相关信息值 INI FILE ================================================ FUNCTION INI_LOAD_INT(INIFILENAME, OBJECT_NAME :STRING; T_DEFAULT:INTEGER ):INTEGER; VAR T : TINIFILE; //暂存对象 BEGIN TRY T := TINIFILE.Create(INIFILENAME); RESULT := T.ReadINTEGER(OBJECT_NAME,'INTEGER', T_DEFAULT); FINALLY T.FREE; END; END; //对象 取回相关信息值 INI FILE ================================================ FUNCTION INI_LOAD_STR(INIFILENAME, OBJECT_NAME :STRING; T_DEFAULT:STRING ):STRING; VAR T : TINIFILE; //暂存对象 BEGIN TRY T := TINIFILE.Create(INIFILENAME); RESULT := T.ReadSTRING(OBJECT_NAME,'STRING', T_DEFAULT); FINALLY T.FREE; END; END; //对象 取回相关信息值 INI FILE ================================================ FUNCTION INI_LOAD_STR2(INIFILENAME, OBJECT_NAME , OBJECT_KIND:STRING; T_DEFAULT:STRING ):STRING; VAR T : TINIFILE; //暂存对象 BEGIN TRY T := TINIFILE.Create(INIFILENAME); RESULT := T.ReadSTRING(OBJECT_NAME,OBJECT_KIND, T_DEFAULT); FINALLY T.FREE; END; END; //对象 取回相关信息值 INI FILE ================================================ FUNCTION INI_LOAD_BOOL(INIFILENAME, OBJECT_NAME :STRING; T_DEFAULT:BOOLEAN ):BOOLEAN; VAR T : TINIFILE; //暂存对象 BEGIN TRY T := TINIFILE.Create(INIFILENAME); RESULT := T.ReadBool(OBJECT_NAME,'BOOL', T_DEFAULT); FINALLY T.FREE; END; END; // ============================================================================= FUNCTION GetAveCharSize(Canvas: TCanvas): TPoint; var I: INTEGER; Buffer: array[0..51] of Char; BEGIN for I := 0 to 25 do Buffer[I] := Chr(I + Ord('A')); for I := 0 to 25 do Buffer[I + 26] := Chr(I + Ord('a')); GetTextExtentPoint(Canvas.Handle, Buffer, 52, TSize(Result)); Result.X := Result.X div 52; END; FUNCTION JInputQuery(const ACaption, APrompt: STRING; VAR Value: STRING): BOOLEAN; var Form: TForm; Prompt: TLabel; Edit: TEdit; DialogUnits: TPoint; ButtonTop, ButtonWidth, ButtonHeight: INTEGER; BEGIN Result := FALSE; Form := TForm.Create(Application); WITH Form do try Canvas.Font := Font; FONT.SIZE := 20; FONT.NAME := 'Arial'; DialogUnits := GetAveCharSize(Canvas); BorderStyle := bsDialog; Caption := ACaption; ClientWidth := MulDiv(180, DialogUnits.X, 4); ClientHeight := MulDiv(64, DialogUnits.Y, 8); Position := poScreenCenter; Prompt := TLabel.Create(Form); WITH Prompt do BEGIN Parent := Form; FONT.SIZE := 46; AutoSize := TRUE; Left := MulDiv(8, DialogUnits.X, 4); Top := MulDiv(2, DialogUnits.Y, 72); Caption := APrompt; END; Edit := TEdit.Create(Form); WITH Edit do BEGIN Parent := Form; FONT.SIZE := 46; Left := Prompt.Left; Top := MulDiv(19, DialogUnits.Y, 8); Width := MulDiv(164, DialogUnits.X, 4); MaxLength := 255; Text := Value; SelectAll; END; ButtonTop := MulDiv(41, DialogUnits.Y, 8); ButtonWidth := MulDiv(50, DialogUnits.X, 4); ButtonHeight := MulDiv(14, DialogUnits.Y, 8); WITH TButton.Create(Form) do BEGIN Parent := Form; Caption := ' 确定 OK '; ModalResult := mrOk; Default := TRUE; SetBounds(MulDiv(60, DialogUnits.X, 4), ButtonTop, ButtonWidth, ButtonHeight); Top := MulDiv(45, DialogUnits.Y, 8); END; { WITH TButton.Create(Form) do BEGIN Parent := Form; Caption := 'SMsgDlgCancel; ModalResult := mrCancel; Cancel := TRUE; SetBounds(MulDiv(92, DialogUnits.X, 4), ButtonTop, ButtonWidth, ButtonHeight); END; } IF ShowModal = mrOk then BEGIN Value := Edit.Text; Result := TRUE; END; finally Form.FREE; END; END; FUNCTION JInputBox(const ACaption, APrompt, ADefault: STRING): STRING; BEGIN Result := ADefault; JInputQuery(ACaption, APrompt, Result); END; FUNCTION JMSGFORM(const ACaption, ADefault: STRING;T_FONTSIZE:INTEGER): BOOLEAN; var Form: TForm; MEMO : TMEMO; DialogUnits: TPoint; ButtonTop, ButtonWidth, ButtonHeight: INTEGER; BEGIN Result := FALSE; Form := TForm.Create(Application); WITH Form do try Canvas.Font := Font; FONT.SIZE := 16; FONT.NAME := 'Arial'; DialogUnits := GetAveCharSize(Canvas); BorderStyle := bsDialog; Caption := ACaption; ClientWidth := MulDiv(180, DialogUnits.X, 4); ClientHeight := MulDiv(160, DialogUnits.Y, 8); Position := poScreenCenter; MEMO := TMEMO.Create(Form); WITH MEMO do BEGIN Parent := Form; SCROLLBARS := SSBOTH; COLOR := CLBLACK; FONT.COLOR := CLWHITE; FONT.Name := 'Courier New'; FONT.SIZE := T_FONTSIZE; Left := 2; Top := 2; Width := FORM.Width -11; HEIGHT := FORM.HEIGHT -70; Lines.Text := ADefault; END; ButtonTop := MulDiv(41, DialogUnits.Y, 8); ButtonWidth := MulDiv(50, DialogUnits.X, 4); ButtonHeight := MulDiv(14, DialogUnits.Y, 8); WITH TButton.Create(Form) do BEGIN Parent := Form; Caption := ' 确定 OK '; ModalResult := mrOk; Default := TRUE; Width := 200; HEIGHT := 40; Top := FORM.Height - HEIGHT - 24; LEFT := 50; END; WITH TButton.Create(Form) do BEGIN Parent := Form; Caption := ' 取消 Cancel '; ModalResult := mrCancel; Cancel := TRUE; Width := 200; HEIGHT := 40; Top := FORM.Height - HEIGHT - 24; LEFT := FORM.WIDTH - 50 - WIDTH; END; IF ShowModal = mrOk then Result := TRUE; finally Form.FREE; END; END; FUNCTION JSHOWMESSAGE(const ACaption, APROMPT: STRING): BOOLEAN; VAR Form: TForm; Prompt: TLabel; DialogUnits: TPoint; ButtonTop, ButtonWidth, ButtonHeight: INTEGER; BEGIN Result := FALSE; Form := TForm.Create(Application); WITH Form do try Canvas.Font := Font; FONT.SIZE := 20; FONT.NAME := 'Arial'; DialogUnits := GetAveCharSize(Canvas); BorderStyle := bsDialog; Caption := ACaption; ClientWidth := MulDiv(180, DialogUnits.X, 4); ClientHeight := MulDiv(32, DialogUnits.Y, 8); Position := poScreenCenter; Prompt := TLabel.Create(Form); WITH Prompt do BEGIN Parent := Form; FONT.SIZE := 32; AutoSize := TRUE; Left := MulDiv(6, DialogUnits.X, 4); Top := MulDiv(12, DialogUnits.Y, 72); Caption := APROMPT; END; ButtonTop := MulDiv(10, DialogUnits.Y, 8); ButtonWidth := MulDiv(50, DialogUnits.X, 4); ButtonHeight := MulDiv(14, DialogUnits.Y, 8); WITH TButton.Create(Form) do BEGIN Parent := Form; Caption := ' 确定 OK '; ModalResult := mrOk; Default := TRUE; SetBounds(MulDiv(60, DialogUnits.X, 4), ButtonTop, ButtonWidth, ButtonHeight); Top := MulDiv(16, DialogUnits.Y, 8); END; IF ShowModal = mrOk then Result := TRUE; finally Form.FREE; END; END; end.
unit UAMC_SendPak_Landmark; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. } { This is specific unit that knowns how to send the 'Appraisal Package' } { to Landmark. Each AMC is slightly different. so we have a unique } { TWorkflowBaseFrame for each AMC. } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, MSXML6_TLB, WinHTTP_TLB, UContainer, UAMC_Globals, UAMC_Base, UAMC_WorkflowBaseFrame, CheckLst; type TAMC_SendPak_Landmark = class(TWorkflowBaseFrame) btnUpload: TButton; StaticText1: TStaticText; chkBxList: TCheckListBox; procedure btnUploadClick(Sender: TObject); private FUserID: string; FUserPassword: String; FOrderID: String; FUploaded: Boolean; procedure UploadAppraisalPackage; procedure PrepFileForUploading(ADataFile: TDataFile; var fData, fDataID: String); function UploadAppraisalFile(ADataFile: TDataFile): Boolean; function UploadDataFile(dataFile, dataFmt: String): Boolean; public procedure InitPackageData; override; function ProcessedOK: Boolean; override; end; implementation {$R *.dfm} uses UWebConfig, UAMC_Utils, UWindowsInfo, UStatus, UBase64, UAMC_Delivery; //Display the package contents to be uploaded procedure TAMC_SendPak_Landmark.InitPackageData; var fileType, strDesc: String; n: integer; begin btnUpload.Enabled := True; StaticText1.Caption :=' Appraisal Package files to Upload:'; //get Landmark specific data if assigned(PackageData.FAMCData) then begin FOrderID := TAMCData_Landmark(PackageData.FAMCData).FOrderID; FUserID := TAMCData_Landmark(PackageData.FAMCData).FUserID; FUserPassword := TAMCData_Landmark(PackageData.FAMCData).FPassword; end; //display the file types that will be uploaded chkBxList.Clear; //incase we are entering multiple times with PackageData.DataFiles do for n := 0 to count-1 do begin fileType := TDataFile(Items[n]).FType; if (CompareText(fileType,fTypXML26) = 0) or (CompareText(fileType,fTypXML26GSE) = 0) then //dont send PDF begin strDesc := DataFileDescriptionText(fileType); chkBxList.items.Add(strDesc); end; end; end; function TAMC_SendPak_Landmark.ProcessedOK: Boolean; begin PackageData.FGoToNextOk := FUploaded; PackageData.FAlertMsg := 'Appraisal files successfully uploaded'; //ending msg to user PackageData.FHardStop := not FUploaded; PackageData.FAlertMsg := ''; if not FUploaded then PackageData.FAlertMsg := 'Please upload the files before moving to the next step.'; result := PackageData.FGoToNextOk; end; procedure TAMC_SendPak_Landmark.btnUploadClick(Sender: TObject); begin UploadAppraisalPackage; end; procedure TAMC_SendPak_Landmark.UploadAppraisalPackage; var n: Integer; dataFmt: String; begin StaticText1.Caption :=' Uploading Appraisal Package files'; btnUpload.Enabled := False; with PackageData do for n := 0 to DataFiles.count -1 do begin dataFmt := TDataFile(PackageData.DataFiles[n]).FType; if (CompareText(dataFmt,fTypXML26) = 0) or (CompareText(dataFmt,fTypXML26GSE) = 0) then //dont send PDF if UploadAppraisalFile(TDataFile(DataFiles[n])) then chkBxList.Checked[n] := True; end; FUploaded := True; for n := 0 to chkBxList.items.count-1 do FUploaded := FUploaded and chkBxList.Checked[n]; if FUploaded then StaticText1.Caption :=' All Appraisal Package files Uploaded' else begin btnUpload.Enabled := True; StaticText1.Caption :=' Appraisal Package files to Upload:'; end; end; function TAMC_SendPak_Landmark.UploadAppraisalFile(ADataFile: TDataFile): Boolean; var fData: String; fDataTyp: String; begin PrepFileForUploading(ADataFile, fData, fDataTyp); result := UploadDataFile(fData, fDataTyp); end; procedure TAMC_SendPak_Landmark.PrepFileForUploading(ADataFile: TDataFile; var fData, fDataID: String); begin //extract the data fData := ADataFile.FData; //get Landmark format identifier //fDataID := ConvertToTitleSourceType(ADataFile.FType); do not need fDataID := ADataFile.FType; //should it be base64 encoded? fData := Base64Encode(fData); fData := StringReplace(fData,'+','-',[rfReplaceAll]); //specific to Landmark fData := StringReplace(fData,'/','_',[rfReplaceAll]); fData := StringReplace(fData,'=','.',[rfReplaceAll]); end; function TAMC_SendPak_Landmark.UploadDataFile(dataFile, dataFmt: String): Boolean; const fnUpload = 'order/upload-final-report/key/%s'; uploadTemplate = 'id=%s&name=appraisal&type=xml&user_email=%s&user_password=%s&content=%s'; var URL: String; uploadStr: String; httpRequest: IWinHTTPRequest; begin result := False; url := LandmarkAPIentry + format(fnUpload,[LandmarkOurVendorKey]); uploadStr := format(uploadTemplate,[FOrderID,FUserID,FUserPassword,dataFile]); httpRequest := CoWinHTTPRequest.Create; with httpRequest do begin Open('POST',URL, False); SetTimeouts(600000,600000,600000,600000); //10 minute for everything SetRequestHeader('Content-type','application/x-www-form-urlencoded'); SetRequestHeader('Content-length', IntToStr(length(uploadStr))); PushMouseCursor(crHourGlass); try try httpRequest.send(uploadStr); except on e:Exception do begin PopMouseCursor; ShowAlert(atWarnAlert, e.Message); end; end; finally PopMouseCursor; end; if status <> httpRespOK then begin ShowAlert(atWarnAlert, 'The ' + dataFmt + ' file was not uploaded successfully. ' + httpRequest.ResponseText); exit; end end; result := True; end; end.
unit QGame.Scene; interface uses QCore.Types, QCore.Input, Strope.Math; type TScene = class abstract (TComponent) strict private FName: string; public constructor Create(const AName: string); procedure OnInitialize(AParameter: TObject = nil); override; procedure OnActivate(AIsActivate: Boolean); override; procedure OnDraw(const ALayer: Integer); override; procedure OnUpdate(const ADelta: Double); override; procedure OnDestroy; override; function OnMouseMove(const AMousePosition: TVectorF): Boolean; override; function OnMouseButtonDown( AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; override; function OnMouseButtonUp( AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; override; function OnMouseWheel(ADirection: Integer): Boolean; override; function OnKeyDown(AKey: TKeyButton): Boolean; override; function OnKeyUp(AKey: TKeyButton): Boolean; override; property Name: string read FName; end; implementation uses SysUtils; {$REGION ' TScene '} constructor TScene.Create(const AName: string); begin FName := AnsiUpperCase(AName); end; procedure TScene.OnActivate(AIsActivate: Boolean); begin //nothing to do end; procedure TScene.OnDestroy; begin //nothing to do end; procedure TScene.OnDraw(const ALayer: Integer); begin //nothing to do end; procedure TScene.OnInitialize(AParameter: TObject); begin //nothing to do end; function TScene.OnKeyDown(AKey: TKeyButton): Boolean; begin Result := False; end; function TScene.OnKeyUp(AKey: TKeyButton): Boolean; begin Result := False; end; function TScene.OnMouseButtonDown(AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; begin Result := False; end; function TScene.OnMouseButtonUp(AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; begin Result := False; end; function TScene.OnMouseMove(const AMousePosition: TVectorF): Boolean; begin Result := False; end; function TScene.OnMouseWheel(ADirection: Integer): Boolean; begin Result := False; end; procedure TScene.OnUpdate(const ADelta: Double); begin //nothing to do end; {$ENDREGION} end.
{ **************************************************************************** } { } { uMMDBInfo - This module is a part of the MMDB Reader project } { } { Created by Vitaly Yakovlev } { Date: October 22, 2019 } { Copyright: (c) 2019 Vitaly Yakovlev } { Website: http://optinsoft.net/ } { } { License: BSD 2-Clause License. } { } { Redistribution and use in source and binary forms, with or without } { modification, are permitted provided that the following conditions are met: } { } { 1. Redistributions of source code must retain the above copyright notice, } { this list of conditions and the following disclaimer. } { } { 2. Redistributions in binary form must reproduce the above copyright notice, } { this list of conditions and the following disclaimer in the documentation } { and/or other materials provided with the distribution. } { } { THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" } { AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, } { THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR } { PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR } { CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, } { EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, } { PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; } { OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, } { WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR } { OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF } { ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } { } { Last edit by: Vitaly Yakovlev } { Date: January 21, 2021 } { Version: 1.2 } { } { Changelog: } { v1.2: } { - added TMMDBLocation } { - added TMMDBIPCountryCityInfoEx.Location } { } { v1.1: } { - TMMDBIPInfo renamed to TMMDBIPCountryInfo } { - TMMDBIPInfoEx renamed to TMMDBIPCountryInfoEx } { - added TMMDBCityInfo } { - added TMMDBCityInfoEx } { - added TMMDBIPCountryCityInfo } { - added TMMDBIPCountryCityInfoEx } { } { v1.0: } { - Initial release } { } { **************************************************************************** } unit uMMDBInfo; interface uses System.Generics.Collections, uMMDBReader; type TMMDBContinentInfo = class private _code: String; _geoname_id: Int64; public [TMMDBAttribute('code')] property Code: String read _code write _code; [TMMDBAttribute('geoname_id')] property GeonameId: Int64 read _geoname_id write _geoname_id; end; TMMDBCountryInfo = class private _geoname_id: Int64; _iso_code: String; public [TMMDBAttribute('geoname_id')] property GeonameId: Int64 read _geoname_id write _geoname_id; [TMMDBAttribute('iso_code')] property ISOCode: String read _iso_code write _iso_code; end; TMMDBIPCountryInfo = class private _continent: TMMDBContinentInfo; _country: TMMDBCountryInfo; _registered_country: TMMDBCountryInfo; public constructor Create; destructor Destroy; override; // [TMMDBAttribute('continent')] property Continent: TMMDBContinentInfo read _continent; [TMMDBAttribute('country')] property Country: TMMDBCountryInfo read _country; [TMMDBAttribute('registered_country')] property RegisteredCountry: TMMDBCountryInfo read _registered_country; end; TMMDBCityInfo = class private _geoname_id: Int64; public constructor Create; destructor Destroy; override; [TMMDBAttribute('geoname_id')] property GeonameId: Int64 read _geoname_id write _geoname_id; end; TMMDBIPCountryCityInfo = class(TMMDBIPCountryInfo) private _city: TMMDBCityInfo; public constructor Create; destructor Destroy; override; // [TMMDBAttribute('city')] property City: TMMDBCityInfo read _city; end; TMMDBContinentInfoEx = class(TMMDBContinentInfo) private _names: TDictionary<string, string>; public constructor Create; destructor Destroy; override; // [TMMDBAttribute('names')] property Names: TDictionary<string, string> read _names; end; TMMDBCountryInfoEx = class(TMMDBCountryInfo) private _names: TDictionary<string, string>; public constructor Create; destructor Destroy; override; // [TMMDBAttribute('names')] property Names: TDictionary<string, string> read _names; end; TMMDBIPCountryInfoEx = class private _continent: TMMDBContinentInfoEx; _country: TMMDBCountryInfoEx; _registered_country: TMMDBCountryInfoEx; public constructor Create; destructor Destroy; override; // [TMMDBAttribute('continent')] property Continent: TMMDBContinentInfoEx read _continent; [TMMDBAttribute('country')] property Country: TMMDBCountryInfoEx read _country; [TMMDBAttribute('registered_country')] property RegisteredCountry: TMMDBCountryInfoEx read _registered_country; end; TMMDBCityInfoEx = class(TMMDBCityInfo) private _names: TDictionary<string, string>; public constructor Create; destructor Destroy; override; // [TMMDBAttribute('names')] property Names: TDictionary<string, string> read _names; end; TMMDBLocation = class private _accuracy_radius: Integer; _latitude: Double; _longitude: Double; _time_zone: String; public [TMMDBAttribute('accuracy_radius')] property Accuracy: Integer read _accuracy_radius write _accuracy_radius; [TMMDBAttribute('latitude')] property Latitude: Double read _latitude write _latitude; [TMMDBAttribute('longitude')] property Longitude: Double read _longitude write _longitude; [TMMDBAttribute('time_zone')] property TimeZone: String read _time_zone write _time_zone; end; TMMDBIPCountryCityInfoEx = class(TMMDBIPCountryInfoEx) private _city: TMMDBCityInfoEx; _location: TMMDBLocation; public constructor Create; destructor Destroy; override; // [TMMDBAttribute('city')] property City: TMMDBCityInfoEx read _city; [TMMDBAttribute('location')] property Location: TMMDBLocation read _location; end; implementation { TMMDBIPCountryInfo } constructor TMMDBIPCountryInfo.Create; begin _continent := TMMDBContinentInfo.Create; _country := TMMDBCountryInfo.Create; _registered_country := TMMDBCountryInfo.Create; end; destructor TMMDBIPCountryInfo.Destroy; begin _registered_country.Free; _country.Free; _continent.Free; inherited; end; { TMMDBContinentInfoEx } constructor TMMDBContinentInfoEx.Create; begin inherited; _names := TDictionary<string, string>.Create; end; destructor TMMDBContinentInfoEx.Destroy; begin _names.Free; inherited; end; { TMMDBCountryInfoEx } constructor TMMDBCountryInfoEx.Create; begin inherited; _names := TDictionary<string, string>.Create; end; destructor TMMDBCountryInfoEx.Destroy; begin _names.Free; inherited; end; { TMMDBIPCountryInfoEx } constructor TMMDBIPCountryInfoEx.Create; begin _continent := TMMDBContinentInfoEx.Create; _country := TMMDBCountryInfoEx.Create; _registered_country := TMMDBCountryInfoEx.Create; end; destructor TMMDBIPCountryInfoEx.Destroy; begin _registered_country.Free; _country.Free; _continent.Free; inherited; end; { TMMDBCityInfo } constructor TMMDBCityInfo.Create; begin end; destructor TMMDBCityInfo.Destroy; begin inherited; end; { TMMDBIPCountryCityInfo } constructor TMMDBIPCountryCityInfo.Create; begin inherited; _city := TMMDBCityInfo.Create; end; destructor TMMDBIPCountryCityInfo.Destroy; begin _city.Free; inherited; end; { TMMDBCityInfoEx } constructor TMMDBCityInfoEx.Create; begin inherited; _names := TDictionary<string, string>.Create; end; destructor TMMDBCityInfoEx.Destroy; begin _names.Free; inherited; end; { TMMDBIPCountryCityInfoEx } constructor TMMDBIPCountryCityInfoEx.Create; begin inherited; _city := TMMDBCityInfoEx.Create; _location := TMMDBLocation.Create; end; destructor TMMDBIPCountryCityInfoEx.Destroy; begin _location.Free; _city.Free; inherited; end; end.
unit uAtendimentoModel; interface uses uTipos, Data.Win.ADODB, Data.DB; type TAtendimentoModel = class private FAcao: TAcao; FDescricao: String; FDtAtend: TDateTime; FIDAtend: Integer; FCPFPaciente: String; procedure SetAcao(const Value: TAcao); procedure SetCPFPaciente(const Value: String); procedure SetDescricao(const Value: String); procedure SetDtAtend(const Value: TDateTime); procedure SetIDAtend(const Value: Integer); public function GetAtendimentoModel: TADOQuery; function Salvar: Boolean; function GetId(AAutoIncrementar: Integer): Integer; property IDAtend : Integer read FIDAtend write SetIDAtend; property DtAtend : TDateTime read FDtAtend write SetDtAtend; property CPFPaciente : String read FCPFPaciente write SetCPFPaciente; property Descricao : String read FDescricao write SetDescricao; property Acao : TAcao read FAcao write SetAcao; end; implementation { TAtendimento } uses uAtendimentoDao; function TAtendimentoModel.GetAtendimentoModel: TADOQuery; var VAtendimentoDao: TAtendimentoDao; begin VAtendimentoDao := TAtendimentoDao.Create; try Result := VAtendimentoDao.GetAtendimentos; finally VAtendimentoDao.Free; end; end; function TAtendimentoModel.GetId(AAutoIncrementar: Integer): Integer; var VAtendimentoDao: TAtendimentoDao; begin VAtendimentoDao := TAtendimentoDao.Create; try Result := VAtendimentoDao.GetId(AAutoIncrementar); finally VAtendimentoDao.Free; end; end; function TAtendimentoModel.Salvar: Boolean; var VAtendimentoDao: TAtendimentoDao; begin Result := False; VAtendimentoDao := TAtendimentoDao.Create; try case FAcao of uTipos.tacIncluir: Result := VAtendimentoDao.Incluir(Self); uTipos.tacAlterar: Result := VAtendimentoDao.Alterar(Self); uTipos.tacExcluir: Result := VAtendimentoDao.Excluir(Self); end; finally VAtendimentoDao.Free; end; end; procedure TAtendimentoModel.SetAcao(const Value: TAcao); begin FAcao := Value; end; procedure TAtendimentoModel.SetCPFPaciente(const Value: String); begin FCPFPaciente := Value; end; procedure TAtendimentoModel.SetDescricao(const Value: String); begin FDescricao := Value; end; procedure TAtendimentoModel.SetDtAtend(const Value: TDateTime); begin FDtAtend := Value; end; procedure TAtendimentoModel.SetIDAtend(const Value: Integer); begin FIDAtend := Value; end; end.
program Data_Penjualan_Mobil_RadixSort; {I.S. : User memilih sebuah menu dari menu pilihan} {F.S. : Menampilkan hasil dan mengasilkan proses dari menu yang dipilih} uses crt; {Kamus Global} const maksMobil = 20; Type reMobil = record nama : string; terjual : integer; end; arMobil = array[1..maksMobil] of reMobil; point = ^node; node = record info : reMobil; next : point; end; arPoint = array[0..9] of point; var mobil : arMobil; varMobil : reMobil; maksData, i : integer; {------------------ Proses Penciptaan ------------------} procedure penciptaan(var mobil : arMobil); {I.S. : Proses menciptakan array yang akan digunakan} {F.S. : Mengasilkan array yang sudah diciptakan} begin maksData := 4; for i := 1 to maksData do begin mobil[i].nama := ' '; mobil[i].terjual := 0; end; end; //endProcedure {------------------ <<<<<<<<>>>>>>>> -------------------} {------------------ Proses Traversal ------------------} procedure isiData(isiMobil : reMobil); {I.S. : User mengisi semua data sebanyak array} {F.S. : Menghasilkan data yang sudah diisi oleh User} begin mobil[i].nama := isiMobil.nama; mobil[i].terjual := isiMobil.terjual; end; procedure tampilData(mobil : arMobil; maksData : integer); {I.S. : Data makanan telah terdefinisi} {F.S. : Menampilkan semua data makanan yang telah diisi oleh User} begin clrscr; gotoxy(25, 8); writeln(' Tampil Data Mobil '); gotoxy(25, 9); writeln('|---------------------------|'); gotoxy(25,10); writeln('| Nama Mobil | Terjual |'); gotoxy(25,11); writeln('|---------------------------|'); for i := 1 to maksData do begin gotoxy(25,11+i); writeln('| | Unit |'); gotoxy(27,11+i); write(mobil[i].nama); gotoxy(42,11+i); writeln(mobil[i].terjual); end; gotoxy(25,12+maksData); writeln('|---------------------------|'); end; procedure hapusData(posisi : integer); {I.S. : Data yang ingin dihapus telah didefinisi} {F.S. : Menghapus data sesuai keinginan User} begin mobil[posisi].nama := ' '; mobil[posisi].terjual := 0; end; procedure GantiData(isiMobil : reMobil); {I.S. : Data yang ingin ditimpa telah didefinisi} {F.S. : Menimpa data sesuai keinginan User} begin mobil[i].nama := isiMobil.nama; mobil[i].terjual := isiMobil.terjual; end; {------------------ <<<<<<<<>>>>>>>> ------------------} {------------------ Proses Pencarian ------------------} procedure cariData; {I.S. : User memasukkan data mobil yang ingin dicari} {F.S. : Mendapatkan atau tidak mendapatkan informasi mobil yang sesuai dengan yang dicari oleh User} var ketemu : boolean; mobilCari : string; begin gotoxy(43,11); readln(mobilCari); i := 0; ketemu := false; while(not ketemu) and (i <= maksData) do begin if mobil[i].nama = mobilCari then ketemu := true else i := i + 1; //endif end; if(ketemu) then begin gotoxy(22,13); write('|- Nama Mobil = ',mobil[i].nama); gotoxy(56,13);writeln(' -|'); gotoxy(22,14); write('|- Terjual = ',mobil[i].terjual); gotoxy(56,14);writeln(' -|'); gotoxy(22,15); writeln('|-----------------------------------|'); end; //endif if(not ketemu) then begin gotoxy(22,13); write('|- Nama Mobil = '); gotoxy(56,13);writeln(' -|'); gotoxy(22,14); write('|- Terjual = '); gotoxy(56,14);writeln(' -|'); gotoxy(22,15); writeln('|-----------------------------------|'); gotoxy(22,16); writeln('>> ',mobilCari,' tidak ditemukan'); end; //endif end; //endprocedure {------------------ <<<<<<<<>>>>>>>> ------------------} {------------------ Proses Pengurutan ------------------} Procedure masukkanRDX(Var penunjuk : arPoint; dihitung : reMobil; posisi : Integer); {I.S. : Memasukkan data kedalam tabel (Proses Radix Sort)} {F.S. : Mendapatkan data yang sudah dimasukkan kedalam tabel (Proses Radix Sort)} Var P, Q : point; {P & Q adalah inisialisasi dari pointer} begin New (P); P^.info := dihitung; P^.next := Nil; Q := penunjuk [posisi]; if Q = Nil then penunjuk [posisi] := P else begin While Q^.next <> Nil do Q := Q^.next; Q^.next := P; end; end; Procedure isiUlangRDX(Var mobil : arMobil; Var penunjuk : arPoint); {I.S. : Mengisi ulang data yang akan diurutkan dengan metode Radix Sort} {F.S. : Menghasilkan data untuk memenuhi proses pengurutan dengan metode Radix Sort} Var indeks, j : integer; P : point; begin j := 1; For indeks := 9 downto 0 do begin P := penunjuk[indeks]; While P <> Nil do begin mobil[j] := P^.info; P := P^.next; j := j + 1; end; end; For indeks := 9 downto 0 do penunjuk[indeks] := Nil; end; Procedure urutDataRDX(Var mobil : arMobil; maksimal : integer); {I.S. : Data yang akan diurutkan telah terdefinisi} {F.S. : Menghasilkan Data yang telah diurutkan dengan metode Radix Sort secara Descending} Var penunjuk : arPoint; indeks, pembagi, daftarNo : integer; dihitung : reMobil; begin For indeks := 9 downto 0 do penunjuk[indeks] := Nil; pembagi := 1; While pembagi <= 1000 do begin indeks := 1; While indeks <= maksimal do begin dihitung := mobil[indeks]; daftarNo := dihitung.terjual div pembagi mod 10; masukkanRDX(penunjuk, dihitung, daftarNo); indeks := indeks + 1; end; isiUlangRDX(mobil, penunjuk); pembagi := 10 * pembagi; end; end; {------------------ <<<<<<<<>>>>>>>> -------------------} {------------------ Proses Penghancuran ------------------} procedure penghancuran(maksData : integer); {I.S. : User mengembalikan semua Data kenilai awal} {F.S. : Semua Data yang telah diisi dikembalikan ke nilai awal} begin for i := 1 to maksData do begin mobil[i].nama := ' '; mobil[i].terjual := 0; end; gotoxy(25,10); writeln('|----------------------------|'); gotoxy(25,11); writeln('|- Semua Data telah dihapus -|'); gotoxy(25,12); writeln('|----------------------------|'); end; //endProcedure {------------------- <<<<<<<<>>>>>>>> --------------------} {Menu Tampilan} procedure menuMobil(maksData : Integer); {I.S. : User memilih sebuah menu dari Menu pilihan} {F.S. : Menampilkan hasil dan mengasilkan proses dari menu yang dipilih} var pil, hapus : integer; begin repeat clrscr; gotoxy(27, 3); writeln(' Data Penjualan Mobil '); gotoxy(27, 6); writeln(' Menu Pilihan '); gotoxy(27, 7); writeln('-------------------------------'); gotoxy(27, 8); writeln(' 1. Isi Data Mobil '); gotoxy(27, 9); writeln(' 2. Tampil Data Mobil '); gotoxy(27,10); writeln(' 3. Hapus Data Mobil '); gotoxy(27,11); writeln(' 4. Ganti Data Mobil '); gotoxy(27,12); writeln(' 5. Urutkan Data Mobil(Dsc) '); gotoxy(27,13); writeln(' 6. Cari Data Mobil '); gotoxy(27,14); writeln(' 7. Hapus Semua Data Mobil '); gotoxy(27,15); writeln(' 0. Keluar '); gotoxy(27,16); writeln('-------------------------------'); gotoxy(27,17); writeln(' Pilihan Anda ? '); gotoxy(50,17); readln(pil); case (pil) of 1 : begin for i := 1 to maksData do begin clrscr; gotoxy(23, 9); writeln(' Isi Mobil Terjual '); gotoxy(23,10); writeln('-------------------------------'); gotoxy(23,11); writeln('Nama Mobil = '); gotoxy(23,12); writeln('Terjual = Unit '); gotoxy(23,13); writeln('-------------------------------'); gotoxy(41,11); readln(varMobil.nama); gotoxy(41,12); readln(varMobil.terjual); isiData(varMobil); end; gotoxy(23,14); write('>> Tekan Enter untuk Kembali!'); readln; end; 2 : begin clrscr; tampilData(mobil,maksData); gotoxy(25,13+maksData); write('>> Tekan Enter untuk Kembali!'); readln; end; 3 : begin clrscr; gotoxy(22, 9); writeln(' Hapus Mobil Terjual '); gotoxy(22,10); writeln('-----------------------------------'); gotoxy(22,11); writeln('Hapus Data Mobil Keberapa ? '); gotoxy(22,12); writeln('-----------------------------------'); gotoxy(56,11); readln(hapus); hapusData(hapus); gotoxy(22,13); writeln(' Data Ke-',hapus,' Telah Terhapus '); gotoxy(22,14); writeln('|-----------------------------------|'); gotoxy(22,15); write('>> Tekan Enter untuk Kembali!'); readln; end; 4 : begin clrscr; gotoxy(22, 8); writeln(' Ganti Data Mobil Terjual '); gotoxy(22, 9); writeln('----------------------------------------'); gotoxy(22,10); writeln('Ganti Data Mobil Keberapa ? '); gotoxy(22,11); writeln('----------------------------------------'); gotoxy(22,12); writeln(' Nama Mobil = '); gotoxy(22,13); writeln(' Terjual = Unit '); gotoxy(22,14); writeln('-------------------------------------'); gotoxy(56,10); readln(i); gotoxy(42,12); readln(varMobil.nama); gotoxy(42,13); readln(varMobil.terjual); GantiData(varMobil); gotoxy(22,15); write('>> Tekan Enter untuk Kembali!'); readln; end; 5 : begin clrscr; urutDataRDX(mobil,maksData); gotoxy(18,10); writeln(' Data telah diurutkan secara Descending '); gotoxy(18,11); writeln(' Berdasarkan Jumlah Terjualnya '); gotoxy(18,12); writeln('--------------------------------------------'); gotoxy(18,13); write('>> Tekan Enter untuk Kembali!'); readln; end; 6 : begin clrscr; gotoxy(22, 9); writeln(' Cari Mobil '); gotoxy(22,10); writeln('------------------------------------'); gotoxy(22,11); writeln(' Nama Mobil ? '); gotoxy(22,12); writeln('------------------------------------'); cariData; gotoxy(22,17); write('>> Tekan Enter untuk Kembali!'); readln; end; 7 : begin clrscr; penghancuran(maksData); gotoxy(25,13); write('>> Tekan Enter untuk Kembali!'); readln; end; 0 : begin clrscr; gotoxy(16,11); writeln(' Terimakasih telah menggunakan Program Kami '); gotoxy(16,12); writeln(' ---------------------------------------------- '); gotoxy(16,13); write('>> Tekan Enter untuk Keluar!'); readln; end; else begin gotoxy(27,19); writeln('>> Anda Salah memasukkan Nilai'); gotoxy(27,20); write('>> Tekan Enter untuk Mengulangi!'); readln; end; end; //endcase until(pil = 0); end; {Program Utama} begin textbackground(green); textcolor(yellow); penciptaan(mobil); menuMobil(maksData); end.
unit Aspect4D; interface uses System.SysUtils, System.Rtti; type EAspectException = class(Exception); AspectAttribute = class(TCustomAttribute); TAspect = class abstract(TInterfacedObject) private { private declarations } protected { protected declarations } public { public declarations } end; IAspect = interface ['{7647B37E-7BEA-42BD-ADEE-E719AF3C6CE9}'] function GetName: string; procedure DoBefore(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out invoke: Boolean; out result: TValue); procedure DoAfter(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; var result: TValue); procedure DoException(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out raiseException: Boolean; theException: Exception; out result: TValue); property Name: string read GetName; end; IAspectWeaver = interface ['{211E40BC-753F-4865-BB35-9CF81F1435C7}'] procedure Proxify(instance: TObject); procedure Unproxify(instance: TObject); end; IAspectContext = interface ['{962E0295-9091-41CA-AF39-F6FD41174231}'] procedure &Register(aspect: IAspect); function Weaver: IAspectWeaver; end; implementation end.
unit FrameRTMotor; interface uses SysUtils, Forms, Rda_TLB, Menus, StdCtrls, ExtCtrls, Controls, Classes, Antena; type TFrame_RTMotor = class(TFrame) Panel2: TPanel; Edit4: TEdit; Edit3: TEdit; Panel1: TPanel; PopupMenu2: TPopupMenu; Angulo1: TMenuItem; Codigo1: TMenuItem; PopupMenu1: TPopupMenu; RPM1: TMenuItem; CPS1: TMenuItem; Antenna: TAntenna; Label1: TLabel; Label2: TLabel; procedure RPM1Click(Sender: TObject); protected function AngleText( Position : integer ) : string; function SpeedText( Speed : integer ) : string; function TextAngle( Text : string ) : integer; function TextSpeed( Text : string ) : integer; private fMotor : IMotorStatus; fControl : IMotorControl; procedure SetMotor( Value : IMotorStatus ); public procedure UpdateView; published property Motor : IMotorStatus read fMotor write SetMotor; property Control : IMotorControl read fControl; end; var Frame_RTMotor: TFrame_RTMotor; implementation {$R *.DFM} uses ElbrusTypes, Angle, Speed; { TFrame_Motor } procedure TFrame_RTMotor.SetMotor(Value: IMotorStatus); begin fMotor := Value; if assigned(fMotor) then fMotor.QueryInterface(IMotorControl, fControl) else fControl := nil; end; function TFrame_RTMotor.AngleText(Position: integer): string; begin if Codigo1.Checked then Result := IntToStr(Position) else if (Antenna.AntennaType = at_Elevation) and (Position >= 2048) then Result := Format('%.1f', [CodeAngle(Position) - 360]) else Result := Format('%.1f', [CodeAngle(Position)]); end; function TFrame_RTMotor.SpeedText(Speed: integer): string; begin if CPS1.Checked then Result := IntToStr(Speed) else Result := Format('%.1f', [CodeSpeed(Speed)]); end; function TFrame_RTMotor.TextAngle(Text: string): integer; begin if Codigo1.Checked then Result := StrToInt(Text) else Result := AngleCode(StrToFloat(Text)); end; function TFrame_RTMotor.TextSpeed(Text: string): integer; begin if CPS1.Checked then Result := StrToInt(Text) else Result := SpeedCode(StrToFloat(Text)); end; procedure TFrame_RTMotor.UpdateView; begin if assigned(Motor) then begin Antenna.Position := Motor.Posicion; Edit3.Text := AngleText(Antenna.Position); Edit4.Text := SpeedText(Motor.Velocidad); end; end; procedure TFrame_RTMotor.RPM1Click(Sender: TObject); begin inherited; (Sender as TMenuItem).Checked := true; UpdateView; end; end.
unit Graphdlg; interface uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons, StdCtrls, ExtCtrls; type TGraphCreateDlg = class(TForm) Panel1: TPanel; Panel2: TPanel; Panel5: TPanel; Panel3: TPanel; Panel4: TPanel; Panel6: TPanel; Panel7: TPanel; Panel8: TPanel; Panel9: TPanel; Panel10: TPanel; Panel11: TPanel; GroupBox1: TGroupBox; Panel12: TPanel; GroupBox2: TGroupBox; Label1: TLabel; CaptionEdit: TEdit; Label2: TLabel; Label3: TLabel; ComboX: TComboBox; ComboY: TComboBox; Label4: TLabel; Label5: TLabel; EditScaleX: TEdit; EditScaleY: TEdit; Panel13: TPanel; Panel14: TPanel; Panel15: TPanel; Panel16: TPanel; Panel17: TPanel; BitBtn1: TBitBtn; Panel18: TPanel; Label6: TLabel; TaktEdit: TEdit; Label7: TLabel; procedure FormCreate(Sender: TObject); procedure ComboXChange(Sender: TObject); procedure ComboYChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var GraphCreateDlg: TGraphCreateDlg; implementation {$R *.DFM} procedure TGraphCreateDlg.FormCreate(Sender: TObject); begin ComboX.Items.LoadFromFile('Vals.txt'); ComboY.Items.LoadFromFile('Vals.txt'); end; procedure TGraphCreateDlg.ComboXChange(Sender: TObject); begin CaptionEdit.Text:=CaptionEdit.Text+' '+ComboX.Text; end; procedure TGraphCreateDlg.ComboYChange(Sender: TObject); begin CaptionEdit.Text:=CaptionEdit.Text+' '+ComboY.Text; end; end.
unit CurrencyMovement; interface uses AncestorEditDialog, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, cxControls, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils, dsdGuides, cxDropDownEdit, cxCalendar, cxMaskEdit, cxButtonEdit, cxTextEdit, cxCurrencyEdit, Vcl.Controls, cxLabel, dsdDB, dsdAction, System.Classes, Vcl.ActnList, cxPropertiesStore, dsdAddOn, Vcl.StdCtrls, cxButtons, dxSkinsCore, dxSkinsDefaultPainters, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue; type TCurrencyMovementForm = class(TAncestorEditDialogForm) cxLabel1: TcxLabel; Код: TcxLabel; edOperDate: TcxDateEdit; ceAmount: TcxCurrencyEdit; cxLabel7: TcxLabel; edCurrencyTo: TcxButtonEdit; GuidesCurrencyTo: TdsdGuides; cxLabel6: TcxLabel; GuidesFiller: TGuidesFiller; edCurrencyFrom: TcxButtonEdit; cxLabel8: TcxLabel; cxLabel10: TcxLabel; edComment: TcxTextEdit; GuidesCurrencyFrom: TdsdGuides; edInvNumber: TcxTextEdit; ceParValue: TcxCurrencyEdit; cxLabel2: TcxLabel; private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} initialization RegisterClass(TCurrencyMovementForm); end.
unit UBinaryImages; interface uses Graphics; type TCBinaryImage = class private ImgHeight: word; ImgWidth: word; ImgPixels: array of array of boolean; procedure SetHeight(newHeight: word); function GetHeight: word; procedure SetWidth(newWidth: word); function GetWidth: word; procedure SetPixelValue(i, j: integer; value: boolean); function GetPixelValue(i, j: integer): boolean; procedure InitPixels; procedure FreePixels; procedure Copy(From: TCBinaryImage); public constructor Create; constructor CreateCopy(From: TCBinaryImage); destructor FreeBinaryImage; function SaveToBitMap: TBitmap; property Height: word read GetHeight write SetHeight; property Width: word read GetWidth write SetWidth; property Pixels[row, col: integer]: boolean read GetPixelValue write SetPixelValue; procedure Invert; procedure SaveToFile(FileName: string); procedure dilatation(Mask: TCBinaryImage; MaskRow, MaskCol: word); procedure erosion(Mask: TCBinaryImage; MaskRow, MaskCol: word); procedure closing(Mask: TCBinaryImage; MaskRow, MaskCol: word); procedure opening(Mask: TCBinaryImage; MaskRow, MaskCol: word); end; implementation uses UPixelConvert, SysUtils, UBitmapFunctions; constructor TCBinaryImage.Create; begin inherited; self.ImgHeight := 0; self.ImgWidth := 0; end; destructor TCBinaryImage.FreeBinaryImage; begin self.FreePixels; inherited; end; procedure TCBinaryImage.FreePixels; var i: word; begin if (self.ImgHeight > 0) and (self.ImgWidth > 0) then begin for i := 0 to self.ImgHeight - 1 do begin SetLength(self.ImgPixels[i], 0); Finalize(self.ImgPixels[i]); self.ImgPixels[i] := nil; end; SetLength(self.ImgPixels, 0); Finalize(self.ImgPixels); self.ImgPixels := nil; end; end; procedure TCBinaryImage.InitPixels; var i, j: word; begin if (self.ImgHeight > 0) and (self.ImgWidth > 0) then begin SetLength(self.ImgPixels, self.ImgHeight); for i := 0 to self.ImgHeight - 1 do begin SetLength(self.ImgPixels[i], self.ImgWidth); for j := 0 to self.ImgWidth - 1 do self.ImgPixels[i, j] := false; end; end; end; function TCBinaryImage.GetPixelValue(i, j: integer): boolean; begin if i < 0 then i := 0; if i >= self.ImgHeight then i := self.ImgHeight - 1; if j < 0 then j := 0; if j >= self.ImgWidth then j := self.ImgWidth - 1; GetPixelValue := self.ImgPixels[i, j]; end; procedure TCBinaryImage.SetPixelValue(i, j: integer; value: boolean); begin if i < 0 then i := 0; if i >= self.ImgHeight then i := self.ImgHeight - 1; if j < 0 then j := 0; if j >= self.ImgWidth then j := self.ImgWidth - 1; self.ImgPixels[i, j] := value; end; procedure TCBinaryImage.SetHeight(newHeight: word); begin FreePixels; self.ImgHeight := newHeight; self.InitPixels; end; function TCBinaryImage.GetHeight: word; begin GetHeight := self.ImgHeight; end; procedure TCBinaryImage.SetWidth(newWidth: word); begin FreePixels; self.ImgWidth := newWidth; self.InitPixels; end; function TCBinaryImage.GetWidth: word; begin GetWidth := self.ImgWidth; end; function TCBinaryImage.SaveToBitMap: TBitmap; var i, j: word; BM: TBitmap; p: TColorPixel; line: pByteArray; begin p := TColorPixel.Create; BM := TBitmap.Create; BM.PixelFormat := pf24bit; BM.Height := self.ImgHeight; BM.Width := self.ImgWidth; for i := 0 to self.ImgHeight - 1 do begin line := BM.ScanLine[i]; for j := 0 to self.ImgWidth - 1 do begin if self.ImgPixels[i, j] then p.SetRGB(0, 0, 0) else p.SetRGB(1, 1, 1); line[3 * j + 2] := round(p.Red * 255); line[3 * j + 1] := round(p.Green * 255); line[3 * j + 0] := round(p.Blue * 255); end; end; SaveToBitMap := BM; p.Free; end; procedure TCBinaryImage.Invert; var i, j: word; begin for i := 0 to self.ImgHeight - 1 do for j := 0 to self.ImgWidth - 1 do self.ImgPixels[i, j] := not self.ImgPixels[i, j]; end; procedure TCBinaryImage.dilatation(Mask: TCBinaryImage; MaskRow, MaskCol: word); var i, j, AreaI, AreaJ, Mi, Mj: integer; r: TCBinaryImage; begin r := TCBinaryImage.Create; r.Height := self.ImgHeight; r.Width := self.ImgWidth; for i := 0 to r.Height - 1 do for j := 0 to r.Width - 1 do if self.Pixels[i, j] then begin Mi := 0; for AreaI := i - MaskRow to i + (Mask.Height - 1 - MaskRow) do begin Mj := 0; for AreaJ := j - MaskCol to j + (Mask.Width - 1 - MaskCol) do begin if (AreaI >= 0) and (AreaI <= r.Height - 1) and (AreaJ >= 0) and (AreaJ <= r.Width - 1) then r.Pixels[AreaI, AreaJ] := self.Pixels[AreaI, AreaJ] or Mask.Pixels[Mi, Mj] or r.Pixels[AreaI, AreaJ]; Mj := Mj + 1; end; Mi := Mi + 1; end; end; self.Copy(r); r.FreeBinaryImage; end; procedure TCBinaryImage.erosion(Mask: TCBinaryImage; MaskRow, MaskCol: word); var i, j, AreaI, AreaJ, Mi, Mj: integer; fl: boolean; r: TCBinaryImage; begin r := TCBinaryImage.Create; r.Height := self.ImgHeight; r.Width := self.ImgWidth; for i := 0 to r.Height - 1 do for j := 0 to r.Width - 1 do begin fl := true; Mi := 0; for AreaI := i - MaskRow to i + (Mask.Height - 1 - MaskRow) do begin Mj := 0; for AreaJ := j - MaskCol to j + (Mask.Width - 1 - MaskCol) do begin if (AreaI >= 0) and (AreaI <= r.Height - 1) and (AreaJ >= 0) and (AreaJ <= r.Width - 1) then begin if Mask.Pixels[Mi, Mj] then fl := fl and self.Pixels[AreaI, AreaJ]; end else fl := false; Mj := Mj + 1; end; Mi := Mi + 1; end; r.Pixels[i, j] := fl; end; self.Copy(r); r.FreeBinaryImage; end; procedure TCBinaryImage.closing(Mask: TCBinaryImage; MaskRow, MaskCol: word); begin self.dilatation(Mask, MaskRow, MaskCol); self.erosion(Mask, MaskRow, MaskCol); end; procedure TCBinaryImage.opening(Mask: TCBinaryImage; MaskRow, MaskCol: word); begin self.erosion(Mask, MaskRow, MaskCol); self.dilatation(Mask, MaskRow, MaskCol); end; procedure TCBinaryImage.Copy(From: TCBinaryImage); var i, j: word; begin self.Height := From.Height; self.Width := From.Width; for i := 0 to self.Height - 1 do for j := 0 to self.Width - 1 do self.Pixels[i, j] := From.Pixels[i, j]; end; constructor TCBinaryImage.CreateCopy(From: TCBinaryImage); begin inherited; self.Copy(From); end; procedure TCBinaryImage.SaveToFile(FileName: string); var BM: TBitmap; begin BM := self.SaveToBitMap; UBitmapFunctions.SaveToFile(BM, FileName); BM.Free; end; end.
UNIT Search; {$D-} {$N+} INTERFACE USES Graph, CUPSmupp, CUPS, CUPSgui; TYPE YValueFunc = FUNCTION(XValue:Real; VAR nValue:Integer):Real; FastYValueFunc = FUNCTION(XValue:Real):Real; VAR FuncYValue : YValueFunc; FuncFastYValue : FastYValueFunc; AbortedSearch: boolean; PROCEDURE SearchForZero(YName,XName:String;lowestV:Real; VAR XValue:real); PROCEDURE FastSearchForZero(minX,maxX:real; VAR XValue:real); IMPLEMENTATION CONST searchBackColor : integer = blue; searchTextColor : integer = white; searchHiBackColor : integer = black; searchHiTextColor : integer = white; searchErrorColor : integer = red; XSTEP : real = 0.0000005; {These are the exit criteria} YSTEP : real = 0.000001; MAXCOUNT : real = 50; NUMSIZE = 10; xCol : Integer = 65; {position for printing on screen} row1 : Integer = 6; row2 : Integer = 9; errorCol : Integer = 14; errorRow : Integer = 12; countCol : Integer = 13; countRow : Integer = 23; VAR upYValue, lowYValue : Real; UpNValue, lowNValue : Integer; inputStr1,inputStr2 : String; {for requesting input} PROCEDURE SetHuntZeroHelpScreen(VAR A:HelpScrType); VAR OK : Boolean; i : Integer; BEGIN FOR i:=1 TO 25 DO A[i] := ''; A[1] := ' This facility illustrates the principle of'; A[2] := ' finding eigenvalues by the method of "hunt'; A[3] := ' and shoot". '; A[4] := ' '; A[5] := ' Before you can use it, you need to know TWO'; A[6] := ' values of the binding energy for which the'; A[7] := ' solution of the equation diverges for large'; A[8] := ' values of x - up for one energy, down for the'; A[9] := ' other. You should have been able to find two'; A[10] := ' such values by using the TRY ENERGY menu item.'; A[11] := ' '; A[12] := ' Since solutions of the wave equation are real'; A[13] := ' exponentials where the potential is zero, the'; A[14] := ' fact that the solution diverges for large x'; A[15] := ' means that a part of the solution is a'; A[16] := ' DIVERGING exponential there. The condition'; A[17] := ' for an eigenfunction is that this part of the'; A[18] := ' solution has zero amplitude.'; A[19] := ' '; A[20] := ' This part of the program chooses energies'; A[21] := ' between the two values you give it, by finer'; A[22] := ' and finer bisection, until it gets to a value'; A[23] := ' for which the solution does not diverge.'; A[24] := ''; A[25] := ' Press <Enter> or click the mouse to continue.'; END; PROCEDURE DisplayBackgroundScreen(YName,XName:String; lowestV,maxX,minX:Real); BEGIN DefineViewport(20,0.00,1.00, 0.00,1.00); OpenViewport(20); SetFillStyle(SolidFill,blue); HideCursor; WITH views[20] DO Bar(Vx1+1,Vy1+1,Vx2-1,Vy2-1); ShowCursor; inputStr1 := concat(' First value of the binding energy (0<EB<', NumStr(abs(lowestV),3,0), ') :'); inputStr2 := concat(' Second value of the binding energy (0<EB<', NumStr(abs(lowestV),3,0), ') :'); SetColor(white); Print(1,1, ' The Schroedinger equation is solved by hunting for a binding energy for'); Print(1,2, ' which the solution at large positive x behaves like a exponential which'); Print(1,3, ' converges to zero. You will be asked to supply two values of EB for which '); Print(1,4, ' the DIVERGING exponential part of the solutions are of different sign. '); Print(1,row1,inputStr1); Print(1,row1+1, ' Diverging exponential part of wave function (large x) ='); Print(1,row2, inputStr2); Print(1,row2+1,' Diverging exponential part of wave function (large x) ='); SetColor(yellow); Print(xCol,row1,NumStr(maxX,3,0)); Print(xCol,row2,NumStr(minX,3,0)); END; PROCEDURE RequestAnEntry(i:Integer; VAR x:Real; VAR escape:Boolean); VAR thisInputScreen : TInputScreen; thisHelpScreen : HelpScrType; BEGIN SetHuntZeroHelpScreen(thisHelpScreen); WITH thisInputScreen DO BEGIN Init; SetHelpScreen(thisHelpScreen); DefineInputPort(0.02,0.98, (0.85-i*0.15),(0.95-i*0.15)); IF i=1 THEN LoadLine(concat(inputStr1,' { }')) ELSE LoadLine(concat(inputStr2,' { }')); LoadLine(' [ Ok ] [Cancel] [ Help ]'); SetNumber(1,x); AcceptScreen; escape := Canceled; IF NOT escape THEN x := GetNumber(1); Done; END; END; PROCEDURE ShowValue(row:Integer; thisValue:Real); VAR message : String; thisRow : Integer; oldVNum : Integer; BEGIN oldVNum := viewportNumber; SelectViewport(20); message := NumStr(thisValue,8,6); RubOut(xCol,row,9,blue); SetColor(yellow); Print(xCol,row,message); SelectViewport(oldVNum); END; PROCEDURE ShowXValue(i:integer; thisXValue:real); BEGIN IF i=1 THEN ShowValue(row1,thisXValue); IF i=2 THEN ShowValue(row2,thisXValue); END; PROCEDURE ShowYValue(i:Integer; ThisYValue:Real); VAR message : String; thisRow : Integer; BEGIN IF i=1 THEN ShowValue(row1+1,-thisYValue); IF i=2 THEN ShowValue(row2+1,-thisYValue); END; PROCEDURE PrintErrorMessage(thisStr:String); VAR oldVNum : Integer; BEGIN oldVNum := viewportNumber; SelectViewport(20); RubOut(errorCol-1,errorRow, length(thisStr)+2,searchErrorColor); SetColor(white); Print (errorCol,errorRow,thisStr); Beep; SelectViewport(oldVNum); END; PROCEDURE EraseErrorMessage(thisStr:String); VAR oldVNum : Integer; BEGIN oldVNum := viewportNumber; SelectViewport(20); RubOut(errorCol-1,errorRow, length(thisStr)+2,blue); SelectViewport(oldVNum); END; PROCEDURE PrepareForCounter; VAR oldVNum : Integer; BEGIN oldVNum := viewportNumber; SelectViewport(20); SetColor(white); Print (4,countRow-1, 'Number of bisections'); SelectViewport(oldVNum); END; PROCEDURE ShowCounter(n:Integer); VAR oldVNum : Integer; BEGIN oldVNum := viewportNumber; SelectViewport(20); RubOut(countCol-1,countRow, 4,searchErrorColor); SetColor(white); Print (countCol,countRow, NumStr(n,2,0)); SelectViewport(oldVNum); END; PROCEDURE NarrowNodes(VAR maxX,minX:Real; VAR goOn:Boolean); VAR thisYValue : Real; thisXValue : Real; thisNValue : Integer; dNup,dNlow : Integer; PROCEDURE PutThisAsUp; BEGIN maxX := thisXValue; upNValue := thisNValue; upYValue := thisYValue END; PROCEDURE PutThisAsLow; BEGIN minX := thisXValue; lowNValue := thisNValue; lowYValue := thisYValue; END; BEGIN thisXValue := (MaxX+MinX)/2; thisYValue := FuncYValue(thisXValue,thisNValue); dNup := abs(upNValue - thisNValue); dNlow := abs(thisNValue - lowNValue); IF (thisYValue*upYValue)<=0 THEN { an acceptable pair of bounds has been found } BEGIN goOn := true; IF dNup<dNlow THEN PutThisAsUp ELSE PutThisAsLow; END ELSE { number of nodes is even and greater than 2 } BEGIN goOn := false; IF dNup=0 THEN PutThisAsUp; IF dNlow=0 THEN PutThisAsLow; IF (dNup<>0) AND (dNlow<>0) THEN IF dNup<dNlow THEN PutThisAsUp ELSE PutThisAsLow; END; END; FUNCTION OKtoProceed(VAR maxX,minX:Real): boolean; CONST blank = ' '; error1 = 'THERE ARE NO EIGENVALUES IN THIS RANGE. TRY AGAIN. '; error2 = 'SEVERAL EIGENVALUES IN THIS RANGE. I WILL FIND ONE.'; VAR goOn : Boolean; BEGIN EraseErrorMessage(blank); IF ((upYValue*lowYValue)<0) {If the input values give asymptotes of different sign proceed } OR ((upYValue=0) AND (lowYValue<>0)) OR ((lowYValue=0) AND (upYValue<>0)) THEN OKToProceed := true ELSE { otherwise we have to count nodes to get a workable starting range } BEGIN IF abs(UpNValue-lowNValue)=0 THEN BEGIN PrintErrorMessage(error1); OKtoProceed := false; END ELSE BEGIN goOn := false; PrintErrorMessage(error2); WHILE NOT goOn DO NarrowNodes(maxX,minX,goOn); OKtoProceed := true; END; END; END; PROCEDURE InitializeSearch(VAR YName,XName:String; lowestV:Real; VAR XValue:Real; VAR nValue:Integer; VAR searchCounter:Integer; VAR maxX,minX:Real); CONST Blank = ' '; Error = 'THE VALUE IS NOT WITHIN THE ALLOWED RANGE. TRY AGAIN. '; VAR i,tmp : Integer; thisYValue,temp : Real; temporaryString : String; act : Char; OKFlag,inRange : Boolean; BEGIN maxX := abs(lowestV*0.99); minX := abs(lowestV*0.01); SearchCounter := 0; DisplayBackgroundScreen(YName,XName,lowestV,maxX,minX); REPEAT i := 1; REPEAT REPEAT IF i=1 THEN XValue := maxX ELSE XValue := minX; RequestAnEntry(i,XValue,abortedSearch); IF abortedSearch THEN EXIT; IF (XValue>0) AND (XValue<abs(lowestV)) THEN BEGIN inRange := true; EraseErrorMessage(blank); END ELSE BEGIN PrintErrorMessage(error); inRange := false; END; UNTIL inRange; thisYValue := FuncYValue(XValue,NValue); IF i=1 THEN BEGIN MaxX := XValue; upYValue := thisYValue; UpNValue := NValue; END ELSE BEGIN MinX := XValue; lowYValue := thisYValue; LowNValue := NValue; END; ShowXValue(i,XValue); ShowYValue(i,ThisYValue); i := i + 1; UNTIL i>2; UNTIL OKToProceed(maxX,minX); IF MinX>MaxX THEN BEGIN temp := MaxX; MaxX := MinX; MinX := temp; temp:=upYValue; upYValue:=lowYValue; lowYValue:=temp; tmp :=UpNValue; UpNValue:=LowNValue; LowNValue:=tmp; ShowXValue(1,maxX); ShowXValue(2,minX); ShowYValue(1,upYValue); ShowYValue(2,lowYValue); END; PrepareForCounter; END; PROCEDURE Narrowbounds(VAR XValue:real; VAR nValue:Integer; VAR searchCounter: integer; VAR maxX,minX: real); VAR ThisYValue : real; UpLow: integer; {counter: 1 for upper, 2 for lower} BEGIN SearchCounter := SearchCounter + 1; XValue := (MaxX+MinX)/2; ThisYValue := FuncYValue(XValue,nValue); IF (ThisYValue*upYValue)>=0 THEN BEGIN MaxX := XValue; UpLow := 1; END ELSE BEGIN MinX := XValue; UpLow := 2; END; ShowXValue(UpLow,XValue); ShowYValue(UpLow,ThisYValue); IF UpLow=1 THEN upYValue:=ThisYValue ELSE lowYValue:=ThisYValue; ShowCounter(searchCounter); END; FUNCTION ReadyToExit(searchCounter:integer; maxX,minX:real): boolean; BEGIN ReadyToExit := false; IF AbortedSearch THEN ReadyToExit := true; IF (SearchCounter>MAXCOUNT-1) THEN ReadyToExit := true; IF ((MaxX-MinX)<XSTEP) THEN ReadyToExit := true; IF (abs(upYValue)<YSTEP) THEN ReadyToExit := true; IF (abs(lowYValue)<YSTEP) THEN ReadyToExit := true; END; PROCEDURE SearchForZero(YName,XName:String; lowestV:Real; VAR XValue:real); VAR searchCounter : Integer; maxX,minX : Real; nValue : Integer; BEGIN IF xStep<macheps THEN xStep := macheps; IF yStep<macheps THEN yStep := macheps; AbortedSearch := false; InitializeSearch(YName,XName,lowestV,xValue,nValue, searchCounter,maxX,minX); IF NOT AbortedSearch THEN BEGIN WHILE NOT ReadyToExit(searchCounter,maxX,minX) DO NarrowBounds(xValue,nValue,searchCounter, maxX,minX); IF upYValue<>lowYValue THEN XValue := (upYValue*MinX-lowYValue*MaxX)/(upYValue-lowYValue) ELSE XValue := (MaxX+MinX)/2; END; END; PROCEDURE FastSearchForZero(minX,maxX:real; VAR XValue:real); VAR searchCounter: integer; temp,thisYvalue: real; upLow: integer; BEGIN IF xStep<macheps THEN xStep := macheps; IF yStep<macheps THEN yStep := macheps; abortedSearch := false; searchCounter := 0; IF MinX>MaxX THEN BEGIN Temp := MaxX; MaxX := MinX; MinX := Temp; END; upYValue := FuncFastYValue(maxX); lowYValue:= FuncFastYValue(minX); WHILE NOT ReadyToExit(searchCounter,maxX,minX) DO BEGIN searchCounter := searchCounter+1; {IF upYValue<>lowYValue THEN XValue := (upYValue*MinX-lowYValue*MaxX)/(upYValue-lowYValue) ELSE} XValue := (MaxX+MinX)/2; ThisYValue := FuncFastYValue(XValue); IF (ThisYValue*upYValue)>=0 THEN BEGIN MaxX := XValue; UpLow := 1; END ELSE BEGIN MinX := XValue; UpLow := 2; END; END; {while not readyToExit} END; BEGIN END.
unit win.x64; interface function DisableWowRedirection: Boolean; function RevertWowRedirection: Boolean; implementation uses Windows; function IsWin64: boolean; var Kernel32Handle: THandle; IsWow64Process: function(Handle: Windows.THandle; var Res: Windows.BOOL): Windows.BOOL; stdcall; GetNativeSystemInfo: procedure(var lpSystemInfo: TSystemInfo); stdcall; isWoW64: Bool; SystemInfo: TSystemInfo; const PROCESSOR_ARCHITECTURE_AMD64 = 9; PROCESSOR_ARCHITECTURE_IA64 = 6; begin Result := False; Kernel32Handle := GetModuleHandle('KERNEL32.DLL'); if Kernel32Handle = 0 then Kernel32Handle := LoadLibrary('KERNEL32.DLL'); if Kernel32Handle <> 0 then begin IsWOW64Process := GetProcAddress(Kernel32Handle,'IsWow64Process'); //GetNativeSystemInfo函数从Windows XP开始才有,而IsWow64Process函数从Windows XP SP2以及Windows Server 2003 SP1开始才有。 //所以使用该函数前最好用GetProcAddress。 GetNativeSystemInfo := GetProcAddress(Kernel32Handle,'GetNativeSystemInfo'); if Assigned(IsWow64Process) then begin IsWow64Process(GetCurrentProcess, isWoW64); Result := isWoW64 and Assigned(GetNativeSystemInfo); if Result then begin GetNativeSystemInfo(SystemInfo); Result := (SystemInfo.wProcessorArchitecture = PROCESSOR_ARCHITECTURE_AMD64) or (SystemInfo.wProcessorArchitecture = PROCESSOR_ARCHITECTURE_IA64); end; end; end; end; (*// 在64位Windows系统中运行的32位程序会被系统欺骗. 例如windows\system32的目录实际是windows\syswow64目录的映射. program files实际是program files(x86)的映射. 注册表的hkey_local_machine\software实际是hkey_local_machine\software\wow6432node子键的映射. 那么如何访问到真正的64位程序的目录和注册表呢? 关掉目录重定向即可. 关闭文件的重定向 //*) function DisableWowRedirection: Boolean; type TWow64DisableWow64FsRedirection = function(var Wow64FsEnableRedirection: LongBool): LongBool; stdcall; var tmpHandle: THandle; Wow64DisableWow64FsRedirection: TWow64DisableWow64FsRedirection; OldWow64RedirectionValue: LongBool; begin Result := true; try tmpHandle := GetModuleHandle('kernel32.dll'); if (0 <> tmpHandle) then begin @Wow64DisableWow64FsRedirection := GetProcAddress(tmpHandle, 'Wow64DisableWow64FsRedirection'); if (nil <> @Wow64DisableWow64FsRedirection) then begin Wow64DisableWow64FsRedirection(OldWow64RedirectionValue); end; end; except Result := False; end; end; function RevertWowRedirection: Boolean; type TWow64RevertWow64FsRedirection = function(var Wow64RevertWow64FsRedirection: LongBool): LongBool; stdcall; var tmpHandle: THandle; Wow64RevertWow64FsRedirection: TWow64RevertWow64FsRedirection; OldWow64RedirectionValue: LongBool; begin Result := true; try tmpHandle := GetModuleHandle('kernel32.dll'); @Wow64RevertWow64FsRedirection := GetProcAddress(tmpHandle, 'Wow64RevertWow64FsRedirection'); if (0 <> tmpHandle) then begin if (nil <> @Wow64RevertWow64FsRedirection) then begin Wow64RevertWow64FsRedirection(OldWow64RedirectionValue); end; end; except Result := False; end; end; (*// 注册表就很简单了. var r: TRegistry; begin r := TRegistry.Create; r.RootKey := HKEY_LOCAL_MACHINE; r.Access := r.Access or KEY_WOW64_64KEY; //注意这一行. if r.OpenKey('SOFTWARE\abc', true) then begin r.WriteString('test', 'test'); end; r.Free; end; //*) end.
unit InfoDlg; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids, StdCtrls, Buttons, ExtCtrls, DBCtrls, Db; type TfrmInfoDlg = class(TForm) Panel1: TPanel; btnClose: TBitBtn; Panel2: TPanel; grdInfo: TStringGrid; DataSource1: TDataSource; DBNavigator1: TDBNavigator; procedure btnCloseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure DBNavigator1Click(Sender: TObject; Button: TNavigateBtn); private { Private declarations } FDataSet: TDataSet; procedure FillGrid; public { Public declarations } published property DataSet:TDataSet read FDataSet write FDataSet; end; implementation {$R *.DFM} procedure TfrmInfoDlg.btnCloseClick(Sender: TObject); begin Close; end; procedure TfrmInfoDlg.FormCreate(Sender: TObject); begin grdInfo.ColWidths[0] := 150; grdInfo.ColWidths[1] := 200; end; procedure TfrmInfoDlg.FormShow(Sender: TObject); begin DataSource1.DataSet := DataSet; grdInfo.RowCount := DataSet.FieldCount; FillGrid; end; procedure TfrmInfoDlg.FillGrid; var i: integer; begin for i := 0 to DataSet.FieldCount-1 do begin grdInfo.Cells[0,i] := DataSet.Fields[i].DisplayLabel; grdInfo.Cells[1,i] := DataSet.Fields[i].Text; end; end; procedure TfrmInfoDlg.DBNavigator1Click(Sender: TObject; Button: TNavigateBtn); begin FillGrid; end; end.
unit FontStyles; // FontStyles : 字体风格的展示 (***** Code Written By Huang YanLai *****) interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,Menus,StdCtrls,IniFiles; type TFontStyles = class; TFontStyleItem = class(TCollectionItem) private FFont: TFont; FStylename: string; procedure SetFont(const Value: TFont); function GetBackGroundColor: TColor; procedure SetStylename(const Value: string); protected function GetDisplayName: string; override; public constructor Create(Collection: TCollection); override; destructor destroy; override; procedure Assign(Source: TPersistent); override; procedure Draw(ACanvas: TCanvas; ARect: TRect; Selected: Boolean); procedure Measure(ACanvas: TCanvas; var Width, Height: Integer); procedure SaveToIniFile(IniFile : TIniFile); procedure LoadFromIniFile(IniFile : TIniFile); published property Font : TFont read FFont write SetFont; property Stylename : string read FStylename write SetStylename; // used when Draw method called property BackGroundColor : TColor read GetBackGroundColor ; end; TFontStyleCollection = class(TCollection) private FOwner: TFontStyles; FOnAddFont : boolean; function GetItems(index: integer): TFontStyleItem; protected function GetOwner: TPersistent; override; procedure Update(Item: TCollectionItem); override; public constructor Create(AOwner: TFontStyles); function AddFont(Font : TFont): TFontStyleItem; property Owner : TFontStyles read FOwner; property Items[index : integer] : TFontStyleItem Read GetItems; default; // if not found return -1 function IndexOfName(const StyleName:string): integer; procedure Delete(index : integer); // if not found return nil function FontByName(const StyleName:string): TFont; end; { when TFontStyles link to a Listbox, it clears listbox' all items, then adds styles' items. the index of listbox item is the index of styles. when TFontStyles link to a PopupMenu or MenuItem, it clears all PopupMenu's or MenuItem's children menuitem, then adds styles' items as MenuItems that tags are the indexes of styles. } TSelectFontEvent = procedure (Sender : TObject; index : integer; SelectFont : TFont) of object; // %TFontStyles : 包含多种字体,可以在PopupMenu,MenuItem,ListBox中显示这些字体 TFontStyles = class(TComponent) private { Private declarations } FStyles: TFontStyleCollection; FBackGroundColor: TColor; FMenuItem: TMenuItem; FListBox: TListBox; FPopupMenu: TPopUpMenu; FOnSelectFont: TSelectFontEvent; FDefaultStyle: String; FOnDefaultStyleChanged: TNotifyEvent; procedure SetStyles(const Value: TFontStyleCollection); procedure SetListBox(const Value: TListBox); procedure setMenuItem(const Value: TMenuItem); procedure SetPopupMenu(const Value: TPopUpMenu); procedure ClearMenuItems(MenuItem : TMenuItem); procedure InternalUpdateMenu(MenuItem : TMenuItem); function AddMenuItem(AMenuItem : TMenuItem; index:integer):TMenuItem; procedure UpdateOneMenuItem(AMenuItem : TMenuItem; index:integer); // FPopupMenu<>nil and not Designing function CanUpdatePopupMenu:boolean; function CanUpdateMenuIem:boolean; function GetDefaultFont: TFont; procedure SetDefaultStyle(const Value: String); procedure DefaultStyleChanged; protected { Protected declarations } public { Public declarations } constructor Create(AOwner : TComponent); override; destructor destroy; override; procedure UpdateAll; procedure UpdateItem(index:integer); procedure UpdateNew; procedure UpdateListBox; procedure UpdatePopupMenu; procedure UpdateMenuItem; // for use to set some components' event procedure OnListBoxDraw(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure OnListBoxMeasure(Control: TWinControl; Index: Integer;var Height: Integer); procedure OnMenuItemDraw(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); procedure OnMenuItemMeasure(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer); procedure OnClick(Sender : TObject); property DefaultFont : TFont read GetDefaultFont; published { Published declarations } property BackGroundColor : TColor read FBackGroundColor write FBackGroundColor default clWhite; property Styles : TFontStyleCollection read FStyles write SetStyles; property PopupMenu : TPopUpMenu Read FPopupMenu Write SetPopupMenu; property MenuItem : TMenuItem read FMenuItem write setMenuItem; property ListBox : TListBox read FListBox write SetListBox; property OnSelectFont : TSelectFontEvent read FOnSelectFont write FOnSelectFont; property DefaultStyle : String read FDefaultStyle write SetDefaultStyle; property OnDefaultStyleChanged : TNotifyEvent Read FOnDefaultStyleChanged Write FOnDefaultStyleChanged; end; implementation uses ComWriUtils; const Margin = 2; { TFontStyleItem } procedure TFontStyleItem.Assign(Source: TPersistent); begin FFont.Assign((Source As TFontStyleItem).Font); FStyleName := (Source As TFontStyleItem).StyleName; Changed(false); end; constructor TFontStyleItem.Create(Collection: TCollection); begin FFont := TFont.Create; inherited Create(Collection); FStylename := 'Style'+IntToStr(ID); end; destructor TFontStyleItem.destroy; begin FFont.free; inherited destroy; end; procedure TFontStyleItem.Draw(ACanvas: TCanvas; ARect: TRect; Selected: Boolean); begin ACanvas.Font := Font; ACanvas.Brush.Color := BackGroundColor; //ACanvas.FillRect(ARect); ACanvas.TextRect(ARect,ARect.left + margin,ARect.top + margin,StyleName); if selected then ACanvas.DrawFocusRect(ARect); end; function TFontStyleItem.GetBackGroundColor: TColor; begin result := TFontStyleCollection(Collection).Owner.BackGroundColor; end; function TFontStyleItem.GetDisplayName: string; begin result := FStylename; end; procedure TFontStyleItem.LoadFromIniFile(IniFile: TIniFile); begin // end; procedure TFontStyleItem.Measure(ACanvas: TCanvas; var Width, Height: Integer); var TheSize : TSize; begin ACanvas.Font := Font; TheSize:=ACanvas.TextExtent(StyleName); Width := theSize.cx+Margin*2; Height := theSize.cy+Margin*2; end; procedure TFontStyleItem.SaveToIniFile(IniFile: TIniFile); begin // end; procedure TFontStyleItem.SetFont(const Value: TFont); begin if FFont<>Value then begin FFont.assign(Value); Changed(false); end; end; procedure TFontStyleItem.SetStylename(const Value: string); begin if FStylename <> Value then begin FStylename := Value; Changed(false); end; end; { TFontStyleCollection } constructor TFontStyleCollection.Create(AOwner: TFontStyles); begin inherited Create(TFontStyleItem); FOwner := AOwner; FOnAddFont := false; end; function TFontStyleCollection.AddFont(Font: TFont): TFontStyleItem; begin FOnAddFont := true; result := TFontStyleItem(inherited Add); result.font := font; FOnAddFont := false; Owner.UpdateNew; end; function TFontStyleCollection.GetItems(index: integer): TFontStyleItem; begin result := TFontStyleItem(inherited Items[index]); end; function TFontStyleCollection.GetOwner: TPersistent; begin result := FOwner; end; procedure TFontStyleCollection.Update(Item: TCollectionItem); begin if not FOnAddFont then if Item=nil then Owner.UpdateAll else Owner.UpdateItem(Item.index); end; procedure TFontStyleCollection.Delete(index: integer); begin Items[index].free; end; function TFontStyleCollection.FontByName(const StyleName: string): TFont; var i : integer; begin i:=IndexOfName(StyleName); if i<0 then result:=nil else result:=Items[i].Font; end; function TFontStyleCollection.IndexOfName( const StyleName: string): integer; var i : integer; begin for i:=0 to count-1 do if Items[i].Stylename=StyleName then begin result:=i; exit; end; result:=-1; end; { TFontStyles } constructor TFontStyles.Create(AOwner: TComponent); begin inherited Create(AOwner); FStyles := TFontStyleCollection.Create(self); FBackGroundColor := clWhite; RegisterRefProp(self,'PopupMenu'); RegisterRefProp(self,'MenuItem'); RegisterRefProp(self,'Listbox'); FPopupMenu := nil; FMenuItem := nil; FListbox := nil; end; destructor TFontStyles.destroy; begin FStyles.free; inherited destroy; end; procedure TFontStyles.ClearMenuItems(MenuItem: TMenuItem); var TheItem : TMenuItem; begin if not (csDesigning in ComponentState) then while MenuItem.count>0 do begin TheItem :=MenuItem[0]; MenuItem.delete(0); TheItem.free; end; end; procedure TFontStyles.OnListBoxDraw(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin Styles.items[index].draw((Control as TListBox).canvas, rect,{(odSelected in State) or }{(odFocused in State)}false); end; procedure TFontStyles.OnListBoxMeasure(Control: TWinControl; Index: Integer; var Height: Integer); var AWidth : integer; begin Styles.items[index].Measure((Control as TListBox).canvas, AWidth,Height); end; procedure TFontStyles.OnMenuItemDraw(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); begin Styles.items[TMenuItem(Sender).tag].Draw (ACanvas,ARect,Selected); end; procedure TFontStyles.OnMenuItemMeasure(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer); begin Styles.items[TMenuItem(Sender).tag].Measure (ACanvas,Width, Height); end; procedure TFontStyles.SetListBox(const Value: TListBox); begin if FListBox <>Value then begin if FListBox<>nil then begin FListBox.style := lbStandard; FListBox.OnMeasureItem := nil; FListBox.OnDrawItem := nil; FListBox.OnClick := nil; end; FListBox := Value; if FListBox<>nil then begin FListBox.style := lbOwnerDrawVariable; FListBox.OnMeasureItem := OnListBoxMeasure; FListBox.OnDrawItem := OnListBoxDraw; FListBox.OnClick := OnClick; UpdateListBox; end; ReferTo(value); end; end; procedure TFontStyles.setMenuItem(const Value: TMenuItem); begin if FMenuItem <> Value then begin if (FMenuItem<>nil) then ClearMenuItems(FMenuItem); FMenuItem := Value; if (FMenuItem<>nil) then FMenuItem.GetParentMenu.OwnerDraw:=true; UpdateMenuItem; ReferTo(value); end; end; procedure TFontStyles.SetPopupMenu(const Value: TPopUpMenu); begin if FPopupMenu<> Value then begin if FPopupMenu<>nil then ClearMenuItems(FPopupMenu.Items); FPopupMenu := Value; if FPopupMenu<>nil then FPopupMenu.OwnerDraw := true; UpdatePopupMenu; ReferTo(value); end; end; procedure TFontStyles.SetStyles(const Value: TFontStyleCollection); begin if FStyles<>Value then FStyles.Assign(value); end; procedure TFontStyles.UpdateListBox; var i : integer; begin if FListbox<>nil then begin FListbox.items.clear; for i:=0 to styles.count-1 do FListbox.items.add(styles[i].stylename); end; end; procedure TFontStyles.UpdateMenuItem; begin if CanUpdateMenuIem then InternalUpdateMenu(FMenuItem); end; procedure TFontStyles.UpdatePopupMenu; begin if CanUpdatePopupMenu then InternalUpdateMenu(FPopupMenu.Items); end; procedure TFontStyles.InternalUpdateMenu(MenuItem: TMenuItem); var i : integer; //AMenuItem : TMenuItem; begin ClearMenuItems(MenuItem); for i:=0 to Styles.count-1 do begin {AMenuItem := TMenuItem.Create(self); AMenuItem.Caption := Styles[i].Stylename; AMenuItem.tag := i; AMenuItem.OnDrawItem := OnMenuItemDraw; AMenuItem.OnMeasureItem := OnMenuItemMeasure; AMenuItem.OnClick := OnClick; MenuItem.Add(AMenuItem);} AddMenuItem(MenuItem,i); end; end; procedure TFontStyles.UpdateAll; begin UpdateListBox; UpdatePopupMenu; UpdateMenuItem; DefaultStyleChanged; end; procedure TFontStyles.OnClick(Sender: TObject); var i : integer; Font : TFont; begin if Assigned(FOnSelectFont) then begin if Sender is TListBox then i := (Sender as TListBox).ItemIndex else i := (Sender as TComponent).tag; if (i>=0) and (i<styles.count) then Font := Styles[i].font else Font := nil; FOnSelectFont(sender,i,font); end; end; procedure TFontStyles.UpdateItem(index: integer); begin assert((index>=0)and (index<styles.count)); if assigned(FListbox) then begin FListbox.items[index]:=styles[index].stylename; FListbox.repaint; end; if CanUpdatePopupMenu then UpdateOneMenuItem(FPopupMenu.Items,index); if CanUpdateMenuIem then UpdateOneMenuItem(FMenuItem,index); if Styles[index].Stylename=FDefaultStyle then DefaultStyleChanged; end; procedure TFontStyles.UpdateNew; var Stylename : string; begin Stylename := styles[styles.count-1].stylename; if assigned(FListbox) then FListbox.items.Add(Stylename); if CanUpdatePopupMenu then AddMenuItem(FPopupMenu.Items,styles.count-1); if CanUpdateMenuIem then AddMenuItem(FMenuItem,styles.count-1); end; function TFontStyles.AddMenuItem(AMenuItem: TMenuItem; index:integer): TMenuItem; begin result := TMenuItem.Create(self); result.Caption := Styles[index].Stylename; result.tag := index; result.OnDrawItem := OnMenuItemDraw; result.OnMeasureItem := OnMenuItemMeasure; result.OnClick := OnClick; AMenuItem.Add(result); end; procedure TFontStyles.UpdateOneMenuItem(AMenuItem: TMenuItem; index: integer); begin assert(AMenuItem[index].tag=index); AMenuItem[index].caption := Styles[index].Stylename; end; function TFontStyles.CanUpdateMenuIem: boolean; begin result := not (csDesigning in ComponentState) and (FMenuItem<>nil); end; function TFontStyles.CanUpdatePopupMenu: boolean; begin result := not (csDesigning in ComponentState) and (FPopupMenu<>nil); end; function TFontStyles.GetDefaultFont: TFont; var i : integer; begin i := Styles.IndexOfName(FDefaultStyle); if i>=0 then result := Styles[i].font else result := nil; end; procedure TFontStyles.SetDefaultStyle(const Value: String); begin if FDefaultStyle <> Value then begin FDefaultStyle := Value; DefaultStyleChanged; end; end; procedure TFontStyles.DefaultStyleChanged; begin if assigned(FOnDefaultStyleChanged) then FOnDefaultStyleChanged(self); end; end.
unit LaunchCore; {$mode objfpc}{$H+} interface uses Classes, SysUtils, BaseModel; type IBaseLaunchCore = interface(IBaseModel) ['{1D2DD805-56DB-497A-AE09-3343F8CA642B}'] function GetCoreId: string; function GetFlight: LongWord; function GetGridfins: Boolean; function GetLandpadId: string; function GetLandingAttempt: Boolean; function GetLandingSuccess: Boolean; function GetLandingType: string; function GetLegs: Boolean; function GetReused: Boolean; procedure SetCoreId(AValue: string); procedure SetFlight(AValue: LongWord); procedure SetGridfins(AValue: Boolean); procedure SetLandpadId(AValue: string); procedure SetLandingAttempt(AValue: Boolean); procedure SetLandingSuccess(AValue: Boolean); procedure SetLandingType(AValue: string); procedure SetLegs(AValue: Boolean); procedure SetReused(AValue: Boolean); end; ILaunchCore = interface(IBaseLaunchCore) ['{C8A6A705-B9EA-4DB0-A0A8-F8AF5C88E0C4}'] property CoreId: string read GetCoreId write SetCoreId; property Flight: LongWord read GetFlight write SetFlight; property Gridfins: Boolean read GetGridfins write SetGridfins; property LandpadId: string read GetLandpadId write SetLandpadId; property LandingAttempt: Boolean read GetLandingAttempt write SetLandingAttempt; property LandingSuccess: Boolean read GetLandingSuccess write SetLandingSuccess; property LandingType: string read GetLandingType write SetLandingType; property Legs: Boolean read GetLegs write SetLegs; property Reused: Boolean read GetReused write SetReused; end; ILaunchCoreList = interface(IBaseModelList) ['{4AB8C91D-8187-4E66-AD76-BA8CC002F10C}'] end; function NewLaunchCore: ILaunchCore; function NewLaunchCoreList: ILaunchCoreList; implementation uses Variants; type { TLaunchCore } TLaunchCore = class(TBaseModel, ILaunchCore) private FCoreId: string; FFlight: LongWord; FGridfins: Boolean; FLandpadId: string; FLandingAttempt: Boolean; FLandingSuccess: Boolean; FLandingType: string; FLegs: Boolean; FReused: Boolean; //Landpad: Lazy<LandpadInfo>; function GetCoreId: string; function GetFlight: LongWord; function GetGridfins: Boolean; function GetLandpadId: string; function GetLandingAttempt: Boolean; function GetLandingSuccess: Boolean; function GetLandingType: string; function GetLegs: Boolean; function GetReused: Boolean; procedure SetCoreId(AValue: string); procedure SetCoreId(AValue: Variant); procedure SetFlight(AValue: LongWord); procedure SetFlight(AValue: Variant); procedure SetGridfins(AValue: Boolean); procedure SetGridfins(AValue: Variant); procedure SetLandpadId(AValue: string); procedure SetLandpadId(AValue: Variant); procedure SetLandingAttempt(AValue: Boolean); procedure SetLandingAttempt(AValue: Variant); procedure SetLandingSuccess(AValue: Boolean); procedure SetLandingSuccess(AValue: Variant); procedure SetLandingType(AValue: string); procedure SetLandingType(AValue: Variant); procedure SetLegs(AValue: Boolean); procedure SetLegs(AValue: Variant); procedure SetReused(AValue: Boolean); procedure SetReused(AValue: Variant); public function ToString: string; override; published property core: Variant write SetCoreId; property flight: Variant write SetFlight; property gridfins: Variant write SetGridfins; property landpad: Variant write SetLandpadId; property landing_attempt: Variant write SetLandingAttempt; property landing_success: Variant write SetLandingSuccess; property landing_type: Variant write SetLandingType; property legs: Variant write SetLegs; property reused: Variant write SetReused; end; { TLaunchCoreList } TLaunchCoreList = class(TBaseModelList, ILaunchCoreList) function NewItem: IBaseModel; override; end; function NewLaunchCore: ILaunchCore; begin Result := TLaunchCore.Create; end; function NewLaunchCoreList: ILaunchCoreList; begin Result := TLaunchCoreList.Create; end; { TLaunchCoreList } function TLaunchCoreList.NewItem: IBaseModel; begin Result := NewLaunchCore; end; { TLaunchCore } function TLaunchCore.GetCoreId: string; begin Result := FCoreId; end; function TLaunchCore.GetFlight: LongWord; begin Result := FFlight;; end; function TLaunchCore.GetGridfins: Boolean; begin Result := FGridfins; end; function TLaunchCore.GetLandpadId: string; begin Result := FLandpadId; end; function TLaunchCore.GetLandingAttempt: Boolean; begin Result := FLandingAttempt; end; function TLaunchCore.GetLandingSuccess: Boolean; begin Result := FLandingSuccess; end; function TLaunchCore.GetLandingType: string; begin Result := FLandingType; end; function TLaunchCore.GetLegs: Boolean; begin Result := FLegs; end; function TLaunchCore.GetReused: Boolean; begin Result := FReused; end; procedure TLaunchCore.SetCoreId(AValue: string); begin FCoreId := AValue; end; procedure TLaunchCore.SetCoreId(AValue: Variant); begin if VarIsNull(AValue) then begin FCoreId := ''; end else if VarIsStr(AValue) then FCoreId := AValue; end; procedure TLaunchCore.SetFlight(AValue: LongWord); begin FFlight := AValue; end; procedure TLaunchCore.SetFlight(AValue: Variant); begin if VarIsNull(AValue) then begin FFlight := -0; end else if VarIsNumeric(AValue) then FFlight := AValue; end; procedure TLaunchCore.SetGridfins(AValue: Boolean); begin FGridfins := AValue; end; procedure TLaunchCore.SetGridfins(AValue: Variant); begin if VarIsNull(AValue) then begin FGridfins := False; end else if VarIsBool(AValue) then FGridfins := AValue; end; procedure TLaunchCore.SetLandpadId(AValue: string); begin FLandpadId := AValue; end; procedure TLaunchCore.SetLandpadId(AValue: Variant); begin if VarIsNull(AValue) then begin FLandpadId := ''; end else if VarIsStr(AValue) then FLandpadId := AValue; end; procedure TLaunchCore.SetLandingAttempt(AValue: Boolean); begin FLandingAttempt := AValue; end; procedure TLaunchCore.SetLandingAttempt(AValue: Variant); begin if VarIsNull(AValue) then begin FLandingAttempt := False; end else if VarIsBool(AValue) then FLandingAttempt := AValue; end; procedure TLaunchCore.SetLandingSuccess(AValue: Boolean); begin FLandingSuccess := AValue; end; procedure TLaunchCore.SetLandingSuccess(AValue: Variant); begin if VarIsNull(AValue) then begin FLandingSuccess := False; end else if VarIsBool(AValue) then FLandingSuccess := AValue; end; procedure TLaunchCore.SetLandingType(AValue: string); begin FLandingType := AValue; end; procedure TLaunchCore.SetLandingType(AValue: Variant); begin if VarIsNull(AValue) then begin FLandingType := ''; end else if VarIsStr(AValue) then FLandingType := AValue; end; procedure TLaunchCore.SetLegs(AValue: Boolean); begin FLegs := AValue; end; procedure TLaunchCore.SetLegs(AValue: Variant); begin if VarIsNull(AValue) then begin FLegs := False; end else if VarIsBool(AValue) then FLegs := AValue; end; procedure TLaunchCore.SetReused(AValue: Boolean); begin FReused := AValue; end; procedure TLaunchCore.SetReused(AValue: Variant); begin if VarIsNull(AValue) then begin FReused := False; end else if VarIsBool(AValue) then FReused := AValue; end; function TLaunchCore.ToString: string; begin Result := Format('' + 'Core ID: %s' + LineEnding + 'Flight: %u' + LineEnding + 'Gridfins: %s' + LineEnding + 'Landpad ID: %s' + LineEnding + 'Landing Attempt: %s' + LineEnding + 'Landing Success: %s' + LineEnding + 'Landing Type: %s' + LineEnding + 'Legs: %s' + LineEnding + 'Reused: %s' , [ GetCoreId, GetFlight, BoolToStr(GetGridfins, True), GetLandpadId, BoolToStr(GetLandingAttempt, True), BoolToStr(GetLandingSuccess, True), GetLandingType, BoolToStr(GetLegs, True), BoolToStr(GetReused, True) ]); end; end.
{**********************************************************************} { } { "The contents of this file are subject to the Mozilla Public } { License Version 1.1 (the "License"); you may not use this } { file except in compliance with the License. You may obtain } { a copy of the License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express } { or implied. See the License for the specific language } { governing rights and limitations under the License. } { } { Copyright Creative IT. } { Current maintainer: Eric Grange } { } {**********************************************************************} unit dwsRTTIFunctions; {$I dws.inc} interface uses dwsFunctions, dwsSymbols, dwsExprs, dwsStrings, dwsOperators, dwsStack, dwsDataContext, dwsExprList, dwsTokenizer, SysUtils, dwsUtils, dwsMagicExprs, dwsUnitSymbols, dwsCoreExprs; type TRTTIRawAttributesFunc = class(TInternalFunction) public procedure Execute(info : TProgramInfo); override; end; TTypeOfClassFunc = class(TInternalFunction) public procedure Execute(info : TProgramInfo); override; end; TRTTITypeInfoNameMethod = class(TInternalRecordMethod) procedure Execute(info : TProgramInfo); override; end; TSameRTTITypeInfoFunc = class(TInternalMagicBoolFunction) function DoEvalAsBoolean(const args : TExprBaseListExec) : Boolean; override; end; TRTTISymbolNameMethod = class(TInternalMethod) procedure Execute(info : TProgramInfo; var ExternalObject: TObject); override; end; TRTTISymbolTypMethod = class(TInternalMethod) procedure Execute(info : TProgramInfo; var ExternalObject: TObject); override; end; TRTTIPropertyCapabilitiesMethod = class(TInternalMethod) procedure Execute(info : TProgramInfo; var ExternalObject: TObject); override; class function Capabilities(propSym : TPropertySymbol) : Integer; static; end; TRTTIPropertyGetterMethod = class(TInternalMethod) procedure Execute(info : TProgramInfo; var ExternalObject: TObject); override; end; TRTTIPropertySetterMethod = class(TInternalMethod) procedure Execute(info : TProgramInfo; var ExternalObject: TObject); override; end; TRTTIMethodInfoMethod = class(TInternalMethod) procedure Execute(info : TProgramInfo; var ExternalObject: TObject); override; class function Info(methSym : TMethodSymbol) : Integer; static; end; TRTTIMethodVMTMethod = class(TInternalMethod) procedure Execute(info : TProgramInfo; var ExternalObject: TObject); override; end; TRTTIMethodCallMethod = class(TInternalMethod) procedure Execute(info : TProgramInfo; var ExternalObject: TObject); override; end; type TRTTIMethodInfoFlags = ( infoOverlap = 1, infoOverride = 2, infoStatic = 4, infoClass = 8, infoOverload = 16, infoAbstract = 32, infoFinal = 64, infoConstructor = 128, infoDestructor = 256 ); const SYS_TRTTITYPEINFO = 'TRTTITypeInfo'; SYS_TRTTIRAWATTRIBUTE = 'TRTTIRawAttribute'; SYS_TRTTIRAWATTRIBUTES = 'TRTTIRawAttributes'; SYS_RTTIRAWATTRIBUTES = 'RTTIRawAttributes'; SYS_RTTIPROPERTYATTRIBUTE = 'RTTIPropertyAttribute'; SYS_RTTIMETHODATTRIBUTE = 'RTTIMethodAttribute'; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses dwsInfo; // RegisterRTTITypes // procedure RegisterRTTITypes(systemTable : TSystemSymbolTable; unitSyms : TUnitMainSymbols; unitTable : TSymbolTable); procedure AddIntClassConst(clsSym : TClassSymbol; const name : String; value : Integer); var ccs : TClassConstSymbol; begin ccs:=TClassConstSymbol.CreateValue(name, systemTable.TypInteger, value); ccs.Visibility:=cvPublic; clsSym.AddConst(ccs); end; var typTypInfo : TRecordSymbol; typRawAttribute : TRecordSymbol; clsPropAttribute : TClassSymbol; clsMethAttribute : TClassSymbol; field : TFieldSymbol; begin typTypInfo:=TRecordSymbol.Create(SYS_TRTTITYPEINFO, nil); systemTable.AddSymbol(typTypInfo); typTypInfo.AddField(TFieldSymbol.Create('ID', systemTable.TypInteger, cvPrivate)); TRTTITypeInfoNameMethod.Create(mkFunction, [], 'Name', [], SYS_STRING, typTypInfo, cvPublic, systemTable); typRawAttribute:=TRecordSymbol.Create(SYS_TRTTIRAWATTRIBUTE, nil); systemTable.AddSymbol(typRawAttribute); field:=TFieldSymbol.Create('T', typTypInfo, cvPublic); field.ExternalName:=field.Name; typRawAttribute.AddField(field); field:=TFieldSymbol.Create('A', systemTable.TypCustomAttribute, cvPublic); field.ExternalName:=field.Name; typRawAttribute.AddField(field); clsPropAttribute:=TClassSymbol.Create(SYS_RTTIPROPERTYATTRIBUTE, nil); systemTable.AddSymbol(clsPropAttribute); clsPropAttribute.InheritFrom(systemTable.TypCustomAttribute); TRTTISymbolNameMethod.Create(mkFunction, [], 'Name', [], SYS_STRING, clsPropAttribute, cvPublic, systemTable); TRTTISymbolTypMethod.Create(mkFunction, [], 'Typ', [], SYS_TRTTITYPEINFO, clsPropAttribute, cvPublic, systemTable); AddIntClassConst(clsPropAttribute, 'capReadable', 1); AddIntClassConst(clsPropAttribute, 'capWriteable', 2); TRTTIPropertyCapabilitiesMethod.Create(mkFunction, [], 'Capabilities', [], SYS_INTEGER, clsPropAttribute, cvPublic, systemTable); TRTTIPropertyGetterMethod.Create(mkFunction, [], 'Getter', ['handle', SYS_VARIANT], SYS_VARIANT, clsPropAttribute, cvPublic, systemTable); TRTTIPropertySetterMethod.Create(mkFunction, [], 'Setter', ['handle', SYS_VARIANT, 'value', SYS_VARIANT], SYS_STRING, clsPropAttribute, cvPublic, systemTable); clsMethAttribute:=TClassSymbol.Create(SYS_RTTIMETHODATTRIBUTE, nil); systemTable.AddSymbol(clsMethAttribute); clsMethAttribute.InheritFrom(systemTable.TypCustomAttribute); TRTTISymbolNameMethod.Create(mkFunction, [], 'Name', [], SYS_STRING, clsMethAttribute, cvPublic, systemTable); TRTTISymbolTypMethod.Create(mkFunction, [], 'Typ', [], SYS_TRTTITYPEINFO, clsMethAttribute, cvPublic, systemTable); AddIntClassConst(clsMethAttribute, 'infoAbstract', Ord(infoAbstract)); AddIntClassConst(clsMethAttribute, 'infoOverride', Ord(infoOverride)); AddIntClassConst(clsMethAttribute, 'infoFinal', Ord(infoFinal)); AddIntClassConst(clsMethAttribute, 'infoOverload', Ord(infoOverload)); AddIntClassConst(clsMethAttribute, 'infoOverlap', Ord(infoOverlap)); AddIntClassConst(clsMethAttribute, 'infoClass', Ord(infoClass)); AddIntClassConst(clsMethAttribute, 'infoStatic', Ord(infoStatic)); TRTTIMethodInfoMethod.Create(mkFunction, [], 'Info', [], SYS_INTEGER, clsMethAttribute, cvPublic, systemTable); TRTTIMethodVMTMethod.Create(mkFunction, [], 'VMTIndex', [], SYS_INTEGER, clsMethAttribute, cvPublic, systemTable); TRTTIMethodCallMethod.Create(mkFunction, [], 'Call', ['instance', SYS_VARIANT, 'args', 'array of const'], SYS_VARIANT, clsMethAttribute, cvPublic, systemTable); systemTable.AddSymbol( TDynamicArraySymbol.Create(SYS_TRTTIRAWATTRIBUTES, typRawAttribute, systemTable.TypInteger) ); end; // RegisterRTTIOperators // procedure RegisterRTTIOperators(systemTable : TSystemSymbolTable; unitTable : TSymbolTable; operators : TOperators); var typTypInfo : TRecordSymbol; begin typTypInfo:=systemTable.FindTypeSymbol(SYS_TRTTITYPEINFO, cvMagic) as TRecordSymbol; operators.RegisterOperator(ttEQ, unitTable.FindSymbol('SameRTTITypeInfo', cvMagic) as TFuncSymbol, typTypInfo, typTypInfo); end; // PrepareRTTIRawAttributes // procedure PrepareRTTIRawAttributes(info : TProgramInfo; var scriptObj : IScriptObj); var typRawAttribute : TRecordSymbol; dynArray : TScriptDynamicArray; attributes : TdwsSymbolAttributes; publishedSymbols : TSimpleSymbolList; i, n : Integer; attrib : TdwsSymbolAttribute; symbolClassType : TClass; rttiPropertyAttributeCreate : IInfo; rttiMethodAttributeCreate : IInfo; attribute : IInfo; symbol : TSymbol; propertySymbol : TPropertySymbol; fieldSymbol : TFieldSymbol; methSymbol : TMethodSymbol; begin typRawAttribute:=info.Execution.Prog.Table.FindTypeSymbol(SYS_TRTTIRAWATTRIBUTE, cvPublic) as TRecordSymbol; dynArray:=TScriptDynamicArray.CreateNew(typRawAttribute); scriptObj:=dynArray; info.Execution.RTTIRawAttributes:=scriptObj; rttiPropertyAttributeCreate:=Info.Vars[SYS_RTTIPROPERTYATTRIBUTE].Method[SYS_TOBJECT_CREATE]; rttiMethodAttributeCreate:=Info.Vars[SYS_RTTIMETHODATTRIBUTE].Method[SYS_TOBJECT_CREATE]; publishedSymbols:=info.Execution.Prog.CollectAllPublishedSymbols; try attributes:=info.Execution.Prog.Attributes; dynArray.ArrayLength:=attributes.Count+publishedSymbols.Count*2; for i:=0 to attributes.Count-1 do begin attrib:=attributes[i]; symbolClassType:=attrib.Symbol.ClassType; if symbolClassType=TClassSymbol then begin dynArray.AsInteger[i*2]:=Int64(attrib.Symbol); dynArray.AsVariant[i*2+1]:=attrib.AttributeConstructor.Eval(info.Execution); end else Assert(False); end; n:=attributes.Count*2; for i:=0 to publishedSymbols.Count-1 do begin symbol:=publishedSymbols[i]; symbolClassType:=symbol.ClassType; if symbolClassType=TPropertySymbol then begin propertySymbol:=TPropertySymbol(symbol); dynArray.AsInteger[n]:=Int64(propertySymbol.OwnerSymbol); attribute:=rttiPropertyAttributeCreate.Call; dynArray.AsVariant[n+1]:=attribute.Value; attribute.ExternalObject:=propertySymbol; Inc(n, 2); end else if symbolClassType=TFieldSymbol then begin fieldSymbol:=TFieldSymbol(symbol); dynArray.AsInteger[n]:=Int64(fieldSymbol.StructSymbol); attribute:=rttiPropertyAttributeCreate.Call; dynArray.AsVariant[n+1]:=attribute.Value; attribute.ExternalObject:=fieldSymbol; Inc(n, 2); end else if symbolClassType.InheritsFrom(TMethodSymbol) then begin methSymbol:=TMethodSymbol(symbol); dynArray.AsInteger[n]:=Int64(methSymbol.StructSymbol); attribute:=rttiMethodAttributeCreate.Call; dynArray.AsVariant[n+1]:=attribute.Value; attribute.ExternalObject:=methSymbol; Inc(n, 2); end; end; finally publishedSymbols.Free; end; end; // ------------------ // ------------------ TRTTIRawAttributesFunc ------------------ // ------------------ // Execute // procedure TRTTIRawAttributesFunc.Execute(info : TProgramInfo); var scriptObj : IScriptObj; begin scriptObj:=info.Execution.RTTIRawAttributes; if not Assigned(scriptObj) then PrepareRTTIRawAttributes(info, scriptObj); info.Vars[SYS_RESULT].Value:=scriptObj; end; // ------------------ // ------------------ TTypeOfClassFunc ------------------ // ------------------ // Execute // procedure TTypeOfClassFunc.Execute(info : TProgramInfo); begin info.Vars[SYS_RESULT].Member['ID'].Value:=info.ValueAsVariant['class']; end; // ------------------ // ------------------ TRTTITypeInfoNameMethod ------------------ // ------------------ // Execute // procedure TRTTITypeInfoNameMethod.Execute(info : TProgramInfo); var id : Int64; begin id:=Info.Vars['Self'].Member['ID'].ValueAsInteger; if id<>0 then Info.ResultAsString:=TSymbol(id).Name else Info.ResultAsString:=''; end; // ------------------ // ------------------ TRTTISymbolNameMethod ------------------ // ------------------ // Execute // procedure TRTTISymbolNameMethod.Execute(info : TProgramInfo; var ExternalObject: TObject); begin Info.ResultAsString:=TSymbol(ExternalObject).Name; end; // ------------------ // ------------------ TSameRTTITypeInfoFunc ------------------ // ------------------ // DoEvalAsBoolean // function TSameRTTITypeInfoFunc.DoEvalAsBoolean(const args : TExprBaseListExec) : Boolean; begin Result:=(args.ExprBase[0].Eval(args.Exec)=args.ExprBase[1].Eval(args.Exec)); end; // ------------------ // ------------------ TRTTISymbolTypMethod ------------------ // ------------------ // Execute // procedure TRTTISymbolTypMethod.Execute(info : TProgramInfo; var ExternalObject: TObject); begin Info.ResultAsInteger:=Int64((ExternalObject as TSymbol).Typ); end; // ------------------ // ------------------ TRTTIPropertyCapabilitiesMethod ------------------ // ------------------ // Execute // procedure TRTTIPropertyCapabilitiesMethod.Execute(info : TProgramInfo; var ExternalObject: TObject); var propSym : TSymbol; begin propSym:=ExternalObject as TSymbol; if propSym.ClassType=TPropertySymbol then Info.ResultAsInteger:=Capabilities(TPropertySymbol(propSym)) else if propSym.ClassType=TFieldSymbol then Info.ResultAsInteger:=3 else Info.ResultAsInteger:=0; end; // Capabilities // class function TRTTIPropertyCapabilitiesMethod.Capabilities(propSym : TPropertySymbol) : Integer; begin Result:=0; if propSym.ReadSym<>nil then Inc(Result, 1); if propSym.WriteSym<>nil then Inc(Result, 2); end; // ------------------ // ------------------ TRTTIPropertyGetterMethod ------------------ // ------------------ // Execute // procedure TRTTIPropertyGetterMethod.Execute(info : TProgramInfo; var ExternalObject: TObject); var handle, propInfo : IInfo; propSym : TSymbol; locData : IDataContext; begin propSym:=ExternalObject as TSymbol; handle:=info.Vars['handle']; if propSym.ClassType=TPropertySymbol then propInfo:=TInfoProperty.Create(info, propSym.Typ, info.Execution.DataContext_Nil, TPropertySymbol(propSym), handle.ScriptObj) else if propSym.ClassType=TFieldSymbol then begin info.Execution.DataContext_Create(handle.ScriptObj.AsData, TFieldSymbol(propSym).Offset, locData); propInfo:=TInfoData.Create(info, propSym.Typ, locData); end; Info.ResultAsVariant:=propInfo.Value; end; // ------------------ // ------------------ TRTTIPropertySetterMethod ------------------ // ------------------ // Execute // procedure TRTTIPropertySetterMethod.Execute(info : TProgramInfo; var ExternalObject: TObject); var handle, propInfo : IInfo; propSym : TSymbol; locData : IDataContext; begin propSym:=ExternalObject as TSymbol; handle:=info.Vars['handle']; if propSym.ClassType=TPropertySymbol then propInfo:=TInfoProperty.Create(info, propSym.Typ, info.Execution.DataContext_Nil, TPropertySymbol(propSym), handle.ScriptObj) else if propSym.ClassType=TFieldSymbol then begin info.Execution.DataContext_Create(handle.ScriptObj.AsData, TFieldSymbol(propSym).Offset, locData); propInfo:=TInfoData.Create(info, propSym.Typ, locData); end; propInfo.Value:=Info.ValueAsVariant['value']; end; // ------------------ // ------------------ TRTTIMethodInfoMethod ------------------ // ------------------ // Execute // procedure TRTTIMethodInfoMethod.Execute(info : TProgramInfo; var ExternalObject: TObject); var methSym : TMethodSymbol; begin methSym:=ExternalObject as TMethodSymbol; Info.ResultAsInteger := Self.Info(methSym); end; // Info // class function TRTTIMethodInfoMethod.Info(methSym : TMethodSymbol) : Integer; begin Result:=0; if methSym.IsAbstract then Inc(Result, Ord(infoAbstract)); if methSym.IsOverride then Inc(Result, Ord(infoOverride)); if methSym.IsFinal then Inc(Result, Ord(infoFinal)); if methSym.IsOverloaded then Inc(Result, Ord(infoOverload)); if methSym.IsOverlap then Inc(Result, Ord(infoOverlap)); if methSym.IsClassMethod then Inc(Result, Ord(infoClass)); if methSym.IsStatic then Inc(Result, Ord(infoStatic)); end; // ------------------ // ------------------ TRTTIMethodVMTMethod ------------------ // ------------------ // Execute // procedure TRTTIMethodVMTMethod.Execute(info : TProgramInfo; var ExternalObject: TObject); var methSym : TMethodSymbol; begin methSym:=ExternalObject as TMethodSymbol; Info.ResultAsInteger := methSym.VMTIndex; end; // ------------------ // ------------------ TRTTIMethodCallMethod ------------------ // ------------------ // Execute // procedure TRTTIMethodCallMethod.Execute(info : TProgramInfo; var ExternalObject: TObject); var methSym : TMethodSymbol; instanceInfo : IInfo; methInfo : IInfo; resultInfo : IInfo; data : TData; locData : IDataContext; begin methSym:=ExternalObject as TMethodSymbol; if methSym.IsClassMethod then begin if methSym.IsStatic then begin SetLength(data, 1); data[0]:=Int64(methSym.StructSymbol); info.Execution.DataContext_Create(data, 0, locData); instanceInfo:=TInfoClass.Create(info, methSym.StructSymbol, locData); methInfo:=TInfoFunc.Create(info, methSym, info.Execution.DataContext_Nil, nil, nil, TClassSymbol(methSym.StructSymbol)); end else begin SetLength(data, 1); data[0]:=info.Vars['instance'].ValueAsInteger; info.Execution.DataContext_Create(data, 0, locData); instanceInfo:=TInfoClass.Create(info, methSym.StructSymbol, locData); methInfo:=TInfoFunc.Create(info, methSym, info.Execution.DataContext_Nil, nil, IScriptObj(IUnknown(data[0])), TClassSymbol(methSym.StructSymbol)); end; end else begin data:=info.Vars['instance'].Data; info.Execution.DataContext_Create(data, 0, locData); instanceInfo:=TInfoClassObj.Create(info, methSym.StructSymbol,locData); methInfo:=TInfoFunc.Create(info, methSym, info.Execution.DataContext_Nil, nil, IScriptObj(IUnknown(data[0])), TClassSymbol(methSym.StructSymbol)); end; resultInfo:=methInfo.Call(info.Vars['args'].Data); if methSym.Typ<>nil then Info.ResultAsVariant:=resultInfo.Value; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ dwsInternalUnit.AddSymbolsRegistrationProc(RegisterRTTITypes); dwsInternalUnit.AddOperatorsRegistrationProc(RegisterRTTIOperators); RegisterInternalFunction(TRTTIRawAttributesFunc, SYS_RTTIRAWATTRIBUTES, [], SYS_TRTTIRAWATTRIBUTES, []); RegisterInternalFunction(TTypeOfClassFunc, 'TypeOf', ['class', SYS_TCLASS], SYS_TRTTITYPEINFO, [iffOverloaded]); RegisterInternalBoolFunction(TSameRTTITypeInfoFunc, 'SameRTTITypeInfo', ['&t1', SYS_TRTTITYPEINFO, '&t2', SYS_TRTTITYPEINFO], [iffOverloaded]); end.
unit ColorToolBar; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ToolWin, Winapi.CommCtrl, Vcl.Menus, Winapi.GDIPAPI, Winapi.GDIPOBJ, Vcl.ImgList, Vcl.StdCtrls; const COLOR_TOOLBAR_WIDTH = 50; COLOR_TOOLBAR_HEIGHT = 23; const CM_COLOR_TOOLBAR_SETCOLOR = WM_USER + 101; type TColorToolBar = class; TColorToolDropdown = procedure(Sender: TColorToolBar) of object; TColorToolChanged = procedure(Sender: TColorToolBar; Color: DWORD) of object; TColorToolBar = class(TWinControl) private { Private declarations } FOnDropdown : TColorToolDropdown; FOnColorChanged: TColorToolChanged; FSelectedColor : DWORD; FDropdown : Boolean; procedure SetSelectedColor(Value: DWORD); protected { Protected declarations } procedure OnSetColor(var Message: TMessage); message CM_COLOR_TOOLBAR_SETCOLOR; procedure CNNotify(var Message: TWMNotifyTLB); message CN_NOTIFY; procedure CustomDraw(dc: HDC); procedure CustomDrawButton(dc: HDC); procedure CreateWnd; override; public { Public declarations } constructor Create(AOwner: TComponent); override; procedure CreateParams(var Params: TCreateParams); override; published { Published declarations } property OnDropdown : TColorToolDropdown read FOnDropdown write FOnDropdown; property OnColorChanged: TColorToolChanged read FOnColorChanged write FOnColorChanged; property SelectedColor : DWORD read FSelectedColor Write SetSelectedColor; end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TColorToolBar]); end; constructor TColorToolBar.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := COLOR_TOOLBAR_WIDTH + 25; Height := COLOR_TOOLBAR_HEIGHT; end; procedure TColorToolBar.CreateParams(var Params: TCreateParams); begin Vcl.ComCtrls.InitCommonControl(ICC_BAR_CLASSES); inherited CreateParams(Params); CreateSubClass(Params, TOOLBARCLASSNAME); Params.Style := WS_CHILD or WS_VISIBLE or TBSTYLE_FLAT or CCS_NOPARENTALIGN or CCS_NOMOVEY or CCS_NORESIZE or CCS_NODIVIDER; Params.ExStyle := 0; Params.WindowClass.Style := 0; end; procedure TColorToolBar.CreateWnd; var ButtonInfo: TTBBUTTON; bResult : LRESULT; Size : TSIZE; begin inherited CreateWnd; SendMessage(Handle, TB_BUTTONSTRUCTSIZE, sizeof(TTBBUTTON), 0); bResult := SendMessage(Handle, TB_SETBITMAPSIZE, 0, 0); bResult := SendMessage(Handle, TB_SETBUTTONSIZE, 0, MakeLParam(COLOR_TOOLBAR_WIDTH, COLOR_TOOLBAR_HEIGHT)); bResult := SendMessage(Handle, TB_SETINDENT, 0, 0); FillChar(ButtonInfo, sizeof(ButtonInfo), 0); ButtonInfo.fsState := TBSTATE_ENABLED; ButtonInfo.fsStyle := BTNS_WHOLEDROPDOWN; bResult := SendStructMessage(Handle, TB_INSERTBUTTON, 0, ButtonInfo); bResult := SendStructMessage(Handle, TB_GETMAXSIZE, 0, Size); SetWindowPos(Handle, 0, 0, 0, Size.cx, Size.cy, SWP_NOZORDER or SWP_NOMOVE); end; procedure TColorToolBar.CNNotify(var Message: TWMNotifyTLB); var TBCustomDraw: PNMTBCustomDraw; begin if Message.NMHdr.code = TBN_DROPDOWN then begin if Assigned(FOnDropdown) then begin if FDropdown = FALSE then begin FDropdown := TRUE; FOnDropdown(Self); FDropdown := FALSE; end; end; end else if Message.NMHdr.code = NM_CUSTOMDRAW then begin Message.Result := CDRF_DODEFAULT; TBCustomDraw := Message.NMTBCustomDraw; case TBCustomDraw.nmcd.dwDrawStage of CDDS_PREPAINT: begin Message.Result := CDRF_NOTIFYITEMDRAW; CustomDraw(TBCustomDraw.nmcd.HDC); end; CDDS_ITEMPREPAINT: begin Message.Result := CDRF_NOTIFYPOSTPAINT; end; CDDS_ITEMPOSTPAINT: begin if TBCustomDraw.nmcd.dwItemSpec <> 0 then Exit; CustomDrawButton(TBCustomDraw.nmcd.HDC); end; end; Exit; end; inherited; end; procedure TColorToolBar.SetSelectedColor(Value: DWORD); var dc: HDC; begin if FSelectedColor = Value then Exit; FSelectedColor := Value; dc := GetDC(Self.Handle); CustomDrawButton(dc); ReleaseDC(Self.Handle, dc); end; procedure TColorToolBar.OnSetColor(var Message: TMessage); begin SetSelectedColor(Message.WParam); if Assigned(FOnColorChanged) then begin FOnColorChanged(Self, FSelectedColor); end; end; procedure TColorToolBar.CustomDraw(dc: HDC); const Color1 = $FFF0F0F0; Color2 = $FFC0C0C0; var Graphics : TGPGraphics; LinearGradientBrush: TGPLinearGradientBrush; GradientRect : TGPRect; ARect : TRect; begin Winapi.Windows.GetClientRect(Handle, ARect); GradientRect.X := ARect.Left; GradientRect.Y := ARect.Top; GradientRect.Width := ARect.Width; GradientRect.Height := ARect.Height - 1; LinearGradientBrush := TGPLinearGradientBrush.Create(GradientRect, Color1, Color2, LinearGradientModeVertical); Graphics := TGPGraphics.Create(dc); Graphics.FillRectangle(LinearGradientBrush, GradientRect); LinearGradientBrush.Free(); Graphics.Free(); end; procedure TColorToolBar.CustomDrawButton(dc: HDC); const BORDER_COLOR = $FF828790; var Graphics : TGPGraphics; SolidBrush: TGPSolidBrush; Pen : TGPPen; ButtonRect: TGPRect; ARect : TRect; begin SendStructMessage(Handle, TB_GETRECT, 0, ARect); ButtonRect.X := ARect.Left + 5; ButtonRect.Y := ARect.Top + 5; ButtonRect.Width := ARect.Width - 23; ButtonRect.Height := ARect.Height - 11; SolidBrush := TGPSolidBrush.Create(FSelectedColor or $FF000000); Pen := TGPPen.Create(BORDER_COLOR, 1); Graphics := TGPGraphics.Create(dc); Graphics.FillRectangle(SolidBrush, ButtonRect); Graphics.DrawRectangle(Pen, ButtonRect); Pen.Free(); SolidBrush.Free(); Graphics.Free(); end; end.
unit Windows.Info; interface type TSystemDir = record private class function GetSpecialFolder(const nFolder: Integer): string; static; public /// <summary> /// <b>Version 5.0</b>. The file system directory that is used to store /// administrative tools for an individual user. The Microsoft Management /// Console (MMC) will save customized consoles to this directory, and it /// will roam with the user /// </summary> class function GetAdminToolsDir: string; static; inline; /// <summary> /// The file system directory that corresponds to the user's nonlocalized /// Startup program group /// </summary> class function GetAltStartupDir: string; static; inline; /// <summary> /// <b>Version 4.71</b>. The file system directory that serves as a /// common repository for application-specific data. A typical path is /// C:\Documents and Settings\<i>username</i>\Application Data. This /// CSIDL is supported by the redistributable Shfolder.dll for systems /// that do not have the Microsoft Internet Explorer 4.0 integrated Shell /// installed /// </summary> class function GetAppDataDir: string; static; inline; /// <summary> /// The virtual folder containing the objects in the user's /// <b>Recycle Bin</b> /// </summary> class function GetBitBucketDir: string; static; inline; /// <summary> /// <b>Version 6.0</b>. The file system directory acting as a staging /// area for files waiting to be written to CD. A typical path is /// C:\Documents and Settings\<i>username</i>\Local Settings\Application /// Data\Microsoft\CD Burning /// </summary> class function GetCDBurnAreaDir: string; static; inline; /// <summary> /// <b>Version 5.0</b>. The file system directory containing /// administrative tools for all users of the computer /// </summary> class function GetCommonAdminToolsDir: string; static; inline; /// <summary> /// The file system directory that corresponds to the nonlocalized /// Startup program group for all users. Valid only for Microsoft Windows /// NT systems /// </summary> class function GetCommonAltStartupDir: string; static; inline; /// <summary> /// <b>Version 5.0</b>. The file system directory containing application /// data for all users. A typical path is C:\Documents and Settings\All /// Users\Application Data /// </summary> class function GetCommonAppDataDir: string; static; inline; /// <summary> /// The file system directory that contains files and folders that appear /// on the desktop for all users. A typical path is C:\Documents and /// Settings\All Users\Desktop. Valid only for Windows NT systems /// </summary> class function GetCommonDesktopDir: string; static; inline; /// <summary> /// The file system directory that contains documents that are common to /// all users. A typical paths is C:\Documents and Settings\All /// Users\Documents. Valid for Windows NT systems and Microsoft Windows /// 95 and Windows 98 systems with Shfolder.dll installed /// </summary> class function GetCommonDocumentsDir: string; static; inline; /// <summary> /// The file system directory that serves as a common repository for /// favorite items common to all users. Valid only for Windows NT systems /// </summary> class function GetCommonFavoritesDir: string; static; inline; /// <summary> /// <b>Version 6.0</b>. The file system directory that serves as a /// repository for music files common to all users. A typical path is /// C:\Documents and Settings\All Users\Documents\My Music /// </summary> class function GetCommonMusicDir: string; static; inline; /// <summary> /// <b>Version 6.0</b>. The file system directory that serves as a /// repository for image files common to all users. A typical path is /// C:\Documents and Settings\All Users\Documents\My Pictures /// </summary> class function GetCommonPicturesDir: string; static; inline; /// <summary> /// The file system directory that contains the directories for the /// common program groups that appear on the <b>Start</b> menu for all /// users. A typical path is C:\Documents and Settings\All Users\Start /// Menu\Programs. Valid only for Windows NT systems /// </summary> class function GetCommonProgramsDir: string; static; inline; /// <summary> /// The file system directory that contains the programs and folders that /// appear on the <b>Start</b> menu for all users. A typical path is /// C:\Documents and Settings\All Users\Start Menu. Valid only for /// Windows NT systems /// </summary> class function GetCommonStartMenuDir: string; static; inline; /// <summary> /// The file system directory that contains the programs that appear in /// the Startup folder for all users. A typical path is C:\Documents and /// Settings\All Users\Start Menu\Programs\Startup. Valid only for /// Windows NT systems /// </summary> class function GetCommonStartupDir: string; static; inline; /// <summary> /// The file system directory that contains the templates that are /// available to all users. A typical path is C:\Documents and /// Settings\All Users\Templates. Valid only for Windows NT systems /// </summary> class function GetCommonTemplatesDir: string; static; inline; /// <summary> /// <b>Version 6.0</b>. The file system directory that serves as a /// repository for video files common to all users. A typical path is /// C:\Documents and Settings\All Users\Documents\My Videos /// </summary> class function GetCommonVideoDir: string; static; inline; /// <summary> /// The folder representing other machines in your workgroup /// </summary> class function GetComputersNearMe: string; static; inline; /// <summary> /// The virtual folder representing Network Connections, containing /// network and dial-up connections /// </summary> class function GetConnectionsDir: string; static; inline; /// <summary> /// The virtual folder containing icons for the Control Panel applications /// </summary> class function GetControlsDir: string; static; inline; /// <summary> /// The file system directory that serves as a common repository for /// Internet cookies. A typical path is C:\Documents and Settings\ /// <i>username</i>\Cookies /// </summary> class function GetCookiesDir: string; static; inline; /// <summary> /// The virtual folder representing the Windows desktop, the root of the /// namespace /// </summary> class function GetDesktop: string; static; inline; /// <summary> /// The file system directory used to physically store file objects on /// the desktop (not to be confused with the desktop folder itself). A /// typical path is C:\Documents and Settings\<i>username</i>\Desktop /// </summary> class function GetDesktopDir: string; static; inline; /// <summary> /// The virtual folder representing My Computer, containing everything on /// the local computer: storage devices, printers, and Control Panel. The /// folder may also contain mapped network drives /// </summary> class function GetDrives: string; static; inline; /// <summary> /// The file system directory that serves as a common repository for the /// user's favorite items. A typical path is C:\Documents and Settings\ /// <i>username</i>\Favorites /// </summary> class function GetFavoritesDir: string; static; inline; /// <summary> /// A virtual folder containing fonts. A typical path is C:\Windows\Fonts /// </summary> class function GetFontsDir: string; static; inline; /// <summary> /// The file system directory that serves as a common repository for /// Internet history items /// </summary> class function GetHistoryDir: string; static; inline; /// <summary> /// A viritual folder for Internet Explorer /// </summary> class function GetInternetDir: string; static; inline; /// <summary> /// <b>Version 4.72</b>. The file system directory that serves as a /// common repository for temporary Internet files. A typical path is /// C:\Documents and Settings\<i>username</i>\Local Settings\Temporary /// Internet Files /// </summary> class function GetInternetCacheDir: string; static; inline; /// <summary> /// <b>Version 5.0</b>. The file system directory that serves as a data /// repository for local (nonroaming) applications. A typical path is /// C:\Documents and Settings\<i>username</i>\Local Settings\Application /// Data /// </summary> class function GetLocalAppDataDir: string; static; inline; /// <summary> /// <b>Version 6.0</b>. The virtual folder representing the My Documents /// desktop item /// </summary> class function GetMyDocumentsDir: string; static; inline; /// <summary> /// The file system directory that serves as a common repository for /// music files. A typical path is C:\Documents and Settings\User\My /// Documents\My Music /// </summary> class function GetMyMusicDir: string; static; inline; /// <summary> /// <b>Version 5.0</b>. The file system directory that serves as a common /// repository for image files. A typical path is C:\Documents and /// Settings\<i>username</i>\My Documents\My Pictures /// </summary> class function GetMyPicturesDir: string; static; inline; /// <summary> /// <b>Version 6.0</b>. The file system directory that serves as a common /// repository for video files. A typical path is C:\Documents and /// Settings\<i>username</i>\My Documents\My Videos /// </summary> class function GetMyVideoDir: string; static; inline; /// <summary> /// A file system directory containing the link objects that may exist in /// the <b>My Network Places</b> virtual folder. It is not the same as /// CSIDL_NETWORK, which represents the network namespace root. A typical /// path is C:\Documents and Settings\<i>username</i>\NetHood /// </summary> class function GetNethoodDir: string; static; inline; /// <summary> /// A virtual folder representing Network Neighborhood, the root of the /// network namespace hierarchy /// </summary> class function GetNetwork: string; static; inline; /// <summary> /// <para> /// <b>Version 6.0</b>. The virtual folder representing the My /// Documents desktop item. This is equivalent to CSIDL_MYDOCUMENTS. /// </para> /// <para> /// <b>Previous to Version 6.0</b>. The file system directory used to /// physically store a user's common repository of documents. A typical /// path is C:\Documents and Settings\<i>username</i>\My Documents. /// This should be distinguished from the virtual <b>My Documents</b> /// folder in the namespace /// </para> /// </summary> class function GetPersonalDir: string; static; inline; /// <summary> /// The virtual folder containing installed printers /// </summary> class function GetPrinters: string; static; inline; /// <summary> /// The file system directory that contains the link objects that can /// exist in the <b>Printers</b> virtual folder. A typical path is /// C:\Documents and Settings\<i>username</i>\PrintHood /// </summary> class function GetPrinthoodDir: string; static; inline; /// <summary> /// <b>Version 5.0</b>. The user's profile folder. A typical path is /// C:\Documents and Settings\<i>username</i>. Applications should not /// create files or folders at this level; they should put their data /// under the locations referred to by CSIDL_APPDATA or /// CSIDL_LOCAL_APPDATA /// </summary> class function GetProfileDir: string; static; inline; /// <summary> /// <b>Version 5.0</b>. The Program Files folder. A typical path is /// C:\Program Files /// </summary> class function GetProgramFilesDir: string; static; inline; /// <summary> /// <b>Version 5.0</b>. A folder for components that are shared across /// applications. A typical path is C:\Program Files\Common. Valid only /// for Windows NT, Windows 2000, and Windows XP systems. Not valid for /// Windows Millennium Edition (Windows Me). /// </summary> class function GetCommonProgramFilesDir: string; static; inline; /// <summary> /// The file system directory that contains the user's program groups /// (which are themselves file system directories). A typical path is /// C:\Documents and Settings\<i>username</i>\Start Menu\Programs /// </summary> class function GetProgramsDir: string; static; inline; /// <summary> /// The file system directory that contains shortcuts to the user's most /// recently used documents. A typical path is C:\Documents and Settings\ /// <i>username</i>\My Recent Documents /// </summary> class function GetRecentDir: string; static; inline; /// <summary> /// Windows Vista. The file system directory that contains resource data. /// A typical path is C:\Windows\Resources /// </summary> class function GetResourcesDir: string; static; inline; /// <summary> /// The file system directory containing <b>Start</b> menu items. A /// typical path is C:\Documents and Settings\<i>username</i>\Start Menu /// </summary> class function GetStartMenuDir: string; static; inline; /// <summary> /// The file system directory that corresponds to the user's Startup /// program group. The system starts these programs whenever any user /// logs onto Windows NT or starts Windows 95. A typical path is /// C:\Documents and Settings\<i>username</i>\Start Menu\Programs\Startup /// </summary> class function GetStartupDir: string; static; inline; /// <summary> /// <b>Version 5.0</b>. The Windows System folder. A typical path is /// C:\Windows\System32 /// </summary> class function GetSystemDir: string; static; inline; /// <summary> /// The file system directory that serves as a common repository for /// document templates. A typical path is C:\Documents and Settings\ /// <i>username</i>\Templates /// </summary> class function GetTemplatesDir: string; static; inline; /// <summary> /// <b>Version 5.0</b>. The Windows directory or SYSROOT. This /// corresponds to the %windir% or %SYSTEMROOT% environment variables. A /// typical path is C:\Windows /// </summary> class function GetWindowsDir: string; static; inline; end; implementation uses WinApi.Windows, WinApi.ShlObj, System.SysUtils; { TSystemDir } class function TSystemDir.GetAdminToolsDir: string; begin Result := GetSpecialFolder(CSIDL_ADMINTOOLS); end; class function TSystemDir.GetAltStartupDir: string; begin Result := GetSpecialFolder(CSIDL_ALTSTARTUP); end; class function TSystemDir.GetAppDataDir: string; begin Result := GetSpecialFolder(CSIDL_APPDATA); end; class function TSystemDir.GetBitBucketDir: string; begin Result := GetSpecialFolder(CSIDL_BITBUCKET); end; class function TSystemDir.GetCDBurnAreaDir: string; begin if Win32MajorVersion < 6 then Exit(EmptyStr); Result := GetSpecialFolder(CSIDL_CDBURN_AREA); end; class function TSystemDir.GetCommonAdminToolsDir: string; begin Result := GetSpecialFolder(CSIDL_COMMON_ADMINTOOLS); end; class function TSystemDir.GetCommonAltStartupDir: string; begin Result := GetSpecialFolder(CSIDL_COMMON_ALTSTARTUP); end; class function TSystemDir.GetCommonAppDataDir: string; begin Result := GetSpecialFolder(CSIDL_COMMON_APPDATA); end; class function TSystemDir.GetCommonDesktopDir: string; begin Result := GetSpecialFolder(CSIDL_COMMON_DESKTOPDIRECTORY); end; class function TSystemDir.GetCommonDocumentsDir: string; begin Result := GetSpecialFolder(CSIDL_COMMON_DOCUMENTS); end; class function TSystemDir.GetCommonFavoritesDir: string; begin Result := GetSpecialFolder(CSIDL_COMMON_FAVORITES); end; class function TSystemDir.GetCommonMusicDir: string; begin if Win32MajorVersion < 6 then Exit(EmptyStr); Result := GetSpecialFolder(CSIDL_COMMON_MUSIC); end; class function TSystemDir.GetCommonPicturesDir: string; begin if Win32MajorVersion < 6 then Exit(EmptyStr); Result := GetSpecialFolder(CSIDL_COMMON_PICTURES); end; class function TSystemDir.GetCommonProgramFilesDir: string; begin Result := GetSpecialFolder(CSIDL_PROGRAM_FILES_COMMON); end; class function TSystemDir.GetCommonProgramsDir: string; begin Result := GetSpecialFolder(CSIDL_COMMON_PROGRAMS); end; class function TSystemDir.GetCommonStartMenuDir: string; begin Result := GetSpecialFolder(CSIDL_COMMON_STARTMENU); end; class function TSystemDir.GetCommonStartupDir: string; begin Result := GetSpecialFolder(CSIDL_COMMON_STARTUP); end; class function TSystemDir.GetCommonTemplatesDir: string; begin Result := GetSpecialFolder(CSIDL_COMMON_TEMPLATES); end; class function TSystemDir.GetCommonVideoDir: string; begin if Win32MajorVersion < 6 then Exit(EmptyStr); Result := GetSpecialFolder(CSIDL_COMMON_VIDEO); end; class function TSystemDir.GetComputersNearMe: string; begin Result := GetSpecialFolder(CSIDL_COMPUTERSNEARME); end; class function TSystemDir.GetConnectionsDir: string; begin Result := GetSpecialFolder(CSIDL_CONNECTIONS); end; class function TSystemDir.GetControlsDir: string; begin Result := GetSpecialFolder(CSIDL_CONTROLS); end; class function TSystemDir.GetCookiesDir: string; begin Result := GetSpecialFolder(CSIDL_COOKIES); end; class function TSystemDir.GetDesktop: string; begin Result := GetSpecialFolder(CSIDL_DESKTOP); end; class function TSystemDir.GetDesktopDir: string; begin Result := GetSpecialFolder(CSIDL_DESKTOPDIRECTORY); end; class function TSystemDir.GetDrives: string; begin Result := GetSpecialFolder(CSIDL_DRIVES); end; class function TSystemDir.GetFavoritesDir: string; begin Result := GetSpecialFolder(CSIDL_FAVORITES); end; class function TSystemDir.GetFontsDir: string; begin Result := GetSpecialFolder(CSIDL_FONTS); end; class function TSystemDir.GetHistoryDir: string; begin Result := GetSpecialFolder(CSIDL_HISTORY); end; class function TSystemDir.GetInternetCacheDir: string; begin Result := GetSpecialFolder(CSIDL_INTERNET_CACHE); end; class function TSystemDir.GetInternetDir: string; begin Result := GetSpecialFolder(CSIDL_INTERNET); end; class function TSystemDir.GetLocalAppDataDir: string; begin Result := GetSpecialFolder(CSIDL_LOCAL_APPDATA); end; class function TSystemDir.GetMyDocumentsDir: string; begin if Win32MajorVersion < 6 then Result := GetSpecialFolder(CSIDL_PERSONAL) else Result := GetSpecialFolder(CSIDL_MYDOCUMENTS); end; class function TSystemDir.GetMyMusicDir: string; begin Result := GetSpecialFolder(CSIDL_MYMUSIC); end; class function TSystemDir.GetMyPicturesDir: string; begin Result := GetSpecialFolder(CSIDL_MYPICTURES); end; class function TSystemDir.GetMyVideoDir: string; begin if Win32MajorVersion < 6 then Exit(EmptyStr); Result := GetSpecialFolder(CSIDL_MYVIDEO); end; class function TSystemDir.GetNethoodDir: string; begin Result := GetSpecialFolder(CSIDL_NETHOOD); end; class function TSystemDir.GetNetwork: string; begin Result := GetSpecialFolder(CSIDL_NETWORK); end; class function TSystemDir.GetPersonalDir: string; begin Result := GetSpecialFolder(CSIDL_PERSONAL); end; class function TSystemDir.GetPrinters: string; begin Result := GetSpecialFolder(CSIDL_PRINTERS); end; class function TSystemDir.GetPrinthoodDir: string; begin Result := GetSpecialFolder(CSIDL_PRINTHOOD); end; class function TSystemDir.GetProfileDir: string; begin Result := GetSpecialFolder(CSIDL_PROFILE); end; class function TSystemDir.GetProgramFilesDir: string; begin Result := GetSpecialFolder(CSIDL_PROGRAM_FILES); end; class function TSystemDir.GetProgramsDir: string; begin Result := GetSpecialFolder(CSIDL_PROGRAMS); end; class function TSystemDir.GetRecentDir: string; begin Result := GetSpecialFolder(CSIDL_RECENT); end; class function TSystemDir.GetResourcesDir: string; begin if Win32MajorVersion < 6 then Exit(EmptyStr); Result := GetSpecialFolder(CSIDL_RESOURCES); end; class function TSystemDir.GetSpecialFolder(const nFolder: Integer): string; var Path: array [0 .. MAX_PATH] of char; begin SHGetSpecialFolderPath(0, Path, nFolder, False); Result := Path; end; class function TSystemDir.GetStartMenuDir: string; begin Result := GetSpecialFolder(CSIDL_STARTMENU); end; class function TSystemDir.GetStartupDir: string; begin Result := GetSpecialFolder(CSIDL_STARTUP); end; class function TSystemDir.GetSystemDir: string; begin Result := GetSpecialFolder(CSIDL_SYSTEM); end; class function TSystemDir.GetTemplatesDir: string; begin Result := GetSpecialFolder(CSIDL_TEMPLATES); end; class function TSystemDir.GetWindowsDir: string; begin Result := GetSpecialFolder(CSIDL_WINDOWS); end; end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Ported to Delphi by Michal Wojcik. // // Copyright (c) 2002 Cunningham & Cunningham, Inc. // Released under the terms of the GNU General Public License version 2 or later. // Ported to Delphi by Salim Nair. {$H+} unit Runtime; interface uses sysUtils, classes, Parse, typinfo; type TRunTime = class(TObject) private Felapsed : Cardinal; Fstart : Cardinal; function d(scale : cardinal) : string; property elapsed : cardinal read FElapsed write Felapsed; public constructor Create; function toString : string; property start : cardinal read Fstart write Fstart; end; implementation uses Windows, Math; { TRuntime } constructor TRunTime.Create; begin inherited; start := getTickCount; elapsed := 0; end; function TRunTime.d(scale : cardinal) : string; var report : cardinal; begin report := elapsed div scale; elapsed := elapsed - report * scale; result := IntToStr(report); end; function TRunTime.toString : string; var e : Cardinal; begin e := GetTickCount; elapsed := e - start; if (elapsed > 600000) then result := d(3600000) + ':' + d(600000) + d(60000) + ':' + d(10000) + d(1000) else result := d(60000) + ':' + d(10000) + d(1000) + '.' + d(100) + d(10); end; end.
unit AbstractFactory.Concretes.ConcreteFactory2; interface uses AbstractFactory.Interfaces.IAbstractProductA, AbstractFactory.Interfaces.IAbstractProductB, AbstractFactory.Interfaces.IAbstractFactory; // Each Concrete Factory has a corresponding product variant. // Cada fabrica concreta possui uma variante de produto correspondente type TConcreteFactory2 = class(TInterfacedObject, IAbstractFactory) public function CreateProductA: IAbstractProductA; function CreateProductB: IAbstractProductB; end; implementation uses AbstractFactory.Concretes.ConcreteProductA2, AbstractFactory.Concretes.ConcreteProductB2; { TConcreteFactory2 } function TConcreteFactory2.CreateProductA: IAbstractProductA; begin Result := TConcreteProductA2.Create; end; function TConcreteFactory2.CreateProductB: IAbstractProductB; begin Result := TConcreteProductB2.Create; end; end.
unit uBase32; {$ZEROBASEDSTRINGS ON} interface uses System.SysUtils, uBase, uUtils; type IBase32 = interface ['{194EDF16-63BB-47AB-BF6A-F0E72B450F30}'] function Encode(data: TArray<Byte>): String; function Decode(const data: String): TArray<Byte>; function EncodeString(const data: String): String; function DecodeToString(const data: String): String; function GetBitsPerChars: Double; property BitsPerChars: Double read GetBitsPerChars; function GetCharsCount: UInt32; property CharsCount: UInt32 read GetCharsCount; function GetBlockBitsCount: Integer; property BlockBitsCount: Integer read GetBlockBitsCount; function GetBlockCharsCount: Integer; property BlockCharsCount: Integer read GetBlockCharsCount; function GetAlphabet: String; property Alphabet: String read GetAlphabet; function GetSpecial: Char; property Special: Char read GetSpecial; function GetHaveSpecial: Boolean; property HaveSpecial: Boolean read GetHaveSpecial; function GetEncoding: TEncoding; procedure SetEncoding(value: TEncoding); property Encoding: TEncoding read GetEncoding write SetEncoding; end; TBase32 = class(TBase, IBase32) public const DefaultAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; DefaultSpecial = '='; constructor Create(const _Alphabet: String = DefaultAlphabet; _Special: Char = DefaultSpecial; _textEncoding: TEncoding = Nil); function Encode(data: TArray<Byte>): String; override; function Decode(const data: String): TArray<Byte>; override; end; implementation constructor TBase32.Create(const _Alphabet: String = DefaultAlphabet; _Special: Char = DefaultSpecial; _textEncoding: TEncoding = Nil); begin Inherited Create(32, _Alphabet, _Special, _textEncoding); FHaveSpecial := True; end; function TBase32.Encode(data: TArray<Byte>): String; var dataLength, i, length5, tempInt: Integer; tempResult: TStringBuilder; x1, x2: Byte; begin if ((data = nil) or (Length(data) = 0)) then begin Exit(''); end; dataLength := Length(data); tempResult := TStringBuilder.Create; try length5 := (dataLength div 5) * 5; i := 0; while i < length5 do begin x1 := data[i]; tempResult.Append(Alphabet[x1 shr 3]); x2 := data[i + 1]; tempResult.Append(Alphabet[((x1 shl 2) and $1C) or (x2 shr 6)]); tempResult.Append(Alphabet[(x2 shr 1) and $1F]); x1 := data[i + 2]; tempResult.Append(Alphabet[((x2 shl 4) and $10) or (x1 shr 4)]); x2 := data[i + 3]; tempResult.Append(Alphabet[((x1 shl 1) and $1E) or (x2 shr 7)]); tempResult.Append(Alphabet[(x2 shr 2) and $1F]); x1 := data[i + 4]; tempResult.Append(Alphabet[((x2 shl 3) and $18) or (x1 shr 5)]); tempResult.Append(Alphabet[x1 and $1F]); Inc(i, 5); end; tempInt := dataLength - length5; Case tempInt of 1: begin x1 := data[i]; tempResult.Append(Alphabet[x1 shr 3]); tempResult.Append(Alphabet[(x1 shl 2) and $1C]); tempResult.Append(Special, 4); end; 2: begin x1 := data[i]; tempResult.Append(Alphabet[x1 shr 3]); x2 := data[i + 1]; tempResult.Append(Alphabet[((x1 shl 2) and $1C) or (x2 shr 6)]); tempResult.Append(Alphabet[(x2 shr 1) and $1F]); tempResult.Append(Alphabet[(x2 shl 4) and $10]); tempResult.Append(Special, 3); end; 3: begin x1 := data[i]; tempResult.Append(Alphabet[x1 shr 3]); x2 := data[i + 1]; tempResult.Append(Alphabet[((x1 shl 2) and $1C) or (x2 shr 6)]); tempResult.Append(Alphabet[(x2 shr 1) and $1F]); x1 := data[i + 2]; tempResult.Append(Alphabet[((x2 shl 4) and $10) or (x1 shr 4)]); tempResult.Append(Alphabet[(x1 shl 1) and $1E]); tempResult.Append(Special, 2); end; 4: begin x1 := data[i]; tempResult.Append(Alphabet[x1 shr 3]); x2 := data[i + 1]; tempResult.Append(Alphabet[((x1 shl 2) and $1C) or (x2 shr 6)]); tempResult.Append(Alphabet[(x2 shr 1) and $1F]); x1 := data[i + 2]; tempResult.Append(Alphabet[((x2 shl 4) and $10) or (x1 shr 4)]); x2 := data[i + 3]; tempResult.Append(Alphabet[((x1 shl 1) and $1E) or (x2 shr 7)]); tempResult.Append(Alphabet[(x2 shr 2) and $1F]); tempResult.Append(Alphabet[(x2 shl 3) and $18]); tempResult.Append(Special); end; end; result := tempResult.ToString; finally tempResult.Free; end; end; function TBase32.Decode(const data: String): TArray<Byte>; var lastSpecialInd, tailLength, length5, i, srcInd, x1, x2, x3, x4, x5, x6, x7, x8: Integer; begin if TUtils.isNullOrEmpty(data) then begin SetLength(result, 1); result := Nil; Exit; end; lastSpecialInd := Length(data); while (data[lastSpecialInd - 1] = Special) do begin dec(lastSpecialInd); end; tailLength := Length(data) - lastSpecialInd; SetLength(result, (((Length(data)) + 7) div 8 * 5 - tailLength)); length5 := Length(result) div 5 * 5; i := 0; srcInd := 0; while i < length5 do begin x1 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x2 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x3 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x4 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x5 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x6 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x7 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x8 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); result[i] := Byte((x1 shl 3) or ((x2 shr 2) and $07)); result[i + 1] := Byte((x2 shl 6) or ((x3 shl 1) and $3E) or ((x4 shr 4) and $01)); result[i + 2] := Byte((x4 shl 4) or ((x5 shr 1) and $F)); result[i + 3] := Byte((x5 shl 7) or ((x6 shl 2) and $7C) or ((x7 shr 3) and $03)); result[i + 4] := Byte((x7 shl 5) or (x8 and $1F)); Inc(i, 5); end; case tailLength of 4: begin x1 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x2 := FInvAlphabet[Ord(data[srcInd])]; result[i] := Byte((x1 shl 3) or ((x2 shr 2) and $07)); end; 3: begin x1 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x2 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x3 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x4 := FInvAlphabet[Ord(data[srcInd])]; result[i] := Byte((x1 shl 3) or ((x2 shr 2) and $07)); result[i + 1] := Byte((x2 shl 6) or ((x3 shl 1) and $3E) or ((x4 shr 4) and $01)); end; 2: begin x1 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x2 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x3 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x4 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x5 := FInvAlphabet[Ord(data[srcInd])]; result[i] := Byte((x1 shl 3) or ((x2 shr 2) and $07)); result[i + 1] := Byte((x2 shl 6) or ((x3 shl 1) and $3E) or ((x4 shr 4) and $01)); result[i + 2] := Byte((x4 shl 4) or ((x5 shr 1) and $F)); end; 1: begin x1 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x2 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x3 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x4 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x5 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x6 := FInvAlphabet[Ord(data[srcInd])]; Inc(srcInd); x7 := FInvAlphabet[Ord(data[srcInd])]; result[i] := Byte((x1 shl 3) or ((x2 shr 2) and $07)); result[i + 1] := Byte((x2 shl 6) or ((x3 shl 1) and $3E) or ((x4 shr 4) and $01)); result[i + 2] := Byte((x4 shl 4) or ((x5 shr 1) and $F)); result[i + 3] := Byte((x5 shl 7) or ((x6 shl 2) and $7C) or ((x7 shr 3) and $03)); end; end; end; end.
// ****************************************************************** // // Program Name : $ProgramName$ // Platform(s) : $Platforms$ // Framework : VCL // // Filename : AT.$ShortName$.DM.ThemeServices.pas/.dfm // File Version : 1.00 // Date Created : $CreateDate$ // Author : Matthew Vesperman // // Description: // // $ProgramName$'s theme services data module. // // Revision History: // // v1.00 : Initial version // // ****************************************************************** // // COPYRIGHT © $Year$ - PRESENT Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // // ****************************************************************** /// <summary> /// $ProgramName$'s theme services data module. /// </summary> unit AT.ShortName.DM.Services.Themes; interface uses System.SysUtils, System.Classes, dxSkinsCore, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, cxClasses, cxLookAndFeels, dxSkinsForm; type /// <summary> /// Theme services data module. /// </summary> TdmThemeServices = class(TDataModule) sknctlrMain: TdxSkinController; /// <summary> /// Data module's OnCreate event handler. /// </summary> /// <remarks> /// Initializes the ThemeServices data module. /// </remarks> procedure DataModuleCreate(Sender: TObject); /// <summary> /// Data module's OnDestroy event handler. /// </summary> /// <remarks> /// Finalizes the ThemeServices data module. /// </remarks> procedure DataModuleDestroy(Sender: TObject); strict protected /// <summary> /// Enabled property getter. /// </summary> function GetEnabled: Boolean; /// <summary> /// NativeStyle property getter. /// </summary> function GetNativeStyle: Boolean; /// <summary> /// ThemeName property getter. /// </summary> function GetThemeName: String; /// <summary> /// TouchMode property getter. /// </summary> function GetTouchMode: Boolean; /// <summary> /// Enabled property setter. /// </summary> procedure SetEnabled(const Value: Boolean); /// <summary> /// NativeStyle property setter. /// </summary> procedure SetNativeStyle(const Value: Boolean); /// <summary> /// ThemeName property setter. /// </summary> procedure SetThemeName(const Value: String); /// <summary> /// TouchMode property setter. /// </summary> procedure SetTouchMode(const Value: Boolean); /// <summary> /// Loads themeing sub-system settings from the CurrentUser /// config file. /// </summary> procedure _LoadSettings; /// <summary> /// Saves themeing sub-system settings to the CurrentUser /// config file. /// </summary> procedure _SaveSettings; /// <summary> /// Informs all forms that support themeing that the current /// theme name has changed. /// </summary> /// <remarks> /// To support theme name change notifications a form must /// implement the IATThemedForm interface. /// </remarks> procedure _ThemeNameChanged; public /// <summary> /// Called at program startup to inform all forms about the /// current theme name. /// </summary> procedure _StartupInit; /// <summary> /// Determines if the themeing sub-system is enabled. /// </summary> /// <remarks> /// When set to TRUE the themeing sub-system is enabled. When /// set to FALSE the themeing sub-system is disabled. /// </remarks> property Enabled: Boolean read GetEnabled write SetEnabled; /// <summary> /// Determines whether TcxControl descendants within the /// current application use the native windows paint style by /// default. /// </summary> property NativeStyle: Boolean read GetNativeStyle write SetNativeStyle; /// <summary> /// Specifies the name of a skin to be applied to all /// TcxControl descendants within the current application by /// default. /// </summary> property ThemeName: String read GetThemeName write SetThemeName; /// <summary> /// Toggles the Touch mode in an application. /// </summary> /// <remarks> /// Set this property to True to enable the Touch mode in an /// application. Setting the property to False reverts all the /// size modifications made to DevExpress controls by enabling /// the Touch mode. /// </remarks> property TouchMode: Boolean read GetTouchMode write SetTouchMode; end; var /// <summary> /// Holds a reference to the global ThemeServices data module. /// </summary> dmThemeServices: TdmThemeServices; /// <summary> /// Returns a reference to the global ThemeServices data module. /// </summary> function ThemeServices: TdmThemeServices; implementation uses Vcl.Forms, AT.ShortName.Intf, AT.GarbageCollector, AT.ShortName.Vcl.Dialogs.SplashDX, AT.ShortName.ResourceStrings, AT.ShortName.DM.Services.Config, AT.ShortName.Config.Consts, AT.ShortName.Consts; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} var /// <summary> /// Module level garbage collector object. /// </summary> MGC: IATGarbageCollector; function ThemeServices: TdmThemeServices; begin if (NOT Assigned(dmThemeServices)) then begin dmThemeServices := TATGC.Collect(TdmThemeServices.Create(NIL), MGC); end; Result := dmThemeServices; end; procedure TdmThemeServices.DataModuleCreate(Sender: TObject); begin TdlgSplashDX.ChangeStartMessage(rstrStartInitThemes, cStartMsgDelay); _LoadSettings; end; procedure TdmThemeServices.DataModuleDestroy(Sender: TObject); begin _SaveSettings; end; function TdmThemeServices.GetEnabled: Boolean; begin Result := sknctlrMain.UseSkins; end; function TdmThemeServices.GetNativeStyle: Boolean; begin Result := sknctlrMain.NativeStyle; end; function TdmThemeServices.GetThemeName: String; begin Result := sknctlrMain.SkinName; end; function TdmThemeServices.GetTouchMode: Boolean; begin Result := sknctlrMain.TouchMode; end; procedure TdmThemeServices.SetEnabled(const Value: Boolean); begin sknctlrMain.UseSkins := Value; end; procedure TdmThemeServices.SetNativeStyle(const Value: Boolean); begin sknctlrMain.NativeStyle := Value; end; procedure TdmThemeServices.SetThemeName(const Value: String); begin sknctlrMain.SkinName := Value; _ThemeNameChanged; end; procedure TdmThemeServices.SetTouchMode(const Value: Boolean); begin sknctlrMain.TouchMode := Value; end; procedure TdmThemeServices._LoadSettings; var ATheme: String; begin ATheme := ConfigServices.CurrentUser.ReadString( cCfgSecThemeing, cCfgKeyThemeName, ThemeName); if (NOT SameText(ATheme, ThemeName)) then begin TdlgSplashDX.ChangeStartMessage(rstrStartSetThemes, cStartMsgDelay); ThemeName := ATheme; end; TouchMode := ConfigServices.CurrentUser.ReadBoolean( cCfgSecThemeing, cCfgKeyTouchMode, TouchMode); NativeStyle := ConfigServices.CurrentUser.ReadBoolean( cCfgSecThemeing, cCfgKeyNativeStyle, NativeStyle); Enabled := ConfigServices.CurrentUser.ReadBoolean( cCfgSecThemeing, cCfgKeyEnabled, Enabled); end; procedure TdmThemeServices._SaveSettings; begin ConfigServices.CurrentUser.WriteString(cCfgSecThemeing, cCfgKeyThemeName, ThemeName); ConfigServices.CurrentUser.WriteBoolean( cCfgSecThemeing, cCfgKeyTouchMode, TouchMode); ConfigServices.CurrentUser.WriteBoolean( cCfgSecThemeing, cCfgKeyNativeStyle, NativeStyle); ConfigServices.CurrentUser.WriteBoolean( cCfgSecThemeing, cCfgKeyEnabled, Enabled); end; procedure TdmThemeServices._StartupInit; begin _ThemeNameChanged; end; procedure TdmThemeServices._ThemeNameChanged; var Cnt: Integer; Idx: Integer; AFrm: TCustomForm; IFrm: IATThemedForm; begin Cnt := Screen.CustomFormCount; for Idx := 0 to (Cnt - 1) do begin AFrm := Screen.CustomForms[Idx]; if (Supports(AFrm, IATThemedForm, IFrm)) then IFrm.ThemeChanged(ThemeName); end; end; end.
unit GeradorNFe; interface uses { Units do Delphi } Contnrs, { Units do ACBr } ACBrNFe, ACBrNFeNotasFiscais, ACBrNFeDANFeRLClass, { Units das entidades do domínio } NotaFiscal, Empresa, // Fatura, ConfiguracoesNF, Generics.Collections, StrUtils, Dialogs, funcoes, ACBrDFeSSL; type TGeradorNFe = class private FACBrNFe :TACBrNFe; FACBrNFeDANFE :TACBrNFeDANFeRL; // FFatura :TFatura; public constructor Create(const CaminhoLogo :String); overload; constructor Create; overload; public destructor Destroy; override; private tot_icm_somado :Real; tot_bcicms_somada :Real; tot_produto_somado :Real; tot_frete_somado :Real; { Gerar NF-e } function GerarNFe (NF :TNotaFiscal) :ACBrNFeNotasFiscais.NotaFiscal; private procedure AjustarConfiguracoesDaEmpresa(ConfiguracoesNF :TConfiguracoesNF); procedure GerarDadosDaCobranca( NFe :ACBrNFeNotasFiscais.NotaFiscal); procedure GerarDadosProdutos (NF :TNotaFiscal; NFe :ACBrNFeNotasFiscais.NotaFiscal); procedure GerarDestinatario (NF :TNotaFiscal; NFe :ACBrNFeNotasFiscais.NotaFiscal); procedure GerarEmitente (NF :TNotaFiscal; NFe :ACBrNFeNotasFiscais.NotaFiscal); procedure GerarIdentificacao (NF :TNotaFiscal; NFe :ACBrNFeNotasFiscais.NotaFiscal); procedure GerarLocalEntrega (NF :TNotaFiscal; NFe :ACBrNFeNotasFiscais.NotaFiscal); procedure GerarObservacao (NF :TNotaFiscal; NFe :ACBrNFeNotasFiscais.NotaFiscal); procedure GerarTransportador (NF :TNotaFiscal; NFe :ACBrNFeNotasFiscais.NotaFiscal); procedure GerarValoresTotais (NF :TNotaFiscal; NFe :ACBrNFeNotasFiscais.NotaFiscal); procedure GerarVolumes (NF :TNotaFiscal; NFe :ACBrNFeNotasFiscais.NotaFiscal); procedure InicializaComponentes(const CaminhoLogo :String); public // procedure AdicionarFatura (Fatura :TFatura); procedure CancelarNFe (NotaFiscal :TNotaFiscal; Justificativa :String); procedure ConsultarNFe (NotaFiscal :TNotaFiscal); procedure EmitirNFe (NotaFiscal :TNotaFiscal); procedure EnviarEmail (NotaFiscal :TNotaFiscal); procedure GerarXML (NotaFiscal :TNotaFiscal); procedure ImprimirComVisualizacao(NotaFiscal :TNotaFiscal); procedure ImprimirDireto (NotaFiscal :TNotaFiscal); procedure Recarregar; function inutilizarNumeracao(nIni, nFim: integer; justificativa: String; Empresa: TEmpresa) :Boolean; public function ObterCertificado :String; end; implementation uses { Units do Delphi } Classes, SysUtils, DateUtils, { Exceções do Domínio } ExcecaoParametroInvalido, ExcecaoNotaFiscalInvalida, { Tipos do Domínio } TipoAmbienteNFe, TipoSerie, TipoNaturezaOperacao, TipoFrete, TipoStatusNotaFiscal, TipoOrigemMercadoria, TipoRegimeTributario, { Utilitários do ACBr } ACBrNFeConfiguracoes, pcnConversao, pcnConversaoNFe, pcnNFe, ACBrMail, { Repositórios } FabricaRepositorio, Repositorio, { Entidades do Domínio } // Pessoa, Produto, // Duplicata, { Objetos valor do domínio } ItemNotaFiscal, Especificacao, // LocalEntregaNotaFiscal, VolumesNotaFiscal, TotaisNotaFiscal, ObservacaoNotaFiscal, { Utilitários } // DateTimeUtilitario, Math, { Busca } frameBuscaCidade, {frameBuscaNcm,} ACBrDFeConfiguracoes, ACBrDFe,// Icms00, ACBrNFeWebServices, pcnProcNFe, Pessoa, UtilitarioEstoque; { TGeradorNFe } { procedure TGeradorNFe.AdicionarFatura(Fatura: TFatura); begin self.FFatura := Fatura; end; } procedure TGeradorNFe.AjustarConfiguracoesDaEmpresa( ConfiguracoesNF: TConfiguracoesNF); begin if (TTipoAmbienteNFeUtilitario.DeStringParaEnumerado(ConfiguracoesNF.ambiente_nfe) = tanfeProducao) then self.FACBrNFe.Configuracoes.WebServices.Ambiente := taProducao else self.FACBrNFe.Configuracoes.WebServices.Ambiente := taHomologacao; self.FACBrNFe.Configuracoes.Certificados.NumeroSerie := ConfiguracoesNF.num_certificado; if not ConfiguracoesNF.senha_certificado.IsEmpty then self.FACBrNFe.Configuracoes.Certificados.Senha := ConfiguracoesNF.senha_certificado; end; procedure TGeradorNFe.CancelarNFe(NotaFiscal :TNotaFiscal; Justificativa :String); var DhEvento :TDateTime; begin if Justificativa.IsEmpty then Justificativa := 'CANCELAMENTO DE NF-E'; self.AjustarConfiguracoesDaEmpresa(NotaFiscal.Empresa.ConfiguracoesNF); self.FACBrNFe.EventoNFe.Evento.Clear; with self.FACBrNFe.EventoNFe.Evento.Add do begin DhEvento := IncSecond(DataSEFAZToDateTime(NotaFiscal.NFe.ObtemValorPorTag('dhRecbto')), 10); infEvento.chNFe := NotaFiscal.NFe.ChaveAcesso; infEvento.CNPJ := NotaFiscal.Emitente.CPF_CNPJ; infEvento.dhEvento := DhEvento; infEvento.tpEvento := teCancelamento; infEvento.detEvento.xJust := Justificativa; infEvento.detEvento.nProt := NotaFiscal.NFe.ObtemValorPorTag('nProt'); end; if self.FACBrNFe.EnviarEvento(1) then begin NotaFiscal.NFe.Retorno.AlterarStatus(IntToStr(self.FACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat), self.FACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.xMotivo); end; end; function TGeradorNFe.inutilizarNumeracao(nIni, nFim: integer; justificativa :String; Empresa: TEmpresa) :Boolean; var retorno :Integer; begin try try result := false; self.AjustarConfiguracoesDaEmpresa(Empresa.ConfiguracoesNF); self.FACBrNFe.WebServices.Inutiliza(Empresa.cpf_cnpj, justificativa, YearOf(Date), //ano 55, //modelo 1, //serie nIni, nFim); result := true; Except on e :Exception do begin raise Exception.Create(e.Message) end; end; finally retorno := FACBrNFe.WebServices.Inutilizacao.cStat; end; end; procedure TGeradorNFe.ConsultarNFe(NotaFiscal: TNotaFiscal); begin if not Assigned(NotaFiscal) then raise TExcecaoParametroInvalido.Create(self.ClassName, 'ConsultarNFe(NotaFiscal: TNotaFiscal)', 'NotaFiscal'); self.AjustarConfiguracoesDaEmpresa(NotaFiscal.Empresa.ConfiguracoesNF); FACBrNFe.Configuracoes.Geral.ValidarDigest := false; FACBrNFe.NotasFiscais.Clear; FACBrNFe.NotasFiscais.LoadFromString(NotaFiscal.NFe.XMLText); //verificar esse xml com o da receita e ver oq difere FACBrNFe.Consultar; NotaFiscal.AdicionarRetornoNFe(IntToStr(self.FACBrNFe.WebServices.Consulta.cStat), self.FACBrNFe.WebServices.Consulta.xMotivo); self.GerarXML(NotaFiscal); if (NotaFiscal.NFe.Retorno.Status = '100') and not(NotaFiscal.EntrouEstoque = 'S') then begin TUtilitarioEstoque.atualizaEstoquePorNFe(NotaFiscal, IfThen(NotaFiscal.Entrada_saida = 'E', -1, 1)); NotaFiscal.EntrouEstoque := 'S'; end; end; constructor TGeradorNFe.Create(const CaminhoLogo :String); begin self.InicializaComponentes(CaminhoLogo); end; constructor TGeradorNFe.Create; begin self.Create(''); end; destructor TGeradorNFe.Destroy; begin self.FACBrNFeDANFe.ACBrNFe := nil; FreeAndNil(self.FACBrNFe); FreeAndNil(self.FACBrNFeDANFE); inherited; end; procedure TGeradorNFe.EmitirNFe(NotaFiscal: TNotaFiscal); begin if not Assigned(NotaFiscal) then raise TExcecaoParametroInvalido.Create(self.ClassName, 'EmitirNFe(NotaFiscal: TNotaFiscal)', 'NotaFiscal'); self.FACBrNFe.NotasFiscais.Clear; self.AjustarConfiguracoesDaEmpresa(NotaFiscal.Empresa.ConfiguracoesNF); self.GerarNFe(NotaFiscal); self.FACBrNFe.NotasFiscais.GerarNFe; self.FACBrNFe.NotasFiscais.Assinar; self.FACBrNFe.NotasFiscais.Validar; self.FACBrNFe.WebServices.Enviar.Lote := IntToStr(NotaFiscal.Lote.Codigo); if not(self.FACBrNFe.WebServices.Enviar.Executar) then raise Exception.Create(self.FACBrNFe.WebServices.Enviar.Msg); NotaFiscal.AdicionarRetornoLote(IntToStr(self.FACBrNFe.WebServices.Enviar.cStat), self.FACBrNFe.WebServices.Enviar.xMotivo, self.FACBrNFe.WebServices.Enviar.Recibo); NotaFiscal.AdicionarChaveAcesso(self.FACBrNFe.NotasFiscais.Items[0].NFe.infNFe.ID, self.FACBrNFe.NotasFiscais.Items[0].XML); end; procedure TGeradorNFe.EnviarEmail(NotaFiscal :TNotaFiscal); var CC :TStrings; EmailsDestinatario :TStrings; nX :Integer; aux :String; ACBrMail1 :TACBrMail; Mensagem :String; begin EmailsDestinatario := nil; CC := nil; if not Assigned(NotaFiscal) then raise TExcecaoParametroInvalido.Create(self.ClassName, 'EnviarEmail(NotaFiscal :TNotaFiscal)', 'NotaFiscal'); if (NotaFiscal.Status <> snfAutorizada) then raise TExcecaoNotaFiscalInvalida.Create('A nota não está com status de enviada. Não é possível enviar e-mail com XML!'); if not Assigned(NotaFiscal.Empresa.ConfiguracoesEmail) then //raise Exception.Create('Nenhuma configuração de e-mail configurada!'); exit; if NotaFiscal.Destinatario.Email.IsEmpty then exit; // raise Exception.Create('O destinatário '+IntToStr(NotaFiscal.Destinatario.Codigo)+' - '+NotaFiscal.Destinatario.Razao+' não possui e-mails cadastrados!'); try ACBrMail1 := TACBrMail.Create(nil); EmailsDestinatario := TStringList.Create; EmailsDestinatario.Delimiter := ';'; EmailsDestinatario.DelimitedText := NotaFiscal.Destinatario.Email; CC := TStringList.Create; for nX := 0 to (EmailsDestinatario.Count-1) do begin if not(EmailsDestinatario[nX].IsEmpty) then CC.Add(EmailsDestinatario[nX]); end; if NotaFiscal.NFe.XMLText.IsEmpty then NotaFiscal.RecarregarNFe; ACBrMail1.Host := NotaFiscal.Empresa.ConfiguracoesEmail.smtp_host; ACBrMail1.Port := NotaFiscal.Empresa.ConfiguracoesEmail.smtp_port; ACBrMail1.Username := NotaFiscal.Empresa.ConfiguracoesEmail.smtp_user; ACBrMail1.Password := NotaFiscal.Empresa.ConfiguracoesEmail.smtp_password; ACBrMail1.From := NotaFiscal.Empresa.ConfiguracoesEmail.smtp_user; { Remetente } ACBrMail1.SetSSL := NotaFiscal.Empresa.ConfiguracoesEmail.usa_ssl = 'S'; // SSL - Conexão Segura ACBrMail1.SetTLS := false; // Auto TLS ACBrMail1.ReadingConfirmation := False; //Pede confirmação de leitura do email ACBrMail1.UseThread := False; //Aguarda Envio do Email(não usa thread) ACBrMail1.FromName := NotaFiscal.Emitente.Razao; self.FACBrNFe.MAIL := ACBrMail1; Mensagem := #13#10+#13#10+'ATENÇÃO, favor não responder. '+#13#10+#13#10+ 'Esta mensagem refere-se à Nota Fiscal Eletrônica de número '+intToStr(NotaFiscal.NumeroNotaFiscal)+', emitida em '+DateToStr(NotaFiscal.DataEmissao)+' por:'+#13#10+ 'Razão Social: '+NotaFiscal.Emitente.Razao+#13#10+ 'CNPJ: '+NotaFiscal.Emitente.CPF_CNPJ+#13#10+#13#10+ 'Chave de acesso: '+NotaFiscal.NFe.ChaveAcesso +#13#10+#13#10+ 'Obs.: Este e-mail foi enviado automaticamente pelo sistema Smart Chef da empresa CBN Informática - (43) 3534-2350.'; NotaFiscal.Empresa.ConfiguracoesEmail.Mensagem.Add(Mensagem); self.FACBrNFe.NotasFiscais.Clear; self.FACBrNFe.NotasFiscais.LoadFromString(NotaFiscal.NFe.XMLText); self.FACBrNFe.NotasFiscais.Items[0].EnviarEmail( CC[0], NotaFiscal.Empresa.ConfiguracoesEmail.Assunto, NotaFiscal.Empresa.ConfiguracoesEmail.Mensagem, True, // Enviar PDF junto CC, // Lista com emails que serão enviado cópias - TStrings nil); // Lista de anexos - TStrings finally FreeAndNil(EmailsDestinatario); FreeAndNil(CC); FreeAndNil(ACBrMail1); end; end; procedure TGeradorNFe.GerarDadosDaCobranca(NFe :ACBrNFeNotasFiscais.NotaFiscal); var nX :Integer; // Duplicata :TDuplicata; begin { if not Assigned(self.FFatura) then exit; { Fatura } { NFe.NFe.Cobr.Fat.nFat := self.FFatura.NumeroFaturaStr; NFe.NFe.Cobr.Fat.vOrig := self.FFatura.ValorBruto; NFe.NFe.Cobr.Fat.vDesc := self.FFatura.ValorDesconto; NFe.NFe.Cobr.Fat.vLiq := self.FFatura.ValorLiquido; NFe.NFe.Cobr.Dup.Clear; { Duplicatas } { for nX := 0 to (self.FFatura.Duplicatas.Count-1) do begin Duplicata := (self.FFatura.Duplicatas[nX] as TDuplicata); with NFe.NFe.Cobr.Dup.Add do begin nDup := Duplicata.NumeroDuplicata; dVenc := Duplicata.DataVencimento; vDup := Duplicata.ValorDuplicata; end; end; } end; procedure TGeradorNFe.GerarDadosProdutos(NF :TNotaFiscal; NFe :ACBrNFeNotasFiscais.NotaFiscal); var nX :Integer; Item :TItemNotaFiscal; ItemNFe :TDetCollectionItem; Itens :TObjectList<TITemNotaFiscal>; tot_desc_somado, diferenca :REal; icms_partilha :Real; perc_destinatario :Real; sim :boolean; begin sim := true; Itens := NF.Itens; tot_desc_somado := 0; tot_icm_somado := 0; tot_frete_somado := 0; tot_bcicms_somada := 0; tot_produto_somado := 0; diferenca := 0; icms_partilha := 0; for nX := 0 to (Itens.Count-1) do begin ItemNFe := nfe.NFe.Det.Add; Item := (Itens[nX] as TItemNotaFiscal); { Grupo de Detalhamento de Produtos e Serviços da NF-e } ItemNFe.Prod.nItem := (nX+1); ItemNFe.Prod.cProd := IntToStr(Item.Produto.codigo); ItemNFe.Prod.xProd := Item.Produto.Descricao; ItemNFe.Prod.NCM := Item.Produto.NCMIbpt.ncm_ibpt; ItemNFe.Prod.CFOP := Item.NaturezaOperacao.CFOP; ItemNFe.Prod.uCom := Item.Produto.Estoque.unidade_medida; ItemNFe.Prod.vUnCom := Item.ValorUnitario; ItemNFe.Prod.qCom := Item.Quantidade; ItemNFe.Prod.vProd := RoundTo(Item.ValorBruto,-2); ItemNFe.Prod.uTrib := Item.Produto.Estoque.unidade_medida; ItemNFe.Prod.vUnTrib := Item.ValorUnitario; ItemNFe.Prod.qTrib := Item.Quantidade; ItemNFe.Prod.vFrete := Item.ValorFrete; ItemNFe.Prod.vSeg := Item.ValorSeguro; ItemNFe.Prod.vDesc := Item.ValorDesconto; ItemNFe.Prod.vOutro := Item.ValorOutrasDespesas; tot_frete_somado := tot_frete_somado + RoundTo(Item.ValorFrete, -2); tot_produto_somado := tot_produto_somado + ItemNFe.Prod.vProd; tot_desc_somado := tot_desc_somado + Item.ValorDesconto; if (nX = (Itens.Count - 1)) then begin diferenca := tot_desc_somado - NF.Totais.Descontos; ItemNFe.Prod.vDesc := ItemNFe.Prod.vDesc - diferenca; end; { ICMS } if Nf.CalculaIcmsCompartilhado then begin ItemNFe.Imposto.ICMSUFDest.vBCUFDest := Item.ValorTotalItem; ItemNFe.Imposto.ICMSUFDest.pFCPUFDest := NF.AliquotaFCP; ItemNFe.Imposto.ICMSUFDest.pICMSUFDest := Nf.AliquotaInterna; ItemNFe.Imposto.ICMSUFDest.pICMSInter := NF.AliquotaInterestadual; ItemNFe.Imposto.ICMSUFDest.pICMSInterPart := Nf.AliquotaPartilhaDestinatario; ItemNFe.Imposto.ICMSUFDest.vFCPUFDest := 0;//((ItemNFe.Imposto.ICMSUFDest.pFCPUFDest * ItemNFe.Imposto.ICMSUFDest.vBCUFDest) /100); icms_partilha := roundto(Item.ValorTotalItem * ((ItemNFe.Imposto.ICMSUFDest.pICMSUFDest - ItemNFe.Imposto.ICMSUFDest.pICMSInter + ItemNFe.Imposto.ICMSUFDest.pFCPUFDest) / 100), -2); ItemNFe.Imposto.ICMSUFDest.vICMSUFDest := 0;//roundTo( (icms_partilha * Nf.AliquotaPartilhaDestinatario) /100, -2); ItemNFe.Imposto.ICMSUFDest.vICMSUFRemet := 0;//roundTo( icms_partilha - ItemNFe.Imposto.ICMSUFDest.vICMSUFDest, -2); end; { ICMS para L.P/L.R. } if Assigned(Item.Icms00) then begin case Item.Icms00.OrigemMercadoria of tomNacional: ItemNFe.Imposto.ICMS.orig := oeNacional; tomEstrangeiraImportacaoDireta: ItemNFe.Imposto.ICMS.orig := oeEstrangeiraImportacaoDireta; tomEstrangeiraAdquiridaMercadoInterno: ItemNFe.Imposto.ICMS.orig := oeEstrangeiraAdquiridaBrasil; end; //padrao ItemNFe.Imposto.ICMS.CST := cst00; ItemNFe.Imposto.ICMS.modBC := dbiValorOperacao; ItemNFe.Imposto.ICMS.vBC := RoundTo(Item.BaseCalculoICMS,-2); ItemNFe.Imposto.ICMS.pICMS := Item.Icms00.Aliquota; //excecao . if Item.NaturezaOperacao.suspensao_icms = 'S' then ItemNFe.Imposto.ICMS.CST := cst50; //cst suspensao ICMS if Nf.NotaDeReducao then begin ItemNFe.Imposto.ICMS.CST := cst51; //cst de diferimento ItemNFe.Imposto.ICMS.pDif := Item.Icms00.PercReducaoBC; ItemNFe.Imposto.ICMS.vICMSOp := RoundTo((ItemNFe.Imposto.ICMS.vBC * Item.Icms00.Aliquota)/100,-2); ItemNFe.Imposto.ICMS.vICMSDif := RoundTo((ItemNFe.Imposto.ICMS.vICMSOp * Item.Icms00.PercReducaoBC) / 100,-2); ItemNFe.Imposto.ICMS.vICMS := RoundTo(ItemNFe.Imposto.ICMS.vICMSOp - ItemNFe.Imposto.ICMS.vICMSDif,-2); end else ItemNFe.Imposto.ICMS.vICMS := RoundTo(Item.ValorICMS,-2); tot_bcicms_somada := tot_bcicms_somada + ItemNFe.Imposto.ICMS.vBC; tot_icm_somado := tot_icm_somado + ItemNFe.Imposto.ICMS.vICMS; if Item.NaturezaOperacao.suspensao_icms = 'S' then ItemNFe.Imposto.ICMS.vBC := 0; end; { ICMS para simples nacional } if Assigned(Item.IcmsSn101) then begin case Item.IcmsSn101.OrigemMercadoria of tomNacional: ItemNFe.Imposto.ICMS.orig := oeNacional; tomEstrangeiraImportacaoDireta: ItemNFe.Imposto.ICMS.orig := oeEstrangeiraImportacaoDireta; tomEstrangeiraAdquiridaMercadoInterno: ItemNFe.Imposto.ICMS.orig := oeEstrangeiraAdquiridaBrasil; end; { if NF.Destinatario.Pessoa = 'F' then begin } ItemNFe.Imposto.ICMS.CSOSN := StrToEnumerado(sim, Item.Produto.NcmIBPT.cst, ['', '101' ,'102', '103', '201', '202', '203', '300', '400', '500', '900'], [csosnVazio, csosn101, csosn102, csosn103, csosn201, csosn202, csosn203, csosn300, csosn400, csosn500,csosn900]); { end else ItemNFe.Imposto.ICMS.CSOSN := csosn102; //csosn101; } ItemNFe.Imposto.ICMS.pCredSN := Item.IcmsSn101.AliquotaCreditoSN; ItemNFe.Imposto.ICMS.vCredICMSSN := Item.IcmsSn101.ValorCreditoSN; end; { IPI } ItemNFe.Imposto.IPI.clEnq := '999'; { IPI para lucro presumido } if Assigned(Item.IpiTrib) then begin ItemNFe.Imposto.IPI.CST := ipi50; ItemNFe.Imposto.IPI.vBC := Item.IpiTrib.BaseCalculo; ItemNFe.Imposto.IPI.pIPI := Item.IpiTrib.Aliquota; ItemNFe.Imposto.IPI.vIPI := Item.IpiTrib.Valor; end; { IPI para simples nacional } if Assigned(Item.IpiNt) then ItemNFe.Imposto.IPI.CST := ipi51; { PIS } { PIS para L.P/L.R. } if Assigned(Item.PisAliq) then begin //padrao ItemNFe.Imposto.PIS.CST := pis02; //excecao if Item.NaturezaOperacao.suspensao_icms = 'S' then ItemNFe.Imposto.PIS.CST := pis09; //cst suspensao PIS ItemNFe.Imposto.PIS.vBC := Item.PisAliq.BaseCalculo; ItemNFe.Imposto.PIS.pPIS := Item.PisAliq.Aliquota; ItemNFe.Imposto.PIS.vPIS := Item.PisAliq.Valor; if Item.NaturezaOperacao.suspensao_icms = 'S' then ItemNFe.Imposto.PIS.vBC := 0; end; { PIS para simples nacional } if Assigned(Item.PisNt) then ItemNFe.Imposto.PIS.CST := pis07; { COFINS } { COFINS para L.P/L.R. } if Assigned(Item.CofinsAliq) then begin //padrao ItemNFe.Imposto.COFINS.CST := cof02; //excecao if Item.NaturezaOperacao.suspensao_icms = 'S' then ItemNFe.Imposto.COFINS.CST := cof09; //cst suspensao COFINS ItemNFe.Imposto.COFINS.vBC := Item.CofinsAliq.BaseCalculo; ItemNFe.Imposto.COFINS.pCOFINS := Item.CofinsAliq.Aliquota; ItemNFe.Imposto.COFINS.vCOFINS := Item.CofinsAliq.Valor; if Item.NaturezaOperacao.suspensao_icms = 'S' then ItemNFe.Imposto.COFINS.vBC := 0; end; { COFINS para simples nacional } if Assigned(Item.CofinsNt) then begin ItemNFe.Imposto.COFINS.CST := cof07; end; end; end; procedure TGeradorNFe.GerarDestinatario (NF :TNotaFiscal; NFe :ACBrNFeNotasFiscais.NotaFiscal); begin if UpperCase(TRIM(NF.Destinatario.RG_IE)) = 'ISENTO' then begin if (length(NF.Destinatario.CPF_CNPJ) < 14) then nfe.NFe.Dest.indIEDest := inNaoContribuinte else begin if NF.Destinatario.Enderecos[0].Cidade.Estado.sigla <> 'SP' then nfe.NFe.Dest.indIEDest := inIsento else begin nfe.NFe.Dest.indIEDest := inNaoContribuinte; nfe.NFe.Ide.indFinal := cfConsumidorFinal; end; end; end else if UpperCase(TRIM(NF.Destinatario.RG_IE)) = '' then nfe.NFe.Dest.indIEDest := inNaoContribuinte else begin nfe.NFe.Dest.indIEDest := inContribuinte; nfe.NFe.Dest.IE := NF.Destinatario.RG_IE; end; nfe.NFe.Dest.CNPJCPF := NF.Destinatario.CPF_CNPJ; nfe.NFe.Dest.xNome := NF.Destinatario.Razao; nfe.NFe.Dest.EnderDest.xLgr := NF.Destinatario.Enderecos[0].Logradouro; nfe.NFe.Dest.EnderDest.cPais := 1058; nfe.NFe.Dest.EnderDest.xPais := 'BRASIL'; nfe.NFe.Dest.EnderDest.nro := NF.Destinatario.Enderecos[0].Numero; nfe.NFe.Dest.EnderDest.xBairro := NF.Destinatario.Enderecos[0].Bairro; nfe.NFe.Dest.EnderDest.cMun := NF.Destinatario.Enderecos[0].Cidade.codibge; nfe.NFe.Dest.EnderDest.xMun := NF.Destinatario.Enderecos[0].Cidade.nome; nfe.NFe.Dest.EnderDest.UF := NF.Destinatario.Enderecos[0].Cidade.Estado.sigla; nfe.NFe.Dest.EnderDest.CEP := StrToIntDef(ApenasNumeros(NF.Destinatario.Enderecos[0].cep),0); nfe.NFe.Dest.EnderDest.fone := ApenasNumeros(NF.Destinatario.Fone1); end; procedure TGeradorNFe.GerarEmitente(NF :TNotaFiscal; NFe: ACBrNFeNotasFiscais.NotaFiscal); begin nfe.NFe.Emit.CNPJCPF := NF.Emitente.CPF_CNPJ; nfe.NFe.Emit.xNome := NF.Emitente.Razao; nfe.NFe.Emit.xFant := NF.Emitente.Razao; nfe.NFe.Emit.EnderEmit.xLgr := NF.Emitente.Enderecos[0].Logradouro; nfe.NFe.Emit.EnderEmit.nro := NF.Emitente.Enderecos[0].Numero; nfe.NFe.Emit.EnderEmit.xBairro := NF.Emitente.Enderecos[0].Bairro; nfe.NFe.Emit.EnderEmit.cMun := NF.Emitente.Enderecos[0].Cidade.codibge; nfe.NFe.Ide.cMunFG := NF.Emitente.Enderecos[0].Cidade.codibge; nfe.NFe.Emit.EnderEmit.xMun := NF.Emitente.Enderecos[0].Cidade.nome; nfe.NFe.Emit.EnderEmit.UF := NF.Emitente.Enderecos[0].Cidade.Estado.sigla; nfe.NFe.Emit.EnderEmit.CEP := StrToInt(ApenasNumeros(NF.Emitente.Enderecos[0].CEP)); nfe.NFe.Emit.EnderEmit.fone := ApenasNumeros(NF.Emitente.Fone1); nfe.NFe.Emit.IE := NF.Emitente.RG_IE; //nfe.NFe.Emit.CRT := crtRegimeNormal; { Para o caso do emitente ser empresa } case NF.Empresa.ConfiguracoesNF.RegimeTributario of trtSimplesNacional: nfe.NFe.Emit.CRT := crtSimplesNacional; trtLucroPresumido: nfe.NFe.Emit.CRT := crtRegimeNormal; end; end; procedure TGeradorNFe.GerarIdentificacao(NF: TNotaFiscal; NFe: ACBrNFeNotasFiscais.NotaFiscal); begin nfe.NFe.Ide.cUF := 41; nfe.NFe.Ide.cNF := NF.NumeroNotaFiscal; nfe.NFe.Ide.natOp := NF.CFOP.Descricao; {if Assigned(self.FFatura) then nfe.NFe.Ide.indPag := ipPrazo else } nfe.NFe.Ide.indPag := ipVista; nfe.NFe.Ide.modelo := 55; nfe.NFe.Ide.serie := StrToInt(NF.Serie); nfe.NFe.Ide.nNF := NF.NumeroNotaFiscal; nfe.NFe.Ide.dEmi := NF.DataEmissao; nfe.NFe.Ide.dSaiEnt := NF.DataSaida; case StrToInt(NF.Finalidade) of 1 : nfe.NFe.Ide.finNFe := fnNormal; 2 : nfe.NFe.Ide.finNFe := fnComplementar; 3 : nfe.NFe.Ide.finNFe := fnAjuste; 4 : nfe.NFe.Ide.finNFe := fnDevolucao; end; if nfe.NFe.Ide.finNFe = fnDevolucao then with nfe.NFe.Ide.NFref.Add do begin refNFe := NF.NFe_referenciada; end; if (NF.CFOP.Tipo in [tnoSaidaDentroEstado, tnoSaidaForaEstado, tnoExportacao]) then nfe.NFe.Ide.tpNF := tnSaida else nfe.NFe.Ide.tpNF := tnEntrada; if not assigned(Nf.Destinatario.Enderecos[0].Cidade) then raise Exception.Create('Cidade do destinatário não foi cadastrada'); case AnsiIndexStr(UpperCase(Nf.Destinatario.Enderecos[0].Cidade.estado.sigla), [NF.Emitente.Enderecos[0].Cidade.estado.sigla, 'XX']) of 0 : nfe.NFe.Ide.idDest := doInterna; 1 : nfe.NFe.Ide.idDest := doExterior; else nfe.NFe.Ide.idDest := doInterestadual; end; case IfThen( length(Nf.Destinatario.CPF_CNPJ)>13,0,1) of 0: nfe.NFe.Ide.indFinal := cfNao; 1: nfe.NFe.Ide.indFinal := cfConsumidorFinal; end; nfe.NFe.Ide.indPres := pcTeleatendimento; nfe.NFe.Ide.cMunFG := 0; nfe.NFe.Ide.tpImp := tiRetrato; nfe.NFe.Ide.tpEmis := self.FACBrNFe.Configuracoes.Geral.FormaEmissao; if NF.Empresa.ConfiguracoesNF.Tipo_emissao = 7 then begin nfe.NFe.Ide.xJust := 'Indisponibilidade do ambiente normal de autorização'; nfe.NFe.Ide.dhCont := NF.Empresa.ConfiguracoesNF.Dt_contingencia; end; nfe.NFe.Ide.cDV := 0; nfe.NFe.Ide.tpAmb := self.FACBrNFe.Configuracoes.WebServices.Ambiente; nfe.NFe.Ide.procEmi := peAplicativoContribuinte; nfe.NFe.Ide.verProc := '1.0'; //versao do erp end; procedure TGeradorNFe.GerarLocalEntrega(NF :TNotaFiscal; NFe: ACBrNFeNotasFiscais.NotaFiscal); //LocalEntrega :TLocalEntregaNotaFiscal; begin { if not Assigned(NF.LocalEntrega) then exit; LocalEntrega := NF.LocalEntrega; if TStringUtilitario.EstaVazia(LocalEntrega.CnpjCpf) then exit; nfe.NFe.Entrega.CNPJCPF := LocalEntrega.CnpjCpf; nfe.NFe.Entrega.xLgr := LocalEntrega.Logradouro; nfe.NFe.Entrega.xCpl := LocalEntrega.Complemento; nfe.NFe.Entrega.xBairro := LocalEntrega.Bairro; nfe.NFE.Entrega.nro := LocalEntrega.Numero; nfe.NFe.Entrega.cMun := LocalEntrega.CodigoMunicipio; nfe.NFe.Entrega.xMun := LocalEntrega.NomeMunicipio; nfe.NFe.Entrega.UF := LocalEntrega.UF; } end; function TGeradorNFe.GerarNFe(NF :TNotaFiscal) :ACBrNFeNotasFiscais.NotaFiscal; begin result := self.FACBrNFe.NotasFiscais.Add; if NF.Empresa.ConfiguracoesNF.Tipo_emissao > 1 then case NF.Empresa.ConfiguracoesNF.Tipo_emissao of 7: self.FACBrNFe.Configuracoes.Geral.FormaEmissao := teSVCRS; end; self.GerarIdentificacao (NF, result); self.GerarEmitente (NF, result); self.GerarDestinatario (NF, result); self.GerarLocalEntrega (NF, result); self.GerarDadosProdutos (NF, result); self.GerarValoresTotais (NF, result); self.GerarTransportador (NF, result); self.GerarVolumes (NF, result); self.GerarObservacao (NF, result); self.GerarDadosDaCobranca(result); end; procedure TGeradorNFe.GerarObservacao(NF :TNotaFiscal; NFe :ACBrNFeNotasFiscais.NotaFiscal); var Observacoes :TObservacaoNotaFiscal; begin if not Assigned(NF.Observacoes) then exit; Observacoes := NF.Observacoes; nfe.NFe.InfAdic.infCpl := Observacoes.DadosAdicionais; if NF.CalculaIcmsCompartilhado then { nfe.NFe.InfAdic.infCpl := nfe.NFe.InfAdic.infCpl + #13#10+'PARTILHA ICMS OPERAÇÃO INTERESTADUAL CONSUMIDOR FINAL, DISPOSTO NA EMENDA CONSTITUCIONAL 87/2015. '+ 'VALOR ICMS UF DESTINO: '+ TStringUtilitario.FormataDinheiro(nfe.NFe.Total.ICMSTot.vICMSUFDest) + ' - VALOR ICMS UF REMETENTE: '+ TStringUtilitario.FormataDinheiro(nfe.NFe.Total.ICMSTot.vICMSUFRemet); } end; procedure TGeradorNFe.GerarTransportador(NF: TNotaFiscal; NFe: ACBrNFeNotasFiscais.NotaFiscal); begin if (NF.TipoFrete = tfCIF) then nfe.NFe.Transp.modFrete := mfContaEmitente else nfe.NFe.Transp.modFrete := mfContaDestinatario; if not assigned(NF.Transportadora) then exit; nfe.NFe.Transp.Transporta.CNPJCPF := NF.Transportadora.CPF_CNPJ; nfe.NFe.Transp.Transporta.xNome := NF.Transportadora.Razao; nfe.NFe.Transp.Transporta.IE := NF.Transportadora.RG_IE; nfe.NFe.Transp.Transporta.xEnder := NF.Transportadora.Enderecos[0].Logradouro; nfe.NFe.Transp.Transporta.xMun := NF.Transportadora.Enderecos[0].Cidade.nome; nfe.NFe.Transp.Transporta.UF := NF.Transportadora.Enderecos[0].Cidade.Estado.sigla; end; procedure TGeradorNFe.GerarValoresTotais(NF :TNotaFiscal; NFe :ACBrNFeNotasFiscais.NotaFiscal); var Totais :TTotaisNotaFiscal; diferenca :Real; begin if not Assigned(NF.Totais) then exit; Totais := NF.Totais; tot_bcicms_somada := RoundTo(tot_bcicms_somada,-2); if tot_bcicms_somada <> Totais.BaseCalculoICMS then begin diferenca := (tot_bcicms_somada - Totais.BaseCalculoICMS); end; nfe.NFe.Total.ICMSTot.vBC := Totais.BaseCalculoICMS + diferenca; diferenca := 0; //gamb pra concertar arredondamento tot_icm_somado := RoundTo(tot_icm_somado,-2); if tot_icm_somado <> Totais.ICMS then begin diferenca := (tot_icm_somado - Totais.ICMS); end; nfe.NFe.Total.ICMSTot.vICMS := Totais.ICMS + diferenca; nfe.NFe.Total.ICMSTot.vBCST := Totais.BaseCalculoST; nfe.NFe.Total.ICMSTot.vST := Totais.ICMSST; nfe.NFe.Total.ICMSTot.vFCPUFDest := 0;//Totais.ICMSFCP; nfe.NFe.Total.ICMSTot.vICMSUFDest := 0;//Totais.ICMSUFDest; nfe.NFe.Total.ICMSTot.vICMSUFRemet := 0;//Totais.ICMSUFRemet; diferenca := 0; tot_produto_somado := RoundTo(tot_produto_somado,-2); if tot_produto_somado <> Totais.TotalProdutos then begin diferenca := (tot_produto_somado - Totais.TotalProdutos); end; nfe.NFe.Total.ICMSTot.vProd := Totais.TotalProdutos + diferenca; diferenca := 0; tot_frete_somado := RoundTo(tot_frete_somado, -2); if tot_frete_somado <> Totais.Frete then begin diferenca := (tot_frete_somado - Totais.Frete); end; nfe.NFe.Total.ICMSTot.vFrete := Totais.Frete + diferenca; nfe.NFe.Total.ICMSTot.vSeg := Totais.Seguro; nfe.NFe.Total.ICMSTot.vDesc := Totais.Descontos; nfe.NFe.Total.ICMSTot.vIPI := Totais.IPI; nfe.NFe.Total.ICMSTot.vOutro := Totais.OutrasDespesas; nfe.NFe.Total.ICMSTot.vNF := Totais.TotalNF; nfe.NFe.Total.ICMSTot.vPIS := Totais.PIS; nfe.NFe.Total.ICMSTot.vCOFINS := Totais.COFINS; end; procedure TGeradorNFe.GerarVolumes(NF :TNotaFiscal; NFe: ACBrNFeNotasFiscais.NotaFiscal); var Volume :TVolCollectionItem; VolumesNotaFiscal :TVolumesNotaFiscal; begin if not Assigned(NF.Volumes) then exit; VolumesNotaFiscal := NF.Volumes; Volume := nfe.NFe.Transp.Vol.Add; Volume.qVol := VolumesNotaFiscal.QuantidadeVolumes; Volume.esp := VolumesNotaFiscal.Especie; Volume.pesoL := VolumesNotaFiscal.PesoLiquido; Volume.pesoB := VolumesNotaFiscal.PesoBruto; end; procedure TGeradorNFe.GerarXML(NotaFiscal: TNotaFiscal); var XMLStream :TStringStream; begin if not Assigned(NotaFiscal) then raise TExcecaoParametroInvalido.Create(self.ClassName, 'GerarXML(NotaFiscal: TNotaFiscal)', 'NotaFiscal'); XMLStream := nil; try if (NotaFiscal.Status = snfAutorizada) or (NotaFiscal.Status = snfRejeitada) then begin XMLStream := TStringStream.Create(''); self.FACBrNFe.NotasFiscais.Items[0].GravarStream(XMLStream); NotaFiscal.NFe.AdicionarXML(XMLStream); end else if (NotaFiscal.Status = snfCancelada) then begin XMLStream := TStringStream.Create(self.FACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.XMl); NotaFiscal.NFe.AdicionarXML(XMLStream); end; finally FreeAndNil(XMLStream); end; end; procedure TGeradorNFe.ImprimirComVisualizacao(NotaFiscal: TNotaFiscal); begin if not Assigned(NotaFiscal) then raise TExcecaoParametroInvalido.Create(self.ClassName, 'ImprimirDireto(NotaFiscal :TNotaFiscal; const CaminhoDoLogo :String)', 'NotaFiscal'); self.FACBrNFe.NotasFiscais.Clear; if (NotaFiscal.Status = snfAutorizada) then self.FACBrNFe.NotasFiscais.LoadFromString(NotaFiscal.NFe.XMLText) else self.GerarNFe(NotaFiscal); self.FACBrNFeDANFE.MostrarPreview := true; self.FACBrNFeDANFE.ImprimirDANFE(); end; procedure TGeradorNFe.ImprimirDireto(NotaFiscal :TNotaFiscal); begin if not Assigned(NotaFiscal) then raise TExcecaoParametroInvalido.Create(self.ClassName, 'ImprimirDireto(NotaFiscal :TNotaFiscal; const CaminhoDoLogo :String)', 'NotaFiscal'); self.FACBrNFe.NotasFiscais.Clear; self.FACBrNFe.NotasFiscais.LoadFromString(NotaFiscal.NFe.XMLText); self.FACBrNFeDANFE.MostrarPreview := false; self.FACBrNFeDANFE.ImprimirDANFE(); end; procedure TGeradorNFe.InicializaComponentes(const CaminhoLogo :String); begin { ACBrNFe (Configurações do WebService) } self.FACBrNFe := TACBrNFe.Create(nil); //Pode mudar isso aqui self.FACBrNFe.Configuracoes.WebServices.IntervaloTentativas := 4000; self.FACBrNFe.Configuracoes.WebServices.Tentativas := 5; self.FACBrNFe.Configuracoes.WebServices.UF := 'PR'; self.FACBrNFe.Configuracoes.WebServices.Visualizar := false; // Mensagens self.FACBrNFe.Configuracoes.Geral.FormaEmissao := teNormal; self.FACBrNFe.Configuracoes.Geral.ModeloDF := moNFe; self.FACBrNFe.Configuracoes.Geral.VersaoDF := ve310; self.FACBrNFe.Configuracoes.Geral.SSLLib := libCapicom; { DANFE (Configurações da Impressão do DANFE)} self.FACBrNFeDANFe := TACBrNFeDANFeRL.Create(nil); self.FACBrNFeDANFe.ACBrNFe := self.FACBrNFe; self.FACBrNFeDANFe.ProdutosPorPagina := 30; if not CaminhoLogo.IsEmpty then self.FACBrNFeDANFE.Logo := CaminhoLogo; // self.FFatura := nil; end; function TGeradorNFe.ObterCertificado: String; begin result := self.FACBrNFe.SSL.SelecionarCertificado; end; procedure TGeradorNFe.Recarregar; var CaminhoLogo :String; begin CaminhoLogo := self.FACBrNFeDANFE.Logo; self.FACBrNFeDANFE.ACBrNFe := nil; FreeAndNil(self.FACBrNFe); FreeAndNil(self.FACBrNFeDANFE); self.InicializaComponentes(CaminhoLogo); end; end.
(* * Pascal wrapper unit for Gordon Henderson wiringPi library. * The source can be found at https://http://wiringpi.com * * wiringpi.pas: version 0.1 by Melchiorre Caruso * Copyright (c) 2014-2019 Melchiorre Caruso * * wiringPi.h: * Arduino like Wiring library for the Raspberry Pi. * Copyright (c) 2012-2016 Gordon Henderson *********************************************************************** * This file is part of wiringPi: * https://projects.drogon.net/raspberry-pi/wiringpi/ * * wiringPi is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * wiringPi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with wiringPi. If not, see <http://www.gnu.org/licenses/>. *********************************************************************** *) unit wiringpi; {$mode objfpc} {$h+} {$linklib c} {$linklib libwiringPi} interface const // Pin mappings from P1 connector to WiringPi library // Px represents to physical pin on the RaspberryPi P1 connector // P1 = 3.3V // P2 = 5V P3 = 8; // P4 = 5V P5 = 9; //P6 = GND P7 = 7; P8 = 15; //P9 = GND P10 = 16; P11 = 0; P12 = 1; P13 = 2; //P14 = GND P15 = 3; P16 = 4; // P17 = 3.3V P18 = 5; P19 = 12; // P20 = GND P21 = 13; P22 = 6; P23 = 14; P24 = 10; // P25 = GND P26 = 11; // pi2 P27 = 30; P28 = 31; P29 = 21; // P30 = GND P31 = 22; P32 = 26; P33 = 23; // P34 = GND P35 = 24; P36 = 27; P37 = 25; P38 = 28; // P39 = GND P40 = 29; // Pin modes INPUT = 0; OUTPUT = 1; PWM_OUTPUT = 2; GPIO_CLOCK = 3; SOFT_PWM_OUTPUT = 4; SOFT_TONE_OUTPUT = 5; PWM_TONE_OUTPUT = 6; LOW = 0; HIGH = 1; // Pull up/down/none PUD_OFF = 0; PUD_DOWN = 1; PUD_UP = 2; // PWM PWM_MODE_MS = 0; PWM_MODE_BAL = 1; // Interrupt levels INT_EDGE_SETUP = 0; INT_EDGE_FALLING = 1; INT_EDGE_RISING = 2; INT_EDGE_BOTH = 3; type // wiringPiNodeStruct pwiringPiNodes = ^wiringPiNodeStruct; pwiringPiNodeStruct = ^wiringPiNodeStruct; wiringPiNodeStruct = packed record pinBase: longint; pinMax: longint; fd: longint; data0: dword; data1: dword; data2: dword; data3: dword; pinMode: procedure (node: pwiringPiNodeStruct; pin: longint; mode: longint); cdecl; pullUpDnControl: procedure (node: pwiringPiNodeStruct; pin: longint; mode: longint); cdecl; digitalRead: function (node: pwiringPiNodeStruct; pin: longint): longint; cdecl; digitalWrite: procedure (node: pwiringPiNodeStruct; pin: longint; value: longint); cdecl; pwmWrite: procedure (node: pwiringPiNodeStruct; pin: longint; value: longint); cdecl; analogRead: function (node: pwiringPiNodeStruct; pin: longint): longint; cdecl; analogWrite: procedure (node: pwiringPiNodeStruct; pin: longint; value: longint); cdecl; next: pwiringPiNodeStruct; end; // Core wiringPi functions function wiringPiFindNode(pin: longint): pwiringPiNodeStruct; cdecl; external; function wiringPiNewNode(pinBase: longint; numPins: longint): pwiringPiNodeStruct; cdecl; external; function wiringPiSetup : longint; cdecl; external; function wiringPiSetupGpio: longint; cdecl; external; procedure pinMode (pin: longint; mode: longint); cdecl; external; procedure pullUpDnControl(pin: longint; pud: longint); cdecl; external; function digitalRead (pin: longint): longint; cdecl; external; procedure digitalWrite(pin: longint; value: longint); cdecl; external; procedure pwmWrite(pin: longint; value: longint); cdecl; external; function analogRead (pin: longint): longint; cdecl; external; procedure analogWrite(pin: longint; value: longint); cdecl; external; // Raspberry Pi Specifics function digitalReadByte: dword; cdecl; external; procedure digitalWriteByte(value:longint); cdecl; external; procedure pwmSetMode (mode: longint); cdecl; external; procedure pwmSetRange(range: dword); cdecl; external; procedure pwmSetClock(divisor: longint); cdecl; external; function piBoardRev: longint; cdecl; external; function wpiPinToGpio(wpiPin: longint): longint; cdecl; external; // Timming procedure delay(howLong: dword); cdecl; external; procedure delayMicroseconds(howLong: dword); cdecl; external; function millis: dword; cdecl; external; function micros: dword; cdecl; external; // Thread Priority function piHiPri(pri: longint): longint; cdecl; external; // Interrupts function wiringPiISR(pin: longint; mode: longint; pcallback: pointer):longint; cdecl; external; // SPI Library function wiringPiSPISetup (channel, speed: longint): longint; cdecl; external; function wiringPiSPIDataRW(channel: longint; data: pointer; len: longint): longint; cdecl; external; // I2C Library function wiringPiI2CSetup(const devId: longint): longint; cdecl; external; function wiringPiI2CRead (fd: longint): longint; cdecl; external; function wiringPiI2CWrite(fd, data: longint): longint; cdecl; external; function wiringPiI2CReadReg8 (fd, reg: longint): longint; cdecl; external; function wiringPiI2CReadReg16(fd, reg: longint): longint; cdecl; external; function wiringPiI2CWriteReg8 (fd, reg, data: longint): longint; cdecl; external; function wiringPiI2CWriteReg16(fd, reg, data: longint): longint; cdecl; external; // Software PWM Library function softPwmCreate(pin, value, range: longint): longint; cdecl; external; procedure softPwmWrite (pin, value: longint); cdecl; external; // Software Tone Library function softToneCreate(pin: longint): longint; cdecl; external; procedure softToneWrite (pin, freq: longint); cdecl; external; implementation end.
unit ConstructorOverloadingForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs; type TForm1 = class(TForm) private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} uses DateUtils; type TDate = class private FDate: TDateTime; public constructor Create; overload; constructor Create(Month, Day, Year: Integer); overload; procedure SetValue(Month, Day, Year: Integer); overload; procedure SetValue(NewDate: TDateTime); overload; function LeapYear: Boolean; function GetText: string; procedure Increase(NumberOfDays: Integer = 1); procedure Decrease(NumberOfDays: Integer = 1); end; { TDate } constructor TDate.Create; begin FDate := Today; end; constructor TDate.Create(Month, Day, Year: Integer); begin FDate := EncodeDate(Year, Month, Day); end; function TDate.GetText: string; begin Result := DateToStr(FDate); end; procedure TDate.Increase(NumberOfDays: Integer = 1); begin FDate := FDate + NumberOfDays; end; procedure TDate.Decrease(NumberOfDays: Integer = 1); begin FDate := FDate - NumberOfDays; end; function TDate.LeapYear: Boolean; begin // Call IsLeapYear in SysUtils and YearOf in DateUtils Result := IsLeapYear(YearOf(FDate)); end; procedure TDate.SetValue(NewDate: TDateTime); begin FDate := NewDate; end; procedure TDate.SetValue(Month, Day, Year: Integer); begin FDate := EncodeDate(Year, Month, Day); end; end.
unit uBase256; {$ZEROBASEDSTRINGS ON} interface uses System.SysUtils, uBase, uUtils; type IBase256 = interface ['{66F55DDE-FC44-4BDC-93C7-94956212B66B}'] function Encode(data: TArray<Byte>): String; function Decode(const data: String): TArray<Byte>; function EncodeString(const data: String): String; function DecodeToString(const data: String): String; function GetBitsPerChars: Double; property BitsPerChars: Double read GetBitsPerChars; function GetCharsCount: UInt32; property CharsCount: UInt32 read GetCharsCount; function GetBlockBitsCount: Integer; property BlockBitsCount: Integer read GetBlockBitsCount; function GetBlockCharsCount: Integer; property BlockCharsCount: Integer read GetBlockCharsCount; function GetAlphabet: String; property Alphabet: String read GetAlphabet; function GetSpecial: Char; property Special: Char read GetSpecial; function GetHaveSpecial: Boolean; property HaveSpecial: Boolean read GetHaveSpecial; function GetEncoding: TEncoding; procedure SetEncoding(value: TEncoding); property Encoding: TEncoding read GetEncoding write SetEncoding; end; TBase256 = class(TBase, IBase256) public const DefaultAlphabet = '!' + '#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁł'; DefaultSpecial = Char(0); constructor Create(const _Alphabet: String = DefaultAlphabet; _Special: Char = DefaultSpecial; _textEncoding: TEncoding = Nil); function Encode(data: TArray<Byte>): String; override; function Decode(const data: String): TArray<Byte>; override; end; implementation constructor TBase256.Create(const _Alphabet: String = DefaultAlphabet; _Special: Char = DefaultSpecial; _textEncoding: TEncoding = Nil); begin Inherited Create(256, _Alphabet, _Special, _textEncoding); FHaveSpecial := False; end; function TBase256.Encode(data: TArray<Byte>): string; var i, dataLength: Integer; tempResult: TStringBuilder; begin if ((data = nil) or (Length(data) = 0)) then begin Exit(''); end; tempResult := TStringBuilder.Create(Length(data)); dataLength := Length(data); try for i := 0 to Pred(dataLength) do begin tempResult.Append(Alphabet[data[i]]); end; result := tempResult.ToString; finally tempResult.Free; end; end; function TBase256.Decode(const data: String): TArray<Byte>; var i: Integer; begin if TUtils.isNullOrEmpty(data) then begin SetLength(result, 1); result := Nil; Exit; end; SetLength(result, Length(data)); for i := 0 to Pred(Length(data)) do begin result[i] := Byte(FInvAlphabet[Ord(data[i])]); end; end; end.
function concat(a,b:string); begin result:=a+b; end;
unit Project87.Types.GameObject; interface uses Generics.Collections, SysUtils, Strope.Math; const MAX_PHYSICAL_VELOCITY = 1600; MAX_FAST_OBJECTS = 200; BORDER_OF_VIEW: TVector2F = (X: 800; Y: 600); VIEW_RANGE = 900; UPDATE_RANGE = 1400; type TObjectManager = class; TPhysicalObject = class; TGameObject = class private FParent: TObjectManager; procedure Move(const ADelta: Double); protected FIsDead: Boolean; FNeedDraw: Boolean; FNeedUpdate: Boolean; FAngle: Single; FPreviosPosition: TVector2F; FPosition: TVector2F; FVelocity: TVector2F; public constructor Create; destructor Destroy; override; procedure OnDraw; virtual; procedure OnUpdate(const ADelta: Double); virtual; procedure OnCollide(OtherObject: TPhysicalObject); virtual; property Manager: TObjectManager read FParent; property Position: TVector2F read FPosition; end; TPhysicalObject = class private FFriction: Single; FCorrection: TVector2F; FParent: TObjectManager; FNeedDraw: Boolean; FNeedUpdate: Boolean; procedure Move(const ADelta: Double); protected FIsDead: Boolean; FUseCollistion: Boolean; FMass: Single; FRadius: Single; FAngle: Single; FPosition: TVector2F; FVelocity: TVector2F; public constructor Create; destructor Destroy; override; procedure OnDraw; virtual; procedure OnUpdate(const ADelta: Double); virtual; procedure OnCollide(OtherObject: TPhysicalObject); virtual; property Manager: TObjectManager read FParent; property Position: TVector2F read FPosition; property IsDead: Boolean read FIsDead; end; TObjectManager = class private class var FInstance: TObjectManager; FGameObjects: TList<TGameObject>; FPhysicalObjects: TList<TPhysicalObject>; constructor Create; procedure RemovePhysicalObject(APhysicalObject: TPhysicalObject); procedure DestroyPhysicalObject(APhysicalObject: TPhysicalObject); procedure AddPhysicalObject(APhysicalObject: TPhysicalObject); procedure RemoveObject(AObject: TGameObject); procedure DestroyObject(AObject: TGameObject); procedure AddObject(AObject: TGameObject); procedure CheckCollisions; procedure CheckFastCollisions; procedure CheckDeadObjects; public destructor Destroy; override; class function GetInstance: TObjectManager; function GetObjects(AType: TClass): TList<TPhysicalObject>; procedure SolveCollisions(ACount: Word); procedure OnDraw; procedure OnUpdate(const ADelta: Double); procedure ClearObjects; end; implementation uses QApplication.Application, QEngine.Core; {$REGION ' TGameObject '} constructor TGameObject.Create; begin FParent := TObjectManager.GetInstance; FParent.AddObject(Self); FIsDead := False; FNeedDraw := False; FNeedUpdate := True; end; destructor TGameObject.Destroy; begin FParent.RemoveObject(Self); inherited; end; procedure TGameObject.OnDraw; begin //nothing to do end; procedure TGameObject.OnUpdate(const ADelta: Double); begin //nothing to do end; procedure TGameObject.OnCollide(OtherObject: TPhysicalObject); begin //nothing to do end; procedure TGameObject.Move(const ADelta: Double); begin FPreviosPosition := FPosition; FPosition := FPosition + FVelocity * ADelta; end; {$ENDREGION} {$REGION ' TPhysicalObject '} constructor TPhysicalObject.Create; begin FIsDead := False; FUseCollistion := False; FParent := TObjectManager.GetInstance; FParent.AddPhysicalObject(Self); FMass := 1; FFriction := 2.5; FRadius := 20; FNeedDraw := False; FNeedUpdate := True; end; destructor TPhysicalObject.Destroy; begin FParent.RemovePhysicalObject(Self); inherited; end; procedure TPhysicalObject.OnDraw; begin //nothing to do end; procedure TPhysicalObject.OnUpdate(const ADelta: Double); begin //nothing to do end; procedure TPhysicalObject.OnCollide(OtherObject: TPhysicalObject); begin //nothing to do end; procedure TPhysicalObject.Move(const ADelta: Double); begin if FVelocity.Length > MAX_PHYSICAL_VELOCITY then FVelocity := FVelocity * (MAX_PHYSICAL_VELOCITY / FVelocity.Length); FPosition := FPosition + FVelocity * ADelta + FCorrection; FCorrection := ZeroVectorF; FVelocity := FVelocity * (1 - ADelta * FFriction); end; {$ENDREGION} {$REGION ' TObjectManager '} constructor TObjectManager.Create; begin FPhysicalObjects := TList<TPhysicalObject>.Create(); FGameObjects := TList<TGameObject>.Create(); end; destructor TObjectManager.Destroy; var AGameObject: TGameObject; APhysicalObject: TPhysicalObject; begin for APhysicalObject in FPhysicalObjects do APhysicalObject.Free; FPhysicalObjects.Free; for AGameObject in FGameObjects do AGameObject.Free; FGameObjects.Free; FInstance := nil; inherited; end; procedure TObjectManager.RemovePhysicalObject(APhysicalObject: TPhysicalObject); begin FPhysicalObjects.Remove(APhysicalObject); end; procedure TObjectManager.DestroyPhysicalObject(APhysicalObject: TPhysicalObject); begin if FPhysicalObjects.Contains(APhysicalObject) then APhysicalObject.Free; end; procedure TObjectManager.AddPhysicalObject(APhysicalObject: TPhysicalObject); begin if Assigned(APhysicalObject) then FPhysicalObjects.Add(APhysicalObject); end; procedure TObjectManager.RemoveObject(AObject: TGameObject); begin FGameObjects.Remove(AObject); end; procedure TObjectManager.DestroyObject(AObject: TGameObject); begin if FGameObjects.Contains(AObject) then AObject.Free; end; procedure TObjectManager.AddObject(AObject: TGameObject); begin if Assigned(AObject) then FGameObjects.Add(AObject); end; class function TObjectManager.GetInstance: TObjectManager; begin if not Assigned(FInstance) then FInstance := TObjectManager.Create; Result := FInstance; end; procedure TObjectManager.OnDraw; var PhysicalObject: TPhysicalObject; GameObject: TGameObject; begin for PhysicalObject in FPhysicalObjects do if not PhysicalObject.FIsDead and PhysicalObject.FNeedDraw then PhysicalObject.OnDraw; for GameObject in FGameObjects do if not GameObject.FIsDead and GameObject.FNeedDraw then GameObject.OnDraw; end; procedure TObjectManager.OnUpdate(const ADelta: Double); var PhysicalObject: TPhysicalObject; GameObject: TGameObject; ViewRange: Single; begin for PhysicalObject in FPhysicalObjects do if not PhysicalObject.FIsDead and PhysicalObject.FNeedUpdate then PhysicalObject.OnUpdate(ADelta); CheckCollisions(); for PhysicalObject in FPhysicalObjects do if not PhysicalObject.FIsDead and PhysicalObject.FNeedUpdate then PhysicalObject.Move(ADelta); for GameObject in FGameObjects do if not GameObject.FIsDead and GameObject.FNeedUpdate then GameObject.OnUpdate(ADelta); CheckFastCollisions(); for GameObject in FGameObjects do if not GameObject.FIsDead and GameObject.FNeedUpdate then GameObject.Move(ADelta); CheckDeadObjects; ViewRange := (VIEW_RANGE / TheEngine.Camera.Scale.X) * (VIEW_RANGE / TheEngine.Camera.Scale.X); for PhysicalObject in FPhysicalObjects do begin PhysicalObject.FNeedDraw := (PhysicalObject.FPosition - TheEngine.Camera.Position).LengthSqr < ViewRange; PhysicalObject.FNeedUpdate := (PhysicalObject.FPosition - TheEngine.Camera.Position).LengthSqr < UPDATE_RANGE * UPDATE_RANGE; end; for GameObject in FGameObjects do begin GameObject.FNeedDraw := (GameObject.FPosition - TheEngine.Camera.Position).LengthSqr < ViewRange; GameObject.FNeedUpdate := (GameObject.FPosition - TheEngine.Camera.Position).LengthSqr < UPDATE_RANGE * UPDATE_RANGE; end; end; procedure TObjectManager.SolveCollisions(ACount: Word); var I: Word; PhysicalObject: TPhysicalObject; begin for i := 0 to ACount do begin CheckCollisions(); for PhysicalObject in FPhysicalObjects do if not PhysicalObject.FIsDead then begin PhysicalObject.FPosition := PhysicalObject.FPosition + PhysicalObject.FCorrection * 1.1; PhysicalObject.FCorrection := ZeroVectorF; end; end; end; function TObjectManager.GetObjects(AType: TClass): TList<TPhysicalObject>; var List: TList<TPhysicalObject>; PhysicalObject: TPhysicalObject; begin List := TList<TPhysicalObject>.Create(); for PhysicalObject in FPhysicalObjects do if PhysicalObject is AType then begin List.Add(PhysicalObject); end; Result := List; end; procedure TObjectManager.CheckCollisions; var GameObject, OtherObject: TPhysicalObject; Connection: TVector2F; ProjectionLength: Single; begin for GameObject in FPhysicalObjects do if GameObject.FNeedUpdate then for OtherObject in FPhysicalObjects do if OtherObject.FNeedUpdate then if (GameObject <> OtherObject) then if ((not GameObject.FIsDead) and (not OtherObject.FIsDead)) then if ((GameObject.FPosition - OtherObject.FPosition).LengthSqr < (GameObject.FRadius + OtherObject.FRadius) * (GameObject.FRadius + OtherObject.FRadius)) then begin GameObject.OnCollide(OtherObject); if GameObject.FUseCollistion and OtherObject.FUseCollistion then begin Connection := OtherObject.FPosition - GameObject.FPosition; ProjectionLength := Dot(OtherObject.FVelocity, Connection) / Connection.Length; GameObject.FVelocity := GameObject.FVelocity - GetRotatedVector( GetAngle(Connection), ProjectionLength / GameObject.FMass * OtherObject.FMass); OtherObject.FVelocity := OtherObject.FVelocity + GetRotatedVector(GetAngle(Connection), ProjectionLength); GameObject.FCorrection := GameObject.FCorrection + (GameObject.FPosition - OtherObject.FPosition).Normalize * (((GameObject.FRadius + OtherObject.FRadius) - Distance(GameObject.FPosition, OtherObject.FPosition)) * 0.5); end; end; end; procedure TObjectManager.CheckFastCollisions; var I, FastListCount: Integer; PhysicalObject: TPhysicalObject; GameObject: TGameObject; FastList: array [0..MAX_FAST_OBJECTS] of TPhysicalObject; ActionCenter: TVector2F; begin FastListCount := 0; ActionCenter := TheEngine.Camera.Position; for PhysicalObject in FPhysicalObjects do if (PhysicalObject <> nil) then if (PhysicalObject.FPosition.X - BORDER_OF_VIEW.X < ActionCenter.X) then if (PhysicalObject.FPosition.Y - BORDER_OF_VIEW.Y < ActionCenter.Y) then if (PhysicalObject.FPosition.X + BORDER_OF_VIEW.X > ActionCenter.X) then if (PhysicalObject.FPosition.Y + BORDER_OF_VIEW.Y > ActionCenter.Y) then begin if FastListCount > MAX_FAST_OBJECTS then Break; FastList[FastListCount] := PhysicalObject; Inc(FastListCount); end; for GameObject in FGameObjects do if (GameObject <> nil) then for I := 0 to FastListCount - 1 do if not GameObject.FIsDead then if LineVsCircle(GameObject.FPosition, GameObject.FPreviosPosition, FastList[I].FPosition, FastList[I].FRadius) then GameObject.OnCollide(FastList[I]); end; procedure TObjectManager.CheckDeadObjects; var AObject: TGameObject; APObject: TPhysicalObject; begin for AObject in FGameObjects do if AObject.FIsDead then AObject.Free; for APObject in FPhysicalObjects do if APObject.FIsDead then APObject.Free; end; procedure TObjectManager.ClearObjects; var AObject: TGameObject; APObject: TPhysicalObject; begin for AObject in FGameObjects do AObject.Free; for APObject in FPhysicalObjects do APObject.Free; FPhysicalObjects.Clear; FGameObjects.Clear; end; {$ENDREGION} end.
unit uDMBoletim; { Esse DataModule é utilizado exclusivamente pela unit ClasseBoletim. Leia o comentário no topo dessa unit antes de fazer qualquer alteração nesse form. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, ADODB, ZAbstractDataset, ZDataset, ZAbstractRODataset, uDMPrincipal, ZAbstractTable; type TDMBoletim = class(TDataModule) tblDisciplina2: TZTable; tblDisciplina2Curso: TWideStringField; tblDisciplina2Serie: TWideStringField; tblDisciplina2Disciplina: TWideStringField; tblDisciplina2Letivo: TWideStringField; tblDisciplina2Carga: TSmallintField; tblDisciplina1: TZTable; tblDisciplina1Letivo: TWideStringField; tblDisciplina1Codigo: TWideStringField; tblDisciplina1Nome: TWideStringField; tblDisciplina1Tipo: TWideStringField; tblDisciplina1Suple: TBooleanField; tblDisciplina1Sigla: TWideStringField; tblDisciplina1Reprova: TBooleanField; tblDisciplina1Historico: TBooleanField; sqlTurmas: TZQuery; sqlAlunos: TZQuery; sqlAlunosMat: TWideStringField; sqlAlunosNome: TWideStringField; sqlAlunosDtNascimento: TDateField; sqlAlunosEndereco: TWideStringField; sqlAlunosBairro: TWideStringField; sqlAlunosCidade: TWideStringField; sqlAlunosCEP: TWideStringField; sqlAlunosUF: TWideStringField; sqlAlunosRGAluno: TWideStringField; sqlAlunossexo: TIntegerField; sqlAlunoscidadeNasc: TWideStringField; sqlAlunosufnasc: TWideStringField; sqlClasses: TZQuery; sqlAulasDadas: TZQuery; sqlAulasDadasDisciplina: TWideStringField; sqlAulasDadasBimestre: TWideStringField; sqlAulasDadasAulasDadas: TIntegerField; sqlDisciplina: TZQuery; sqlNotasFaltas: TZQuery; sqlAbono: TZQuery; sqlConselho: TZQuery; sqlConselhoMatricula: TStringField; sqlConselhoDisc: TStringField; sqlConselhoAlterarMedia: TSmallintField; sqlConselhoAlterarSituacao: TSmallintField; sqlConselhoMedia: TFloatField; sqlConselhoMostrarsit_Conselho: TSmallintField; sqlDispensa: TZQuery; sqlDispensaMat: TWideStringField; sqlDispensaDisc: TWideStringField; sqlDispensaBim: TWideStringField; sqlDispensaTipo: TWideStringField; sqlDisciplina1: TZQuery; sqlNotasFilhas: TZQuery; sqlDiscDependencias: TZQuery; sqlNotasDependencia: TZQuery; sqlClassesidClasse1: TStringField; sqlClassesidCursos: TStringField; sqlClassesSerie: TStringField; sqlClassesTurma: TStringField; sqlTurmasMat: TStringField; sqlTurmasNumero: TStringField; sqlTurmasSituacao: TStringField; sqlDisciplinaDisciplina: TStringField; sqlDisciplinaNome: TStringField; sqlDisciplinaReprova: TSmallintField; sqlDisciplinaSigla: TStringField; sqlDisciplinaTipo: TStringField; sqlDisciplinaHistorico: TSmallintField; sqlDisciplinaTipoComposicao: TStringField; sqlDisciplinaOrdem: TIntegerField; sqlDisciplinaCarga: TIntegerField; sqlAbonoMat: TStringField; sqlAbonoDisc: TStringField; sqlAbonoBim: TStringField; sqlAbonoFaltas: TIntegerField; sqlNotasFaltasMat: TStringField; sqlNotasFaltasDisc: TStringField; sqlNotasFaltasBim: TStringField; sqlNotasFaltasNota: TFloatField; sqlNotasFaltasFalta: TIntegerField; sqlNotasFaltasAtrasos: TIntegerField; sqlNotasFaltasNotaRecPeriodo: TFloatField; sqlNotasFaltasAulasDadas: TIntegerField; sqlNotasFilhasID: TIntegerField; sqlNotasFilhasMat: TStringField; sqlNotasFilhasNumero: TStringField; sqlNotasFilhasNota: TFloatField; sqlNotasFilhasFalta: TIntegerField; sqlNotasFilhasAtrasos: TIntegerField; sqlNotasFilhasAulasDadas: TIntegerField; sqlNotasDependenciaId: TIntegerField; sqlNotasDependenciaMat: TStringField; sqlNotasDependenciaDisciplina: TStringField; sqlNotasDependenciaLetivoDisciplina: TStringField; sqlNotasDependenciaBim: TStringField; sqlNotasDependenciaNota: TFloatField; sqlNotasDependenciaFaltas: TIntegerField; sqlNotasDependenciaAulasDadas: TIntegerField; sqlNotasDependenciaNotaRecPeriodo: TFloatField; sqlDiscDependenciasMat: TStringField; sqlDiscDependenciasDisciplina: TStringField; sqlDiscDependenciasLetivoDisciplina: TStringField; sqlDiscDependenciasNome: TStringField; sqlDiscDependenciasSigla: TStringField; sqlDiscDependenciasTipo: TStringField; sqlDisciplina1TipoComposicao: TStringField; sqlDisciplina1CalculoComp: TStringField; private { Private declarations } public procedure FecharTabelas(); end; var DMBoletim: TDMBoletim; implementation {$R *.DFM} { TDMBoletim } procedure TDMBoletim.FecharTabelas; var i : Integer; begin for i := 0 to ComponentCount - 1 do if Components[i] is TDataset then with Components[i] as TdataSet do if Active then Close; end; end.
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} unit IdOpenSSLHeaders_ui; interface // Headers for OpenSSL 1.1.1 // ui.h {$i IdCompilerDefines.inc} uses IdCTypes, IdGlobal, IdOpenSSLConsts, IdOpenSSLHeaders_ossl_typ, IdOpenSSLHeaders_crypto, IdOpenSSLHeaders_pem, IdOpenSSLHeaders_uierr; {$MINENUMSIZE 4} const (* These are the possible flags. They can be or'ed together. *) (* Use to have echoing of input *) UI_INPUT_FLAG_ECHO = $01; (* * Use a default password. Where that password is found is completely up to * the application, it might for example be in the user data set with * UI_add_user_data(). It is not recommended to have more than one input in * each UI being marked with this flag, or the application might get * confused. *) UI_INPUT_FLAG_DEFAULT_PWD = $02; (* * The user of these routines may want to define flags of their own. The core * UI won't look at those, but will pass them on to the method routines. They * must use higher bits so they don't get confused with the UI bits above. * UI_INPUT_FLAG_USER_BASE tells which is the lowest bit to use. A good * example of use is this: * * #define MY_UI_FLAG1 (0x01 << UI_INPUT_FLAG_USER_BASE) * *) UI_INPUT_FLAG_USER_BASE = 16; (* The commands *) (* * Use UI_CONTROL_PRINT_ERRORS with the value 1 to have UI_process print the * OpenSSL error stack before printing any info or added error messages and * before any prompting. *) UI_CTRL_PRINT_ERRORS = 1; (* * Check if a UI_process() is possible to do again with the same instance of * a user interface. This makes UI_ctrl() return 1 if it is redoable, and 0 * if not. *) UI_CTRL_IS_REDOABLE = 2; type (* * Give a user interface parameterised control commands. This can be used to * send down an integer, a data pointer or a function pointer, as well as be * used to get information from a UI. *) UI_ctrl_f = procedure; (* * The UI_STRING type is the data structure that contains all the needed info * about a string or a prompt, including test data for a verification prompt. *) ui_string_st = type Pointer; UI_STRING = ui_string_st; PUI_STRING = ^UI_STRING; // DEFINE_STACK_OF(UI_STRING) (* * The different types of strings that are currently supported. This is only * needed by method authors. *) UI_string_types = ( UIT_NONE = 0, UIT_PROMPT, (* Prompt for a string *) UIT_VERIFY, (* Prompt for a string and verify *) UIT_BOOLEAN, (* Prompt for a yes/no response *) UIT_INFO, (* Send info to the user *) UIT_ERROR (* Send an error message to the user *) ); (* Create and manipulate methods *) UI_method_opener_cb = function(ui: PUI): TIdC_INT; UI_method_writer_cb = function(ui: PUI; uis: PUI_String): TIdC_INT; UI_method_flusher_cb = function(ui: PUI): TIdC_INT; UI_method_reader_cb = function(ui: PUI; uis: PUI_String): TIdC_INT; UI_method_closer_cb = function(ui: PUI): TIdC_INT; UI_method_data_duplicator_cb = function(ui: PUI; ui_data: Pointer): Pointer; UI_method_data_destructor_cb = procedure(ui: PUI; ui_data: Pointer); UI_method_prompt_constructor_cb = function(ui: PUI; const object_desc: PIdAnsiChar; const object_name: PIdAnsiChar): PIdAnsiChar; var (* * All the following functions return -1 or NULL on error and in some cases * (UI_process()) -2 if interrupted or in some other way cancelled. When * everything is fine, they return 0, a positive value or a non-NULL pointer, * all depending on their purpose. *) (* Creators and destructor. *) function UI_new: PUI; function UI_new_method(const method: PUI_Method): PUI; procedure UI_free(ui: PUI); (* * The following functions are used to add strings to be printed and prompt * strings to prompt for data. The names are UI_{add,dup}_<function>_string * and UI_{add,dup}_input_boolean. * * UI_{add,dup}_<function>_string have the following meanings: * add add a text or prompt string. The pointers given to these * functions are used verbatim, no copying is done. * dup make a copy of the text or prompt string, then add the copy * to the collection of strings in the user interface. * <function> * The function is a name for the functionality that the given * string shall be used for. It can be one of: * input use the string as data prompt. * verify use the string as verification prompt. This * is used to verify a previous input. * info use the string for informational output. * error use the string for error output. * Honestly, there's currently no difference between info and error for the * moment. * * UI_{add,dup}_input_boolean have the same semantics for "add" and "dup", * and are typically used when one wants to prompt for a yes/no response. * * All of the functions in this group take a UI and a prompt string. * The string input and verify addition functions also take a flag argument, * a buffer for the result to end up with, a minimum input size and a maximum * input size (the result buffer MUST be large enough to be able to contain * the maximum number of characters). Additionally, the verify addition * functions takes another buffer to compare the result against. * The boolean input functions take an action description string (which should * be safe to ignore if the expected user action is obvious, for example with * a dialog box with an OK button and a Cancel button), a string of acceptable * characters to mean OK and to mean Cancel. The two last strings are checked * to make sure they don't have common characters. Additionally, the same * flag argument as for the string input is taken, as well as a result buffer. * The result buffer is required to be at least one byte long. Depending on * the answer, the first character from the OK or the Cancel character strings * will be stored in the first byte of the result buffer. No NUL will be * added, so the result is *not* a string. * * On success, the all return an index of the added information. That index * is useful when retrieving results with UI_get0_result(). *) function UI_add_input_string(ui: PUI; const prompt: PIdAnsiChar; flags: TIdC_INT; result_buf: PIdAnsiChar; minsize: TIdC_INT; maxsize: TIdC_INT): TIdC_INT; function UI_dup_input_string(ui: PUI; const prompt: PIdAnsiChar; flags: TIdC_INT; result_buf: PIdAnsiChar; minsize: TIdC_INT; maxsize: TIdC_INT): TIdC_INT; function UI_add_verify_string(ui: PUI; const prompt: PIdAnsiChar; flags: TIdC_INT; result_buf: PIdAnsiChar; minsize: TIdC_INT; maxsize: TIdC_INT; const test_buf: PIdAnsiChar): TIdC_INT; function UI_dup_verify_string(ui: PUI; const prompt: PIdAnsiChar; flags: TIdC_INT; result_buf: PIdAnsiChar; minsize: TIdC_INT; maxsize: TIdC_INT; const test_buf: PIdAnsiChar): TIdC_INT; function UI_add_input_boolean(ui: PUI; const prompt: PIdAnsiChar; const action_desc: PIdAnsiChar; const ok_chars: PIdAnsiChar; const cancel_chars: PIdAnsiChar; flags: TIdC_INT; result_buf: PIdAnsiChar): TIdC_INT; function UI_dup_input_boolean(ui: PUI; const prompt: PIdAnsiChar; const action_desc: PIdAnsiChar; const ok_chars: PIdAnsiChar; const cancel_chars: PIdAnsiChar; flags: TIdC_INT; result_buf: PIdAnsiChar): TIdC_INT; function UI_add_info_string(ui: PUI; const text: PIdAnsiChar): TIdC_INT; function UI_dup_info_string(ui: PUI; const text: PIdAnsiChar): TIdC_INT; function UI_add_error_string(ui: PUI; const text: PIdAnsiChar): TIdC_INT; function UI_dup_error_string(ui: PUI; const text: PIdAnsiChar): TIdC_INT; (* * The following function helps construct a prompt. object_desc is a * textual short description of the object, for example "pass phrase", * and object_name is the name of the object (might be a card name or * a file name. * The returned string shall always be allocated on the heap with * OPENSSL_malloc(), and need to be free'd with OPENSSL_free(). * * If the ui_method doesn't contain a pointer to a user-defined prompt * constructor, a default string is built, looking like this: * * "Enter {object_desc} for {object_name}:" * * So, if object_desc has the value "pass phrase" and object_name has * the value "foo.key", the resulting string is: * * "Enter pass phrase for foo.key:" *) function UI_construct_prompt(ui_method: PUI; const object_desc: PIdAnsiChar; const object_name: PIdAnsiChar): PIdAnsiChar; (* * The following function is used to store a pointer to user-specific data. * Any previous such pointer will be returned and replaced. * * For callback purposes, this function makes a lot more sense than using * ex_data, since the latter requires that different parts of OpenSSL or * applications share the same ex_data index. * * Note that the UI_OpenSSL() method completely ignores the user data. Other * methods may not, however. *) function UI_add_user_data(ui: PUI; user_data: Pointer): Pointer; (* * Alternatively, this function is used to duplicate the user data. * This uses the duplicator method function. The destroy function will * be used to free the user data in this case. *) function UI_dup_user_data(ui: PUI; user_data: Pointer): TIdC_INT; (* We need a user data retrieving function as well. *) function UI_get0_user_data(ui: PUI): Pointer; (* Return the result associated with a prompt given with the index i. *) function UI_get0_result(ui: PUI; i: TIdC_INT): PIdAnsiChar; function UI_get_result_length(ui: PUI; i: TIdC_INT): TIdC_INT; (* When all strings have been added, process the whole thing. *) function UI_process(ui: PUI): TIdC_INT; (* * Give a user interface parameterised control commands. This can be used to * send down an integer, a data pointer or a function pointer, as well as be * used to get information from a UI. *) function UI_ctrl(ui: PUI; cmd: TIdC_INT; i: TIdC_LONG; p: Pointer; f: UI_ctrl_f): TIdC_INT; (* Some methods may use extra data *) //# define UI_set_app_data(s,arg) UI_set_ex_data(s,0,arg) //# define UI_get_app_data(s) UI_get_ex_data(s,0) //# define UI_get_ex_new_index(l, p, newf, dupf, freef) \ // CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_UI, l, p, newf, dupf, freef) function UI_set_ex_data(r: PUI; idx: TIdC_INT; arg: Pointer): TIdC_INT; function UI_get_ex_data(r: PUI; idx: TIdC_INT): Pointer; (* Use specific methods instead of the built-in one *) procedure UI_set_default_method(const meth: PUI_Method); function UI_get_default_method: PUI_METHOD; function UI_get_method(ui: PUI): PUI_METHOD; function UI_set_method(ui: PUI; const meth: PUI_METHOD): PUI_METHOD; (* The method with all the built-in thingies *) function UI_OpenSSL: PUI_Method; (* * NULL method. Literally does nothing, but may serve as a placeholder * to avoid internal default. *) function UI_null: PUI_METHOD; (* ---------- For method writers ---------- *) (* A method contains a number of functions that implement the low level of the User Interface. The functions are: an opener This function starts a session, maybe by opening a channel to a tty, or by opening a window. a writer This function is called to write a given string, maybe to the tty, maybe as a field label in a window. a flusher This function is called to flush everything that has been output so far. It can be used to actually display a dialog box after it has been built. a reader This function is called to read a given prompt, maybe from the tty, maybe from a field in a window. Note that it's called with all string structures, not only the prompt ones, so it must check such things itself. a closer This function closes the session, maybe by closing the channel to the tty, or closing the window. All these functions are expected to return: 0 on error. 1 on success. -1 on out-of-band events, for example if some prompting has been canceled (by pressing Ctrl-C, for example). This is only checked when returned by the flusher or the reader. The way this is used, the opener is first called, then the writer for all strings, then the flusher, then the reader for all strings and finally the closer. Note that if you want to prompt from a terminal or other command line interface, the best is to have the reader also write the prompts instead of having the writer do it. If you want to prompt from a dialog box, the writer can be used to build up the contents of the box, and the flusher to actually display the box and run the event loop until all data has been given, after which the reader only grabs the given data and puts them back into the UI strings. All method functions take a UI as argument. Additionally, the writer and the reader take a UI_STRING. *) function UI_create_method(const name: PIdAnsiChar): PUI_Method; procedure UI_destroy_method(ui_method: PUI_Method); function UI_method_set_opener(method: PUI_Method; opener: UI_method_opener_cb): TIdC_INT; function UI_method_set_writer(method: PUI_Method; writer: UI_method_writer_cb): TIdC_INT; function UI_method_set_flusher(method: PUI_Method; flusher: UI_method_flusher_cb): TIdC_INT; function UI_method_set_reader(method: PUI_Method; reader: UI_method_reader_cb): TIdC_INT; function UI_method_set_closer(method: PUI_Method; closer: UI_method_closer_cb): TIdC_INT; function UI_method_set_data_duplicator(method: PUI_Method; duplicator: UI_method_data_duplicator_cb; destructor_: UI_method_data_destructor_cb): TIdC_INT; function UI_method_set_prompt_constructor(method: PUI_Method; prompt_constructor: UI_method_prompt_constructor_cb): TIdC_INT; function UI_method_set_ex_data(method: PUI_Method; idx: TIdC_INT; data: Pointer): TIdC_INT; function UI_method_get_opener(const method: PUI_METHOD): UI_method_opener_cb; function UI_method_get_writer(const method: PUI_METHOD): UI_method_writer_cb; function UI_method_get_flusher(const method: PUI_METHOD): UI_method_flusher_cb; function UI_method_get_reader(const method: PUI_METHOD): UI_method_reader_cb; function UI_method_get_closer(const method: PUI_METHOD): UI_method_closer_cb; function UI_method_get_prompt_constructor(const method: PUI_METHOD): UI_method_prompt_constructor_cb; function UI_method_get_data_duplicator(const method: PUI_METHOD): UI_method_data_duplicator_cb; function UI_method_get_data_destructor(const method: PUI_METHOD): UI_method_data_destructor_cb; function UI_method_get_ex_data(const method: PUI_METHOD; idx: TIdC_INT): Pointer; (* * The following functions are helpers for method writers to access relevant * data from a UI_STRING. *) (* Return type of the UI_STRING *) function UI_get_string_type(uis: PUI_String): UI_string_types; (* Return input flags of the UI_STRING *) function UI_get_input_flags(uis: PUI_String): TIdC_INT; (* Return the actual string to output (the prompt, info or error) *) function UI_get0_output_string(uis: PUI_String): PIdAnsiChar; (* * Return the optional action string to output (the boolean prompt * instruction) *) function UI_get0_action_string(uis: PUI_String): PIdAnsiChar; (* Return the result of a prompt *) function UI_get0_result_string(uis: PUI_String): PIdAnsiChar; function UI_get_result_string_length(uis: PUI_String): TIdC_INT; (* * Return the string to test the result against. Only useful with verifies. *) function UI_get0_test_string(uis: PUI_String): PIdAnsiChar; (* Return the required minimum size of the result *) function UI_get_result_minsize(uis: PUI_String): TIdC_INT; (* Return the required maximum size of the result *) function UI_get_result_maxsize(uis: PUI_String): TIdC_INT; (* Set the result of a UI_STRING. *) function UI_set_result(ui: PUI; uis: PUI_String; const result: PIdAnsiChar): TIdC_INT; function UI_set_result_ex(ui: PUI; uis: PUI_String; const result: PIdAnsiChar; len: TIdC_INT): TIdC_INT; (* A couple of popular utility functions *) function UI_UTIL_read_pw_string(buf: PIdAnsiChar; length: TIdC_INT; const prompt: PIdAnsiChar; verify: TIdC_INT): TIdC_INT; function UI_UTIL_read_pw(buf: PIdAnsiChar; buff: PIdAnsiChar; size: TIdC_INT; const prompt: PIdAnsiChar; verify: TIdC_INT): TIdC_INT; function UI_UTIL_wrap_read_pem_callback(cb: pem_password_cb; rwflag: TIdC_INT): PUI_Method; implementation end.
unit Antenna; {$WARN SYMBOL_PLATFORM OFF} interface uses ComObj, RDAObj, Rda_TLB; type TAntenna = class( TRDAObject, IAntenna, IAntennaControl ) protected // IAntenna function Get_Excitacion: WordBool; safecall; function Get_Limite_N: WordBool; safecall; function Get_Limite_P: WordBool; safecall; function Get_Motor_Az: IMotorStatus; safecall; function Get_Motor_El: IMotorStatus; safecall; function Get_Cupula_Cerrada: WordBool; safecall; function Get_Local: WordBool; safecall; function Get_Ventilacion: WordBool; safecall; function Get_SyncMark: Integer; safecall; function Get_SyncMarkDirection: WordBool; safecall; function Get_Fuente_Exitacion_Code: Integer; safecall; function Get_Fuente_Exitacion_Unit: Double; safecall; function Get_Fuente_5V_Code: Integer; safecall; function Get_Fuente_5V_Unit: Double; safecall; function Get_Fuente_12V_Code: Integer; safecall; function Get_Fuente_24V_Code: Integer; safecall; function Get_Fuente_24V_Unit: Double; safecall; function Get_Fuente_12V_Unit: Double; safecall; function Get_Rango_Fuente_5V: Integer; safecall; function Get_Rango_Fuente_12V: Integer; safecall; function Get_Rango_Fuente_24V: Integer; safecall; function Get_Rango_Fuente_Excitacion: Integer; safecall; function Get_Sector_Fuente_5V: Integer; safecall; function Get_Sector_Fuente_12V: Integer; safecall; function Get_Sector_Fuente_24V: Integer; safecall; function Get_Sector_Fuente_Excitacion: Integer; safecall; function Get_Status: RadarStatus; safecall; protected // IAntennaControl procedure Encender_Acc; safecall; procedure Apagar_Acc; safecall; procedure Alarma_Sonora(Tiempo: Integer); safecall; procedure Set_SyncMark(direction: WordBool; rays: Shortint); safecall; procedure Set_Rango_Fuente_5V(Value: Integer); safecall; procedure Set_Sector_Fuente_5V(Value: Integer); safecall; procedure Set_Sector_Fuente_12V(Value: Integer); safecall; procedure Set_Rango_Fuente_12V(Value: Integer); safecall; procedure Set_Rango_Fuente_24V(Value: Integer); safecall; procedure Set_Sector_Fuente_24V(Value: Integer); safecall; procedure Set_Rango_Fuente_Excitacion(Value: Integer); safecall; procedure Set_Sector_Fuente_Excitacion(Value: Integer); safecall; end; const Class_Antenna: TGUID = '{A20AD06A-1DED-4BD0-8738-0B1F136629F5}'; implementation uses ComServ, ElbrusTypes, Elbrus, MotorAz, MotorEl, ManagerDRX, DRX_Sync_WS; function TAntenna.Get_Excitacion: WordBool; begin Result := Snapshot.Digital_Input and di_Excitacion = di_Excitacion; end; function TAntenna.Get_Limite_N: WordBool; begin Result := Snapshot.Digital_Input and di_Antena_Limite_N = di_Antena_Limite_N; end; function TAntenna.Get_Limite_P: WordBool; begin Result := Snapshot.Digital_Input and di_Antena_Limite_P = di_Antena_Limite_P; end; procedure TAntenna.Encender_Acc; begin if InControl then Elbrus.Encender_Accionamiento; end; procedure TAntenna.Apagar_Acc; begin if InControl then Elbrus.Apagar_Accionamiento; end; procedure TAntenna.Alarma_Sonora(Tiempo: Integer); begin if InControl then Elbrus.Alarma_Sonora(Tiempo); end; function TAntenna.Get_Motor_Az: IMotorStatus; begin Result := TMotor_Az.Create(UserName, Level); end; function TAntenna.Get_Motor_El: IMotorStatus; begin Result := TMotor_El.Create(UserName, Level); end; function TAntenna.Get_Cupula_Cerrada: WordBool; begin Result := Snapshot.Digital_Input and di_Cupula_Cerrada = di_Cupula_Cerrada; end; function TAntenna.Get_SyncMark: Integer; begin result := Snapshot^.SyncMark; end; function TAntenna.Get_SyncMarkDirection: WordBool; begin result := Snapshot^.SyncMarkDirection; end; procedure TAntenna.Set_SyncMark(direction: WordBool; rays: Shortint); begin if InControl then Elbrus.Set_SyncMark(direction, rays); end; function TAntenna.Get_Fuente_12V_Code: Integer; begin Result := Snapshot.Analog_Input[ai_Fuente_12V_P]; end; function TAntenna.Get_Fuente_12V_Unit: Double; begin Result := Snapshot.Analog_Input_Voltage[ai_Fuente_12V_P]; end; function TAntenna.Get_Fuente_24V_Code: Integer; begin Result := Snapshot.Analog_Input[ai_Fuente_24V_P]; end; function TAntenna.Get_Fuente_24V_Unit: Double; begin Result := Snapshot.Analog_Input_Voltage[ai_Fuente_24V_P]; end; function TAntenna.Get_Fuente_5V_Code: Integer; begin Result := Snapshot.Analog_Input[ai_Fuente_5V_P]; end; function TAntenna.Get_Fuente_5V_Unit: Double; begin Result := Snapshot.Analog_Input_Voltage[ai_Fuente_5V_P]; end; function TAntenna.Get_Fuente_Exitacion_Code: Integer; begin Result := Snapshot.Analog_Input[ai_Fuente_Excitacion]; end; function TAntenna.Get_Fuente_Exitacion_Unit: Double; begin Result := Snapshot.Analog_Input_Voltage[ai_Fuente_Excitacion]; end; function TAntenna.Get_Rango_Fuente_12V: Integer; begin Result := integer(Snapshot.AI_Range[ai_Fuente_12V_P]); end; function TAntenna.Get_Rango_Fuente_24V: Integer; begin Result := integer(Snapshot.AI_Range[ai_Fuente_24V_P]); end; function TAntenna.Get_Rango_Fuente_5V: Integer; begin Result := integer(Snapshot.AI_Range[ai_Fuente_5V_P]); end; function TAntenna.Get_Rango_Fuente_Excitacion: Integer; begin Result := integer(Snapshot.AI_Range[ai_Fuente_Excitacion]); end; function TAntenna.Get_Sector_Fuente_12V: Integer; begin Result := integer(Snapshot.AI_Sector[ai_Fuente_12V_P]); end; function TAntenna.Get_Sector_Fuente_24V: Integer; begin Result := integer(Snapshot.AI_Sector[ai_Fuente_24V_P]); end; function TAntenna.Get_Sector_Fuente_5V: Integer; begin Result := integer(Snapshot.AI_Sector[ai_Fuente_5V_P]); end; function TAntenna.Get_Sector_Fuente_Excitacion: Integer; begin Result := integer(Snapshot.AI_Sector[ai_Fuente_Excitacion]); end; procedure TAntenna.Set_Rango_Fuente_12V(Value: Integer); begin if InControl then Elbrus.Set_AI_Range(ai_Fuente_12V_P, TAIRange(Value)); end; procedure TAntenna.Set_Rango_Fuente_24V(Value: Integer); begin if InControl then Elbrus.Set_AI_Range(ai_Fuente_24V_P, TAIRange(Value)); end; procedure TAntenna.Set_Rango_Fuente_5V(Value: Integer); begin if InControl then Elbrus.Set_AI_Range(ai_Fuente_5V_P, TAIRange(Value)); end; procedure TAntenna.Set_Rango_Fuente_Excitacion(Value: Integer); begin if InControl then Elbrus.Set_AI_Range(ai_Fuente_Excitacion, TAIRange(Value)); end; procedure TAntenna.Set_Sector_Fuente_12V(Value: Integer); begin if InControl then Elbrus.Set_AI_Sector(ai_Fuente_12V_P, TAIRange(Value)); end; procedure TAntenna.Set_Sector_Fuente_24V(Value: Integer); begin if InControl then Elbrus.Set_AI_Sector(ai_Fuente_24V_P, TAIRange(Value)); end; procedure TAntenna.Set_Sector_Fuente_5V(Value: Integer); begin if InControl then Elbrus.Set_AI_Sector(ai_Fuente_5V_P, TAIRange(Value)); end; procedure TAntenna.Set_Sector_Fuente_Excitacion(Value: Integer); begin if InControl then Elbrus.Set_AI_Sector(ai_Fuente_Excitacion, TAIRange(Value)); end; function TAntenna.Get_Status: RadarStatus; begin if Snapshot.Antena_ON then if Snapshot.Antena_Ok then result := rsOk else result := rsFailure else result := rsOff; end; function TAntenna.Get_Local: WordBool; begin Result := Snapshot.Digital_Input and di_Antena_Local = di_Antena_Local; end; function TAntenna.Get_Ventilacion: WordBool; begin Result := Snapshot.Digital_Input and di_Antena_Ventilacion_On = di_Antena_Ventilacion_On; end; initialization TComObjectFactory.Create(ComServer, TAntenna, Class_Antenna, 'Antenna', '', ciMultiInstance, tmApartment); end.
unit FileInfo_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Buttons, ExtCtrls, Advanced; type TdlgFileInfo = class(TForm) pcMain: TPageControl; tsGeneral: TTabSheet; btnOk: TBitBtn; btnCancel: TBitBtn; lbName: TLabel; lbFolder: TLabel; lbSize: TLabel; lbPackedSize: TLabel; lbCreate: TLabel; lbModify: TLabel; lbOpen: TLabel; lbAttr: TLabel; lbCRC: TLabel; Bevel1: TBevel; Bevel2: TBevel; tsArchive: TTabSheet; lbFileName: TLabel; lbFileFolder: TLabel; lbFileSize: TLabel; lbFilePackedSize: TLabel; lbFileCreationTIme: TLabel; lbFileModifyTime: TLabel; lbFileLastAccessTime: TLabel; lbFileAttr: TLabel; lbFileCRC: TLabel; pbRatio: TProgressBar; lbRatio: TLabel; lbVersion: TLabel; lbFileCount: TLabel; lbArchUnpacked: TLabel; lbComment: TLabel; Bevel3: TBevel; Bevel4: TBevel; lbArchiveVersion: TLabel; lbArchiveFileCount: TLabel; lbArchiveSize: TLabel; lbArchiveComment: TLabel; lbUnPackSize: TLabel; lbArchiveUnPacked: TLabel; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var dlgFileInfo: TdlgFileInfo; implementation {$R *.dfm} procedure TdlgFileInfo.FormCreate(Sender: TObject); begin Caption:=ReadFromLanguage('Windows','wndFileInfo',Caption); btnCancel.Caption:=ReadFromLanguage('Buttons','btnCancel',btnCancel.Caption); tsGeneral.Caption:=ReadFromLanguage('Tabs','tbGeneral',tsGeneral.Caption); tsArchive.Caption:=ReadFromLanguage('Tabs','tbArchive',tsArchive.Caption); lbName.Caption:=ReadFromLanguage('Labels','lbFileName',lbName.Caption); lbFolder.Caption:=ReadFromLanguage('Labels','lbPath',lbFolder.Caption); lbSize.Caption:=ReadFromLanguage('Labels','lbSize',lbSize.Caption); lbPackedSize.Caption:=ReadFromLanguage('Labels','lbPackedSize',lbPackedSize.Caption); lbCreate.Caption:=ReadFromLanguage('Labels','lbCreate',lbCreate.Caption); lbModify.Caption:=ReadFromLanguage('Labels','lbModify',lbModify.Caption); lbOpen.Caption:=ReadFromLanguage('Labels','lbOpen',lbOpen.Caption); lbAttr.Caption:=ReadFromLanguage('Labels','lbAttr',lbAttr.Caption); lbCRC.Caption:=ReadFromLanguage('Labels','lbCRC',lbCRC.Caption); lbVersion.Caption:=ReadFromLanguage('Labels','lbVersion',lbVersion.Caption); lbFileCount.Caption:=ReadFromLanguage('Labels','lbFileCount',lbFileCount.Caption); lbArchUnpacked.Caption:=ReadFromLanguage('Labels','lbArchUnpacked',lbArchUnpacked.Caption); lbUnPackSize.Caption:=ReadFromLanguage('Labels','lbUnPackSize',lbUnPackSize.Caption); lbComment.Caption:=ReadFromLanguage('Labels','lbComment',lbComment.Caption); end; end.
unit BCrypt.Types; interface uses {$IFDEF FPC}SysUtils{$ELSE}System.SysUtils{$ENDIF}; type {$SCOPEDENUMS ON} THashType = (Default, PHP, BSD, Unknown); {$SCOPEDENUMS OFF} THashInfo = object &Type: THashType; Cost: Word; Salt: string; Hash: string; end; EBCrypt = class(Exception); {$IFDEF POSIX} UTF8String = type AnsiString(CP_UTF8); {$ENDIF POSIX} implementation end.
{******************************************************************************} { } { XML Data Binding } { } { Generated on: 21.11.2019 13:38:17 } { Generated from: D:\Work\Project\XML\order_201911211034_545637022.xml } { Settings stored in: D:\Work\Project\XML\order_201911211034_545637022.xdb } { } {******************************************************************************} unit OrderXML; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLORDERType = interface; IXMLHEADType = interface; IXMLPOSITIONType = interface; IXMLPOSITIONTypeList = interface; IXMLCHARACTERISTICType = interface; { IXMLORDERType } IXMLORDERType = interface(IXMLNode) ['{F47D343F-C768-47DB-9D5F-C9918594D97D}'] { Property Accessors } function Get_DOCUMENTNAME: Integer; function Get_NUMBER: UnicodeString; function Get_DATE: UnicodeString; function Get_DELIVERYDATE: UnicodeString; function Get_DELIVERYTIME: UnicodeString; function Get_CAMPAIGNNUMBER: UnicodeString; function Get_CURRENCY: UnicodeString; function Get_DOCTYPE: UnicodeString; function Get_INFO: UnicodeString; function Get_HEAD: IXMLHEADType; procedure Set_DOCUMENTNAME(Value: Integer); procedure Set_NUMBER(Value: UnicodeString); procedure Set_DATE(Value: UnicodeString); procedure Set_DELIVERYDATE(Value: UnicodeString); procedure Set_DELIVERYTIME(Value: UnicodeString); procedure Set_CAMPAIGNNUMBER(Value: UnicodeString); procedure Set_CURRENCY(Value: UnicodeString); procedure Set_DOCTYPE(Value: UnicodeString); procedure Set_INFO(Value: UnicodeString); { Methods & Properties } property DOCUMENTNAME: Integer read Get_DOCUMENTNAME write Set_DOCUMENTNAME; property NUMBER: UnicodeString read Get_NUMBER write Set_NUMBER; property DATE: UnicodeString read Get_DATE write Set_DATE; property DELIVERYDATE: UnicodeString read Get_DELIVERYDATE write Set_DELIVERYDATE; property DELIVERYTIME: UnicodeString read Get_DELIVERYTIME write Set_DELIVERYTIME; property CAMPAIGNNUMBER: UnicodeString read Get_CAMPAIGNNUMBER write Set_CAMPAIGNNUMBER; property CURRENCY: UnicodeString read Get_CURRENCY write Set_CURRENCY; property DOCTYPE: UnicodeString read Get_DOCTYPE write Set_DOCTYPE; property INFO: UnicodeString read Get_INFO write Set_INFO; property HEAD: IXMLHEADType read Get_HEAD; end; { IXMLHEADType } IXMLHEADType = interface(IXMLNode) ['{2A753337-BA77-4A22-99FB-B99DDF48953F}'] { Property Accessors } function Get_SUPPLIER: Integer; function Get_BUYER: Integer; function Get_DELIVERYPLACE: Integer; function Get_INVOICEPARTNER: Integer; function Get_SENDER: Integer; function Get_RECIPIENT: Integer; function Get_EDIINTERCHANGEID: UnicodeString; function Get_POSITION: IXMLPOSITIONTypeList; procedure Set_SUPPLIER(Value: Integer); procedure Set_BUYER(Value: Integer); procedure Set_DELIVERYPLACE(Value: Integer); procedure Set_INVOICEPARTNER(Value: Integer); procedure Set_SENDER(Value: Integer); procedure Set_RECIPIENT(Value: Integer); procedure Set_EDIINTERCHANGEID(Value: UnicodeString); { Methods & Properties } property SUPPLIER: Integer read Get_SUPPLIER write Set_SUPPLIER; property BUYER: Integer read Get_BUYER write Set_BUYER; property DELIVERYPLACE: Integer read Get_DELIVERYPLACE write Set_DELIVERYPLACE; property INVOICEPARTNER: Integer read Get_INVOICEPARTNER write Set_INVOICEPARTNER; property SENDER: Integer read Get_SENDER write Set_SENDER; property RECIPIENT: Integer read Get_RECIPIENT write Set_RECIPIENT; property EDIINTERCHANGEID: UnicodeString read Get_EDIINTERCHANGEID write Set_EDIINTERCHANGEID; property POSITION: IXMLPOSITIONTypeList read Get_POSITION; end; { IXMLPOSITIONType } IXMLPOSITIONType = interface(IXMLNode) ['{6044D634-85FC-43FD-B120-875D3D8E3985}'] { Property Accessors } function Get_POSITIONNUMBER: Integer; function Get_PRODUCT: Integer; function Get_PRODUCTIDBUYER: Integer; function Get_ORDEREDQUANTITY: UnicodeString; function Get_ORDERUNIT: UnicodeString; function Get_MINIMUMORDERQUANTITY: UnicodeString; function Get_CHARACTERISTIC: IXMLCHARACTERISTICType; procedure Set_POSITIONNUMBER(Value: Integer); procedure Set_PRODUCT(Value: Integer); procedure Set_PRODUCTIDBUYER(Value: Integer); procedure Set_ORDEREDQUANTITY(Value: UnicodeString); procedure Set_ORDERUNIT(Value: UnicodeString); procedure Set_MINIMUMORDERQUANTITY(Value: UnicodeString); { Methods & Properties } property POSITIONNUMBER: Integer read Get_POSITIONNUMBER write Set_POSITIONNUMBER; property PRODUCT: Integer read Get_PRODUCT write Set_PRODUCT; property PRODUCTIDBUYER: Integer read Get_PRODUCTIDBUYER write Set_PRODUCTIDBUYER; property ORDEREDQUANTITY: UnicodeString read Get_ORDEREDQUANTITY write Set_ORDEREDQUANTITY; property ORDERUNIT: UnicodeString read Get_ORDERUNIT write Set_ORDERUNIT; property MINIMUMORDERQUANTITY: UnicodeString read Get_MINIMUMORDERQUANTITY write Set_MINIMUMORDERQUANTITY; property CHARACTERISTIC: IXMLCHARACTERISTICType read Get_CHARACTERISTIC; end; { IXMLPOSITIONTypeList } IXMLPOSITIONTypeList = interface(IXMLNodeCollection) ['{640E5D95-C999-4F54-BA1B-488C8AAB71E7}'] { Methods & Properties } function Add: IXMLPOSITIONType; function Insert(const Index: Integer): IXMLPOSITIONType; function Get_Item(Index: Integer): IXMLPOSITIONType; property Items[Index: Integer]: IXMLPOSITIONType read Get_Item; default; end; { IXMLCHARACTERISTICType } IXMLCHARACTERISTICType = interface(IXMLNode) ['{0A2FA409-78DB-4795-A731-C9B8715F5E88}'] { Property Accessors } function Get_DESCRIPTION: UnicodeString; procedure Set_DESCRIPTION(Value: UnicodeString); { Methods & Properties } property DESCRIPTION: UnicodeString read Get_DESCRIPTION write Set_DESCRIPTION; end; { Forward Decls } TXMLORDERType = class; TXMLHEADType = class; TXMLPOSITIONType = class; TXMLPOSITIONTypeList = class; TXMLCHARACTERISTICType = class; { TXMLORDERType } TXMLORDERType = class(TXMLNode, IXMLORDERType) protected { IXMLORDERType } function Get_DOCUMENTNAME: Integer; function Get_NUMBER: UnicodeString; function Get_DATE: UnicodeString; function Get_DELIVERYDATE: UnicodeString; function Get_DELIVERYTIME: UnicodeString; function Get_CAMPAIGNNUMBER: UnicodeString; function Get_CURRENCY: UnicodeString; function Get_DOCTYPE: UnicodeString; function Get_INFO: UnicodeString; function Get_HEAD: IXMLHEADType; procedure Set_DOCUMENTNAME(Value: Integer); procedure Set_NUMBER(Value: UnicodeString); procedure Set_DATE(Value: UnicodeString); procedure Set_DELIVERYDATE(Value: UnicodeString); procedure Set_DELIVERYTIME(Value: UnicodeString); procedure Set_CAMPAIGNNUMBER(Value: UnicodeString); procedure Set_CURRENCY(Value: UnicodeString); procedure Set_DOCTYPE(Value: UnicodeString); procedure Set_INFO(Value: UnicodeString); public procedure AfterConstruction; override; end; { TXMLHEADType } TXMLHEADType = class(TXMLNode, IXMLHEADType) private FPOSITION: IXMLPOSITIONTypeList; protected { IXMLHEADType } function Get_SUPPLIER: Integer; function Get_BUYER: Integer; function Get_DELIVERYPLACE: Integer; function Get_INVOICEPARTNER: Integer; function Get_SENDER: Integer; function Get_RECIPIENT: Integer; function Get_EDIINTERCHANGEID: UnicodeString; function Get_POSITION: IXMLPOSITIONTypeList; procedure Set_SUPPLIER(Value: Integer); procedure Set_BUYER(Value: Integer); procedure Set_DELIVERYPLACE(Value: Integer); procedure Set_INVOICEPARTNER(Value: Integer); procedure Set_SENDER(Value: Integer); procedure Set_RECIPIENT(Value: Integer); procedure Set_EDIINTERCHANGEID(Value: UnicodeString); public procedure AfterConstruction; override; end; { TXMLPOSITIONType } TXMLPOSITIONType = class(TXMLNode, IXMLPOSITIONType) protected { IXMLPOSITIONType } function Get_POSITIONNUMBER: Integer; function Get_PRODUCT: Integer; function Get_PRODUCTIDBUYER: Integer; function Get_ORDEREDQUANTITY: UnicodeString; function Get_ORDERUNIT: UnicodeString; function Get_MINIMUMORDERQUANTITY: UnicodeString; function Get_CHARACTERISTIC: IXMLCHARACTERISTICType; procedure Set_POSITIONNUMBER(Value: Integer); procedure Set_PRODUCT(Value: Integer); procedure Set_PRODUCTIDBUYER(Value: Integer); procedure Set_ORDEREDQUANTITY(Value: UnicodeString); procedure Set_ORDERUNIT(Value: UnicodeString); procedure Set_MINIMUMORDERQUANTITY(Value: UnicodeString); public procedure AfterConstruction; override; end; { TXMLPOSITIONTypeList } TXMLPOSITIONTypeList = class(TXMLNodeCollection, IXMLPOSITIONTypeList) protected { IXMLPOSITIONTypeList } function Add: IXMLPOSITIONType; function Insert(const Index: Integer): IXMLPOSITIONType; function Get_Item(Index: Integer): IXMLPOSITIONType; end; { TXMLCHARACTERISTICType } TXMLCHARACTERISTICType = class(TXMLNode, IXMLCHARACTERISTICType) protected { IXMLCHARACTERISTICType } function Get_DESCRIPTION: UnicodeString; procedure Set_DESCRIPTION(Value: UnicodeString); end; { Global Functions } function GetOrder(Doc: IXMLDocument): IXMLORDERType; function LoadOrder(const FileName: string): IXMLORDERType; function NewOrder: IXMLORDERType; const TargetNamespace = ''; implementation { Global Functions } function GetOrder(Doc: IXMLDocument): IXMLORDERType; begin Result := Doc.GetDocBinding('Order', TXMLORDERType, TargetNamespace) as IXMLORDERType; end; function LoadOrder(const FileName: string): IXMLORDERType; begin Result := LoadXMLDocument(FileName).GetDocBinding('Order', TXMLORDERType, TargetNamespace) as IXMLORDERType; end; function NewOrder: IXMLORDERType; begin Result := NewXMLDocument.GetDocBinding('Order', TXMLORDERType, TargetNamespace) as IXMLORDERType; end; { TXMLORDERType } procedure TXMLORDERType.AfterConstruction; begin RegisterChildNode('HEAD', TXMLHEADType); inherited; end; function TXMLORDERType.Get_DOCUMENTNAME: Integer; begin Result := ChildNodes['DOCUMENTNAME'].NodeValue; end; procedure TXMLORDERType.Set_DOCUMENTNAME(Value: Integer); begin ChildNodes['DOCUMENTNAME'].NodeValue := Value; end; function TXMLORDERType.Get_NUMBER: UnicodeString; begin Result := ChildNodes['NUMBER'].Text; end; procedure TXMLORDERType.Set_NUMBER(Value: UnicodeString); begin ChildNodes['NUMBER'].NodeValue := Value; end; function TXMLORDERType.Get_DATE: UnicodeString; begin Result := ChildNodes['DATE'].Text; end; procedure TXMLORDERType.Set_DATE(Value: UnicodeString); begin ChildNodes['DATE'].NodeValue := Value; end; function TXMLORDERType.Get_DELIVERYDATE: UnicodeString; begin Result := ChildNodes['DELIVERYDATE'].Text; end; procedure TXMLORDERType.Set_DELIVERYDATE(Value: UnicodeString); begin ChildNodes['DELIVERYDATE'].NodeValue := Value; end; function TXMLORDERType.Get_DELIVERYTIME: UnicodeString; begin Result := ChildNodes['DELIVERYTIME'].Text; end; procedure TXMLORDERType.Set_DELIVERYTIME(Value: UnicodeString); begin ChildNodes['DELIVERYTIME'].NodeValue := Value; end; function TXMLORDERType.Get_CAMPAIGNNUMBER: UnicodeString; begin Result := ChildNodes['CAMPAIGNNUMBER'].Text; end; procedure TXMLORDERType.Set_CAMPAIGNNUMBER(Value: UnicodeString); begin ChildNodes['CAMPAIGNNUMBER'].NodeValue := Value; end; function TXMLORDERType.Get_CURRENCY: UnicodeString; begin Result := ChildNodes['CURRENCY'].Text; end; procedure TXMLORDERType.Set_CURRENCY(Value: UnicodeString); begin ChildNodes['CURRENCY'].NodeValue := Value; end; function TXMLORDERType.Get_DOCTYPE: UnicodeString; begin Result := ChildNodes['DOCTYPE'].Text; end; procedure TXMLORDERType.Set_DOCTYPE(Value: UnicodeString); begin ChildNodes['DOCTYPE'].NodeValue := Value; end; function TXMLORDERType.Get_INFO: UnicodeString; begin Result := ChildNodes['INFO'].Text; end; procedure TXMLORDERType.Set_INFO(Value: UnicodeString); begin ChildNodes['INFO'].NodeValue := Value; end; function TXMLORDERType.Get_HEAD: IXMLHEADType; begin Result := ChildNodes['HEAD'] as IXMLHEADType; end; { TXMLHEADType } procedure TXMLHEADType.AfterConstruction; begin RegisterChildNode('POSITION', TXMLPOSITIONType); FPOSITION := CreateCollection(TXMLPOSITIONTypeList, IXMLPOSITIONType, 'POSITION') as IXMLPOSITIONTypeList; inherited; end; function TXMLHEADType.Get_SUPPLIER: Integer; begin Result := ChildNodes['SUPPLIER'].NodeValue; end; procedure TXMLHEADType.Set_SUPPLIER(Value: Integer); begin ChildNodes['SUPPLIER'].NodeValue := Value; end; function TXMLHEADType.Get_BUYER: Integer; begin Result := ChildNodes['BUYER'].NodeValue; end; procedure TXMLHEADType.Set_BUYER(Value: Integer); begin ChildNodes['BUYER'].NodeValue := Value; end; function TXMLHEADType.Get_DELIVERYPLACE: Integer; begin Result := ChildNodes['DELIVERYPLACE'].NodeValue; end; procedure TXMLHEADType.Set_DELIVERYPLACE(Value: Integer); begin ChildNodes['DELIVERYPLACE'].NodeValue := Value; end; function TXMLHEADType.Get_INVOICEPARTNER: Integer; begin Result := ChildNodes['INVOICEPARTNER'].NodeValue; end; procedure TXMLHEADType.Set_INVOICEPARTNER(Value: Integer); begin ChildNodes['INVOICEPARTNER'].NodeValue := Value; end; function TXMLHEADType.Get_SENDER: Integer; begin Result := ChildNodes['SENDER'].NodeValue; end; procedure TXMLHEADType.Set_SENDER(Value: Integer); begin ChildNodes['SENDER'].NodeValue := Value; end; function TXMLHEADType.Get_RECIPIENT: Integer; begin Result := ChildNodes['RECIPIENT'].NodeValue; end; procedure TXMLHEADType.Set_RECIPIENT(Value: Integer); begin ChildNodes['RECIPIENT'].NodeValue := Value; end; function TXMLHEADType.Get_EDIINTERCHANGEID: UnicodeString; begin Result := ChildNodes['EDIINTERCHANGEID'].Text; end; procedure TXMLHEADType.Set_EDIINTERCHANGEID(Value: UnicodeString); begin ChildNodes['EDIINTERCHANGEID'].NodeValue := Value; end; function TXMLHEADType.Get_POSITION: IXMLPOSITIONTypeList; begin Result := FPOSITION; end; { TXMLPOSITIONType } procedure TXMLPOSITIONType.AfterConstruction; begin RegisterChildNode('CHARACTERISTIC', TXMLCHARACTERISTICType); inherited; end; function TXMLPOSITIONType.Get_POSITIONNUMBER: Integer; begin Result := ChildNodes['POSITIONNUMBER'].NodeValue; end; procedure TXMLPOSITIONType.Set_POSITIONNUMBER(Value: Integer); begin ChildNodes['POSITIONNUMBER'].NodeValue := Value; end; function TXMLPOSITIONType.Get_PRODUCT: Integer; begin Result := ChildNodes['PRODUCT'].NodeValue; end; procedure TXMLPOSITIONType.Set_PRODUCT(Value: Integer); begin ChildNodes['PRODUCT'].NodeValue := Value; end; function TXMLPOSITIONType.Get_PRODUCTIDBUYER: Integer; begin Result := ChildNodes['PRODUCTIDBUYER'].NodeValue; end; procedure TXMLPOSITIONType.Set_PRODUCTIDBUYER(Value: Integer); begin ChildNodes['PRODUCTIDBUYER'].NodeValue := Value; end; function TXMLPOSITIONType.Get_ORDEREDQUANTITY: UnicodeString; begin Result := ChildNodes['ORDEREDQUANTITY'].Text; end; procedure TXMLPOSITIONType.Set_ORDEREDQUANTITY(Value: UnicodeString); begin ChildNodes['ORDEREDQUANTITY'].NodeValue := Value; end; function TXMLPOSITIONType.Get_ORDERUNIT: UnicodeString; begin Result := ChildNodes['ORDERUNIT'].Text; end; procedure TXMLPOSITIONType.Set_ORDERUNIT(Value: UnicodeString); begin ChildNodes['ORDERUNIT'].NodeValue := Value; end; function TXMLPOSITIONType.Get_MINIMUMORDERQUANTITY: UnicodeString; begin Result := ChildNodes['MINIMUMORDERQUANTITY'].Text; end; procedure TXMLPOSITIONType.Set_MINIMUMORDERQUANTITY(Value: UnicodeString); begin ChildNodes['MINIMUMORDERQUANTITY'].NodeValue := Value; end; function TXMLPOSITIONType.Get_CHARACTERISTIC: IXMLCHARACTERISTICType; begin Result := ChildNodes['CHARACTERISTIC'] as IXMLCHARACTERISTICType; end; { TXMLPOSITIONTypeList } function TXMLPOSITIONTypeList.Add: IXMLPOSITIONType; begin Result := AddItem(-1) as IXMLPOSITIONType; end; function TXMLPOSITIONTypeList.Insert(const Index: Integer): IXMLPOSITIONType; begin Result := AddItem(Index) as IXMLPOSITIONType; end; function TXMLPOSITIONTypeList.Get_Item(Index: Integer): IXMLPOSITIONType; begin Result := List[Index] as IXMLPOSITIONType; end; { TXMLCHARACTERISTICType } function TXMLCHARACTERISTICType.Get_DESCRIPTION: UnicodeString; begin Result := ChildNodes['DESCRIPTION'].Text; end; procedure TXMLCHARACTERISTICType.Set_DESCRIPTION(Value: UnicodeString); begin ChildNodes['DESCRIPTION'].NodeValue := Value; end; end.
unit SaleMovementItemTest; interface uses dbMovementItemTest, dbTest, ObjectTest; type TSaleMovementItemTest = class(TdbTest) protected procedure SetUp; override; // возвращаем данные для тестирования procedure TearDown; override; published // загрузка процедура из определенной директории procedure ProcedureLoad; virtual; procedure Test; virtual; end; TSaleMovementItem = class(TMovementItemTest) public function InsertDefault: integer; override; public function InsertUpdateSaleMovementItem (Id, MovementId, GoodsId: Integer; Amount, AmountPartner, AmountChangePercent, ChangePercentAmount, Price, CountForPrice, HeadCount: double; PartionGoods:String; GoodsKindId, AssetId: Integer): integer; constructor Create; override; end; implementation uses UtilConst, Db, SysUtils, PersonalTest, dbMovementTest, UnitsTest, Storage, Authentication, TestFramework, CommonData, dbObjectTest, Variants, dbObjectMeatTest, SaleTest, GoodsTest; { TSaleMovementItemTest } procedure TSaleMovementItemTest.ProcedureLoad; begin ScriptDirectory := ProcedurePath + 'MovementItem\Sale\'; inherited; ScriptDirectory := ProcedurePath + 'Movement\Sale\'; inherited; end; procedure TSaleMovementItemTest.SetUp; begin inherited; TAuthentication.CheckLogin(TStorageFactory.GetStorage, 'Админ', 'Админ', gc_User); end; procedure TSaleMovementItemTest.TearDown; begin inherited; end; function TSaleMovementItem.InsertDefault: integer; var Id, MovementId, GoodsId: Integer; Amount, AmountPartner, Price, CountForPrice, HeadCount, AmountChangePercent, ChangePercentAmount: double; PartionGoods:String; GoodsKindId, AssetId: Integer; begin Id:=0; MovementId := TSale.Create.GetDefault; GoodsId := TGoods.Create.GetDefault; Amount:=10; AmountPartner:=11; ChangePercentAmount := 10; Price:=2.34; CountForPrice:=1; HeadCount:=5; PartionGoods:=''; GoodsKindId:=0; AssetId:=0; AmountChangePercent := 0; // result := InsertUpdateSaleMovementItem(Id, MovementId, GoodsId, Amount, AmountPartner, AmountChangePercent, ChangePercentAmount, Price, CountForPrice, HeadCount, PartionGoods, GoodsKindId, AssetId); end; procedure TSaleMovementItemTest.Test; var SaleMovementItem: TSaleMovementItem; Id: Integer; begin inherited; // Создаем документ SaleMovementItem := TSaleMovementItem.Create; Id := SaleMovementItem.InsertDefault; // создание документа try // редактирование finally SaleMovementItem.Delete(Id); end; end; { TSaleMovementItem } constructor TSaleMovementItem.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_MovementItem_Sale'; end; function TSaleMovementItem.InsertUpdateSaleMovementItem( Id, MovementId, GoodsId: Integer; Amount, AmountPartner, AmountChangePercent, ChangePercentAmount, Price, CountForPrice, HeadCount: double; PartionGoods:String; GoodsKindId, AssetId: Integer): integer; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inMovementId', ftInteger, ptInput, MovementId); FParams.AddParam('inGoodsId', ftInteger, ptInput, GoodsId); FParams.AddParam('inAmount', ftFloat, ptInput, Amount); FParams.AddParam('inAmountPartner', ftFloat, ptInput, AmountPartner); FParams.AddParam('inAmountChangePercent', ftFloat, ptInput, AmountChangePercent); FParams.AddParam('inChangePercentAmount', ftFloat, ptInput, ChangePercentAmount); FParams.AddParam('inPrice', ftFloat, ptInput, Price); FParams.AddParam('i0CountForPrice', ftFloat, ptInputOutput, CountForPrice); FParams.AddParam('inHeadCount', ftFloat, ptInput, HeadCount); FParams.AddParam('inPartionGoods', ftString, ptInput, PartionGoods); FParams.AddParam('inGoodsKindId', ftInteger, ptInput, GoodsKindId); FParams.AddParam('inAssetId', ftInteger, ptInput, AssetId); result := InsertUpdate(FParams); end; initialization // TestFramework.RegisterTest('Строки Документов', TSaleMovementItemTest.Suite); end.
unit WinKeyer; interface const // Admin <00><nn> nn is a value from 0 to 8 WK_ADMIN_CMD = $00; WK_ADMIN_CAL = $00; WK_ADMIN_RESET = $01; WK_ADMIN_OPEN = $02; WK_ADMIN_CLOSE = $03; WK_ADMIN_ECHO = $04; WK_ADMIN_PADDLE_A2D = $05; WK_ADMIN_SET_WK2_MODE = 11; WK_ADMIN_SET_LOW_BAUD = 17; // Set Low Baud Change serial comm. Baud Rate to 1200 (default) WK_ADMIN_SET_HIGH_BAUD = 18; // Set High Baud Change serial comm. Baud Rate to 9600 WK_ADMIN_SET_WK3_MODE = 20; WK_ADMIN_SIDETONE_VOLUME = 24; // 25: Set Sidetone Volume <00><24><n> where n =0x1 for low and n=0x4 for high // Sidetone Frequency <01><nn> nn is a value from 1 to 10 WK_SIDETONE_CMD = $01; WK_SIDETONE_PADDLEONLY = $80; // Set WPM Speed <02><nn> nn is in the range of 5-99 WPM // Example: <02><12> set 18 WPM WK_SETWPM_CMD = $02; //Set PTT Lead/Tail <04><nn1><nn2> nn1 sets lead in time, nn2 sets tail time //both values range 0 to 250 in 10 mSecs steps WK_SET_PTTDELAY_CMD = $04; // Setup Speed Pot <05><nn1><nn2><nn3> // nn1 = MINWPM, nn2 = WPMRANGE, nn3 = POTRANGE WK_SET_SPEEDPOT_CMD = $05; // Get Speed Pot <07> no parameter // Request to WinKey to return current speed pot setting. WK_GET_SPEEDPOT_CMD = $07; // Backspace <08> Backup the input buffer pointer by one character. WK_BACKSPACE_CMD = $08; // Set PinConfig <09><nn> Set the PINCFG Register WK_SET_PINCFG_CMD = $09; // Clear Buffer <0A> no parameters WK_CLEAR_CMD = $0a; // Key Immediate <0B><nn> nn = 01 key down, n = 00 key up WK_KEY_IMMEDIATE_CMD = $0b; WK_KEY_IMMEDIATE_KEYDOWN = $01; WK_KEY_IMMEDIATE_KEYUP = $00; // Set WinKeyer Mode <0E><nn> nn = Mode bit field in binary WK_SETMODE_CMD = $0e; WK_SETMODE_CTSPACING = $01; // 0 (LSB) CT Spacing when=1, Normal Wordspace when=0 WK_SETMODE_AUTOSPACE = $02; // 1 Autospace (1=Enabled, 0=Disabled) WK_SETMODE_SERIALECHOBACK = $04; // 2 Serial Echoback (1=Enabled, 0=Disabled) WK_SETMODE_PADDLESWAP = $08; // 3 Paddle Swap (1=Swap, 0=Normal) WK_SETMODE_Iambic_A = $10; // 4 10 = Ultimatic 11 = Bug Mode WK_SETMODE_Ultimatic = $20; // 5 Key Mode: 00 = Iambic B 01 = Iambic A WK_SETMODE_Iambic_B = $00; WK_SETMODE_BUGMODE = $30; WK_SETMODE_PADDLE_ECHOBACK = $40; // 6 Paddle Echoback (1=Enabled, 0=Disabled) WK_SETMODE_DISABLE_PADDLE_WATCHDOG = $80; // 7 (MSB) Disable Paddle watchdog // Request Winkeyer2 Status <15> no parameter, Return Winkeyer2fs status byte WK_STATUS_CMD = $15; WK_STATUS_XOFF = $01; // Buffer is more than 2/3 full when = 1 WK_STATUS_BREAKIN = $02; // Paddle break-in active when = 1 WK_STATUS_BUSY = $04; // Keyer is busy sending Morse when = 1 WK_STATUS_KEYDOWN = $08; // Keydown status (Tune) 1 = keydown WK_STATUS_WAIT = $10; // WK is waiting for an internally timed event to finish // Buffered Commands // PTT On/Off <18><nn> nn = 01 PTT on, n = 00 PTT off WK_PTT_CMD = $18; WK_PTT_ON = 1; WK_PTT_OFF = 0; implementation end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC pool standard implementation } { } { Copyright(c) 2004-2013 Embarcadero Technologies, Inc. } { } {*******************************************************} {$I FireDAC.inc} {$IFDEF WIN32} {$HPPEMIT '#pragma link "FireDAC.Stan.Pool.obj"'} {$ELSE} {$HPPEMIT '#pragma link "FireDAC.Stan.Pool.o"'} {$ENDIF} unit FireDAC.Stan.Pool; interface implementation uses {$IFDEF MSWINDOWS} Winapi.Windows, {$ENDIF} System.SysUtils, System.Classes, System.SyncObjs, FireDAC.Stan.Intf, FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Error, FireDAC.Stan.Factory; type TFDResourcePoolItem = class(TObject) private FObj: IFDStanObject; FInUse: Boolean; FLastUsed: LongWord; public property Obj: IFDStanObject read FObj; property InUse: Boolean read FInUse; property LastUsed: LongWord read FLastUsed; end; TFDResourcePool = class(TFDObject, IFDStanObjectFactory) private FHost: IFDStanObjectHost; FList: TFDObjList; FLock: TCriticalSection; FTimer: TFDTimer; FCleanupTimeout: LongWord; FExpireTimeout: LongWord; FMaximumItems: Integer; FBusyItems: LongWord; FCloseTimeout: LongWord; procedure DoCleanup; procedure InternalRelease(const AObject: IFDStanObject); protected // IFDStanObjectFactory procedure Open(const AHost: IFDStanObjectHost; const ADef: IFDStanDefinition); procedure Close; procedure Acquire(out AObject: IFDStanObject); procedure Release(const AObject: IFDStanObject); public procedure Initialize; override; destructor Destroy; override; end; { ---------------------------------------------------------------------------- } { TFDResourcePool } { ---------------------------------------------------------------------------- } procedure TFDResourcePool.Initialize; begin inherited Initialize; FCleanupTimeout := C_FD_PoolCleanupTimeout; FExpireTimeout := C_FD_PoolExpireTimeout; FCloseTimeout := C_FD_PoolCloseTimeout; FMaximumItems := C_FD_PoolMaximumItems; FList := TFDObjList.Create; FLock := TCriticalSection.Create; FTimer := TFDTimer.Create(nil); FTimer.Interval := FCleanupTimeout; FTimer.OnTimer := DoCleanup; end; { ---------------------------------------------------------------------------- } destructor TFDResourcePool.Destroy; begin Close; FDFreeAndNil(FTimer); FDFreeAndNil(FList); FDFreeAndNil(FLock); inherited Destroy; end; { ---------------------------------------------------------------------------- } procedure TFDResourcePool.DoCleanup; var i: integer; oList: TFDObjList; begin if FLock.TryEnter then begin oList := TFDObjList.Create; try try for i := FList.Count - 1 downto 0 do if not TFDResourcePoolItem(FList[i]).InUse and FDTimeout(TFDResourcePoolItem(FList[i]).LastUsed, FExpireTimeout) then begin oList.Add(FList[i]); FList.Delete(i); end; finally FLock.Leave; end; for i := 0 to oList.Count - 1 do FDFree(TFDResourcePoolItem(oList[i])); finally FDFree(oList); end; end; end; { ---------------------------------------------------------------------------- } procedure TFDResourcePool.Acquire(out AObject: IFDStanObject); var i, iCreate: integer; oItem: TFDResourcePoolItem; begin AObject := nil; FLock.Enter; try ASSERT(FHost <> nil); for i := 0 to FList.Count - 1 do begin oItem := TFDResourcePoolItem(FList[i]); if not oItem.InUse then begin AObject := oItem.Obj; oItem.FInUse := True; Inc(FBusyItems); Break; end; end; if AObject = nil then begin if (FMaximumItems > 0) and (FMaximumItems <= FList.Count) then FDException(Self, [S_FD_LStan], er_FD_StanPoolTooManyItems, [FMaximumItems]); iCreate := 5; oItem := nil; if (FMaximumItems > 0) and (iCreate > FMaximumItems - FList.Count) then iCreate := FMaximumItems - FList.Count; while iCreate > 0 do begin oItem := TFDResourcePoolItem.Create; try oItem.FLastUsed := FDGetTickCount; FHost.CreateObject(oItem.FObj); except FDFree(oItem); raise; end; FList.Add(oItem); Dec(iCreate); end; ASSERT((oItem <> nil) and not oItem.FInUse and (oItem.FObj <> nil)); AObject := oItem.FObj; oItem.FInUse := True; Inc(FBusyItems); end; finally FLock.Leave; end; try AObject.BeforeReuse; except InternalRelease(AObject); AObject := nil; raise; end; end; { ---------------------------------------------------------------------------- } procedure TFDResourcePool.InternalRelease(const AObject: IFDStanObject); var i: integer; oItem: TFDResourcePoolItem; begin FLock.Enter; try for i := 0 to FList.Count - 1 do begin oItem := TFDResourcePoolItem(FList[i]); if oItem.Obj = AObject then begin oItem.FInUse := False; oItem.FLastUsed := FDGetTickCount; Dec(FBusyItems); Exit; end; end; finally FLock.Leave; end; end; { ---------------------------------------------------------------------------- } procedure TFDResourcePool.Release(const AObject: IFDStanObject); begin try AObject.AfterReuse; finally InternalRelease(AObject); end; end; {-------------------------------------------------------------------------------} procedure TFDResourcePool.Open(const AHost: IFDStanObjectHost; const ADef: IFDStanDefinition); function Def(AValue, ADef: Integer): Integer; begin if AValue = 0 then Result := ADef else Result := AValue; end; begin FLock.Enter; try ASSERT(FHost = nil); if ADef <> nil then begin FCleanupTimeout := LongWord(Def(ADef.AsInteger[S_FD_PoolParam_CleanupTimeout], C_FD_PoolCleanupTimeout)); FExpireTimeout := LongWord(Def(ADef.AsInteger[S_FD_PoolParam_ExpireTimeout], C_FD_PoolExpireTimeout)); FMaximumItems := Def(ADef.AsInteger[S_FD_PoolParam_MaximumItems], C_FD_PoolMaximumItems); end; FHost := AHost; FTimer.Enabled := True; finally FLock.Leave; end; end; {-------------------------------------------------------------------------------} procedure TFDResourcePool.Close; var i: Integer; iStartTime: LongWord; begin if FHost <> nil then begin FHost := nil; iStartTime := FDGetTickCount; while (FBusyItems > 0) and not FDTimeout(iStartTime, FCloseTimeout) do Sleep(1); FLock.Enter; try FTimer.Enabled := False; for i := 0 to FList.Count - 1 do FDFree(TFDResourcePoolItem(FList[i])); FList.Clear; finally FLock.Leave; end; end; end; {-------------------------------------------------------------------------------} var oFact: TFDFactory; initialization oFact := TFDMultyInstanceFactory.Create(TFDResourcePool, IFDStanObjectFactory); finalization FDReleaseFactory(oFact); end.
unit TreeItems; (***** Code Written By Huang YanLai *****) interface uses windows,Sysutils,classes,IntfUtils, SafeCode,ComWriUtils,ComCtrls,Commctrl; type TTreeItemType = integer; ITreeItem = interface; ITreeFolder = interface; ITreeItem = interface ['{F732EE60-57AB-11D2-B3AB-0080C85570FA}'] function GetCaption: string; procedure SetCaption(const Value: string); function GetItemType:TTreeItemType; function GetParent:ITreeFolder; property Caption : string Read GetCaption Write SetCaption; property ItemType : TTreeItemType Read GetItemType; property Parent : ITreeFolder read GetParent; procedure Delete; function CanEdit : boolean; function CanDelete : boolean; function IsFolder : boolean; // return the object that implements the interface. function GetObject : TObject; // when attached to A TreeNode, // tree will call AfterAttach(TreeNode) procedure AfterAttach(AttachTo : TObject); end; ITreeFolder = interface(ITreeItem) ['{F732EE61-57AB-11D2-B3AB-0080C85570FA}'] function GetOpened: boolean; function GetCount: integer; function GetChildren(index: integer): ITreeItem; property Opened: boolean Read GetOpened ; procedure Open; procedure Close; // manage all items property Count : integer read GetCount; property Children[index : integer] : ITreeItem Read GetChildren; end; TTreeItem = class(TVCLDelegateObject{,ITreeItem}) private FParent : ITreeFolder; FItemType : TTreeItemType; // implement ITreeItem public // FCaption is only for its owner to use FCaption : string; constructor Create(AOwner:TObject; AParent : ITreeFolder;AItemType : TTreeItemType); // implement ITreeItem function GetCaption: string; procedure SetCaption(const Value: string); function GetItemType:TTreeItemType; function GetParent:ITreeFolder; property Caption : string Read GetCaption Write SetCaption; property ItemType : TTreeItemType Read GetItemType Write FItemType; property Parent : ITreeFolder read GetParent; procedure Delete; virtual; function CanEdit : boolean; //virtual; function CanDelete : boolean; //virtual; function IsFolder : boolean; //virtual; function GetObject : TObject; procedure AfterAttach(AttachTo : TObject); end; TMyTreeItem = class(TComponent,ITreeItem) private FTreeItem: TTreeItem; public constructor Create(AOwner : TComponent); override; property TreeItem: TTreeItem read FTreeItem implements ITreeItem; end; TTreeFolder = class(TTreeItem{,IUnknown,ITreeItem,ITreeFolder}) private FOpened : boolean; FItems : TObjectList; public FreeNodeWhenClose : boolean; constructor Create(AOwner:TObject; AParent : ITreeFolder;AItemType : TTreeItemType); destructor destroy; override; // TreeItem implements ITreeItem function IsFolder : boolean; function GetOpened: boolean; function GetCount: integer; function GetChildren(index: integer): ITreeItem; procedure Open; //virtual; procedure Close; //virtual; // manage all items property Opened: boolean Read FOpened write FOpened; property Count : integer read GetCount; property Children[index : integer] : ITreeItem Read GetChildren; property Items : TObjectList read FItems; procedure Clear; procedure Add(TreeItem:TObject); end; TFolderView = class(TTreeView) private { FFolderMan: TFolderMan; FOnInitItemImage: TInitImageIndexEvent; procedure SetFolderMan(const Value: TFolderMan);} function GetSelectedTreeItem: ITreeItem; function GetRootItem: ITreeItem; procedure SetRootItem(const Value: ITreeItem); protected function CanEdit(Node: TTreeNode): Boolean; override; procedure Edit(const Item: TTVItem); override; function CanExpand(Node: TTreeNode): Boolean; override; function GetNodeFromItem(const Item: TTVItem): TTreeNode; function InternalOpen(Node : TTreeNode; Reload : boolean):boolean; procedure Collapse(Node: TTreeNode); override; public //property FolderMan : TFolderMan read FFolderMan write SetFolderMan; property SelectedTreeItem : ITreeItem Read GetSelectedTreeItem; function OpenNode(Node : TTreeNode):boolean; function UpdateNode(Node : TTreeNode):boolean; function AddTreeItem(ParentNode : TTreeNode; TreeItem : ITreeItem): TTreeNode; property RootItem : ITreeItem Read GetRootItem write SetRootItem; function ItemFromNode(Node: TTreeNode): ITreeItem; function ItemObjectFromNode(Node: TTreeNode): TObject; published { property OnInitItemImage: TInitImageIndexEvent Read FOnInitItemImage Write FOnInitItemImage;} end; implementation { TTreeItem } constructor TTreeItem.Create(AOwner: TObject; AParent : ITreeFolder; AItemType: TTreeItemType); begin inherited Create(AOwner); FItemType := AItemType; FParent := AParent; end; function TTreeItem.CanDelete: boolean; begin result := false; end; function TTreeItem.CanEdit: boolean; begin result := false; end; procedure TTreeItem.Delete; begin // do nothing. end; function TTreeItem.GetCaption: string; begin result := FCaption; end; procedure TTreeItem.SetCaption(const Value: string); begin FCaption := value; end; function TTreeItem.GetItemType: TTreeItemType; begin result := FItemType; end; function TTreeItem.GetObject: TObject; begin result := Owner; end; function TTreeItem.GetParent: ITreeFolder; begin result := FParent; end; function TTreeItem.IsFolder: boolean; begin result := false; end; procedure TTreeItem.AfterAttach(AttachTo: TObject); begin // do nothing end; { TMyTreeItem } constructor TMyTreeItem.Create(AOwner: TComponent); begin inherited Create(AOwner); FTreeItem := TTreeItem.Create(self,nil,0); end; { TTreeFolder } constructor TTreeFolder.Create(AOwner: TObject; AParent: ITreeFolder; AItemType: TTreeItemType); begin inherited Create(AOwner,AParent,AItemType); FItems := TObjectList.Create(true); FreeNodeWhenClose := false; end; destructor TTreeFolder.destroy; begin FItems.free; inherited destroy; end; function TTreeFolder.GetChildren(index: integer): ITreeItem; begin if FItems[index]<>nil then FItems[index].GetInterface(ITreeItem, result) else result:=nil; end; function TTreeFolder.GetCount: integer; begin result := FItems.count; end; function TTreeFolder.GetOpened: boolean; begin result := FOpened; end; procedure TTreeFolder.Open; begin Fopened := true; end; procedure TTreeFolder.Close; begin //Fopened := false; if FreeNodeWhenClose then Clear; end; procedure TTreeFolder.Add(TreeItem:TObject); var intf : ITreeItem; begin if (TreeItem<>nil) and (TreeItem.GetInterface(ITreeItem,intf)) then items.add(TreeItem) else RaiseInvalidParam; end; procedure TTreeFolder.Clear; begin items.Clear; Fopened := false; end; function TTreeFolder.IsFolder: boolean; begin result := true; end; { TFolderView } function TFolderView.CanEdit(Node: TTreeNode): Boolean; begin result := inherited CanEdit(Node) and ITreeItem(node.data).CanEdit; end; function TFolderView.CanExpand(Node: TTreeNode): Boolean; begin result := inherited CanExpand(Node) and ITreeItem(Node.data).IsFolder; if result then result := OpenNode(Node); end; procedure TFolderView.Edit(const Item: TTVItem); var Node: TTreeNode; begin inherited Edit(Item); Node := GetNodeFromItem(Item); if Node<>nil then try ITreeItem(Node.data).caption := Node.text; except Node.text := ITreeItem(Node.data).caption; raise ; end; end; function TFolderView.GetSelectedTreeItem: ITreeItem; begin if selected=nil then result := nil else result := ITreeItem(selected.data); end; function TFolderView.AddTreeItem(ParentNode: TTreeNode; TreeItem: ITreeItem): TTreeNode; begin assert(TreeItem<>nil); result := Items.AddChildObject(ParentNode, TreeItem.caption, pointer(TreeItem)); result.HasChildren := TreeItem.IsFolder; TreeItem.AfterAttach(result); //TreeItem.TreeNode := {if Assigned(FOnInitItemImage) then FOnInitItemImage(self,result,TreeItem);} end; function TFolderView.OpenNode(Node: TTreeNode): boolean; {var i : integer;} begin {assert(Node<>nil); if ITreeItem(Node.data).IsFolder then with ITreeItem(Node.data) as ITreeFolder do begin if not opened then begin // not yet open Node.DeleteChildren; Open; result := Opened; if result then for i:=0 to count-1 do AddTreeItem(node,Children[i]); end else result:=true // already opened end else result:=false; // not is folder} result := InternalOpen(Node,false); end; { procedure TFolderView.SetFolderMan(const Value: TFolderMan); begin if FFolderMan <> Value then begin if FFolderMan<>nil then FFolderMan.FFolderView := nil; FFolderMan := Value; if FFolderMan<>nil then FFolderMan.FFolderView := self; items.Clear; if (FFolderMan<>nil) and (FFolderMan.root<>nil) then AddTreeItem(nil,FFolderMan.root); end; end; } function TFolderView.GetNodeFromItem(const Item: TTVItem): TTreeNode; begin with Item do if (state and TVIF_PARAM) <> 0 then Result := Pointer(lParam) else Result := Items.GetNode(hItem); end; function TFolderView.GetRootItem: ITreeItem; begin if Items.count=0 then result:=nil else result := ITreeItem(Items.GetFirstNode.Data); end; procedure TFolderView.SetRootItem(const Value: ITreeItem); begin if GetRootItem<>value then begin items.Clear; if value<>nil then begin //items.AddChildObjectFirst(nil, AddTreeItem(nil,value); end; end; end; function TFolderView.ItemFromNode(Node: TTreeNode): ITreeItem; begin if Node=nil then result := nil else result := ITreeItem(Node.data); end; function TFolderView.UpdateNode(Node: TTreeNode): boolean; var Expanded : boolean; begin Expanded := Node.Expanded; result := InternalOpen(Node,true); if Expanded then Node.Expand(false); end; function TFolderView.InternalOpen(Node: TTreeNode; Reload: boolean): boolean; var i : integer; begin assert(Node<>nil); {with ITreeFolder(Node.data) do begin if not opened then begin Node.DeleteChildren; Opened := true; end; if opened and (Node.Count=0) then for i:=0 to count-1 do begin AddTreeItem(node,items[i]); end; result := opened; end;} if ITreeItem(Node.data).IsFolder then with ITreeItem(Node.data) as ITreeFolder do begin if reload or not opened or (opened and (Node.count<>count)) then begin // not yet open try self.items.BeginUpdate; Node.DeleteChildren; Open; result := Opened; if result then for i:=0 to count-1 do AddTreeItem(node,Children[i]); finally self.items.EndUpdate; end; end else result:=true // already opened end else result:=false; // not is folder end; function TFolderView.ItemObjectFromNode(Node: TTreeNode): TObject; var TreeItem : ITreeItem; begin TreeItem := ItemFromNode(Node); if TreeItem=nil then result:=nil else result:=TreeItem.GetObject; end; procedure TFolderView.Collapse(Node: TTreeNode); var TreeItem : ITreeItem; begin inherited Collapse(Node); TreeItem := ItemFromNode(Node); if (TreeItem<>nil) and TreeItem.IsFolder then with (TreeItem as ITreeFolder) do begin Close; if Count<>Node.Count then Node.DeleteChildren; end; end; end.
unit DenseLayerUnit; {Neural Network library, by Eric C. Joyce Model a Dense Layer as two matrices and two vectors: input vec(x) weights W masks M [ x1 x2 x3 x4 1 ] [ w11 w12 w13 w14 ] [ m11 m12 m13 m14 ] [ w21 w22 w23 w24 ] [ m21 m22 m23 m24 ] [ w31 w32 w33 w34 ] [ m31 m32 m33 m34 ] [ w41 w42 w43 w44 ] [ m41 m42 m43 m44 ] [ w51 w52 w53 w54 ] [ 1 1 1 1 ] activation function vector f [ func1 func2 func3 func4 ] auxiliary vector alpha [ param1 param2 param3 param4 ] Broadcast W and M = W' vec(x) dot W' = x' vec(output) is func[i](x'[i], param[i]) for each i Not all activation functions need a parameter. It's just a nice feature we like to offer. Note that this file does NOT seed the randomizer. That should be done by the parent program.} interface {************************************************************************************************** Constants } const RELU = 0; { [ 0.0, inf) } LEAKY_RELU = 1; { (-inf, inf) } SIGMOID = 2; { ( 0.0, 1.0) } HYPERBOLIC_TANGENT = 3; { [-1.0, 1.0] } SOFTMAX = 4; { [ 0.0, 1.0] } SYMMETRICAL_SIGMOID = 5; { (-1.0, 1.0) } THRESHOLD = 6; { 0.0, 1.0 } LINEAR = 7; { (-inf, inf) } LAYER_NAME_LEN = 32; { Length of a Layer 'name' string } //{$DEFINE __DENSE_DEBUG 1} {************************************************************************************************** Typedefs } type DenseLayer = record inputs: cardinal; { Number of inputs--NOT COUNTING the added bias-1 } nodes: cardinal; { Number of processing units in this layer } W: array of double; { ((inputs + 1) x nodes) matrix } M: array of real; { ((inputs + 1) x nodes) matrix, all either 0.0 or 1.0 } functions: array of byte; { n-array } alphas: array of double; { n-array } layerName: array [0..LAYER_NAME_LEN - 1] of char; out: array of double; end; {************************************************************************************************** Prototypes } { Set entirety of layer's weight matrix } procedure setW_Dense(const w: array of double; var layer: DenseLayer); { Set entirety of weights for i-th column/neuron/unit } procedure setW_i_Dense(const w: array of double; const i: cardinal; var layer: DenseLayer); { Set element [i, j] of layer's weight matrix } procedure setW_ij_Dense(const w: double; const i: cardinal; const j: cardinal; var layer: DenseLayer); { Set entirety of layer's mask matrix } procedure setM_Dense(const m: array of boolean; var layer: DenseLayer); { Set entirety of masks for i-th column/neuron/unit } procedure setM_i_Dense(const m: array of boolean; const i: cardinal; var layer: DenseLayer); { Set element [i, j] of layer's mask matrix } procedure setM_ij_Dense(const m: boolean, const i, j: cardinal; var layer: DenseLayer); { Set activation function of i-th neuron/unit } procedure setF_i_Dense(const func: byte, const i: cardinal; var layer: DenseLayer); { Set activation function auxiliary parameter of i-th neuron/unit } procedure setA_i_Dense(const a: double; const i: cardinal; var layer: DenseLayer); procedure setName_Dense(const n: array of char; var layer: DenseLayer); procedure print_Dense(const layer: DenseLayer); function outputLen_Dense(const layer: DenseLayer): cardinal; function run_Dense(const x: array of double; var layer: DenseLayer): cardinal; implementation {************************************************************************************************** Dense-Layers } { Set entirety of layer's weight matrix. Input buffer 'w' is expected to be ROW-MAJOR weights W [ w0 w1 w2 w3 ] [ w4 w5 w6 w7 ] [ w8 w9 w10 w11 ] [ w12 w13 w14 w15 ] [ w16 w17 w18 w19 ] <--- biases } procedure setW_Dense(const w: array of double; var layer: DenseLayer); var i: cardinal; begin {$ifdef __DENSE_DEBUG} writeln('setW_Dense()'); {$endif} for i := 0 to (layer.inputs + 1) * layer.nodes - 1 do layer.W[i] := w[i]; end; { Set entirety of weights for i-th column/neuron/unit. } procedure setW_i_Dense(const w: array of double; const i: cardinal; var layer: DenseLayer); var j: cardinal; begin {$ifdef __DENSE_DEBUG} writeln('setW_i_Dense(', i, ')'); {$endif} for i := 0 to layer.inputs - 1 do layer.W[j * layer.nodes + i] := w[j]; end; { Set unit[i], weight[j] of the given layer } procedure setW_ij_Dense(const w: double; const i: cardinal; const j: cardinal; var layer: DenseLayer); begin {$ifdef __DENSE_DEBUG} writeln('setW_ij_Dense(', i, ', ', j, ')'); {$endif} if j * layer.nodes + i < (layer.inputs + 1) * layer.nodes then layer.W[j * layer.nodes + i] := w; end; { Set entirety of layer's mask matrix Input buffer 'm' is expected to be ROW-MAJOR masks M [ m0 m1 m2 m3 ] [ m4 m5 m6 m7 ] [ m8 m9 m10 m11 ] [ m12 m13 m14 m15 ] [ m16 m17 m18 m19 ] <--- biases } procedure setM_Dense(const m: array of boolean; var layer: DenseLayer); var i: cardinal; begin {$ifdef __DENSE_DEBUG} writeln('setM_Dense()'); {$endif} for i := 0 to (layer.inputs + 1) * layer.nodes - 1 do begin if m[i] then layer.M[i] := 1.0 else layer.M[i] := 0.0; end; end; { Set entirety of masks for i-th column/neuron/unit } procedure setM_i_Dense(const m: array of boolean; const i: cardinal; var layer: DenseLayer); var j: cardinal; begin {$ifdef __DENSE_DEBUG} writeln('setM_i_Dense(', i, ')'); {$endif} for j := 0 to layer.inputs do begin if m[j] then layer.M[j * layer.nodes + i] := 1.0 else layer.M[j * layer.nodes + i] := 0.0; end; end; { Set unit[i], weight[j] of the given layer } procedure setM_ij_Dense(const m: boolean; const i, j: cardinal; var layer: DenseLayer); begin {$ifdef __DENSE_DEBUG} if m then writeln('setM_ij_Dense(LIVE, ', i, ', ', j, ')') else writeln('setM_ij_Dense(MASKED, ', i, ', ', j, ')'); {$endif} if j * layer.nodes + i < (layer.inputs + 1) * layer.nodes) then begin if m then layer.M[j * layer.nodes + i] := 1.0 else layer.M[j * layer.nodes + i] := 0.0; end; end; { Set the activation function for unit[i] of the given layer } procedure setF_i_Dense(const func: byte; const i: cardinal; var layer: DenseLayer); begin {$ifdef __DENSE_DEBUG} writeln('setF_i_Dense(', func, ', ', i, ')'); {$endif} if i < layer.nodes then layer.functions[i] := func; end; { Set the activation function parameter for unit[i] of the given layer } procedure setA_i_Dense(const a: double; const i: cardinal; var layer: DenseLayer); begin {$ifdef __DENSE_DEBUG} writeln('setA_i_Dense(', a, ', ', i, ')'); {$endif} if i < layer.nodes then layer.alphas[i] := a; end; { Set the name of the given Dense Layer } procedure setName_Dense(const n: array of char; var layer: DenseLayer); var i: byte; lim: byte; begin if length(n) < LAYER_NAME_LEN then lim := length(n) else lim := LAYER_NAME_LEN; for i := 0 to lim - 1 do layer.layerName[i] := n[i]; layer.layerName[lim] := chr(0); end; { Print the details of the given DenseLayer 'layer' } procedure print_Dense(const layer: DenseLayer); var i, j: cardinal; begin unsigned int i, j; {$ifdef __DENSE_DEBUG} writeln('print_Dense()'); {$endif} for i := 0 to layer.inputs do begin if i = layer.inputs then write('bias [') else write(' ['); for j := 0 to layer.nodes - 1 do begin if layer.W[i * layer.nodes + j] >= 0.0 then write(' ', layer.W[i * layer.nodes + j], ' ') else write(layer.W[i * layer.nodes + j], ' '); end; writeln(']'); end; write('f = ['); for i := 0 to layer.nodes - 1 do begin case (layer.functions[i]) of RELU: write('ReLU '); LEAKY_RELU: write('L.ReLU '); SIGMOID: write('Sig. '); HYPERBOLIC_TANGENT: write('tanH '); SOFTMAX: write('SoftMx '); SYMMETRICAL_SIGMOID: write('SymSig '); THRESHOLD: write('Thresh '); LINEAR: write('Linear '); end; writeln(']'); write('a = ['); for i := 0 to layer.nodes - 1 do write(layer.alphas[i], ' '); writeln(']'); end; { Return the layer's output length (For Dense layers, this is the number of units) } function outputLen_Dense(const layer: DenseLayer): cardinal; begin {$ifdef __DENSE_DEBUG} writeln('outputLen_Dense()'); {$endif} result := layer.nodes; end; { Run the given input vector 'x' of length 'layer'.'inputs' through the DenseLayer 'layer'. Output is stored internally in layer.out. } function run_Dense(const x: array of double; var layer: DenseLayer): cardinal; var xprime: array [0..layer.inputs] of double; // Input vector augmented with additional (bias) 1.0 // (1 * (length-of-input + 1)) // ((length-of-input + 1) * nodes) Wprime: array [0..(layer.inputs + 1) * layer.nodes - 1] of double; softmaxdenom: double; // Accumulate exp()'s to normalize any softmax i: cardinal; begin end; {$ifdef __DENSE_DEBUG} writeln('run_Dense(', layer.inputs, ')'); {$endif} softmaxdenom := 0.0; for i := 0 to layer.inputs - 1 do // Append 1.0 to input vector xprime[i] := x[i]; xprime[i] := 1.0; // weights W masks M // i = 0 ----------------------------> layer->nodes i = 0 ----------------------------> layer->nodes // j [ A+0 A+((len+1)*i) A+((len+1)*i)+j ] j [ A+0 A+((len+1)*i) A+((len+1)*i)+j ] // | [ A+1 A+((len+1)*i)+1 A+((len+1)*i)+j ] | [ A+1 A+((len+1)*i)+1 A+((len+1)*i)+j ] // | [ A+2 A+((len+1)*i)+2 A+((len+1)*i)+j ] | [ A+2 A+((len+1)*i)+2 A+((len+1)*i)+j ] // | [ ... ... ... ] | [ ... ... ... ] // V [ A+len A+((len+1)*i)+len A+((len+1)*i)+j ] V [ A+len A+((len+1)*i)+len A+((len+1)*i)+j ] // len+1 [ A+len+1 A+((len+1)*i)+len+1 A+((len+1)*i)+j ] len+1 [ 1 1 1 ] for i := 0 to (layer.inputs + 1) * layer.nodes - 1 do // Broadcast weights and masks into W' Wprime[i] := layer.W[i] * layer.[i]; // Dot-product xprime Wprime ---> layer->out cblas_dgemv(CblasRowMajor, // The order in which data in Wprime are stored CblasNoTrans, // Transpose layer.inputs + 1, // Number of ROWS in Wprime = number of inputs + 1 row of biases layer.nodes, // Number of COLUMNS in Wprime = number of layer units 1.0, // alpha (ignore this) Wprime, layer.nodes, // Stride in Wprime equals the number of COLUMNS when order = CblasRowMajor xprime, 1, // Stride in xprime 0.0, layer.out, 1); for i := 0 to layer.nodes - 1 do // In case one of the units is a softmax unit, softmaxdenom := softmaxdenom + exp(layer.out[i]); // compute all exp()'s so we can sum them. for i := 0 to layer.nodes - 1 do // Run each element in out through appropriate function begin // with corresponding parameter case (layer.functions[i]) of RELU: if layer.out[i] < 0.0 then layer.out[i] := 0.0; LEAKY_RELU: if layer.out[i] < 0.0 then layer.out[i] := layer.out[i] * layer.alphas[i]; SIGMOID: layer.out[i] := 1.0 / (1.0 + exp(-layer.out[i] * layer.alphas[i])); HYPERBOLIC_TANGENT: layer.out[i] := (2.0 / (1.0 + exp(-2.0 * layer.out[i] * layer.alphas[i]))) - 1.0; SOFTMAX: layer.out[i] := exp(layer.out[i]) / softmaxdenom; SYMMETRICAL_SIGMOID: layer.out[i] := (1.0 - exp(-layer.out[i] * layer.alphas[i])) / (1.0 + exp(-layer.out[i] * layer.alphas[i])); THRESHOLD: if layer.out[i] > layer.alphas[i] then layer.out[i] := 1.0 else layer.out[i] := 0.0; LINEAR: layer.out[i] := layer.out[i] * layer.alpha[i]; end; result := layer.nodes; // Return the length of layer->out end;
unit uClasses; interface uses InvokeRegistry, Classes; type TCliente = class (TRemotable) private FId: integer; FNome: string; FCidade: string; FEndereco: string; FTelefone: string; FEstado: String; procedure SetCidade(const Value: string); procedure SetEndereco(const Value: string); procedure SetEstado(const Value: String); procedure SetId(const Value: integer); procedure SetNome(const Value: string); procedure SetTelefone(const Value: string); published property Id:integer read FId write SetId; property Nome:string read FNome write SetNome; property Cidade:string read FCidade write SetCidade; property Estado:String read FEstado write SetEstado; property Endereco:string read FEndereco write SetEndereco; property Telefone:string read FTelefone write SetTelefone; end; implementation uses uDM, SysUtils; { TCliente } procedure TCliente.SetCidade(const Value: string); begin FCidade := Value; end; procedure TCliente.SetEndereco(const Value: string); begin FEndereco := Value; end; procedure TCliente.SetEstado(const Value: String); begin FEstado := Value; end; procedure TCliente.SetId(const Value: integer); begin FId := Value; end; procedure TCliente.SetNome(const Value: string); begin FNome := Value; end; procedure TCliente.SetTelefone(const Value: string); begin FTelefone := Value; end; end.
unit Tokenizer; interface type TDynStrArray = array of string; TTokenizer = class private dsa: TDynStrArray; procedure Add(var Arr: TDynStrArray; Value: string); function Is1CharOp(S: string): Boolean; function Is2CharOp(S: string): Boolean; public function Tokenize(Str: string): TDynStrArray; function TokenizeFile(Filename: string): TDynStrArray; end; implementation uses SysUtils, Classes; procedure TTokenizer.Add(var Arr: TDynStrArray; Value: string); begin SetLength(Arr, Length(Arr) + 1); Arr[Length(Arr) - 1] := Value; end; function TTokenizer.Is1CharOp(S: string): Boolean; begin Result := Pos(S, '+-*/%<>:;()=,.[]') <> 0 end; function TTokenizer.Is2CharOp(S: string): Boolean; begin Result := Pos(S, ':=|<=|>=|<>') <> 0 end; function TTokenizer.Tokenize(Str: string): TDynStrArray; var Next2Chars: string[2]; InQuote: Boolean; i: Integer; Tks: TDynStrArray; LastTknPos: Integer; Tkn: string; begin i := 1; InQuote := False; while (Str <> '') do begin Next2Chars := Copy(Str, i, 2); if (Next2Chars = '//') then begin while ((i < Length(Str)) and (Next2Chars <> #13#10) and (Str[i] <> #13)) do begin Inc(i); Next2Chars := Copy(Str, i, 2); end; Delete(Str, 1, i); i := 0; end else if (Str[i] = '''') then begin Tkn := Trim(Copy(Str, 1, i - 1)); if (Tkn <> '') then Add(Tks, Tkn); Delete(Str, 1, i - 1); i := 2; Next2Chars := Copy(Str, i, 2); while (i < Length(Str)) do begin if (Str[i] = '''') and (Next2Chars <> '''''') then begin Break; end else begin Inc(i); Next2Chars := Copy(Str, i, 2); end; end; if (i < Length(Str)) then begin Tkn := Trim(Copy(Str, 1, i)); if (Tkn <> '') then Add(Tks, Tkn); Delete(Str, 1, i); InQuote := False; i := 0; end; end else if (Is2CharOp(Next2Chars)) then begin Tkn := Trim(Copy(Str, 1, i - 1)); if (Tkn <> '') then Add(Tks, Tkn); Add(Tks, Next2Chars); Delete(Str, 1, i + 1); i := 0; end else if (Is1CharOp(Str[i])) then begin Tkn := Trim(Copy(Str, 1, i - 1)); if (Tkn <> '') then Add(Tks, Tkn); Add(Tks, Str[i]); Delete(Str, 1, i); i := 0; end else if ((Str[i] = ' ') or (Next2Chars = #13#10) or (Str[i] = #13)) then begin Tkn := Trim(Copy(Str, 1, i - 1)); if (Tkn <> '') then Add(Tks, Tkn); if (Str[i] = ' ') then Delete(Str, 1, i) else Delete(Str, 1, i + 1); i := 0; end; Inc(i); if (i > Length(Str)) then begin Break; end; end; if (Str <> '') then Add(Tks, Str); Result := Tks; end; function TTokenizer.TokenizeFile(Filename: string): TDynStrArray; var List: TStringList; begin if (FileExists(Filename)) then begin List := TStringList.Create; try List.LoadFromFile(Filename); Result := Tokenize(List.Text); finally List.Free; end; end; end; end.
unit SystemAdministrationPrivilegeViewModel; interface uses SectionRecordViewModel, SysUtils, Classes; type TSystemAdministrationPrivilegeViewModel = class (TSectionRecordViewModel) private function GetPrivilegeId: Variant; function GetPrivilegeName: String; function GetTopLevelPrivilegeId: Variant; procedure SetPrivilegeId(const Value: Variant); procedure SetPrivilegeName(const Value: String); procedure SetTopLevelPrivilegeId(const Value: Variant); public property PrivilegeId: Variant read GetPrivilegeId write SetPrivilegeId; property TopLevelPrivilegeId: Variant read GetTopLevelPrivilegeId write SetTopLevelPrivilegeId; property PrivilegeName: String read GetPrivilegeName write SetPrivilegeName; end; TSystemAdministrationPrivilegeViewModelClass = class of TSystemAdministrationPrivilegeViewModel; implementation { TSystemAdministrationPrivilegeViewModel } function TSystemAdministrationPrivilegeViewModel.GetPrivilegeId: Variant; begin Result := Id; end; function TSystemAdministrationPrivilegeViewModel.GetPrivilegeName: String; begin Result := Name; end; function TSystemAdministrationPrivilegeViewModel.GetTopLevelPrivilegeId: Variant; begin Result := ParentId; end; procedure TSystemAdministrationPrivilegeViewModel.SetPrivilegeId( const Value: Variant); begin Id := Value; end; procedure TSystemAdministrationPrivilegeViewModel.SetPrivilegeName( const Value: String); begin Name := Value; end; procedure TSystemAdministrationPrivilegeViewModel.SetTopLevelPrivilegeId( const Value: Variant); begin ParentId := Value; end; end.
unit CidadeNFCe; interface type TCidade = class private FCodigoIBGE: Integer; FNome: String; FUF: String; private procedure SetCodigoIBGE(const Value: Integer); procedure SetNome(const Value: String); procedure SetUF(const Value: String); public property UF :String read FUF write SetUF; property CodigoIBGE :Integer read FCodigoIBGE write SetCodigoIBGE; property Nome :String read FNome write SetNome; end; implementation { TCidade } procedure TCidade.SetCodigoIBGE(const Value: Integer); begin FCodigoIBGE := Value; end; procedure TCidade.SetNome(const Value: String); begin FNome := Value; end; procedure TCidade.SetUF(const Value: String); begin FUF := Value; end; end.
unit gdipCheckBox; interface uses Windows, Messages; var ACBox : array of HWND; procedure CheckBoxDestroy; procedure CheckBoxSetText(h:HWND; Text:PChar); stdcall; procedure CheckBoxGetText(h: HWND; Text: PChar; var NewSize: integer); stdcall; function CheckBoxCreateFromRes(hParent:HWND; Left,Top,Width,Height:integer; Memory:Pointer; GroupID, TextIndent:integer):HWND; stdcall; function CheckBoxCreate(hParent:HWND; Left,Top,Width,Height:integer; FileName:PChar; GroupID, TextIndent:integer):HWND; stdcall; procedure CheckBoxSetFont(h:HWND; Font:HFONT); stdcall; procedure CheckBoxSetEvent(h:HWND; EventID:integer; Event:Pointer); stdcall; procedure CheckBoxSetFontColor(h:HWND; NormalFontColor, FocusedFontColor, PressedFontColor, DisabledFontColor: Cardinal); stdcall; function CheckBoxGetEnabled(h:HWND):boolean; stdcall; procedure CheckBoxSetEnabled(h:HWND; Value:boolean); stdcall; function CheckBoxGetVisibility(h:HWND):boolean; stdcall; procedure CheckBoxSetVisibility(h:HWND; Value:boolean); stdcall; procedure CheckBoxSetCursor(h:HWND; hCur:HICON); stdcall; procedure CheckBoxSetChecked(h:HWND; Value:boolean); stdcall; function CheckBoxGetChecked(h:HWND):boolean; stdcall; procedure CheckBoxRefresh(h:HWND); stdcall; procedure CheckBoxSetPosition(h:HWND; NewLeft, NewTop, NewWidth, NewHeight: integer); stdcall; procedure CheckBoxGetPosition(h:HWND; var Left, Top, Width, Height: integer); stdcall; implementation uses for_png, addfunc, gdipButton; procedure CheckBoxGroupChange(h:HWND); var cb, cb2:PCBox; i:integer; begin cb:=GetCheckBox(h); if cb=nil then Exit; for i:=Low(ACBox) to High(ACBox) do begin cb2:=GetCheckBox(ACBox[i]); if (cb2<>nil) and (cb<>cb2) and (cb^.GroupID=cb2^.GroupID) and IsCheckBoxState(cb2,bsChecked) then begin cb2^.bsState:=cb2^.bsState and not bsChecked; InvalidateRect(cb2.Handle,nil,False); UpdateWindow(cb2^.Handle); end; end; end; procedure CheckBoxGetPosition(h:HWND; var Left, Top, Width, Height: integer); stdcall; var cbtn:PCBox; begin cbtn:=GetCheckBox(h); if cbtn=nil then Exit; Left:=cbtn^.Left; Top:=cbtn^.Top; Width:=cbtn^.Width; Height:=cbtn^.Height; end; procedure CheckBoxSetPosition(h:HWND; NewLeft, NewTop, NewWidth, NewHeight: integer); stdcall; begin MoveWindow(h, NewLeft, NewTop, NewWidth, NewHeight, True); end; procedure CheckBoxRefresh(h:HWND); stdcall; begin BtnRefresh(h); end; function CheckBoxGetChecked(h:HWND):boolean; stdcall; var cbtn:PCBox; begin Result:=False; cbtn:=GetCheckBox(h); if cbtn=nil then Exit; Result:=IsCheckBoxState(cbtn,bsChecked); end; procedure CheckBoxSetChecked(h:HWND; Value:boolean); stdcall; var cbtn:PCBox; begin cbtn:=GetCheckBox(h); if cbtn=nil then Exit; if IsCheckBoxState(cbtn,bsChecked)<>Value then begin if Value then begin cbtn^.bsState:=cbtn^.bsState or bsChecked; if cbtn^.GroupID>0 then CheckBoxGroupChange(cbtn^.Handle); end else cbtn^.bsState:=cbtn^.bsState and not bsChecked; InvalidateRect(h,nil,False); end; end; procedure CheckBoxSetCursor(h:HWND; hCur:HICON); stdcall; var cbtn:PCBox; begin cbtn:=GetCheckBox(h); if (cbtn=nil) or (hCur=0) then Exit; DestroyCursor(cbtn^.Cursor); cbtn^.Cursor:=hCur; end; function CheckBoxGetVisibility(h:HWND):boolean; stdcall; var cbtn:PCBox; begin cbtn:=GetCheckBox(h); if cbtn=nil then begin Result:=False; Exit; end; Result:=cbtn^.Visible; end; procedure CheckBoxSetVisibility(h:HWND; Value:boolean); stdcall; var cbtn:PCBox; begin cbtn:=GetCheckBox(h); if cbtn=nil then Exit; if cbtn^.Visible<>Value then begin ShowWindow(h,integer(Value)); cbtn^.Visible:=Value; end; end; function CheckBoxGetEnabled(h:HWND):boolean; stdcall; begin Result := BtnGetEnabled(h); end; procedure CheckBoxSetEnabled(h:HWND; Value:boolean); stdcall; begin BtnSetEnabled(h, Value); end; procedure CheckBoxSetFontColor(h:HWND; NormalFontColor, FocusedFontColor, PressedFontColor, DisabledFontColor: Cardinal); stdcall; var cbtn:PCBox; begin cbtn:=GetCheckBox(h); if cbtn=nil then Exit; cbtn^.NormalFontColor:=NormalFontColor; cbtn^.DisabledFontColor:=DisabledFontColor; cbtn^.FocusedFontColor:=FocusedFontColor; cbtn^.PressedFontColor:=PressedFontColor; InvalidateRect(h,nil,False); end; procedure CheckBoxSetEvent(h:HWND; EventID:integer; Event:Pointer); stdcall; var btn:PCBox; begin btn:=GetCheckBox(h); if btn=nil then Exit; case EventID of BtnClickEventID : btn^.OnClick:=Event; BtnMouseEnterEventID : btn^.OnMouseEnter:=Event; BtnMouseLeaveEventID : btn^.OnMouseLeave:=Event; BtnMouseMoveEventID : btn^.OnMouseMove:=Event; BtnMouseDownEventID : btn^.OnMouseDown:=Event; BtnMouseUpEventID : btn^.OnMouseUp:=Event; end; end; procedure CheckBoxSetFont(h:HWND; Font:HFONT); stdcall; begin BtnSetFont(h, Font); end; procedure CheckBoxSetText(h:HWND; Text:PChar); stdcall; begin BtnSetText(h, Text); end; procedure CheckBoxGetText(h: HWND; Text: PChar; var NewSize: integer); stdcall; begin BtnGetText(h, Text, NewSize); end; procedure DrawCheckBox(hBtnDC:HDC; r:TRect; btn:PCBox; img:Pointer; FontColor:DWORD); var pGraphics:Pointer; ir,rw,r2:TRect; TextBtn:string; LenTextBtn:integer; BtnFont:HFONT; hParent:HWND; h:integer; iw,ih:UINT; hPDC,hDCMem:HDC; hBmp:HBITMAP; begin if img=nil then Exit; // рисуем фон hParent:=GetAncestor(btn^.Handle,GA_PARENT); GetClientRect(hParent,r2); hPDC:=GetDC(hParent); hDCMem:=CreateCompatibleDC(hPDC); hBmp:=CreateCompatibleBitmap(hPDC,r2.Right,r2.Bottom); SelectObject(hDCMem,hBmp); ReleaseDC(hParent,hPDC); SendMessage(hParent,WM_ERASEBKGND,Longint(hDCMem),0); CallWindowProc(Pointer(GetWindowLong(hParent,GWL_WNDPROC)),hParent,WM_PAINT,Longint(hDCMem),0); // рисуем кнопку pGraphics:=nil; GdipCreateFromHDC(hDCMem,pGraphics); GdipSetSmoothingMode(pGraphics, SmoothingModeHighSpeed{SmoothingModeAntiAlias}); GdipSetInterpolationMode(pGraphics, InterpolationModeHighQualityBilinear{InterpolationModeHighQualityBicubic}); GdipGetImageWidth(img,iw); GdipGetImageHeight(img,ih); ir.Left:=btn^.Left; ir.Top:=btn^.Top + (btn^.Height div 2) - (integer(ih) div 2); ir.Right:=iw; ir.Bottom:=ih; GdipDrawImageRectI(pGraphics,img,ir.Left,ir.Top,ir.Right,ir.Bottom); //GdipDrawImageRectI(pGraphics,img,btn^.Left,btn^.Top,btn^.Width,btn^.Height); GdipDeleteGraphics(pGraphics); //выводим текст LenTextBtn:=0; CheckBoxGetText(btn^.Handle, PChar(TextBtn), LenTextBtn); if LenTextBtn > 0 then begin SetLength(TextBtn, LenTextBtn); ZeroMemory(@TextBtn[1], LenTextBtn); BtnGetText(btn^.Handle, PChar(TextBtn), LenTextBtn); //SetRect(rw,btn^.Left+btn^.ShadowX+btn^.TextHorIndent,btn^.Top+btn^.ShadowY+btn^.TextVertIndent,btn^.Left+btn^.Width-btn^.ShadowX-btn^.TextHorIndent,btn^.Top+btn^.Height-btn^.ShadowY-btn^.TextVertIndent); SetRect(rw,btn^.Left+integer(iw)+btn^.TextIndent,btn^.Top,btn^.Left+btn^.Width,btn^.Top+btn^.Height); SetBkMode(hDCMem,TRANSPARENT); BtnFont:=SendMessage(btn^.Handle,WM_GETFONT,0,0); SelectObject(hDCMem,BtnFont); SetTextColor(hDCMem,FontColor); //GetTextColor(hBtnDC) //выравнивание по центру if (btn^.TextFormat and balVCenter)=balVCenter then begin CopyRect(r2,rw); h:=DrawText(hDCMem, PChar(TextBtn), LenTextBtn,r2,btn^.TextFormat or DT_CALCRECT); if h<(rw.Bottom-rw.Top) then begin h:=(rw.Bottom-rw.Top-h) div 2; rw.Top:=rw.Top+h; rw.Bottom:=rw.Bottom-h; end; end; //if IsCheckBoxState(btn,bsPressed) and IsCheckBoxState(btn,bsFocused) then OffsetRect(rw,1,0); DrawText(hDCMem, PChar(TextBtn), LenTextBtn,rw,btn^.TextFormat and not balVCenter); //DT_VCENTER не применяют вместе с DT_WORDBREAK end; BitBlt(hBtnDC,r.Left,r.Top,r.Right-r.Left,r.Bottom-r.Top,hDCMem,r.Left+btn^.Left,r.Top+btn^.Top,SRCCOPY); DeleteObject(hBmp); DeleteDC(hDCMem); end; function CheckBoxProc(hBtn: HWnd; Message: Cardinal; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; var hBtnDC : HDC; PBtnStr : paintstruct; Pt : TPoint; tme : tagTRACKMOUSEEVENT; OldState : Cardinal;//integer; // i : Cardinal; btn : PCBox; begin Result:=0; btn:=nil; if Message<>WM_UPDATE then begin btn:=GetCheckBox(hBtn); if btn=nil then //begin //Result:=CallWindowProc(Pointer(GetWindowLong(hBtn,GWL_WNDPROC)),hBtn, Message, wParam, lParam); Exit; //end; end; case Message of WM_UPDATE: begin InvalidateRect(hBtn,nil,False); UpdateWindow(hBtn); end; WM_NCPAINT:; WM_ERASEBKGND: Result:=1; WM_MOUSEMOVE: begin OldState:=btn^.bsState; GetCursorPos(Pt); //сначала перерисовываем, потом все остальное if not CursorInCheckBox(btn,Pt) then begin if not btn^.IsMouseLeave then btn^.bsState:=btn^.bsState and not bsFocused; end else btn^.bsState:=btn^.bsState or bsFocused; //это придется выполнять всегда, несмотря на IsMouseLeave if btn^.bsState<>OldState then begin InvalidateRect(hBtn,nil,False); UpdateWindow(hBtn); end; //теперь все остальное, а то при вызове callback'ов кнопка не успевает перерисоваться if CursorInCheckBox(btn,Pt) then begin if not btn^.bsNextBtnTrack then begin tme.cbSize:=SizeOf(tagTRACKMOUSEEVENT); tme.hwndTrack:=hBtn; tme.dwFlags:=TME_LEAVE; tme.dwHoverTime:=HOVER_DEFAULT; btn^.bsNextBtnTrack:=TrackMouseEvent(tme); btn^.IsMouseLeave:=False; if btn^.OnMouseEnter<>nil then TBtnEventProc(btn^.OnMouseEnter)(hBtn); end; if not btn^.IsMouseLeave then begin if btn^.OnMouseMove<>nil then TBtnEventProc(btn^.OnMouseMove)(hBtn); end; end else begin if not btn^.IsMouseLeave then if not IsCheckBoxState(btn,bsPressed) then begin btn^.IsMouseLeave:=True; btn^.bsNextBtnTrack:=False; if btn^.OnMouseLeave<>nil then TBtnEventProc(btn^.OnMouseLeave)(hBtn); end; end; end; WM_MOUSELEAVE: begin if not btn^.IsMouseLeave then begin OldState:=btn^.bsState; btn^.IsMouseLeave:=True; btn^.bsState:=btn^.bsState and not bsFocused;// and not bsPressed; //добавил and not bsPressed для трэкбара btn^.bsNextBtnTrack:=False; if btn^.bsState<>OldState then begin InvalidateRect(hBtn,nil,False); UpdateWindow(hBtn); end; if btn^.OnMouseLeave<>nil then TBtnEventProc(btn^.OnMouseLeave)(hBtn); end; end; WM_LBUTTONDOWN, WM_LBUTTONDBLCLK: begin if IsCheckBoxState(btn,bsEnabled) then begin GetCursorPos(Pt); if CursorInCheckBox(btn,Pt) then begin if GetCapture<>hBtn then SetCapture(hBtn); OldState:=btn^.bsState; btn^.bsState:=btn^.bsState or bsFocused or bsPressed; if btn^.bsState<>OldState then begin InvalidateRect(hBtn,nil,False); UpdateWindow(hBtn); end; if btn^.OnMouseDown<>nil then TBtnEventProc(btn^.OnMouseDown)(hBtn); end else Result:=SendMessage(GetAncestor(hBtn,GA_PARENT){GetParent(hBtn)},Message,wParam,lParam); end; end; WM_LBUTTONUP: begin if IsCheckBoxState(btn,bsEnabled) then begin ReleaseCapture; if IsCheckBoxState(btn,bsPressed) then begin OldState:=btn^.bsState; btn^.bsState:=btn^.bsState and not bsPressed; GetCursorPos(Pt); if CursorInCheckBox(btn,Pt) then begin // if btn^.IsCheckbox then begin if btn^.GroupID>0 then begin btn^.bsState:=btn^.bsState or bsChecked; CheckBoxGroupChange(hBtn); end else begin if IsCheckBoxState(btn,bsChecked) then btn^.bsState:=btn^.bsState and not bsChecked else btn^.bsState:=btn^.bsState or bsChecked; end; // end; end; if btn^.bsState<>OldState then begin InvalidateRect(hBtn,nil,False); UpdateWindow(hBtn); end; if CursorInCheckBox(btn,Pt) and (btn^.OnClick<>nil) then TBtnEventProc(btn^.OnClick)(hBtn); end; if btn^.OnMouseUp<>nil then TBtnEventProc(btn^.OnMouseUp)(hBtn); end; end; WM_ENABLE: begin OldState:=btn^.bsState; if boolean(wParam) then btn^.bsState:=btn^.bsState or bsEnabled else btn^.bsState:=0;; if btn^.bsState<>OldState then begin InvalidateRect(hBtn,nil,False); UpdateWindow(hBtn); end; Result:=CallWindowProc(Pointer(btn^.OldProc),hBtn, Message, wParam, lParam); end; WM_SETCURSOR: begin GetCursorPos(Pt); if CursorInCheckBox(btn,Pt) then SetCursor(btn^.Cursor) else Result:=SendMessage(GetAncestor(hBtn,GA_PARENT){GetParent(hBtn)},WM_SETCURSOR,GetAncestor(hBtn,GA_PARENT){GetParent(hBtn)},lParam); end; WM_WINDOWPOSCHANGING: begin if (PWindowPos(lParam)^.flags and SWP_NOSIZE = 0) or (PWindowPos(lParam)^.flags and SWP_NOMOVE = 0) then begin if PWindowPos(lParam)^.flags and SWP_NOSIZE = 0 then begin //if btn^.OrigShadowWidth<>0 then begin // GdipGetImageWidth(btn^.imgNormal,i); // btn^.ShadowX:=Round(btn^.OrigShadowWidth*(PWindowPos(lParam)^.cx/i)); // GdipGetImageHeight(btn^.imgNormal,i); // btn^.ShadowY:=Round(btn^.OrigShadowWidth*(PWindowPos(lParam)^.cy/i)); //end; btn^.Width:=PWindowPos(lParam)^.cx; btn^.Height:=PWindowPos(lParam)^.cy; end; if PWindowPos(lParam)^.flags and SWP_NOMOVE = 0 then begin btn^.Left:=PWindowPos(lParam)^.x; btn^.Top:=PWindowPos(lParam)^.y; end; PWindowPos(lParam)^.flags:=PWindowPos(lParam)^.flags or SWP_NOCOPYBITS; //PostMessage(hBtn,WM_UPDATE,0,0); end; end; WM_PAINT: begin //Рисуем на кнопке //if HDC(wParam)=0 then begin hBtnDC:=BeginPaint(hBtn,PBtnStr); if IsCheckBoxState(btn,bsEnabled) then begin if IsCheckBoxState(btn,bsPressed) and IsCheckBoxState(btn,bsFocused) then begin if IsCheckBoxState(btn,bsChecked) then DrawCheckBox(hBtnDC,PBtnStr.rcPaint,btn,btn^.imgChkPressed,btn^.PressedFontColor)//CheckPressed else DrawCheckBox(hBtnDC,PBtnStr.rcPaint,btn,btn^.imgPressed,btn^.PressedFontColor)//Pressed end else begin if not IsCheckBoxState(btn,bsPressed) and IsCheckBoxState(btn,bsFocused) then begin if IsCheckBoxState(btn,bsChecked) then DrawCheckBox(hBtnDC,PBtnStr.rcPaint,btn,btn^.imgChkFocused,btn^.FocusedFontColor)//CheckFocused else DrawCheckBox(hBtnDC,PBtnStr.rcPaint,btn,btn^.imgFocused,btn^.FocusedFontColor)//Focused end else begin if IsCheckBoxState(btn,bsChecked) then DrawCheckBox(hBtnDC,PBtnStr.rcPaint,btn,btn^.imgChkNormal,btn^.NormalFontColor)//CheckNormal else DrawCheckBox(hBtnDC,PBtnStr.rcPaint,btn,btn^.imgNormal,btn^.NormalFontColor)//Normal end; end; end else begin if IsCheckBoxState(btn,bsChecked) then DrawCheckBox(hBtnDC,PBtnStr.rcPaint,btn,btn^.imgChkDisabled,btn^.DisabledFontColor)//CheckDisabled else DrawCheckBox(hBtnDC,PBtnStr.rcPaint,btn,btn^.imgDisabled,btn^.DisabledFontColor)//Disabled end; EndPaint(hBtn,PBtnStr); //end; end; WM_DESTROY: begin DeleteCheckBox(btn); Result:=CallWindowProc(Pointer(GetWindowLong(hBtn,GWL_WNDPROC)),hBtn, Message, wParam, lParam); end; else Result:=CallWindowProc(Pointer(btn^.OldProc),hBtn, Message, wParam, lParam); end; end; function CheckBoxCreateFromRes(hParent:HWND; Left,Top,Width,Height:integer; Memory:Pointer; GroupID, TextIndent:integer):HWND; stdcall; begin Result:=0; end; function CheckBoxCreate(hParent:HWND; Left,Top,Width,Height:integer; FileName:PChar; GroupID, TextIndent:integer):HWND; stdcall; var len,j:integer; img,simg,g,g1:Pointer; ImgCount,iw,ih:Cardinal; // rect:TRect; // DC:HDC; cb:PCBox; begin Result:=0; if not gdipStart then Exit; try New(cb); except Exit; end; Result:=CreateWindow{Ex}({WS_EX_CONTROLPARENT,}'BUTTON','',WS_CHILD or WS_CLIPSIBLINGS or WS_TABSTOP or BS_OWNERDRAW or WS_VISIBLE,Left,Top,Width,Height,hParent,hInstance,0,nil); //BringWindowToTop(hBtn); if Result=0 then begin Dispose(cb); Exit; end; ZeroMemory(cb,SizeOf(TgdipCheckBox)); cb^.Handle:=Result; cb^.bsState:=bsEnabled; cb^.bsNextBtnTrack:=False; //*************************** img:=nil; CreateImage(img,FileName); GdipGetImageWidth(img,iw); GdipGetImageHeight(img,ih); ImgCount:=8; //8 состояний ih:=ih div ImgCount; g1:=nil; GdipGetImageGraphicsContext(img,g1); for j:=1 to ImgCount do begin simg:=nil; GdipCreateBitmapFromGraphics(iw,ih,g1,simg); g:=nil; GdipGetImageGraphicsContext(simg,g); GdipSetSmoothingMode(g,SmoothingModeAntiAlias); GdipSetInterpolationMode(g,InterpolationModeHighQualityBicubic); GdipDrawImageRectRectI(g,img,0,0,integer(iw),integer(ih),0,integer(ih)*(j-1),integer(iw),integer(ih),UnitPixel,nil,nil,nil); GdipDeleteGraphics(g); case j of 1: cb^.imgNormal:=simg; 2: cb^.imgFocused:=simg; 3: cb^.imgPressed:=simg; 4: cb^.imgDisabled:=simg; 5: cb^.imgChkNormal:=simg; 6: cb^.imgChkFocused:=simg; 7: cb^.imgChkPressed:=simg; 8: cb^.imgChkDisabled:=simg; end; end; GdipDisposeImage(img); GdipDeleteGraphics(g1); //*************************** //cb^.hDCMem:=CreateCompatibleDC(0); //GetClientRect(hParent,rect); //DC:=GetDC(hParent); //cb^.hBmp:=CreateCompatibleBitmap(DC,rect.Right,rect.Bottom); //ReleaseDC(hParent,DC); //cb^.hOld:=SelectObject(cb^.hDCMem,cb^.hBmp); cb^.Left:=Left; cb^.Top:=Top; cb^.Width:=Width; cb^.Height:=Height; cb^.OnClick:=nil; cb^.OnMouseEnter:=nil; cb^.OnMouseLeave:=nil; cb^.OnMouseMove:=nil; cb^.OnMouseDown:=nil; cb^.OnMouseUp:=nil; cb^.IsMouseLeave:=True; //cb^.OrigShadowWidth:=ShadowWidth; //SetShadowWidth(btn); cb^.Cursor:=GetSysCursorHandle(OCR_NORMAL); //btn^.IsCheckBox:=IsCheckBtn; cb^.NormalFontColor:=0; cb^.DisabledFontColor:=0; cb^.FocusedFontColor:=0; cb^.PressedFontColor:=0; cb^.TextFormat:=balLeft or balVCenter;// DefaultTextFormat or DT_CENTER or balVCenter;//DT_CENTER or DT_VCENTER or DT_SINGLELINE; //cb^.Text:='CheckBox'; cb^.TextIndent:=TextIndent; cb^.GroupID:=GroupID; //cb^.TextHorIndent:=0; //cb^.TextVertIndent:=0; cb^.Delete:=False; cb^.Visible:=True; //SendMessage(Result,WM_SETFONT,GetStockObject(DEFAULT_GUI_FONT),0); CheckBoxSetFont(Result,GetStockObject(DEFAULT_GUI_FONT)); cb^.OldProc:=SetWindowLong(Result,GWL_WNDPROC,LongInt(@CheckBoxProc)); SetWindowLong(Result,GWL_USERDATA,Longint(cb)); InvalidateRect(Result,nil,False); len:=Length(ACBox); SetLength(ACBox,len+1); ACBox[len]:=Result; end; procedure CheckBoxDestroy; var btn:PCBox; i:integer; begin for i:=Low(ACBox) to High(ACBox) do begin btn:=GetCheckBox(ACBox[i]); if btn<>nil then DeleteCheckBox(btn); end; SetLength(ACBox,0); 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.StdCtrls, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes, Androidapi.Helpers, FMX.Controls.Presentation; type // JString は Androidapi.JNI.JavaTypes に // JIntent は Androidapi.JNI.GraphicsContentViewText に // JStringToString は Androidapi.Helpers に // それぞれ定義されています TForm1 = class(TForm) btnRegister: TButton; procedure btnRegisterClick(Sender: TObject); private procedure Received(const iAction: JString); public end; var Form1: TForm1; implementation uses Android.BroadcastReceiver; {$R *.fmx} { TForm1 } procedure TForm1.btnRegisterClick(Sender: TObject); var TSL: TStrings; begin BroadcastReceiver.OnReceived := Received; // スクリーン ON / OFF を受け取るように設定 BroadcastReceiver.AddAction( [ TJIntent.JavaClass.ACTION_SCREEN_OFF, TJIntent.JavaClass.ACTION_SCREEN_ON ] ); end; procedure TForm1.Received(const iAction: JString); begin Log.d('Broadcast Received = ' + JStringToString(iAction)); end; end.
{============================================================================== Iris Model Editor - Copyright by Alexander Oster, tensor@ultima-iris.de The contents of this file are used with permission, 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/MPL-1.1.html 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 Unit_ViewPort; interface uses Unit_OpenGL, Controls, Graphics, Classes, Unit_OpenGLWrapper, Windows, Unit_Matrix, Unit_OpenGLGeometry; type TViewPortOrientation = (voCustom, voTop, voBottom, voLeft, voRight, voFront, voBack, voIso); TViewPort = class (TObject) private FLeft, FTop, FWidth, FHeight: Integer; FButton: Integer; OldX, OldY: Integer; FRotateMode: Integer; FStartWinkel: Single; FAllowRotation: Boolean; FMatrix: TMatrix4f; FProjectionMatrix: TMatrix4f; FUpdated: Boolean; FViewCenter: TVector3f; function GetUpdated: Boolean; public property Matrix: TMatrix4f read FMatrix; property Updated: Boolean read GetUpdated; property Left: Integer read FLeft write FLeft; property Top: Integer read FTop write FTop; property Width: Integer read FWidth write FWidth; property Height: Integer read FHeight write FHeight; property AllowRotation: Boolean read FAllowRotation write FAllowRotation; constructor Create(ALeft, ATop, AWidth, AHeight: Integer); procedure ResetView; procedure LoadView; procedure MouseDown (X, Y: Integer; Button: TMouseButton); procedure MouseUp; function MouseMove(X, Y: Integer; Shift: TShiftState): TCursor; procedure MouseWheel (Delta: Integer); procedure Apply (Engine: TGLEngine; WindowHeight: Integer); procedure SetOrientation (Orientation: TViewPortOrientation); procedure Resize (AWidth, AHeight: Integer); procedure SetPosition (ALeft, ATop: Integer); function TransformCoord (X, Y, Z: Single): TPoint; procedure Move(X, Y, Z: Single); function GetPickRay (X, Y: Integer): TMRay; function BerechneClickWinkel(X, Y: Single; CenterX, CenterY: Single): Single; procedure InitOrtho; procedure DoneOrtho; end; implementation function ApplyMatrix (Matrix: TMatrix4f; Vertex: TVector4f): TVector4f; var Index: Integer; begin For Index := 0 to 3 do result[Index] := Matrix[0, Index] * Vertex[0] + Matrix[1, Index] * Vertex[1] + Matrix[2, Index] * Vertex[2] + Matrix[3, Index] * Vertex[3]; end; constructor TViewPort.Create(ALeft, ATop, AWidth, AHeight: Integer); begin FLeft := ALeft; FTop := ATop; Resize(AWidth, AHeight); FAllowRotation := True; FViewCenter [0] := 0; FViewCenter [1] := 0; FViewCenter [2] := 5; ResetView (); end; procedure TViewPort.ResetView; begin glLoadIdentity(); glRotatef (- 90, 1, 0, 0); glScalef (- 1, 1, 1.0); glGetFloatv(GL_MODELVIEW_MATRIX, @FMatrix[0,0]); end; procedure TViewPort.LoadView; var AMatrix : TMatrix4f; begin AMatrix := FMatrix; AMatrix[3,0] := AMatrix[3,0] - FViewCenter[0]; AMatrix[3,1] := AMatrix[3,1] - FViewCenter[1]; AMatrix[3,2] := AMatrix[3,2] - FViewCenter[2]; glLoadMatrixf(@AMatrix[0]); end; procedure TViewPort.MouseDown (X, Y: Integer; Button: TMouseButton); begin dec (X, FLeft); dec (Y, FTop); if (X < 0) or (Y < 0) or (X >= FWidth) or (Y >= FHeight) then exit; if Button = mbLeft then FButton := 1 else FButton := 2; FRotateMode := 0; if (X < FWidth * 0.15) or (X > FWidth * 0.85) or (Y < FHeight *0.15) or (Y > FHeight *0.85) then begin FRotateMode := 1; FStartWinkel := BerechneClickWinkel(X, Y, FWidth / 2, FHeight / 2); end; end; procedure TViewPort.MouseUp; begin FButton := 0; end; function TViewPort.MouseMove(X, Y: Integer; Shift: TShiftState): TCursor; var Winkel: Single; isLeft, isRight, isTop, isBottom: Boolean; begin result := crNone; dec (X, FLeft); dec (Y, FTop); if (X < 0) or (Y < 0) or (X >= FWidth) or (Y >= FHeight) then exit; isLeft := X < FWidth * 0.15; isRight := X > FWidth * 0.85; isTop := Y < FHeight * 0.15; isBottom := Y > FHeight * 0.85; if (isLeft and isTop) or (isRight and isBottom) then result := crSizeNESW; if (isLeft and isBottom) or (isRight and isTop) then result := crSizeNWSE; if (isLeft or isRight) and not (isTop or isBottom) then result := crSizeNS; if (isTop or isBottom) and not (isLeft or isRight) then result := crSizeWE; if (ssCtrl in Shift) and (FButton <> 0) then begin Move (0, 0, (Y - OldY) * 0.1); end else begin if (FButton = 2) and FAllowRotation and (not ((ssCtrl in Shift) or (ssShift in Shift))) then begin if FRotateMode = 0 then begin glLoadIdentity; glRotatef((X - OldX), 0,1,0); glMultMatrixf(@FMatrix[0,0]); glGetFloatv(GL_MODELVIEW_MATRIX, @FMatrix[0,0]); glLoadIdentity; glRotatef((Y - OldY), 1,0,0); glMultMatrixf(@FMatrix[0,0]); glGetFloatv(GL_MODELVIEW_MATRIX, @FMatrix[0,0]); end else begin Winkel := BerechneClickWinkel(X, Y, FWidth / 2, FHeight / 2); if (Winkel <> FStartWinkel) then begin glLoadIdentity; glRotatef((FStartWinkel - Winkel) / PI * 180, 0,0,1); glMultMatrixf(@FMatrix[0,0]); glGetFloatv(GL_MODELVIEW_MATRIX, @FMatrix[0,0]); FStartWinkel := Winkel; end; end; end; if (FButton <> 0) and (ssShift in Shift) then begin Move ((OldX - X) * 0.02, (Y - OldY) * 0.02, 0); // glLoadIdentity; { if (FWidth <> 0) and (FHeight <> 0) then glTranslatef((X - OldX) / FWidth * SizeX, - (Y - OldY) / FHeight * SizeY, 0); } { glMultMatrixf(@FMatrix[0,0]); glGetFloatv(GL_MODELVIEW_MATRIX, @FMatrix[0,0]);} end; end; if FButton <> 0 then FUpdated := True; OldX := X; OldY := Y; end; procedure TViewPort.MouseWheel (Delta: Integer); begin Move (0, 0, Delta * 0.002); end; function TViewPort.BerechneClickWinkel(X, Y: Single; CenterX, CenterY: Single): Single; var dx, dy: Single; begin dx := X - CenterX; dy := Y - CenterY; if dx = 0 then dx := 0.01; result := arctan(dy / dx); if (dx < 0) and (dy > 0) then result := result + PI; if (dx < 0) and (dy < 0) then result := result - PI; end; function TViewPort.GetUpdated: Boolean; begin result := FUpdated; FUpdated := False; end; procedure TViewPort.Apply (Engine: TGLEngine; WindowHeight: Integer); begin Assert(Assigned(Engine)); Engine.SetViewPortPerspective(FLeft, WindowHeight - 1 - FTop - FHeight, FWidth, FHeight); glGetFloatv(GL_PROJECTION_MATRIX, @FProjectionMatrix[0]); end; procedure TViewPort.SetOrientation (Orientation: TViewPortOrientation); begin glPushMatrix (); glLoadIdentity (); case Orientation of voLeft: begin glRotatef(90, 0, 1, 0); glRotatef(- 90, 1, 0, 0); end; voRight: begin glRotatef(- 90, 0, 1, 0); glRotatef(- 90, 1, 0, 0); end; voFront: glRotatef(- 90, 1, 0, 0); voBack: begin glRotatef(- 90, 1, 0, 0); glRotatef(180, 0, 0, 1); end; voIso: begin glRotatef(- 60, 1, 0, 0); glRotatef(120, 0, 0, 1); end; voBottom: glRotatef(180, 1, 0, 0); end; glScalef(-1,1,1.0); glGetFloatv(GL_MODELVIEW_MATRIX, @FMatrix[0,0]); glPopMatrix (); end; procedure TViewPort.Resize (AWidth, AHeight: Integer); begin FWidth := AWidth; FHeight := AHeight; end; procedure TViewPort.SetPosition (ALeft, ATop: Integer); begin FLeft := ALeft; FTop := ATop; end; function TViewPort.TransformCoord (X, Y, Z: Single): TPoint; var vecTemp1, vecTemp2, vecTemp3: TVector4f; AMatrix : TMatrix4f; begin AMatrix := FMatrix; AMatrix[3,0] := AMatrix[3,0] - FViewCenter[0]; AMatrix[3,1] := AMatrix[3,1] - FViewCenter[1]; AMatrix[3,2] := AMatrix[3,2] - FViewCenter[2]; vecTemp1[0] := X; vecTemp1[1] := Y; vecTemp1[2] := Z; vecTemp1[3] := 1; vecTemp2 := ApplyMatrix(AMatrix, vecTemp1); vecTemp3 := ApplyMatrix(FProjectionMatrix, vecTemp2); if vecTemp3[3] = 0 then vecTemp3[3] := 0.00001; result.X := trunc((vecTemp3[0] / vecTemp3[3] + 1) * 0.5 * FWidth); result.Y := trunc((1 - vecTemp3[1] / vecTemp3[3]) * 0.5 * FHeight); end; procedure TViewPort.Move(X, Y, Z: Single); begin glLoadIdentity; FViewCenter[0] := FViewCenter[0] + X; FViewCenter[1] := FViewCenter[1] + Y; FViewCenter[2] := FViewCenter[2] + Z; if FViewCenter[2] < 1 then FViewCenter[2] := 1; // glTranslatef(X, Y, Z); // glMultMatrixf(@FMatrix[0,0]); // glGetFloatv(GL_MODELVIEW_MATRIX, @FMatrix[0,0]); end; function TViewPort.GetPickRay (X, Y: Integer): TMRay; var Matrix, InvMatrix: TMMatrix; vecTempOrigin, vecTempDir: TMVector; vecDir: TMVector; vecOrigin: TMVector; AMatrix : TMatrix4f; begin AMatrix := FMatrix; AMatrix[3,0] := AMatrix[3,0] - FViewCenter[0]; AMatrix[3,1] := AMatrix[3,1] - FViewCenter[1]; AMatrix[3,2] := AMatrix[3,2] - FViewCenter[2]; Matrix := TMMatrix.CreateFromGLMatrix(AMatrix); try InvMatrix := Matrix.Inverse; vecTempOrigin := TMVector.Create; vecTempDir := TMVector.Create(0,0,0); try vecTempDir[0] := ( ( ( 2.0 * (X - FLeft) ) / FWidth ) - 1 ) / FProjectionMatrix[0,0]; vecTempDir[1] := -( ( ( 2.0 * (Y - FTop) ) / FHeight ) - 1 ) / FProjectionMatrix[1,1]; vecTempDir[2] := -1.0; vecDir := InvMatrix.Apply (vecTempDir); vecOrigin := TMVector.Create(InvMatrix [0, 3], InvMatrix [1, 3], InvMatrix [2, 3]); vecDir.Subtract (vecOrigin); { vecTempOrigin[0] := ((X - FLeft) / FWidth - 0.5) * SizeX; vecTempOrigin[1] := (0.5 - (Y - FTop) / FHeight ) * SizeY; vecTempOrigin[2] := 0;} { vecTempDir.Add(vecTempOrigin); vecOrigin := InvMatrix.Apply(vecTempOrigin); vecDir := InvMatrix.Apply(vecTempDir); vecDir.Subtract(vecOrigin);} try vecDir.Normalize; result := TMRay.Create; result.Origin.Assign(vecOrigin); result.Dir.Assign(vecDir); finally vecDir.Free; vecOrigin.Free end; finally vecTempOrigin.Free; vecTempDir.Free; InvMatrix.Free; end; finally Matrix.Free; end; end; procedure TViewPort.InitOrtho; begin glMatrixMode(GL_MODELVIEW); glPushMatrix (); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix (); glLoadIdentity(); glOrtho(0, FWidth, FHeight, 0, NearClipping, FarClipping); glMatrixMode(GL_MODELVIEW); end; procedure TViewPort.DoneOrtho; begin glMatrixMode(GL_PROJECTION); glPopMatrix (); glMatrixMode(GL_MODELVIEW); glPopMatrix (); end; end.
{$I XLib.inc } Unit XForms; Interface Uses Classes, Controls, Forms, Messages, XMisc, Misc; Const fcDefaultClass ='fcDefault'; type { TXForm } TSysCommandEvent = procedure (var Message: TWMSysCommand) of object; TXFormClass = class of TXForm; TXForm = class(TForm) private { FXFormLink: TFormLink;} FFormControl: TXLibControl; FSysEvent: TSysCommandEvent; FOnClose: TCloseEvent; FOnCloseQuery: TCloseQueryEvent; function GetCaption: TCaption; procedure SetCaption(Const Value: TCaption); function IsStoredCaption: Boolean; procedure WMSysCommand(var Message: TWMSysCommand); message WM_SYSCOMMAND; procedure FormCreate(AControl: TComponent); procedure FormDestroy; procedure FormLinkSetName(Reader: TReader; Component: TComponent; var Name: string); procedure FormClose(var Action: TCloseAction); procedure SelfClose(Sender: TObject; var Action: TCloseAction); procedure FormCloseQuery(var CanClose: Boolean); procedure SelfCloseQuery(Sender: TObject; var CanClose: Boolean); procedure SetFormControl(Value: TXLibControl); protected { procedure CreateParams(VAR Params: TCreateParams); override;} procedure InsideFormLinkSetName(Component: TComponent; var Name: string);dynamic; procedure Activate; override; procedure Deactivate; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ReadState(Reader: TReader); override; function DefaultXControl: TWinControl; virtual; { property XFormLink: TFormLink read FXFormLink write FXFormLink;} property SysEvent: TSysCommandEvent read FSysEvent write FSysEvent; published property Caption: TCaption read GetCaption write SetCaption stored isStoredCaption; property FormControl: TXLibControl read FFormControl write SetFormControl; property OnClose: TCloseEvent read FOnClose write FOnClose; property OnCloseQuery: TCloseQueryEvent read FOnCloseQuery write FOnCloseQuery; end; { TXForm } Implementation Uses Dialogs, XTFC, EtvBor; { TXForm } Constructor TXForm.Create(AOwner: TComponent); var AControl: TComponent; begin if AOwner is TFormControl then begin AControl:=AOwner; AOwner:=Application{Nil}; end else AControl:=nil; {FormCreate(AControl);} Inherited Create(AOwner); FormCreate(AControl); end; Procedure TXForm.InsideFormLinkSetName(Component: TComponent; var Name: string); begin { if Name='FormLink' then begin XFormLink:=TFormLink(Component); end;} end; Procedure TXForm.FormLinkSetName(Reader: TReader; Component: TComponent; var Name: string); begin InsideFormLinkSetName(Component,Name); end; Procedure TXForm.ReadState(Reader: TReader); var SavSetName: TSetNameEvent; begin SavSetName:=Reader.OnSetName; Reader.OnSetName:=FormLinkSetName; inherited ReadState(Reader); Reader.OnSetName:=SavSetName; end; Destructor TXForm.Destroy; begin FormDestroy; Inherited Destroy; end; Procedure TXForm.SetFormControl(Value: TXLibControl); begin if Value<>FFormControl then begin FFormControl:=Value; if Value <> nil then begin TFormControl(Value).Form:=Self; Caption:=TFormControl(Value).Caption; Value.FreeNotification(Self); end; end; end; Function TXForm.GetCaption: TCaption; begin if Assigned(FFormControl) then Result:=TFormControl(FFormControl).Caption else Result:= Inherited Caption; end; Procedure TXForm.SetCaption(Const Value: TCaption); begin if Assigned(FFormControl) then TFormControl(FFormControl).Caption:=Value else Inherited Caption:=Value; end; Function TXForm.IsStoredCaption: Boolean; begin Result:=(Caption<>'') and (not Assigned(FFormControl)); end; Procedure TXForm.Notification(AComponent: TComponent; Operation: TOperation); begin (*** TEST!!! Writeln(FFFF,'TXForm.Notification #1 :',AComponent.Name); ***) Inherited Notification(AComponent, Operation); (*** TEST!!! Writeln(FFFF,'TXForm.Notification #2 :',AComponent.Name); ***) if (Operation = opRemove) and (AComponent is TFormControl) and (AComponent=FFormControl) then begin FFormControl:=nil; end; (*** TEST!!! Writeln(FFFF,'TXForm.Notification #3 :',AComponent.Name); ***) end; { procedure TLForm.CreateParams(VAR Params: TCreateParams); begin Inherited CreateParams(Params); Params.WndParent := GetDesktopWindow; end; } Procedure TXForm.WMSysCommand(var Message: TWMSysCommand); begin Inherited; if Assigned(FSysEvent) then FSysEvent(Message); end; Function TXForm.DefaultXControl: TWinControl; begin Result:=nil; end; Procedure TXForm.FormCreate(AControl: TComponent); var Priz: Boolean; begin Inherited OnClose:=SelfClose; Inherited OnCloseQuery:=SelfCloseQuery; Priz:=True; { if Assigned(XFormLink) then } begin if AControl=nil then begin { AControl:=XFormLink.LinkControl;} AControl:=FormControl; end; if Assigned(AControl) then with TFormControl(AControl) do begin try { if Not Assigned(FormLink) then begin FormLink:=Self.XFormLink; Self.XFormLink.LinkControl:=AControl; end else Priz:=False;} if Assigned(Form) then Priz:=False; except; ShowMessage('Error create XForm!'); raise; end; end; end; if Assigned(AControl) then with TFormControl(AControl) do begin if Priz then with FormRect do if Active then begin Left:=FormLeft; Top:=FormTop; Width:=FormWidth; Height:=FormHeight; end else AMScaleForm(Self, True); Form:=Self; FormControl:=TXLibControl(AControl); CreateLink; CreateForms; end; end; procedure TXForm.FormDestroy; begin { if Assigned(XFormLink) and Assigned(XFormLink.LinkControl) then TFormControl(XFormLink.LinkControl).DestroyForms;} if Assigned(FormControl) then TFormControl(FormControl).DestroyForms; { if Assigned(XFormLink) and Assigned(XFormLink.LinkControl) then TFormControl(XFormLink.LinkControl).Form:=Nil;} if Assigned(FormControl) then TFormControl(FormControl).Form:=nil; end; Procedure TXForm.FormClose(var Action: TCloseAction); begin { if Assigned(XFormLink) and Assigned(XFormLink.LinkControl) then TFormControl(XFormLink.LinkControl).CloseForm(Action);} if Assigned(FormControl) then TFormControl(FormControl).CloseForm(Action); end; Procedure TXForm.SelfClose(Sender: TObject; var Action: TCloseAction); begin FormClose(Action); if Assigned(FOnClose) then FOnClose(Self, Action); end; Procedure TXForm.FormCloseQuery(var CanClose: Boolean); begin { if Assigned(XFormLink) and Assigned(XFormLink.LinkControl) then TFormControl(XFormLink.LinkControl).CloseQueryForm(CanClose);} if Assigned(FormControl) then TFormControl(FormControl).CloseQueryForm(CanClose); end; Procedure TXForm.SelfCloseQuery(Sender: TObject; var CanClose: Boolean); begin FormCloseQuery(CanClose); if Assigned(FOnCloseQuery) then FOnCloseQuery(Self, CanClose); end; Procedure TXForm.Activate; begin { if Assigned(XFormLink) and Assigned(XFormLink.LinkControl) then TFormControl(XFormLink.LinkControl).ActivateForm;} if Assigned(FormControl) and not Application.Terminated then TFormControl(FormControl).ActivateForm; Inherited Activate; end; Procedure TXForm.Deactivate; begin Inherited Deactivate; { if Assigned(XFormLink) and Assigned(XFormLink.LinkControl) then TFormControl(XFormLink.LinkControl).DeactivateForm;} if Assigned(FormControl) then TFormControl(FormControl).DeactivateForm; end; Initialization RegisterClasses([TXForm]); end.
unit testofxreader; interface uses TestFramework, classes, SysUtils, ofxreader; type // Test methods for OFC file TestTOFCReader = class(TTestCase) strict private FOFCReader: TOFXReader; public procedure SetUp; override; procedure TearDown; override; published procedure TestImport; procedure TestBank; procedure TestBranch; procedure TestAccount; procedure TestAccountType; procedure TestFinalBalance; procedure TestMov0; procedure TestMov1; procedure TestMov4; end; type // Test methods for OFX file TestTOFXReader = class(TTestCase) strict private FOFXReader: TOFXReader; public procedure SetUp; override; procedure TearDown; override; published procedure TestImport; procedure TestBank; procedure TestBranch; procedure TestAccount; procedure TestAccountType; procedure TestFinalBalance; procedure TestMov0; procedure TestMov1; procedure TestMov4; end; implementation { TestTOFXReader } procedure TestTOFXReader.SetUp; var ReturnValue: Boolean; begin FOFXReader := TOFXReader.Create(nil); FOFXReader.ofxFile := 'extrato.ofx'; ReturnValue := FOFXReader.Import; CheckTrue(ReturnValue); end; procedure TestTOFXReader.TearDown; begin FOFXReader.Free; FOFXReader := nil; end; procedure TestTOFXReader.TestImport; begin CheckEquals(7, FOFXReader.Count); end; procedure TestTOFXReader.TestBank; begin CheckEquals('1', FOFXReader.BankID); end; procedure TestTOFXReader.TestBranch; begin CheckEquals('1234-1', FOFXReader.BranchID); end; procedure TestTOFXReader.TestAccount; begin CheckEquals('54321-9', FOFXReader.AccountID); end; procedure TestTOFXReader.TestAccountType; begin CheckEquals('CHECKING', FOFXReader.AccountType); end; procedure TestTOFXReader.TestFinalBalance; begin CheckEquals('-10.00', FOFXReader.FinalBalance); end; procedure TestTOFXReader.TestMov0; var i: Integer; begin for i := 0 to FOFXReader.Count-1 do begin case i of 0: begin CheckEquals('OTHER', FOFXReader.Get(i).MovType); CheckEquals('01/06/2016', DateToStr(FOFXReader.Get(i).MovDate)); CheckEquals('-10.00', FOFXReader.Get(i).Value); CheckEquals('2016060111650', FOFXReader.Get(i).ID); CheckEquals('000391100701', FOFXReader.Get(i).Document); CheckEquals('Cobrança de I.O.F.', FOFXReader.Get(i).Description); end; end; end; end; procedure TestTOFXReader.TestMov1; var i: Integer; begin for i := 0 to FOFXReader.Count-1 do begin case i of 1: begin CheckEquals('OTHER', FOFXReader.Get(i).MovType); CheckEquals('02/06/2016', DateToStr(FOFXReader.Get(i).MovDate)); CheckEquals('880.00', FOFXReader.Get(i).Value); CheckEquals('2016060202176000', FOFXReader.Get(i).ID); CheckEquals('000000121482', FOFXReader.Get(i).Document); CheckEquals('Recebimento de Proventos', FOFXReader.Get(i).Description); end; end; end; end; procedure TestTOFXReader.TestMov4; var i: Integer; begin for i := 0 to FOFXReader.Count-1 do begin case i of 4: begin CheckEquals('OTHER', FOFXReader.Get(i).MovType); CheckEquals('03/06/2016', DateToStr(FOFXReader.Get(i).MovDate)); CheckEquals('-200.00', FOFXReader.Get(i).Value); CheckEquals('20160603149980', FOFXReader.Get(i).ID); CheckEquals('000000141658', FOFXReader.Get(i).Document); CheckEquals('Compra com Cartão - 03/06 11:34 LOJAS X', FOFXReader.Get(i).Description); end; end; end; end; { TestTOFCReader } procedure TestTOFCReader.SetUp; var ReturnValue: Boolean; begin FOFCReader := TOFXReader.Create(nil); FOFCReader.ofxFile := 'extrato.ofc'; ReturnValue := FOFCReader.Import; CheckTrue(ReturnValue); end; procedure TestTOFCReader.TearDown; begin FOFCReader.Free; FOFCReader := nil; end; procedure TestTOFCReader.TestImport; begin CheckEquals(7, FOFCReader.Count); end; procedure TestTOFCReader.TestBank; begin CheckEquals('001', FOFCReader.BankID); end; procedure TestTOFCReader.TestBranch; begin CheckEquals('1234-13', FOFCReader.BranchID); end; procedure TestTOFCReader.TestAccount; begin CheckEquals('00000543219', FOFCReader.AccountID); end; procedure TestTOFCReader.TestAccountType; begin CheckEquals('0', FOFCReader.AccountType); end; procedure TestTOFCReader.TestFinalBalance; begin CheckEquals('-10.00', FOFCReader.FinalBalance); end; procedure TestTOFCReader.TestMov0; var i: Integer; begin for i := 0 to FOFCReader.Count-1 do begin case i of 0: begin CheckEquals('D', FOFCReader.Get(i).MovType); CheckEquals('01/06/2016', DateToStr(FOFCReader.Get(i).MovDate)); CheckEquals('-10.00', FOFCReader.Get(i).Value); CheckEquals('2016060111650', FOFCReader.Get(i).ID); CheckEquals('91100701', FOFCReader.Get(i).Document); CheckEquals('Cobrança de I.O.F.', FOFCReader.Get(i).Description); end; end; end; end; procedure TestTOFCReader.TestMov1; var i: Integer; begin for i := 0 to FOFCReader.Count-1 do begin case i of 1: begin CheckEquals('C', FOFCReader.Get(i).MovType); CheckEquals('02/06/2016', DateToStr(FOFCReader.Get(i).MovDate)); CheckEquals('880.00', FOFCReader.Get(i).Value); CheckEquals('2016060202176000', FOFCReader.Get(i).ID); CheckEquals('00121482', FOFCReader.Get(i).Document); CheckEquals('Recebimento de Proventos', FOFCReader.Get(i).Description); end; end; end; end; procedure TestTOFCReader.TestMov4; var i: Integer; begin for i := 0 to FOFCReader.Count-1 do begin case i of 4: begin CheckEquals('D', FOFCReader.Get(i).MovType); CheckEquals('03/06/2016', DateToStr(FOFCReader.Get(i).MovDate)); CheckEquals('-200.00', FOFCReader.Get(i).Value); CheckEquals('20160603149980', FOFCReader.Get(i).ID); CheckEquals('00141658', FOFCReader.Get(i).Document); CheckEquals('Compra com Cartão - 03/06 11:34 LOJAS X', FOFCReader.Get(i).Description); end; end; end; end; initialization RegisterTest(TestTOFXReader.Suite); RegisterTest(TestTOFCReader.Suite); end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2013 Embarcadero Technologies, Inc. } { } {*******************************************************} unit REST.HttpClient; interface uses System.SysUtils, System.Classes, System.Generics.Collections, IPPeerAPI; // Note that IPPeerClient must be used by the application in order to register // the actual IPPeerAPI Indy implementation type /// <summary> /// EHTTPProtocolException is an alias for EIPHTTPProtocolExceptionPeer, so that /// there is no need to use IPPeerClient just for getting access to that exception type. /// </summary> EHTTPProtocolException = EIPHTTPProtocolExceptionPeer; /// <summary> /// Provides HTTP client functionality /// </summary> TRESTHTTP = class(TObject) private FPeer: IIPHTTP; FIPImplementationID: string; FPeerProcs: IIPPeerProcs; function GetProtocol: string; function GetRequest: IIPHTTPRequest; function GetResponse: IIPHTTPResponse; function GetHTTPOptions: TIPHTTPOptionsPeer; procedure SetHTTPOptions(options: TIPHTTPOptionsPeer); function GetProxyParams: IIPProxyConnectionInfo; function GetResponseCode: Integer; function GetURL: IIPURI; function GetHandleRedirects: Boolean; procedure SetHandleRedirects(AValue: Boolean); function GetAllowCookies: Boolean; procedure SetAllowCookies(AValue: Boolean); function GetCookieManager: IIPCookieManager; procedure SetCookieManager(const Value: IIPCookieManager); procedure SetProtocol(const Value: string); function GetConnectTimeout: integer; procedure SetConnectTimeout(const Value: integer); function GetReadTimeout: integer; procedure SetReadTimeout(const Value: integer); public // Utilities class function CreateMultipartFormStream(const AIPImplementationID: string): IIPMultipartFormDataStream; overload; static; class function FixupURL(const AIPImplementationID: string; const AURL: string): string; overload; function CreateMultipartFormStream: IIPMultipartFormDataStream; overload; function FixupURL(const AURL: string): string; overload; function URLEncode(const AURL: string): string; function ParamsEncode(const AURL: string): string; function HashStringAsHex(const AValue: string): string; function HashHMACSHA1(const AData, AKey: string): string; function CreateBasicAuthenticationString(const AUserName, APassword: string): string; function UriFromString(AUriString: string): IIPURI; function ReadStringAsCharset(AStream: TStream; const ACharset: string): string; public constructor Create; reintroduce; overload; virtual; constructor Create(const AIPImplementationID: string); reintroduce; overload; virtual; destructor Destroy; override; function Delete(AURL: string): string; overload; function Delete(AURL: string; AResponseStream: TStream): string; overload; procedure Merge(AURL: string; RequestStream: TStream); procedure Head(AURL: string); /// <summary> /// PUT command with empty content. /// </summary> function Put(AURL: string): string; overload; function Put(AURL: string; ASource: TStream): string; overload; procedure Put(AURL: string; ASource, AResponseContent: TStream); overload; function Post(AURL: string; ASource: TStream): string; overload; procedure Post(AURL: string; ASource, AResponseContent: TStream); overload; function Get(AURL: string): string; overload; function Get(AURL: string; AResponseContent: TStream): string; overload; procedure Disconnect; procedure AddServerCookie(const ACookie: string; const AURL: string); property Protocol: string read GetProtocol write SetProtocol; property Request: IIPHTTPRequest read GetRequest; property Response: IIPHTTPResponse read GetResponse; property HTTPOptions: TIPHTTPOptionsPeer read GetHTTPOptions write SetHTTPOptions; property ProxyParams: IIPProxyConnectionInfo read GetProxyParams; property ResponseCode: Integer read GetResponseCode; property URL: IIPURI read GetURL; property Peer: IIPHTTP read FPeer; property IPImplementationID: string read FIPImplementationID; property HandleRedirects: Boolean read GetHandleRedirects write SetHandleRedirects; property AllowCookies: Boolean read GetAllowCookies write SetAllowCookies; property CookieManager: IIPCookieManager read GetCookieManager write SetCookieManager; property ConnectTimeout: integer read GetConnectTimeout write SetConnectTimeout; property ReadTimeout: integer read GetReadTimeout write SetReadTimeout; end; implementation {$IFDEF MACOS} uses Macapi.CoreFoundation; {$ENDIF} { TRESTHTTP } function TRESTHTTP.Delete(AURL: string): string; var LStream: TMemoryStream; begin LStream := TMemoryStream.Create; try FPeer.DoRequestDelete(AURL, nil, LStream, []); LStream.Position := 0; // This is here instead of a TStringStream for .net conversions? Result := IPProcs(IPImplementationID).ReadStringFromStream(LStream, -1); // , ContentTypeToEncoding(Response.ContentType)); finally FreeAndNil(LStream); end; end; constructor TRESTHTTP.Create; begin Create(''); end; procedure TRESTHTTP.AddServerCookie(const ACookie, AURL: string); begin FPeer.CookieManager.AddServerCookie(ACookie, AURL); end; constructor TRESTHTTP.Create(const AIPImplementationID: string); begin inherited Create; FIPImplementationID := AIPImplementationID; FPeer := PeerFactory.CreatePeer(AIPImplementationID, IIPHTTP, nil) as IIPHTTP; FPeerProcs := IPProcs(AIPImplementationID); HTTPOptions := Self.HTTPOptions - [hoForceEncodeParams]; Protocol := 'http'; //to have a default AllowCookies := true; end; function TRESTHTTP.CreateBasicAuthenticationString(const AUserName, APassword: string): string; var LAuthentication: IIPBasicAuthentication; begin LAuthentication := PeerFactory.CreatePeer(FIPImplementationID, IIPBasicAuthentication) as IIPBasicAuthentication; Assert(LAuthentication <> nil); if LAuthentication <> nil then begin LAuthentication.Password := APassword; LAuthentication.Username := AUserName; Result := LAuthentication.GetAuthentication; end; end; class function TRESTHTTP.CreateMultipartFormStream(const AIPImplementationID: string): IIPMultipartFormDataStream; begin Result := PeerFactory.CreatePeer(AIPImplementationID, IPPeerAPI.IIPMultipartFormDataStream) as IIPMultipartFormDataStream; end; function TRESTHTTP.CreateMultipartFormStream: IIPMultipartFormDataStream; begin Result := CreateMultipartFormStream(FIPImplementationID); end; function TRESTHTTP.Delete(AURL: string; AResponseStream: TStream): string; begin FPeer.DoRequestDelete(AURL, nil, AResponseStream, []); end; destructor TRESTHTTP.Destroy; begin // this is done internally : FPeer.IOHandler := nil; FPeer := nil; inherited; end; procedure TRESTHTTP.Disconnect; begin FPeer.Disconnect; end; function TRESTHTTP.FixupURL(const AURL: string): string; begin Result := TRESTHTTP.FixupURL(Self.IPImplementationID, AURL); end; /// <summary> /// Clean up/fix the given URL. Add a possibly missing protocol (http is default), remove trailing white spaces. /// Ensures no trailing slash exists. /// </summary> /// <example> /// <see href="http://www.example.com">www.example.com</see> -&gt; <see href="http://www.example.com/" /><br /> /// <see href="http://www.example.com/some/path">www.example.com/some/path</see> -&gt; /// <see href="http://www.example.com/some/path" /> /// </example> class function TRESTHTTP.FixupURL(const AIPImplementationID: string; const AURL: string): string; var LUri: IIPURI; begin if trim(AURL) = '' then Result := '' else begin LUri := PeerFactory.CreatePeer(AIPImplementationID, IPPeerAPI.IIPURI) as IIPURI; LUri.URI := AURL; if LUri.GetProtocol = '' then begin LUri.URI := 'http://' + AURL; end; Result := trim(LUri.GetFullURI); // we don't want a trailing slash! if Result.Chars[Length(Result)-1] = '/' then System.Delete(Result, Length(Result), 1); end; end; function TRESTHTTP.Get(AURL: string; AResponseContent: TStream): string; begin Result := FPeer.DoGet(AURL, AResponseContent); end; function TRESTHTTP.GetAllowCookies: Boolean; begin Result := FPeer.AllowCookies; end; function TRESTHTTP.GetConnectTimeout: integer; begin result := FPeer.ConnectTimeout; end; function TRESTHTTP.GetCookieManager: IIPCookieManager; begin Result := FPeer.CookieManager; end; function TRESTHTTP.Get(AURL: string): string; begin Result := FPeer.DoGet(AURL); end; function TRESTHTTP.GetHandleRedirects: Boolean; begin Result := FPeer.HandleRedirects; end; function TRESTHTTP.GetHTTPOptions: TIPHTTPOptionsPeer; begin Result := FPeer.HTTPOptions; end; function TRESTHTTP.GetProtocol: string; begin Result := FPeer.Protocol; end; function TRESTHTTP.GetProxyParams: IIPProxyConnectionInfo; begin Result := FPeer.ProxyParams; end; function TRESTHTTP.GetReadTimeout: integer; begin result := FPeer.ReadTimeout; end; function TRESTHTTP.GetRequest: IIPHTTPRequest; begin Result := FPeer.Request; end; function TRESTHTTP.GetResponse: IIPHTTPResponse; begin Result := FPeer.Response; end; function TRESTHTTP.GetResponseCode: Integer; begin Result := FPeer.ResponseCode; end; function TRESTHTTP.GetURL: IIPURI; begin Result := FPeer.URL; end; // class function TRESTHTTP.HasPeerCertificate: Boolean; // begin // Result := False; // end; function TRESTHTTP.HashHMACSHA1(const AData, AKey: string): string; begin Result := FPeerProcs.HashHMACSHA1(AData, AKey); end; function TRESTHTTP.HashStringAsHex(const AValue: string): string; var LMD5: IIPHashMessageDigest5; begin LMD5 := PeerFactory.CreatePeer(FIPImplementationID, IPPeerAPI.IIPHashMessageDigest5) as IIPHashMessageDigest5; Assert(LMD5 <> nil); if LMD5 <> nil then Result := LMD5.HashStringAsHex(AValue) end; procedure TRESTHTTP.Head(AURL: string); begin FPeer.DoRequestHead(AURL, nil, nil, []); end; procedure TRESTHTTP.Merge(AURL: string; RequestStream: TStream); begin FPeer.DoRequestMethod('MERGE', AURL, RequestStream, nil, []); end; function TRESTHTTP.Put(AURL: string): string; var emptyStream: TMemoryStream; begin emptyStream := TMemoryStream.Create; try Result := FPeer.DoPut(AURL, emptyStream); finally emptyStream.Free; end; end; // class procedure TRESTHTTP.RegisterProtocol(const AName: string; // AClass: TRESTHTTPClass); // begin // FProtocols.Add(LowerCase(AName), AClass); // end; // procedure TRESTHTTP.SetAuthentication(auth: IIPAuthentication); // begin // FAuthentication := auth; // FPeer.Request.Authentication := auth; // end; // // procedure TRESTHTTP.SetBasicAuthentication(const user, password: string); // begin // FAuthentication := PeerFactory.CreatePeer(FIPImplementationID, IIPBasicAuthentication) as IIPBasicAuthentication; // FAuthentication.Password := password; // FAuthentication.Username := user; // FPeer.Request.Authentication := FAuthentication; // end; procedure TRESTHTTP.SetAllowCookies(AValue: Boolean); begin FPeer.AllowCookies := AValue; end; procedure TRESTHTTP.SetConnectTimeout(const Value: integer); begin FPeer.ConnectTimeout := value; end; procedure TRESTHTTP.SetCookieManager(const Value: IIPCookieManager); begin // FPeer.CookieManager := Value; end; procedure TRESTHTTP.SetHandleRedirects(AValue: Boolean); begin FPeer.HandleRedirects := AValue; end; procedure TRESTHTTP.SetHTTPOptions(options: TIPHTTPOptionsPeer); begin FPeer.HTTPOptions := options; end; procedure TRESTHTTP.SetProtocol(const Value: string); var LProtocol: string; LIOHandler: IIPIOHandler; begin LProtocol := Value.ToLower.trim; if FPeer.Protocol <> LProtocol then begin // for now we only support http and https. Other protocols via a "Register Protocol" mechanism // might be implemented later if (LProtocol = 'http') or (LProtocol = 'https') then begin Disconnect; FPeer.Protocol := Value; if LProtocol = 'http' then begin // HTTP - Create a plain Socket IOHandler with no owner LIOHandler := PeerFactory.CreatePeer(IPImplementationID, IIPIOHandlerSocket, nil) as IIPIOHandlerSocket; end else begin // HTPPS - Create a TIdSSLIOHandlerSocketOpenSSL with no owner LIOHandler := PeerFactory.CreatePeer(IPImplementationID, IIPSSLIOHandlerSocketOpenSSL, nil) as IIPSSLIOHandlerSocketOpenSSL; // LIOHandler.OnVerifyPeer := IdValidateCertificate; // LIOHandler.SSLOptions.VerifyMode := [TIPSSLVerifyModePeer.sslvrfClientOnce]; end; FPeer.IOHandler := LIOHandler; end else raise EIPPeerException.Create('Unsupported Protocol!'); end; end; procedure TRESTHTTP.SetReadTimeout(const Value: integer); begin FPeer.ReadTimeout := Value; end; function TRESTHTTP.UriFromString(AUriString: string): IIPURI; begin Result := PeerFactory.CreatePeer(Self.FIPImplementationID, IPPeerAPI.IIPURI) as IIPURI; Result.URI := AUriString; end; function TRESTHTTP.URLEncode(const AURL: string): string; begin Result := FPeerProcs.URLEncode(AURL); end; function TRESTHTTP.ParamsEncode(const AURL: string): string; begin Result := FPeerProcs.ParamsEncode(AURL); end; // class procedure TRESTHTTP.UnregisterProtocol(const AName: string); // begin // if FProtocols <> nil then // FProtocols.Remove(LowerCase(AName)); // end; // // class function TRESTHTTP.RegisteredProtocolList: TArray<string>; // var // List: TArray<string>; // LName: string; // I: Integer; // begin // SetLength(List, FProtocols.Count); // I := 0; // for LName in FProtocols.Keys do // begin // List[I] := LName; // Inc(I); // end; // Result := List; // end; procedure TRESTHTTP.Post(AURL: string; ASource, AResponseContent: TStream); begin FPeer.DoPost(AURL, ASource, AResponseContent); end; function TRESTHTTP.Post(AURL: string; ASource: TStream): string; begin Result := FPeer.DoPost(AURL, ASource); end; // class function TRESTHTTP.ProtocolClass(const AName: string): TRESTHTTPClass; // begin // Result := FProtocols[LowerCase(AName)]; // end; procedure TRESTHTTP.Put(AURL: string; ASource, AResponseContent: TStream); begin FPeer.DoPut(AURL, ASource, AResponseContent); end; function TRESTHTTP.ReadStringAsCharset(AStream: TStream; const ACharset: string): string; begin Result := IPProcs(IPImplementationID).ReadStringAsCharset(AStream, ACharset); end; function TRESTHTTP.Put(AURL: string; ASource: TStream): string; begin Result := FPeer.DoPut(AURL, ASource); end; // function TRESTHTTPS.IdValidateCertificate(Certificate: IIPX509; AOk: Boolean; ADepth, AError: Integer): Boolean; // var // Cert: TX509Certificate; // begin // Result := true; // if Assigned(FOnValidateCertificate) then // begin // Cert := TX509CertificateIndy.Create(Certificate); // try // // prepare the TX509Ceritifcate and invoke user method // FOnValidateCertificate(self, Cert, ADepth, Result); // finally // Cert.Free; // end; // end; // end; end.
unit UContentView; interface uses Windows, SysUtils, Forms, Classes, Controls, Graphics, ExtCtrls, FileCtrl, Dialogs, ComCtrls, ShellAPI, Messages, ApiBmp, SPIs, SPIBmp, GIFImage, PNGImage, UMSPageControl, UAnimatedPaintBox, UCardinalList; type //スクロールホイールが効かず、ドラッグで動かせるスクロールバーが付いたパネル TDragScrollPanel = class(TPanel) protected MouseOrigine:TPoint; HBarOrigin:Integer; VBarOrigin:Integer; MousePrevious:TPoint; FScrollOpposite:Boolean; procedure CMMouseLeave(var Message: TMessage); message CM_MouseLeave; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);override; procedure MouseMove(Shift: TShiftState; X,Y: Integer);override; procedure ScrollBoxMouseMove(Sender: TObject; Shift: TShiftState; X,Y: Integer); public ScrollBox:TScrollBox; constructor Create(AOwner:TComponent);override; destructor Destroy;override; published property ScrollOpposite:Boolean read FScrollOpposite write FScrollOpposite; end; TContentViewCompleteEvent = procedure (Sender:TObject; Error :Boolean) of object; //イマイチ役に立たないインターフェイス方式を採用。 IContentView = Interface(IUnknown) procedure Action; procedure Hide; procedure Halt; procedure RequestCancel; procedure Highlight(Value:Boolean; FromOwnOriginTo:TPageControlDierction); procedure TerminateHighlight; procedure Scroll(const x,y:Integer); procedure AssignData(AData:TStringStream); function GetSmallBitmap:TBitmap; property SmallBitmap:TBitmap read GetSmallBitmap; function GetInfo:string; procedure SetInfo(AInfo:string); property Info:string read GetInfo write SetInfo; function GetProtect:boolean; procedure SetProtect(AProtect:boolean); property Protect:boolean read GetProtect write SetProtect; function GetScale:Integer; property Scale:Integer read GetScale; function GetOriginalSize:TPoint; property OriginalSize:TPoint read GetOriginalSize; function GetAdjustToWindow:Boolean; procedure SetAdjustToWindow(ASetAdjustToWindow:Boolean); property AdjustToWindow:Boolean read GetAdjustToWindow write SetAdjustToWindow; function GetOnComplete:TContentViewCompleteEvent; procedure SetOnComplete(AOnComplete:TContentViewCompleteEvent); property OnComplete:TContentViewCompleteEvent read GetOnComplete write SetOnComplete; function GetBitmap:TBitmap; property Bitmap:TBitmap read GetBitmap; function GetOnMouseDown:TMouseEvent; procedure SetOnMouseDown(AOnMouseDown:TMouseEvent); property OnMouseDown:TMouseEvent read GetOnMouseDown write SetOnMouseDown; function GetOnMouseUp:TMouseEvent; procedure SetOnMouseUp(AOnMouseUp:TMouseEvent); property OnMouseUp:TMouseEvent read GetOnMouseUp write SetOnMouseUp; function GetOnEdge:TPageControlOnEdgeEvent; procedure SetOnEdge(Value: TPageControlOnEdgeEvent); property OnEdge:TPageControlOnEdgeEvent read GetOnEdge write SetOnEdge; function GetOnSelectionTerminate:TNotifyEvent; procedure SetOnSelectionTerminate(Value: TNotifyEvent); property OnSelectionTerminate:TNotifyEvent read GetOnSelectionTerminate write SetOnSelectionTerminate; function GetOnContentClose:TNotifyEvent; procedure SetOnContentClose(Value: TNotifyEvent); property OnContentClose:TNotifyEvent read GetOnContentClose write SetOnContentClose; end; //画像表示の基本クラス //JpegViewとImageViewが統一されて現在は基本クラスの意味なし。 TCustomImageView = class(TInterfacedObject,IContentView) protected FOwner:TWinControl; FInfo:string; FSmallBitmap:TBitmap; FData:TStringStream; Bitmap:TBitmap; Mosaic:TBitmap; // FImageList:TBitmapList; // FDelayTimeList:TCardinalList; // FLoopLimit:Integer; FAnimateImage: TImage; FGifImage: TGifImage; Panel:TDragScrollPanel; PaintBox:TAnimatedPaintBox; FProtect:Boolean; FAdjustToWindow:Boolean; FOnComplete:TcontentviewcompleteEvent; FOnEdge:TPageControlOnEdgeEvent; FOnSelectionTerminate:TNotifyEvent; FOnContentClose:TNotifyEvent; function GetInfo:string; procedure SetInfo(AInfo:string); function GetProtect:boolean; procedure SetProtect(AProtect: Boolean); virtual; function GetOriginalSize:TPoint; function GetScale:Integer; procedure MakeSmallImage; function GetOnComplete:TContentViewCompleteEvent; procedure SetOnComplete(AOnComplete:TContentViewCompleteEvent); function GetAdjustToWindow:Boolean; procedure SetAdjustToWindow(AAdjustToWindow:Boolean); function GetOnMouseDown:TMouseEvent; procedure SetOnMouseDown(AOnMouseDown:TMouseEvent); function GetOnMouseUp:TMouseEvent; procedure SetOnMouseUp(AOnMouseUp:TMouseEvent); function GetOnEdge:TPageControlOnEdgeEvent; procedure SetOnEdge(Value: TPageControlOnEdgeEvent); function GetOnSelectionTerminate:TNotifyEvent; procedure SetOnSelectionTerminate(Value: TNotifyEvent); function GetOnContentClose:TNotifyEvent; procedure SetOnContentClose(Value: TNotifyEvent); public constructor Create(AOwner:TWinControl); destructor Destroy; override; procedure Action;virtual; procedure Hide;virtual; procedure Halt;virtual; procedure RequestCancel;virtual; procedure Highlight(Value:Boolean; FromOwnOriginTo:TPageControlDierction);virtual; procedure TerminateHighlight;virtual; procedure Scroll(const x,y:Integer);virtual; procedure AssignData(AData:TStringStream);virtual;abstract; function GetSmallBitmap:TBitmap; function GetBitmap:TBitmap; property SmallBitmap:TBitmap read GetSmallBitmap; property Protect:boolean read GetProtect write SetProtect; property OnMouseDown:TMouseEvent read GetOnMouseDown write SetOnMouseDown; property OnEdge:TPageControlOnEdgeEvent read GetOnEdge write SetOnEdge; end; //現在使用する唯一のCustomImageVew継承クラス TImageView = class(TCustomImageView) private // GifData:TGifData; // procedure GifDataOnComplete(Sender:TObject); public destructor Destroy;override; procedure Action;override; procedure Halt;override; procedure AssignData(AData:TStringStream);override; end; implementation uses UImageViewer, UImageViewConfig, Main; { TDragScrollPanel } constructor TDragScrollPanel.Create(AOwner: TComponent); begin inherited; ScrollBox:=TScrollBox.Create(AOwner); ScrollBox.Parent:=Self; ScrollBox.Align:=alClient; ScrollBox.DoubleBuffered:=True; ScrollBox.OnMouseMove:=Self.ScrollBoxMouseMove; ScrollBox.BorderStyle:=bsNone; ScrollBox.Color:=clWhite; ScrollBox.VertScrollBar.Tracking:=True; ScrollBox.VertScrollBar.Size:=14; ScrollBox.HorzScrollBar.Tracking:=True; ScrollBox.HorzScrollBar.Size:=14; ScrollBox.Enabled := False; end; destructor TDragScrollPanel.Destroy; begin ScrollBox.Free; inherited; end; procedure TDragScrollPanel.CMMouseLeave(var Message: TMessage); begin ScrollBox.Enabled:=False; inherited; end; procedure TDragScrollPanel.MouseMove(Shift: TShiftState; X, Y: Integer); var Point:TPoint; begin if ssLeft in Shift then begin if (MousePrevious.x<>Mouse.CursorPos.x) or (MousePrevious.y<>Mouse.CursorPos.y) then begin if ImageViewConfig.ScrollOpposite then begin ScrollBox.HorzScrollBar.Position:=HBarOrigin + (Mouse.CursorPos.x - MouseOrigine.x)*ScrollBox.HorzScrollBar.Range div ScrollBox.ClientWidth; ScrollBox.VertScrollBar.Position:=VBarOrigin + (Mouse.CursorPos.y - MouseOrigine.y)*ScrollBox.VertScrollBar.Range div ScrollBox.ClientHeight; end else begin ScrollBox.HorzScrollBar.Position:=HBarOrigin - (Mouse.CursorPos.x - MouseOrigine.x); ScrollBox.VertScrollBar.Position:=VBarOrigin - (Mouse.CursorPos.y - MouseOrigine.y); end; MousePrevious:=Mouse.CursorPos; end; end else begin Point := ScrollBox.ScreenToClient(Mouse.CursorPos); if PtInRect(ScrollBox.ClientRect,Point) then ScrollBox.enabled:=False else if PtInRect(ScrollBox.BoundsRect,Point) then ScrollBox.enabled:=True else ScrollBox.enabled:=False; end; end; procedure TDragScrollPanel.ScrollBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin MouseMove(Shift,X,Y); end; procedure TDragScrollPanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button=mbLeft) and ((ScrollBox.VertScrollBar.Range>ScrollBox.ClientHeight) or (ScrollBox.HorzScrollBar.Range>ScrollBox.ClientWidth)) then begin MouseOrigine:=Mouse.CursorPos; HBarOrigin:=ScrollBox.HorzScrollBar.Position; VBarOrigin:=ScrollBox.VertScrollBar.Position; Screen.Cursor:=crSizeAll; end; inherited; end; procedure TDragScrollPanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Screen.Cursor:=crDefault; inherited; end; { TCustomImageView } //生成 constructor TCustomImageView.Create(AOwner:TWinControl); begin inherited Create; FOwner:=AOwner; FAdjustToWindow:=ImageViewConfig.AdjustToWindow; Panel:=TDragScrollPanel.Create(AOwner); Panel.Parent:=AOwner; Panel.align:=alClient; Panel.BorderStyle:=bsNone; Panel.ScrollBox.Color:=clWhite; end; //破棄 destructor TCustomImageView.Destroy; begin Mosaic.Free; if Assigned(PaintBox) then begin PaintBox.Hide; PaintBox.Free; end; FGifImage.Free; if Assigned(FAnimateImage) then begin FAnimateImage.Free; end; Panel.Free; FSmallBitmap.Free; Bitmap.Free; // FImageList.Free; // FDelayTimeList.Free; inherited Destroy; end; //画像のスクロール procedure TCustomImageView.Scroll(const x,y:Integer); begin with panel.ScrollBox do begin if x>0 then HorzScrollBar.Position:=HorzScrollBar.Position+(ClientWidth div 5); if x<0 then HorzScrollBar.Position:=HorzScrollBar.Position-(ClientWidth div 5); if y>0 then VertScrollBar.Position:=VertScrollBar.Position+(ClientHeight div 5); if y<0 then VertScrollBar.Position:=VertScrollBar.Position-(ClientHeight div 5); end; end; //画像を表示/隠す/止める(上位クラスで使用) procedure TCustomImageView.Action; begin ; end; procedure TCustomImageView.Hide; begin ; end; procedure TCustomImageView.Halt; begin ; end; procedure TCustomImageView.Highlight; begin ; end; procedure TCustomImageView.TerminateHighlight; begin ; end; //プロパティ関係 function TCustomImageView.GetSmallBitmap:TBitmap; begin Result:=FSmallBitmap; end; function TCustomImageView.GetBitmap:TBitmap; begin if Protect and Assigned(Mosaic) then Result:=Mosaic else Result:=Bitmap; end; function TCustomImageView.GetInfo:string; begin Result:=FInfo; end; procedure TCustomImageView.SetInfo(AInfo:string); begin FInfo:=AInfo; end; function TCustomImageView.GetOnComplete:TContentViewCompleteEvent; begin Result:=FOnComplete; end; procedure TCustomImageView.SetOnComplete(AOnComplete:TContentViewCompleteEvent); begin FOnComplete:=AOnComplete; end; function TCustomImageView.GetAdjustToWindow:Boolean; begin Result:=FAdjustToWindow; end; function TCustomImageView.GetOnEdge:TPageControlOnEdgeEvent; begin Result:=FOnEdge; end; procedure TCustomImageView.SetOnEdge(Value: TPageControlOnEdgeEvent); begin FOnEdge:=Value; end; function TCustomImageView.GetOnSelectionTerminate:TNotifyEvent; begin Result:=FOnSelectionTerminate; end; procedure TCustomImageView.SetOnSelectionTerminate(Value: TNotifyEvent); begin FOnSelectionTerminate:=Value; end; function TCustomImageView.GetOnContentClose:TNotifyEvent; begin Result:=FOnContentClose; end; procedure TCustomImageView.SetOnContentClose(Value: TNotifyEvent); begin FOnContentClose:=Value; end; procedure TCustomImageView.SetAdjustToWindow(AAdjustToWindow:Boolean); begin FAdjustToWindow:=AAdjustToWindow; if Assigned(PaintBox) then if FAdjustToWindow then begin PaintBox.Adjust:=ajBitmapResize; PaintBox.Align:=alClient; end else begin PaintBox.Align:=alNone; PaintBox.Adjust:=ajFieldResize; end else if Assigned(FAnimateImage) then if FAdjustToWindow then begin FAnimateImage.Align := alClient; FAnimateImage.Center := True; FAnimateImage.Proportional := True; end else begin FAnimateImage.Align := alNone; FAnimateImage.SetBounds(0, 0, FAnimateImage.Picture.Graphic.Width, FAnimateImage.Picture.Graphic.Height); FAnimateImage.Center := False; FAnimateImage.Proportional := False; end; end; function TCustomImageView.GetOriginalSize:TPoint; begin Result.X:=0; Result.Y:=0; if Assigned(Bitmap) then begin Result.X:=Bitmap.Width; Result.Y:=Bitmap.Height; end; end; function TCustomImageView.GetScale:Integer; begin Result:=100; if Assigned(PaintBox) then Result:=PaintBox.Scale else if Assigned(FAnimateImage) then begin if FAdjustToWindow then begin Result := FAnimateImage.Width * 100 div FAnimateImage.Picture.Width; if Result > 100 then begin Result := FAnimateImage.Height * 100 div FAnimateImage.Picture.Height; if Result > 100 then Result := 100; end; end; end; end; function TCustomImageView.GetOnMouseDown:TMouseEvent; begin Result:=Panel.OnMouseDown; end; procedure TCustomImageView.SetOnMouseDown(AOnMouseDown:TMouseEvent); begin if Assigned(Panel) then Panel.OnMouseDown:=AOnMouseDown; if Assigned(PaintBox) then PaintBox.OnMouseDown:=AOnMouseDown;//一応 end; function TCustomImageView.GetOnMouseUp:TMouseEvent; begin Result:=Panel.OnMouseUp; end; procedure TCustomImageView.SetOnMouseUp(AOnMouseUp:TMouseEvent); begin if Assigned(Panel) then Panel.OnMouseUp:=AOnMouseUp; if Assigned(PaintBox) then PaintBox.OnMouseUp:=AOnMouseUp;//一応 end; //画像表示(モザイク処理など) function TCustomImageView.GetProtect:Boolean; begin Result:=FProtect; end; procedure TCustomImageView.SetProtect(AProtect:boolean); var tmpImage:TBitmap; begin FProtect:=AProtect; if not(Assigned(Bitmap)) or not(Assigned(Bitmap)) then Exit; FreeAndNil(Mosaic); if FProtect then begin tmpImage:=TBitmap.Create; tmpImage.Width:=Bitmap.Width div ImageViewConfig.ProtectMosaicSize; tmpImage.Height:=Bitmap.Height div ImageViewConfig.ProtectMosaicSize; if ImageViewConfig.ShrinkType=stHighQuality then begin SetStretchBltMode(tmpImage.Canvas.Handle,HALFTONE); SetBrushOrgEx(tmpImage.Canvas.Handle, 0, 0, nil); end else begin SetStretchBltMode(tmpImage.Canvas.Handle,COLORONCOLOR); end; tmpImage.Canvas.CopyRect(Rect(0,0,tmpImage.Width,tmpImage.Height), Bitmap.Canvas,Rect(0,0,Bitmap.Width,Bitmap.Height)); Mosaic:=TBitmap.Create; Mosaic.Width:=Bitmap.Width; Mosaic.Height:=Bitmap.Height; SetStretchBltMode(Mosaic.Canvas.Handle,COLORONCOLOR); Mosaic.Canvas.CopyRect(Rect(0,0,Mosaic.Width,Mosaic.Height), tmpImage.Canvas,Rect(0,0,tmpImage.Width,tmpImage.Height)); if Assigned(PaintBox) then PaintBox.Bitmap:=Mosaic else if Assigned(FAnimateImage) then FAnimateImage.Picture.Graphic := Mosaic; tmpImage.Free; end else begin if Assigned(FAnimateImage) then begin FAnimateImage.Picture.Graphic := FGifImage; Action; end else TAnimatedPaintBox(PaintBox).Bitmap:=Bitmap; end; end; //縮小アイコンの作成(タブとモザイクで使用) procedure TCustomImageView.MakeSmallImage; var SmallImageWidth,SmallImageHeight:Integer; begin if not Assigned(Bitmap) or (Bitmap.Width<=0) or (Bitmap.Height<=0) then Exit; if (BitMap.Height * ImageTabWidth) > (BitMap.Width*ImageTabHeight) then begin SmallImageWidth:=(ImageTabHeight*BitMap.Width) div BitMap.Height; SmallImageHeight:=ImageTabHeight; end else begin SmallImageWidth:=ImageTabWidth; SmallImageHeight:=(ImageTabWidth*BitMap.Height) div BitMap.Width; end; FSmallBitmap:=TBitmap.Create; FSmallBitmap.Width:=SmallImageWidth; FSmallBitmap.Height:=SmallImageHeight; if ImageViewConfig.ShrinkType=stHighQuality then begin SetStretchBltMode(FSmallBitmap.Canvas.Handle,HALFTONE); SetBrushOrgEx(FSmallBitmap.Canvas.Handle, 0, 0, nil); end else begin SetStretchBltMode(FSmallBitmap.Canvas.Handle,COLORONCOLOR); end; FSmallBitmap.Canvas.CopyRect(Rect(0,0,SmallImageWidth,SmallImageHeight), BitMap.Canvas,Rect(0,0,BitMap.Width,BitMap.Height)); end; //時間がかかるタスクの途中でキャンセルのリクエスト procedure TCustomImageView.RequestCancel; begin ; end; { TImageView } destructor TImageView.Destroy; begin // GifData.Free; inherited; end; const PngHeader: Array[0..7] of Char = (#137, 'P', 'N', 'G', #13, #10, #26, #10); //データの取り込み、必要に応じてデコードスレッド起動 procedure TImageView.AssignData(AData:TStringStream); var ImageConv: TGraphic; HeaderPointer: PChar; DummyBMP: TBitmap; begin if AData.Size = 0 then begin Log('Null Data'); if Assigned(FOnComplete) then FOnComplete(Self, True); Exit; end; FData := AData; if not Assigned(PaintBox) then begin PaintBox:=TAnimatedPaintBox.Create(Panel.ScrollBox); PaintBox.Bitmap:=nil; PaintBox.Parent:=Panel.ScrollBox; PaintBox.Enabled:=False; PaintBox.Align:=alClient; TAnimatedPaintBox(PaintBox).ShrinkType:=ImageViewConfig.ShrinkType; SetAdjustToWindow(FAdjustToWindow); end; if SeekSkipMacBin(FData) then HeaderPointer := Pchar(FData.Datastring) + 128 else HeaderPointer := Pchar(FData.Datastring); if not Assigned(Bitmap) then Bitmap:=TBitmap.Create; ImageConv := nil; if (StrLComp(HeaderPointer,'GIF', 3) = 0) then begin FGifImage := TGifImage.Create; DummyBMP := TBitmap.Create; try FGifImage.LoadFromStream(FData); DummyBMP.Width := FGifImage.Width; DummyBMP.Height := FGifImage.Height; DummyBMP.Canvas.Draw(0, 0, FGifImage); Bitmap.Assign(DummyBMP); MakeSmallImage; if (FGifImage.Images.Count = 1) then begin SetProtect(FProtect); if Assigned(FOnComplete) then FOnComplete(Self, False); end else begin if Assigned(PaintBox) then FreeAndNil(PaintBox); if not Assigned(FAnimateImage) then begin FAnimateImage := TImage.Create(Panel.ScrollBox); FAnimateImage.Parent := Panel.ScrollBox; FAnimateImage.Align := alClient; end; SetProtect(FProtect); SetAdjustToWindow(FAdjustToWindow); if Assigned(FOnComplete) then FOnComplete(Self,False); end; except on e:Exception do begin Log(e.Message); if Assigned(PaintBox) then PaintBox.Bitmap:=nil; FreeAndNil(Bitmap);//エラーの時はビットマップを解放 FreeAndNil(FGifImage); if Assigned(FOnComplete) then FOnComplete(Self, True); end; end; FreeAndNil(DummyBMP); (* pngの展開にPNGImageを使う (aiai) *) end else if (StrLComp(HeaderPointer, PngHeader, 8) = 0) then begin ImageConv := TPNGObject.Create; DummyBMP := TBitmap.Create; try try ImageConv.LoadFromStream(FData); DummyBMP.Width := TPNGObject(ImageConv).Width; DummyBMP.Height := TPNGObject(ImageConv).Height; DummyBMP.Canvas.Draw(0, 0, TPNGObject(ImageConv)); Bitmap.Assign(DummyBMP); MakeSmallImage; SetProtect(FProtect); if Assigned(FOnComplete) then FOnComplete(Self, False); finally FreeAndNil(ImageConv); FreeAndNil(DummyBMP); end; except on e:Exception do begin Log(e.Message); PaintBox.Bitmap:=nil; FreeAndNil(Bitmap);//エラーの時はビットマップを解放 if Assigned(FOnComplete) then FOnComplete(Self, True); end; end; end else begin if (StrLComp(HeaderPointer, #$FF#$D8#$FF#$E0#$00#$10'JFIF', 10) = 0) or (StrLComp(HeaderPointer, #$FF#$D8#$FF#$E1, 4) = 0) then ImageConv := TApiBitmap.Create else ImageConv:=TSPIBitmap.Create; try try ImageConv.LoadFromStream(FData); Bitmap.Assign(ImageConv); MakeSmallImage; SetProtect(FProtect); if Assigned(FOnComplete) then FOnComplete(Self, False); finally FreeAndNil(ImageConv); end; except on e:Exception do begin Log(e.Message); PaintBox.Bitmap:=nil; FreeAndNil(Bitmap);//エラーの時はビットマップを解放 if Assigned(FOnComplete) then FOnComplete(Self, True); end; end; end; end; //GIFデータのデコード処理完了 //procedure TImageView.GifDataOnComplete(Sender:TObject); {var i: Integer; MaxDelay: Cardinal;} //begin {if GifData.ErrorText<>'' then begin FreeAndNil(FImageList); FreeAndNil(FDelayTimeList); Bitmap:=nil; Log(GifData.ErrorText); if Assigned(FOnComplete) then FOnComplete(Self,True); end else begin FLoopLimit:=GifData.LoopCount; if FDelayTimeList.Count > 1 then begin MaxDelay := 0; for i := 0 to FDelayTimeList.Count -1 do if FDelayTimeList[i] > MaxDelay then MaxDelay := FDelayTimeList[i]; if MaxDelay = 0 then for i := 0 to FDelayTimeList.Count -1 do FDelayTimeList[i] := 10; end; Bitmap.Assign(FImageList[0]); MakeSmallImage; SetProtect(FProtect); if Assigned(FOnComplete) then FOnComplete(Self,False); end; FreeAndNil(GifData);//イベントハンドラ中での自殺} //end; //アニメーションを再生/停止 procedure TImageView.Action; var gif: TGraphic; begin if assigned(FAnimateImage) then begin FAnimateImage.Visible := True; gif := FAnimateImage.Picture.Graphic; if gif is TGifImage then TGifImage(gif).PaintStart; end; inherited; end; procedure TImageView.Halt; var gif: TGraphic; begin if assigned(FAnimateImage) then begin FAnimateImage.Visible := True; gif := FAnimateImage.Picture.Graphic; if gif is TGifImage then TGifImage(gif).PaintStop; end; inherited; end; end.
unit DialogConsultaFactura; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DialogConsulta, cxGraphics, Menus, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, ADODB, dxLayoutControl, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid, StdCtrls, cxButtons, cxTextEdit, cxContainer, cxMaskEdit, cxDropDownEdit, DialogCobro; type TfrmDialogConsultaFactura = class(TfrmDialogConsulta) dbDatosTotalPagado: TcxGridDBColumn; dbDatosTotalPendiente: TcxGridDBColumn; dbDatosEntredaID: TcxGridDBColumn; dbDatosFecha: TcxGridDBColumn; dbDatosPacienteID: TcxGridDBColumn; dbDatosClienteID: TcxGridDBColumn; dbDatosNeto: TcxGridDBColumn; dbDatosNombrePaciente: TcxGridDBColumn; dbDatosClienteNombre: TcxGridDBColumn; qrFacturas: TADOQuery; qrFacturasENTRADAID: TStringField; qrFacturasFECHA: TDateTimeField; qrFacturasHORAENTRADA: TStringField; qrFacturasPACIENTEID: TStringField; qrFacturasCLIENTEID: TStringField; qrFacturasDOCTORID: TStringField; qrFacturasPOLIZAID: TStringField; qrFacturasENCLINICA: TIntegerField; qrFacturasRECORDCLINICA: TStringField; qrFacturasNUMEROHABITACION: TStringField; qrFacturasFECHAENTRADA: TDateTimeField; qrFacturasFECHADEALTA: TDateTimeField; qrFacturasRESULTADOPACIENTE: TIntegerField; qrFacturasRESULTADODOCTOR: TIntegerField; qrFacturasFECHAPROMETIDA: TDateTimeField; qrFacturasHORAPROMETIDA: TStringField; qrFacturasFLEBOTOMISTAID: TStringField; qrFacturasNOTA: TStringField; qrFacturasPROYECTOID: TStringField; qrFacturasRECORDID: TIntegerField; qrFacturasBRUTO: TBCDField; qrFacturasDESCUENTO: TBCDField; qrFacturasSUBTOTAL: TBCDField; qrFacturasNETO: TBCDField; qrFacturasNOMBREPACIENTE: TStringField; qrFacturasDIRECCION: TStringField; qrFacturasTELEFONOS: TStringField; qrFacturasTELEFONO2: TStringField; qrFacturasEMAIL: TStringField; qrFacturasCLIENTENOMBRE: TStringField; qrFacturasSUCURSALID: TStringField; qrFacturasUSERID: TStringField; qrFacturasCOBROID: TStringField; qrFacturasTOTALPAGADO: TBCDField; qrFacturasPRIORIDAD: TIntegerField; qrFacturasFAX: TStringField; qrFacturasTIPODOCUMENTO: TIntegerField; qrFacturasCOBERTURAPORC: TBCDField; qrFacturasCOBERTURASEGURO: TBCDField; qrFacturasCOBERTURAVALOR: TBCDField; qrFacturasDESCUENTOPORC: TBCDField; qrFacturasDESCUENTOVALOR: TBCDField; qrFacturasDESCUENTOBONO: TBCDField; qrFacturasORIGEN: TStringField; qrFacturasAPROBACIONNO: TStringField; qrFacturasAPROBACIONPOR: TStringField; qrFacturasCOBERTURARECHAZADA: TIntegerField; qrFacturasCOBERTURACONFIRMADA: TIntegerField; qrFacturasFECHAASEGURADORA: TDateTimeField; qrFacturasMUESTRANO: TStringField; qrFacturasMONEDAID: TStringField; qrFacturasCOBERTURAEXPPORC: TIntegerField; qrFacturasEDADPACIENTE: TIntegerField; qrFacturasSEXO: TIntegerField; qrFacturasNOMBREDOCTOR: TStringField; qrFacturasPUBLICARINTERNET: TIntegerField; qrFacturasCARNET: TStringField; qrFacturasPUBLICARINTERNETDOCTOR: TIntegerField; qrFacturasCUADREGLOBAL: TStringField; qrFacturasCUADREUSUARIO: TStringField; qrFacturasDESCAUTORIZADOPOR: TStringField; qrFacturasGASTOSVARIOS: TBCDField; qrFacturasNOAS400: TIntegerField; qrFacturasNOAXAPTA: TIntegerField; qrFacturasNOFACTURA: TIntegerField; qrFacturasFACTEXTERIOR: TIntegerField; qrFacturasHOLD: TIntegerField; qrFacturasREPMUESTRA: TIntegerField; qrFacturasENTRADAIDANT: TStringField; qrFacturasTIPOENTRADA: TStringField; qrFacturasFORMADEPAGO: TStringField; qrFacturasDESCUENTOCARD: TStringField; qrFacturasDESCUENTOTEXTO: TStringField; qrFacturasACUERDOPROPIO: TIntegerField; qrFacturasCLIENTEPADRE: TStringField; qrFacturasDESCUENTOPLANID: TStringField; qrFacturasFECHAREGISTRO: TDateTimeField; qrFacturasHORAREGISTRO: TStringField; qrFacturasTASA: TBCDField; qrFacturasESTATUS: TIntegerField; qrFacturasTIPOCLIENTEAS400: TIntegerField; qrFacturasCLASECREDITO: TStringField; qrFacturasCARNETNUMERO: TStringField; qrFacturasCLIENTEPADREAXAPTA: TStringField; qrFacturasPACIENTEIDAXAPTA: TStringField; qrFacturasCLIENTEIDAXAPTA: TStringField; qrFacturasDOCTORIDAXAPTA: TStringField; qrFacturasDATAAREAID: TStringField; qrFacturasRECID: TIntegerField; qrFacturasTotalPendiente: TBCDField; qrFacturasSTATUS: TStringField; qrFacturasNCF: TStringField; procedure cgDatosExit(Sender: TObject); procedure cgDatosEnter(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure edbuscarPropertiesChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BuscarData; private { Private declarations } public { Public declarations } procedure Run; end; var frmDialogConsultaFactura: TfrmDialogConsultaFactura; adentrogrid : Boolean; implementation uses DataModule,dataBanco, Main; {$R *.dfm} procedure TfrmDialogConsultaFactura.Run; Var qfind : TADOQuery; begin showmodal; if ModalResult = mrOk then begin DMB.RetornarFactura := qrFacturasEntradaId.value; //frmMain.frmTmp.BuscarDatos; //frmMain.frmTmp.RefrescarInterface; end; end; procedure TfrmDialogConsultaFactura.BuscarData; var sqlString : String; begin //sqlString := 'Select * from dbo.PTENTRADAPACIENTE INNER JOIN dbo.BSDonacion ON dbo.PTENTRADAPACIENTE.ENTRADAID = dbo.BSDonacion.DonacionID '; sqlString := 'Select * from BSVenta '; if edbuscar.Text <> '' then begin case edbuscarpor.ItemIndex of 0 : sqlString := sqlString + ' where EntradaID like '+#39+'%'+edbuscar.Text+'%'+#39; 1 : sqlString := sqlString + ' where PacienteID like '+#39+'%'+edbuscar.Text+'%'+#39; 2 : sqlString := sqlString + ' where NombrePaciente like '+#39+'%'+'%'+edbuscar.Text+'%'+#39; 3 : sqlString := sqlString + ' where ClienteID like '+#39+'%'+edbuscar.Text+'%'+#39; 4 : sqlString := sqlString + ' where ClienteNombre like '+#39+'%'+edbuscar.Text+'%'+#39; 5 : sqlString := sqlString + ' where Telefonos like '+#39+'%'+edbuscar.Text+'%'+#39; end; end; qrFacturas.Close; qrFacturas.SQL.Text := sqlString + ' Order by fecha desc,horaentrada desc,entradaId'; qrFacturas.Open; end; procedure TfrmDialogConsultaFactura.cgDatosEnter(Sender: TObject); begin inherited; adentrogrid := true; end; procedure TfrmDialogConsultaFactura.cgDatosExit(Sender: TObject); begin inherited; adentrogrid := false; end; procedure TfrmDialogConsultaFactura.edbuscarPropertiesChange(Sender: TObject); begin inherited; BuscarData; end; procedure TfrmDialogConsultaFactura.FormCreate(Sender: TObject); begin inherited; qrFacturas.Close; qrFacturas.SQL.Text := 'Select * from BSVenta '; qrFacturas.Open; edbuscarpor.ItemIndex := 2; end; procedure TfrmDialogConsultaFactura.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (key = Vk_Down) and (not AdentroGrid) then PostMessage(Handle, Wm_NextDlgCtl, 0, 0); if (key = 13) and (not AdentroGrid) then PostMessage(Handle, Wm_NextDlgCtl, 0, 0); if (key = 13) and (AdentroGrid) then begin Close; ModalResult := mrOk; end; if (key = Vk_Up) and (not AdentroGrid) then PostMessage(Handle, Wm_NextDlgCtl, 1, 0); if (key = 27) then begin Close; end; end; procedure TfrmDialogConsultaFactura.FormShow(Sender: TObject); begin inherited; edbuscar.SetFocus; end; end.
unit DataJC; // TJCTableData - trida starajici se o vyplneni tabulky jizdnich cest interface uses ComCtrls, SysUtils, StrUtils; type TJCTableData=class private LV:TListView; public procedure LoadToTable(); procedure UpdateTable(); procedure UpdateLine(line:Integer); procedure AddJC(index:Integer); procedure RemoveJC(index:Integer); procedure MoveJC(source, target:Integer); constructor Create(LV:TListView); end; var JCTableData : TJCTableData; implementation uses TBlokUsek, TBlokVyhybka, TJCDatabase, TechnologieJC, TBlok, TBloky, fMain, TBlokSCom; //////////////////////////////////////////////////////////////////////////////// constructor TJCTableData.Create(LV:TListView); begin inherited Create(); Self.LV := LV; end;//ctor //////////////////////////////////////////////////////////////////////////////// procedure TJCTableData.LoadToTable(); var i, j:Integer; LI:TListItem; begin F_Main.E_dataload_JC.text := JCDb.filename; Self.LV.Clear(); for i := 0 to JCDb.Count-1 do begin LI := Self.LV.Items.Add; LI.Caption := IntToStr(i); for j := 0 to Self.LV.Columns.Count-2 do LI.SubItems.Add(''); try Self.UpdateLine(i); except end; end;//for i end;//procedure procedure TJCTableData.UpdateTable(); var i:Integer; begin for i := 0 to JCDb.Count-1 do if (JCDb.GetJCByIndex(i).changed) then begin try Self.UpdateLine(i); Self.LV.UpdateItems(i, i); except end; end; end;//procedure procedure TJCTableData.UpdateLine(line:Integer); var JCData:TJCprop; JC:TJC; j:Integer; str:string; Blk:TBlk; begin JC := JCDb.GetJCByIndex(line); JCData := JC.data; JC.changed := false; Self.LV.Items.Item[line].Caption := IntToStr(JCData.id); Self.LV.Items.Item[line].SubItems.Strings[0] := JCData.Nazev; Self.LV.Items.Item[line].SubItems.Strings[4] := Blky.GetBlkName(JCData.NavestidloBlok); // stav: Self.LV.Items.Item[line].SubItems.Strings[1] := IntToStr(JC.stav.RozpadBlok); Self.LV.Items.Item[line].SubItems.Strings[2] := IntToStr(JC.stav.RozpadRuseniBlok); Self.LV.Items.Item[line].SubItems.Strings[3] := IntToStr(JC.stav.Krok); case (JCData.TypCesty) of TJCType.vlak : Self.LV.Items.Item[line].SubItems.Strings[7] := 'VC'; TJCType.posun : Self.LV.Items.Item[line].SubItems.Strings[7] := 'PC'; TJCType.nouz : Self.LV.Items.Item[line].SubItems.Strings[7] := 'NC'; end; if (JCData.DalsiNNavaznostTyp = 0) then begin Self.LV.Items.Item[line].SubItems.Strings[8] := 'Zadna navaznost'; end else begin if (JCData.DalsiNNavaznostTyp = 1) then begin Self.LV.Items.Item[line].SubItems.Strings[8] := 'Trat'; end else begin Self.LV.Items.Item[line].SubItems.Strings[8] := Blky.GetBlkName(JCData.DalsiNNavaznost); end;//else DalsiNNavaznostTyp = 1 end;//else DalsiNNavaznostTyp = 0 // vyhybky str := ''; for j := 0 to JCData.Vyhybky.Count-1 do begin case (JCData.Vyhybky[j].Poloha) of TVyhPoloha.plus : str := str + '(' + Blky.GetBlkName(JCData.Vyhybky[j].Blok)+', +)'; TVyhPoloha.minus : str := str + '(' + Blky.GetBlkName(JCData.Vyhybky[j].Blok)+', -)'; end; end;//for j Self.LV.Items.Item[line].SubItems.Strings[5] := str; // useky str := ''; for j := 0 to JCData.Useky.Count-1 do str := str + Blky.GetBlkName(JCData.Useky[j])+'; '; Self.LV.Items.Item[line].SubItems.Strings[6] := LeftStr(str, Length(str)-2); Self.LV.Items.Item[line].SubItems.Strings[9] := IntToStr(JCData.RychlostDalsiN * 10)+' km/h'; Self.LV.Items.Item[line].SubItems.Strings[10] := IntToStr(JCData.RychlostNoDalsiN * 10)+' km/h'; // odvraty str := ''; for j := 0 to JCData.Odvraty.Count-1 do begin case (JCData.Odvraty[j].Poloha) of TVyhPoloha.plus : str := str + '(' + Blky.GetBlkName(JCData.Odvraty[j].Blok)+', +, '+Blky.GetBlkName(JCData.Odvraty[j].ref_blk)+')'; TVyhPoloha.minus : str := str + '(' + Blky.GetBlkName(JCData.Odvraty[j].Blok)+', -, '+Blky.GetBlkName(JCData.Odvraty[j].ref_blk)+')'; end; end;//for j Self.LV.Items.Item[line].SubItems.Strings[11] := str; // prislusenstvi str := ''; for j := 0 to JCData.Prisl.Count-1 do str := str + '(' + Blky.GetBlkName(JCData.Prisl[j].Blok)+', '+Blky.GetBlkName(JCData.Prisl[j].ref_blk)+' )'; Self.LV.Items.Item[line].SubItems.Strings[12] := str; if (JCData.Trat > -1) then Self.LV.Items.Item[line].SubItems.Strings[13] := Blky.GetBlkName(JCData.Trat) else Self.LV.Items.Item[line].SubItems.Strings[13] := ''; // prejezdy str := ''; for j := 0 to JCData.Prejezdy.Count-1 do str := str + Blky.GetBlkName(JCData.Prejezdy[j].Prejezd)+'; '; Self.LV.Items.Item[line].SubItems.Strings[14] := LeftStr(str, Length(str)-2); // podminky zamky str := ''; for j := 0 to JCData.zamky.Count-1 do str := str + '('+Blky.GetBlkName(JCData.zamky[j].Blok)+' : ' + Blky.GetBlkName(JCData.zamky[j].ref_blk) + ')'; Self.LV.Items.Item[line].SubItems.Strings[15] := str; // neprofilove useky str := ''; for j := 0 to JCData.Vyhybky.Count-1 do begin Blky.GetBlkByID(JCData.Vyhybky[j].Blok, Blk); if ((JCData.Vyhybky[j].Poloha = TVyhPoloha.plus) and (TBlkVyhybka(Blk).npBlokPlus <> nil)) then str := str + TBlkVyhybka(Blk).npBlokPlus.name + ', ' else if ((JCData.Vyhybky[j].Poloha = TVyhPoloha.minus) and (TBlkVyhybka(Blk).npBlokMinus <> nil)) then str := str + TBlkVyhybka(Blk).npBlokMinus.name + ', '; end; Self.LV.Items.Item[line].SubItems.Strings[16] := LeftStr(str, Length(str)-2); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TJCTableData.AddJC(index:Integer); var LI:TListItem; j:Integer; begin LI := Self.LV.Items.Insert(index); LI.Caption := IntToStr(Self.LV.Items.Count); for j := 0 to Self.LV.Columns.Count-2 do LI.SubItems.Add(''); Self.UpdateLine(index); end;//procedure procedure TJCTableData.RemoveJC(index:Integer); begin Self.LV.Items.Delete(index); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TJCTableData.MoveJC(source, target:Integer); var LI:TListItem; i:Integer; begin Self.LV.Items.Delete(source); LI := Self.LV.Items.Insert(target); for i := 0 to Self.LV.Columns.Count-2 do LI.SubItems.Add(''); Self.UpdateLine(target); end;//procedure //////////////////////////////////////////////////////////////////////////////// initialization finalization JCTableData.Free(); end.//unit
program fodP2E7GenerarTxt; const corte = -1; type registroMaestro = record codigo: integer; nombre: string; precio: real; stockAct: integer; stockMin: integer; end; registroDetalle = record codigo: integer; ventas: integer; end; detalle = file of registroDetalle; maestro = file of registroMaestro; //---------------------------------------------------------------------- procedure leerRM(var rm: registroMaestro); begin with rm do begin write('* Código: '); readln(codigo); if (codigo <> corte) then begin write('* Nombre: '); readln(nombre); write('* Precio: '); readln(precio); write('* Stock Actual: '); readln(stockAct); write('* Stock Mínimo: '); readln(stockMin); writeln(); end; end; End; procedure leerRD(var rd: registroDetalle); begin with rd do begin write('* codigo: '); readln(codigo); if(codigo <> corte)then begin write('* Total de ventas: '); readln(ventas); writeln(); end; end; End; //---------------------------------------------------------------------- procedure generarMaestroTxt(var t: Text); var rm: registroMaestro; begin writeln('********* GENERANDO TXT MAESTRO **********'); writeln(); assign(t,'productos.txt'); rewrite(t); leerRM(rm); while (rm.codigo <> corte) do begin with rm do begin writeln(t,codigo,' ',precio:0:2,' ',nombre); writeln(t,stockAct,' ',stockMin); end; leerRM(rm); end; close(t); End; procedure generarDetalleTxt(var t: Text); var rd: registroDetalle; begin writeln('********* GENERANDO TXT DETALLE **********'); writeln(); assign(t,'ventas.txt'); rewrite(t); leerRD(rd); while(rd.codigo <> corte) do begin with rd do writeln(t,codigo,' ',ventas); leerRD(rd); end; close(t); End; //---------------------------------------------------------------------- VAR t: Text; BEGIN //generarMaestroTxt(t); generarDetalleTxt(t); END.
unit GsvThread; { Объектная оболочка для параллельных потоков - Windows threads. Сергей Гурин. Россия, Томск. 2005. gurin@mail.tomsknet.ru http://gurin.tomsknet.ru } interface uses Windows, Classes, SysUtils; type TGsvThread = class; IGsvThreadList = interface ['{2B09399A-07E9-47F5-9CB7-3E34230D37D1}'] function Count: Integer; function GetItem(aIndex: Integer): TGsvThread; property Items[aIndex: Integer]: TGsvThread read GetItem; default; end; TGsvThreadManager = class private FLatch: TRTLCriticalSection; FHashTable: array of TGsvThread; FCurHandle: Integer; FCount: Integer; FOnEmpty: TNotifyEvent; public constructor Create(aCapacity: Integer = 64); destructor Destroy; override; function Add(aThread: TGsvThread; aStart: Boolean = True): Integer; procedure Release(aHandle: Integer); function Lock(aHandle: Integer): TGsvThread; function TerminateAll: Integer; function ActiveThreadList: IGsvThreadList; property OnEmpty: TNotifyEvent read FOnEmpty write FOnEmpty; end; TGsvThread = class public constructor Create; destructor Destroy; override; private // эти поля нужны для менеджера потоков FManager: TGsvThreadManager; FGsvHandle: Integer; FRefCount: Integer; FCollision: TGsvThread; // это собственные данные объекта потока FSysHandle: THandle; FTerminated: Boolean; FFinished: Boolean; FTerminationEvent: THandle; procedure ThreadExecute; procedure Terminate; function GetPriority: Cardinal; procedure SetPriority(const Value: Cardinal); protected procedure Execute; virtual; abstract; procedure OnThreadError(const E: Exception); virtual; procedure OnFinished; virtual; procedure Pause(aTime: Cardinal); property Terminated: Boolean read FTerminated write FTerminated; public procedure Resume; procedure Suspend; property GsvHandle: Integer read FGsvHandle; property SysHandle: THandle read FSysHandle; property Finished: Boolean read FFinished; property Priority: Cardinal read GetPriority write SetPriority; property TerminationEvent: THandle read FTerminationEvent; end; TGsvLatch = class private FLatch: TRTLCriticalSection; public constructor Create; destructor Destroy; override; procedure Lock; procedure Unlock; end; TGsvEvent = class public constructor Create; destructor Destroy; override; private FHandle: THandle; procedure SetState(aState: Boolean); public function Wait(aThread: TGsvThread; aTimeout: Cardinal = INFINITE): Boolean; property Handle: THandle read FHandle; property State: Boolean write SetState; end; TGsvSelectMethod = procedure of object; TGsvSelect = class private FEvents: array[0..MAXIMUM_WAIT_OBJECTS - 1] of THandle; FMethods: array[0..MAXIMUM_WAIT_OBJECTS - 1] of TGsvSelectMethod; FCount: Cardinal; public constructor Create(aThread: TGsvThread); procedure Init; procedure Add(aEvent: THandle; aMethod: TGsvSelectMethod); function Wait(aTimeout: Cardinal = INFINITE): Boolean; end; TGsvQueue = class public constructor Create(aMaxCount: Integer); destructor Destroy; override; private FGetEvent: TGsvEvent; FPutEvent: TGsvEvent; FLatch: TGsvLatch; FList: TList; FMaxCount: Integer; function GetCount: Integer; procedure SetEvents; public function Get(aThread: TGsvThread; aTimeout: Cardinal = INFINITE): TObject; function Put(aThread: TGsvThread; aMessage: TObject; aTimeout: Cardinal = INFINITE): Boolean; procedure PutOutOfTurn(aMessage: TObject); property GetEvent: TGsvEvent read FGetEvent; property PutEvent: TGsvEvent read FPutEvent; property Count: Integer read GetCount; property MaxCount: Integer read FMaxCount; end; TGsvChannelMethod = procedure(aThread: TGsvThread) of object; TGsvChannel = class private FSendEvent: TGsvEvent; FReceiveEvent: TGsvEvent; FReceiveThread: TGsvThread; FLatch: TGsvLatch; FResult: Boolean; public constructor Create; destructor Destroy; override; function Send(aThread: TGsvThread; aMethod: TGsvChannelMethod; aTimeout: Cardinal = INFINITE): Boolean; function Receive(aThread: TGsvThread; aTimeout: Cardinal = INFINITE): Boolean; end; implementation type TGsvThreadList = class(TInterfacedObject, IGsvThreadList) private FManager: TGsvThreadManager; FItems: TList; public constructor Create(aManager: TGsvThreadManager); destructor Destroy; override; function Count: Integer; function GetItem(aIndex: Integer): TGsvThread; end; { TGsvThreadList } constructor TGsvThreadList.Create(aManager: TGsvThreadManager); var hash: Integer; th: TGsvThread; begin inherited Create; FManager := aManager; FItems := TList.Create; // заносим в список все активные потоки из хеш-таблицы with FManager do for hash := Low(FManager.FHashTable) to High(FHashTable) do begin th := FHashTable[hash]; while Assigned(th) do begin if not th.FTerminated then begin // увеличиваем счетчик ссылок потока, так как теперь он используется списком Inc(th.FRefCount); FItems.Add(th); end; // проходим по цепочке коллизий th := th.FCollision; end; end; end; destructor TGsvThreadList.Destroy; var i: Integer; begin // освобождаем все объекты потоков for i := 0 to Pred(FItems.Count) do FManager.Release(TGsvThread(FItems[i]).FGsvHandle); inherited Destroy; end; function TGsvThreadList.Count: Integer; begin Result := FItems.Count; end; function TGsvThreadList.GetItem(aIndex: Integer): TGsvThread; begin Result := TGsvThread(FItems[aIndex]); end; { TGsvThreadManager } constructor TGsvThreadManager.Create(aCapacity: Integer); var i: Integer; begin if aCapacity < 1 then aCapacity := 1; InitializeCriticalSection(FLatch); SetLength(FHashTable, aCapacity); // явно инициализируем хеш-таблицу for i := Low(FHashTable) to High(FHashTable) do FHashTable[i] := nil; FCurHandle := 0; // явная инициализация, которую можно было бы не делать FCount := 0; end; destructor TGsvThreadManager.Destroy; begin // Программная ошибка - недопустимо уничтожать менеджер, если имеются // незавершенные потоки, так как при своем завершении они будут обращаться // к менеджеру Assert(FCount = 0); DeleteCriticalSection(FLatch); inherited Destroy; end; function TGsvThreadManager.Add(aThread: TGsvThread; aStart: Boolean): Integer; var hash: Integer; // хеш-код дескриптора: индекс в хеш-таблице begin // делаем все операции внутри критической секции чтобы исключить // наложение параллельных потоков EnterCriticalSection(FLatch); try Inc(FCurHandle); // создаем следующий дескриптор hash := FCurHandle mod Length(FHashTable); aThread.FManager := Self; aThread.FGsvHandle := FCurHandle; aThread.FRefCount := 1; // включаем объект в начало цепочки коллизий (если она есть) и // вносим объект в хеш-таблицу aThread.FCollision := FHashTable[hash]; FHashTable[hash] := aThread; Inc(FCount); Result := FCurHandle; finally LeaveCriticalSection(FLatch); end; // активизируем параллельное выполнение потока if aStart then aThread.Resume; end; procedure TGsvThreadManager.Release(aHandle: Integer); var hash: Integer; th: TGsvThread; // поток, связанный с дескриптором prev: TGsvThread; // предыдущий поток в цепочке коллизий begin EnterCriticalSection(FLatch); try // поиск объекта, связанного с дескриптором и предыдущего объекта в // цепочке коллизий. Предыдущий объект нужен из-за того, что // цепочка коллизий представляет собой односвязный список, а нам может // потребоваться удаление объекта из середины или конца списка hash := aHandle mod Length(FHashTable); prev := nil; th := FHashTable[hash]; while Assigned(th) do begin if th.FGsvHandle = aHandle then Break; // проходим по цепочке коллизий prev := th; th := th.FCollision; end; if Assigned(th) then begin // объект потока еще существует, уменьшаем его счетчик ссылок Dec(th.FRefCount); // используем сравнение ( <= 0) для защиты от ошибки повторного уничтожения if th.FRefCount <= 0 then begin // объект потока больше никому не нужен if not th.FFinished then begin // объект потока еще не завершен. Завершаем его th.Terminate; // после своего завершения поток самостоятельно вызовет Release, // поэтому временно увеличиваем его счетчик ссылок без уничтожения // объекта (не допускаем отрицательного значения счетчика ссылок) Inc(th.FRefCount); end else begin // объект потока завершен, // удаляем объект из хеш-таблицы и из цепочки коллизий if Assigned(prev) then prev.FCollision := th.FCollision // объект в середине или в конце else FHashTable[hash] := th.FCollision; // объект в начале цепочки Dec(FCount); // уничтожаем объект потока th.Free; end; end; end; // else - объекта с таким дескриптором не существует, ничего не делаем // Если список потоков пуст, то вызываем событие OnEmpty if (FCount = 0) and Assigned(FOnEmpty) then FOnEmpty(Self); finally LeaveCriticalSection(FLatch); end; end; function TGsvThreadManager.Lock(aHandle: Integer): TGsvThread; var hash: Integer; begin EnterCriticalSection(FLatch); try hash := aHandle mod Length(FHashTable); // поиск объекта потока по его дескриптору Result := FHashTable[hash]; while Assigned(Result) do begin if Result.FGsvHandle = aHandle then Break; Result := Result.FCollision; end; // объект существует, увеличиваем его счетчик ссылок, так как у объекта // появился еще один "пользователь" if Assigned(Result) then Inc(Result.FRefCount); finally LeaveCriticalSection(FLatch); end; end; // Функция завершает все активные потоки и возвращает количество потоков, // которые еще не достигли фазы полного завершения function TGsvThreadManager.TerminateAll: Integer; var hash: Integer; th: TGsvThread; begin Result := 0; EnterCriticalSection(FLatch); try // обходим всю хеш-таблицу for hash := Low(FHashTable) to High(FHashTable) do begin th := FHashTable[hash]; while Assigned(th) do begin // завершаем поток. Если он уже завершен, то Terminate не вызывает // побочных действий th.Terminate; if not th.FFinished then Inc(Result); // проходим по цепочке коллизий th := th.FCollision; end; end; finally LeaveCriticalSection(FLatch); end; end; function TGsvThreadManager.ActiveThreadList: IGsvThreadList; begin EnterCriticalSection(FLatch); try Result := TGsvThreadList.Create(Self); finally LeaveCriticalSection(FLatch); end; end; { TGsvThread } function ThreadProc(p: TGsvThread): Integer; begin // Процедура, которую вызывает операционная система при старте параллельного // потока Result := 0; with p do begin // жизненный цикл потока ThreadExecute; // самозавершение потока if Assigned(FManager) then FManager.Release(FGsvHandle); end; EndThread(0); end; constructor TGsvThread.Create; var id: Cardinal; begin inherited Create; // завершающее событие создается в режиме ручной переустановки (True), // начальное состояние события - несигнализирующее (False) FTerminationEvent := CreateEvent(nil, True, False, nil); if FTerminationEvent = 0 then RaiseLastOSError; // параллельный поток создается в приостановленном состоянии. Delphi-функция // BeginThread используется вместо Windows-функции CreateThread для того, // чтобы корректно установить параметры многопоточности Delphi-приложения. FSysHandle := BeginThread(nil, 0, @ThreadProc, Self, CREATE_SUSPENDED, id); if FSysHandle = 0 then RaiseLastOSError; end; destructor TGsvThread.Destroy; begin if FTerminationEvent <> 0 then begin CloseHandle(FTerminationEvent); FTerminationEvent := 0; end; inherited Destroy; end; procedure TGsvThread.ThreadExecute; begin try Execute; except on E: Exception do begin try OnThreadError(E); except end; end; end; FTerminated := True; if FSysHandle <> 0 then begin CloseHandle(FSysHandle); FSysHandle := 0; end; FFinished := True; try OnFinished; except end; end; procedure TGsvThread.Terminate; begin if not FTerminated then begin FTerminated := True; SetEvent(FTerminationEvent); Resume; end; end; function TGsvThread.GetPriority: Cardinal; begin if FSysHandle <> 0 then Result := GetThreadPriority(FSysHandle) else Result := THREAD_PRIORITY_NORMAL; end; procedure TGsvThread.SetPriority(const Value: Cardinal); begin if FSysHandle <> 0 then SetThreadPriority(FSysHandle, Value); end; // Метод вызывается в контексте параллельного потока при возникновении // исключительной ситуации в Execute procedure TGsvThread.OnThreadError(const E: Exception); begin end; // Это последний метод, который вызывается в контексте параллельного потока. // Метод вызывается независимо от того, по какой причине произошло завершение // потока. После вызова этого метода параллельный поток прекращает свою работу, // но объект потока может еще существовать до тех пор, пока на него остаются // ссылки procedure TGsvThread.OnFinished; begin end; // Пауза с контролем внешнего завершения потока. Время 0 используется // для того, чтобы вызвать диспетчер параллельных потоков Windows и // передать выполнение другому параллельному потоку procedure TGsvThread.Pause(aTime: Cardinal); begin if not FTerminated then begin if aTime = 0 then Sleep(0) else WaitForSingleObject(FTerminationEvent, aTime); end; end; procedure TGsvThread.Resume; begin if FSysHandle <> 0 then ResumeThread(FSysHandle); end; procedure TGsvThread.Suspend; begin if FSysHandle <> 0 then SuspendThread(FSysHandle); end; { TGsvLatch } constructor TGsvLatch.Create; begin inherited Create; InitializeCriticalSection(FLatch); end; destructor TGsvLatch.Destroy; begin DeleteCriticalSection(FLatch); inherited Destroy; end; procedure TGsvLatch.Lock; begin EnterCriticalSection(FLatch); end; procedure TGsvLatch.Unlock; begin LeaveCriticalSection(FLatch); end; { TGsvEvent } constructor TGsvEvent.Create; begin inherited Create; FHandle := CreateEvent(nil, False, False, nil); if FHandle = 0 then RaiseLastOSError; end; destructor TGsvEvent.Destroy; begin if FHandle <> 0 then CloseHandle(FHandle); inherited Destroy; end; procedure TGsvEvent.SetState(aState: Boolean); begin if aState then SetEvent(FHandle) else ResetEvent(FHandle); end; function TGsvEvent.Wait(aThread: TGsvThread; aTimeout: Cardinal): Boolean; var objs: array[0..1] of THandle; cnt: Integer; begin objs[0] := FHandle; cnt := 1; if Assigned(aThread) then begin objs[1] := aThread.FTerminationEvent; cnt := 2; end; Result := WaitForMultipleObjects(cnt, @objs[0], False, aTimeout) = WAIT_OBJECT_0; end; { TGsvSelect } constructor TGsvSelect.Create(aThread: TGsvThread); begin inherited Create; FEvents[0] := aThread.FTerminationEvent; FMethods[0] := nil; FCount := 1; end; procedure TGsvSelect.Init; begin FCount := 1; end; procedure TGsvSelect.Add(aEvent: THandle; aMethod: TGsvSelectMethod); begin Assert(FCount <= High(FEvents)); FEvents[FCount] := aEvent; FMethods[FCount] := aMethod; Inc(FCount); end; function TGsvSelect.Wait(aTimeout: Cardinal): Boolean; var res, i: Cardinal; begin Result := False; res := WaitForMultipleObjects(FCount, @FEvents[0], False, aTimeout); if res < (WAIT_OBJECT_0 + FCount) then begin Result := res > WAIT_OBJECT_0; if Result then begin i := res - WAIT_OBJECT_0; if Assigned(FMethods[i]) then FMethods[i](); end; end; end; { TGsvQueue } constructor TGsvQueue.Create(aMaxCount: Integer); begin inherited Create; FGetEvent := TGsvEvent.Create; FPutEvent := TGsvEvent.Create; FLatch := TGsvLatch.Create; FList := TList.Create; FMaxCount := aMaxCount; FList.Capacity := FMaxCount; end; destructor TGsvQueue.Destroy; var i: Integer; begin for i := 0 to Pred(FList.Count) do TObject(FList.Items[i]).Free; FList.Free; FLatch.Free; FPutEvent.Free; FGetEvent.Free; inherited Destroy; end; function TGsvQueue.GetCount: Integer; begin FLatch.Lock; Result := FList.Count; FLatch.Unlock; end; procedure TGsvQueue.SetEvents; begin FGetEvent.State := FList.Count <> 0; FPutEvent.State := FList.Count < FMaxCount; end; function TGsvQueue.Get(aThread: TGsvThread; aTimeout: Cardinal): TObject; begin Result := nil; if not FGetEvent.Wait(aThread, aTimeout) then Exit; FLatch.Lock; try if FList.Count <> 0 then begin Result := TObject(FList.Items[0]); FList.Delete(0); SetEvents; end; finally FLatch.Unlock; end; end; function TGsvQueue.Put(aThread: TGsvThread; aMessage: TObject; aTimeout: Cardinal): Boolean; begin Result := False; if not FPutEvent.Wait(aThread, aTimeout) then Exit; FLatch.Lock; try FList.Add(aMessage); SetEvents; Result := True; finally FLatch.Unlock; end; end; procedure TGsvQueue.PutOutOfTurn(aMessage: TObject); begin FLatch.Lock; try FList.Add(aMessage); SetEvents; finally FLatch.Unlock; end; end; { TGsvChannel } constructor TGsvChannel.Create; begin inherited Create; FSendEvent := TGsvEvent.Create; FReceiveEvent := TGsvEvent.Create; FLatch := TGsvLatch.Create; FResult := False; end; destructor TGsvChannel.Destroy; begin FLatch.Free; FReceiveEvent.Free; FSendEvent.Free; inherited Destroy; end; function TGsvChannel.Send(aThread: TGsvThread; aMethod: TGsvChannelMethod; aTimeout: Cardinal): Boolean; begin Result := False; FResult := False; if not FSendEvent.Wait(aThread, aTimeout) then Exit; FLatch.Lock; try if Assigned(FReceiveThread) then begin aMethod(FReceiveThread); // обмен данными FReceiveEvent.State := True; // активизация получателя Result := True; // успешное рандеву FResult := True; end; finally FLatch.Unlock; end; end; function TGsvChannel.Receive(aThread: TGsvThread; aTimeout: Cardinal): Boolean; begin FLatch.Lock; try FReceiveThread := aThread; FReceiveEvent.State := False; // сброс ожидающего события FSendEvent.State := True; // активизация отправителя finally FLatch.Unlock; end; FReceiveEvent.Wait(aThread, aTimeout); FLatch.Lock; try Result := FResult; FResult := False; // приведение канала в исходное состояние FSendEvent.State := False; FReceiveThread := nil; finally FLatch.Unlock; end; end; end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Ported to Delphi by Michal Wojcik. // // Modified or written by Object Mentor, Inc. for inclusion with FitNesse. // Copyright (c) 2002 Cunningham & Cunningham, Inc. // Released under the terms of the GNU General Public License version 2 or later. {$H+} unit PrimitiveFixture; interface uses Fixture, Parse; type TPrimitiveFixture = class(TFixture) public function parseLong(cell : TParse) : longint; function parseDouble(cell : TParse) : double; procedure check(cell : TParse; value : string); overload; procedure check(cell : TParse; value : longint); overload; procedure check(cell : TParse; value : double); overload; end; implementation uses SysUtils, Classes; { TPrimitiveFixture } function TPrimitiveFixture.parseLong(cell : TParse) : longint; begin result := StrToInt(cell.text()); end; function TPrimitiveFixture.parseDouble(cell : TParse) : double; begin result := StrToFloat(cell.text()); end; procedure TPrimitiveFixture.check(cell : TParse; value : string); begin if ((cell.text() = value)) then right(cell) else wrong(cell, value) end; procedure TPrimitiveFixture.check(cell : TParse; value : longint); begin if (parseLong(cell) = value) then right(cell) else wrong(cell, IntToStr(value)); end; procedure TPrimitiveFixture.check(cell : TParse; value : double); begin if (parseDouble(cell) = value) then right(cell) else wrong(cell, FloatToStr(value)) end; initialization RegisterClass(TPrimitiveFixture); finalization UnRegisterClass(TPrimitiveFixture); end.
unit AlxFileMergeStrF; interface uses SysUtils, Classes, AlxCommon, Math; Const AlxStr = $53584C41; type TAlxFileMergeStr = class(TObject) private FFileName: String; //Имя файла соединенного FFileCount: Integer; //Кол-во файлов в файле FArrCount: Integer; //Кол-во заполненых элементов в массиве CurrFile: TAlxSpecFileRecStr; //Структура текущего файла FItemIndex: Integer; //Текущий индекс FIsAutoDelEmpty: Boolean; //Флаг автоматического удаления пустого файла FFileList: Array of TAlxSpecFileRecStr; //Массив структур описывающих вложенные файлы ArrayStep: Integer; //Шаг наращивания массива procedure SetFileName(const FName: String); procedure SetItemIndex(ind: Integer); procedure ReadFlie(var fs: TFileStream; Index: Integer); //Чтение информации о файле из объединенного файла procedure WriteFlie(var fs: TFileStream; var fd: TFileStream); public Constructor Create; overload; Constructor Create(IsAutoDel: Boolean); overload; Constructor Create(const FName: String; IsAutoDel: Boolean = False); overload; Destructor Destroy; override; function NewFile(const FName: String):Boolean; overload; //Создание нового файла function NewFile(const FName, FSource: String):Boolean; overload; //Создание нового файла + включить файл procedure Add(const FSource: String; DirName: String = ''); //Добавить файл в файл procedure AddFromDir(DirDest: String; DirName: String = ''); //Добавить все файлы из дирректории procedure Delete; overload; //Удалить текущий файл из файла procedure Delete(FName: String); overload; //Удалить файл (по имени) из файла function ExtractFile(FName: String; DirDest: String):Boolean; overload; function ExtractFile(DirDest: String):Boolean; overload; procedure ExtractAll(DirDest: String); property FileCount: Integer read FFileCount; property Currently: TAlxSpecFileRecStr read CurrFile; property FileName: String read FFileName write SetFileName; property ItemIndex: Integer read FItemIndex write SetItemIndex; property IsAutoDelEmpty: Boolean read FIsAutoDelEmpty write FIsAutoDelEmpty; end; implementation uses AlxFileMergeStr; constructor TAlxFileMergeStr.Create; begin inherited Create; FFileCount := 0; FArrCount := 0; FFileName := ''; FFileList := nil; FItemIndex := -1; FIsAutoDelEmpty := False; CurrFile.FileName := ''; CurrFile.FileBegin := 0; CurrFile.FileSize := 0; ArrayStep := 64; end; constructor TAlxFileMergeStr.Create(IsAutoDel: Boolean); begin inherited Create; FFileCount := 0; FArrCount := 0; FFileName := ''; FFileList := nil; FItemIndex := -1; FIsAutoDelEmpty := IsAutoDel; CurrFile.FileName := ''; CurrFile.FileBegin := 0; CurrFile.FileSize := 0; ArrayStep := 64; end; constructor TAlxFileMergeStr.Create(const FName: String; IsAutoDel: Boolean = False); var fs: TFileStream; m, i: Integer; f: Extended; temp: Integer; //ln - длина строки; ln: Integer; pc: PChar; begin inherited Create; FFileName := FName; CurrFile.FileName := ''; CurrFile.FileBegin := 0; CurrFile.FileSize := 0; FIsAutoDelEmpty := IsAutoDel; ArrayStep := 64; pc := nil; if FileExists(FName) then begin fs := TFileStream.Create(FName,fmOpenRead); if fs.Size = 0 then begin fs.Free; if FIsAutoDelEmpty then DeleteFile(FName); //Файл можно не удалять (строку можно закоментировать) FFileCount := 0; FItemIndex := -1; SetLength(FFileList,ArrayStep); //Выделяем массив для дальнейшей работы FArrCount := ArrayStep; exit; end; fs.Read(temp,SizeOf(Integer)); if temp <> AlxStr then begin fs.Free; FFileName := ''; FFileCount := 0; FItemIndex := -1; FFileList := nil; Raise Exception.Create('Неверный тип файла!'); end; fs.Read(FFileCount,SizeOf(Integer)); //читаем кол-во файлов в файле f := FFileCount; m := Ceil(f/ArrayStep); SetLength(FFileList,ArrayStep*m); //выделяем массив FArrCount := ArrayStep*m; i := 0; While i <= FFileCount-1 do begin ReadFlie(fs,i); {ln := fs.Read(ln,SizeOf(Integer)); //читаем длину строки имени файла ReallocMem(pc,ln+1); fs.Read(pc^,ln); (pc+ln)^ := #0; FFileList[i].FileName := StrPas(pc); fs.Read(FFileList[i].FileSize,SizeOf(Int64)); //читаем размер файла FFileList[i].FileBegin := fs.Position; fs.Seek(FFileList[i].FileSize,soFromCurrent); //переходим к следующему файлу ReallocMem(pc,0);} inc(i); end; fs.Free; FItemIndex := 0; CurrFile := FFileList[0]; end else begin FFileCount := 0; FItemIndex := -1; SetLength(FFileList,ArrayStep); FArrCount := ArrayStep; end; end; procedure TAlxFileMergeStr.ReadFlie(var fs: TFileStream; Index: Integer); var ln: Integer; //ln - длина строки; pc: PChar; begin pc := nil; fs.Read(ln,SizeOf(Integer)); //читаем длину строки имени файла ReallocMem(pc,ln+1); fs.Read(pc^,ln); (pc+ln)^ := #0; FFileList[Index].FileName := StrPas(pc); fs.Read(FFileList[Index].FileSize,SizeOf(Int64)); //читаем размер файла FFileList[Index].FileBegin := fs.Position; fs.Seek(FFileList[Index].FileSize,soFromCurrent); //переходим к следующему файлу ReallocMem(pc,0); end; procedure TAlxFileMergeStr.WriteFlie(var fs: TFileStream; var fd: TFileStream); var ln: Integer; begin ln := Length(FFileList[FFileCount-1].FileName); fs.Write(ln,SizeOf(ln)); //записываем длину строки имени файла fs.Write(PChar(FFileList[FFileCount-1].FileName)^,ln); //записываем имя файла fs.Write(FFileList[FFileCount-1].FileSize,SizeOf(Int64)); //записываем размер файла FFileList[FFileCount-1].FileBegin := fs.Position; //заполняем массив записей о файле (позиция начала файла) fs.CopyFrom(fd,fd.size); //далее копируем файл end; function TAlxFileMergeStr.NewFile(const FName: String):Boolean; begin Result := False; //---Надо подумать if FileExists(FName) then begin //DeleteFile(FName); {fs.Create(FName,fmCreate); fs.Free;} FFileName := ''; CurrFile.FileName := ''; CurrFile.FileBegin := 0; CurrFile.FileSize := 0; FFileList := nil; FFileCount := 0; FItemIndex := -1; SetLength(FFileList,ArrayStep); FArrCount := ArrayStep; exit; end; FFileName := FName; CurrFile.FileName := ''; CurrFile.FileBegin := 0; CurrFile.FileSize := 0; FFileList := nil; FFileCount := 0; FItemIndex := -1; SetLength(FFileList,ArrayStep); FArrCount := ArrayStep; Result := True; end; function TAlxFileMergeStr.NewFile(const FName, FSource: String):Boolean; var fs, fd: TFileStream; fn: Int64; temp, ln: Integer; Fext, Fnm: String; begin Result := False; //---Надо подумать if FileExists(FName) then begin //DeleteFile(FName); {fs.Create(FName,fmCreate); fs.Free;} FFileName := ''; CurrFile.FileName := ''; CurrFile.FileBegin := 0; CurrFile.FileSize := 0; FFileList := nil; FFileCount := 0; FItemIndex := -1; SetLength(FFileList,ArrayStep); FArrCount := ArrayStep; exit; end; FFileName := FName; CurrFile.FileName := ''; CurrFile.FileBegin := 0; CurrFile.FileSize := 0; FFileList := nil; FFileCount := 0; FItemIndex := -1; SetLength(FFileList,ArrayStep); FArrCount := ArrayStep; try fd := TFileStream.Create(FSource,fmOpenRead); except fd.Free; Raise Exception.Create('Невозможно открыть файл источник!'); exit; end; ForceDirectories(ExtractFileDir(FName)); try fs := TFileStream.Create(FName,fmCreate); except fd.Free; fs.Free; Raise Exception.Create('Невозможно создать файл назначения!'); exit; end; inc(FFileCount); FFileList[FFileCount-1].FileName := ExtractFileName(FSource); FFileList[FFileCount-1].FileSize := fd.Size; //заполняем массив записей о файле (имя + размер) temp := AlxStr; fs.Write(temp,SizeOf(AlxStr)); fs.Write(FFileCount,SizeOf(Integer)); //записываем заголовок (префикс + кол-во файлов в файле) WriteFlie(fs,fd); fd.Free; fs.Free; FItemIndex := 0; CurrFile := FFileList[FFileCount-1]; Result := True; end; procedure TAlxFileMergeStr.SetFileName(const FName: String); var fs: TFileStream; m, i, ln: Integer; pc: PChar; temp: Integer; f: Extended; begin if FFileName = FName then exit; FFileName := FName; CurrFile.FileNo := 0; CurrFile.FileBegin := 0; CurrFile.FileSize := 0; FFileList := nil; if FileExists(FName) then begin fs := TFileStream.Create(FName,fmOpenRead); fs.Read(temp,SizeOf(Integer)); if temp <> AlxStr then begin fs.Free; FFileName := ''; FFileCount := 0; FItemIndex := -1; FFileList := nil; Raise Exception.Create('Неверный тип файла!'); end; fs.Read(FFileCount,SizeOf(Integer)); f := FFileCount; m := Ceil(f/ArrayStep); SetLength(FFileList,ArrayStep*m); FArrCount := ArrayStep*m; i := 0; While i <= FFileCount-1 do begin ReadFlie(fs,i); inc(i); end; fs.Free; FItemIndex := 0; CurrFile := FFileList[0]; end else begin //ForceDirectories(ExtractFileDir(FName)); FFileCount := 0; FItemIndex := -1; SetLength(FFileList,ArrayStep); FArrCount := ArrayStep; end; end; procedure TAlxFileMergeStr.Add(const FSource: String; DirName: String = ''); var fs, fd: TFileStream; fn, ln: Integer; temp: Integer; Fext, Fnm: String; begin if FFileName = '' then exit; if FFileCount = FArrCount then begin Inc(FArrCount,ArrayStep); SetLength(FFileList,FArrCount); end; try fd := TFileStream.Create(FSource,fmOpenRead); except fd.Free; exit; end; if FFileCount = 0 then begin ForceDirectories(ExtractFileDir(FFileName)); fs := TFileStream.Create(FFileName,fmCreate); end else fs := TFileStream.Create(FFileName,fmOpenReadWrite); if (DirName <> '') AND (DirName[Length(DirName)] <> '\') then DirName := DirName + '\'; FFileList[FFileCount].FileName := DirName + ExtractFileName(FSource); FFileList[FFileCount].FileSize := fd.Size; fn := FFileCount+1; temp := AlxStr; fs.Write(temp,SizeOf(AlxStr)); fs.Write(fn,SizeOf(Integer)); If FFileCount > 0 then fs.Seek(FFileList[FFileCount-1].FileBegin+FFileList[FFileCount-1].FileSize,soFromBeginning); inc(FFileCount); WriteFlie(fs,fd); fd.Free; fs.Free; FItemIndex := FFileCount-1; CurrFile := FFileList[FFileCount-1]; end; procedure TAlxFileMergeStr.SetItemIndex(ind: Integer); begin If ind = FItemIndex then exit; if ind > FFileCount-1 then FItemIndex := FFileCount-1 else FItemIndex := ind; If FItemIndex < 0 then exit else CurrFile := FFileList[FItemIndex]; end; Function TAlxFileMergeStr.ExtractFile(FName: String; DirDest: String):Boolean; var i: Integer; fs, fd: TFileStream; begin if DirDest = '' then begin Result := False; exit; end; if CurrFile.FileName <> FName then begin Result := False; i := 0; While i <= FFileCount-1 do begin if FFileList[i].FileName = FName then begin CurrFile := FFileList[i]; FItemIndex := i; Result := True; Break; end; inc(i); end; end else Result := True; if Result = False then Exit; if DirDest[Length(DirDest)] <> '\' then DirDest := DirDest + '\'; ForceDirectories(DirDest); try try ForceDirectories(ExtractFileDir(DirDest+CurrFile.FileName)); fs := TFileStream.Create(FFileName,fmOpenRead); fd := TFileStream.Create(DirDest+CurrFile.FileName,fmCreate); fs.Seek(CurrFile.FileBegin,soFromBeginning); fd.CopyFrom(fs,CurrFile.FileSize); finally fd.Free; fs.Free; end; except Result := False; end; Result := True; end; Function TAlxFileMergeStr.ExtractFile(DirDest: String):Boolean; var fs, fd: TFileStream; begin if DirDest = '' then begin Result := False; exit; end; if DirDest[Length(DirDest)] <> '\' then DirDest := DirDest + '\'; ForceDirectories(DirDest); try try ForceDirectories(ExtractFileDir(DirDest+CurrFile.FileName)); fs := TFileStream.Create(FFileName,fmOpenRead); fd := TFileStream.Create(DirDest+CurrFile.FileName,fmCreate); fs.Seek(CurrFile.FileBegin,soFromBeginning); fd.CopyFrom(fs,CurrFile.FileSize); finally fd.Free; fs.Free; end; except Result := False; end; Result := True; end; Destructor TAlxFileMergeStr.Destroy; begin if FFileList <> nil then FFileList := nil; inherited; end; procedure TAlxFileMergeStr.ExtractAll(DirDest: String); var i: Integer; fs, fd: TFileStream; begin if FFileCount = 0 then exit; if DirDest = '' then exit; if DirDest[Length(DirDest)] <> '\' then DirDest := DirDest + '\'; ForceDirectories(DirDest); try fs := TFileStream.Create(FFileName,fmOpenRead); i := 0; While i <= FFileCount-1 do begin try ForceDirectories(ExtractFileDir(DirDest+FFileList[i].FileName)); fd := TFileStream.Create(DirDest+FFileList[i].FileName,fmCreate); fs.Seek(FFileList[i].FileBegin,soFromBeginning); fd.CopyFrom(fs,FFileList[i].FileSize); inc(i); finally fd.Free; end; end; finally fs.Free; end; end; procedure TAlxFileMergeStr.AddFromDir(DirDest: String; DirName: String = ''); var sr: TSearchRec; begin if DirDest = '' then exit; if DirDest[Length(DirDest)] <> '\' then DirDest := DirDest + '\'; if (DirName <> '') AND (DirName[Length(DirName)] <> '\') then DirName := DirName + '\'; if FindFirst(DirDest+'*.*', faAnyFile, sr) = 0 then begin repeat if (sr.Attr AND faDirectory) = 0 then Add(DirDest+sr.Name, DirName); until FindNext(sr) <> 0; FindClose(sr); end; end; procedure TAlxFileMergeStr.Delete; var i, FCountTemp, ln: Integer; temp: Integer; Dir, FlName: String; D, M, Y, Ch, Mi, S, Ss: Word; fs, fd: TFileStream; begin if FFileCount = 0 then exit; FCountTemp := FFileCount-1; if FCountTemp = 0 then begin if FIsAutoDelEmpty then DeleteFile(FFileName) else begin fs := TFileStream.Create(FFileName,fmCreate); fs.Free; end; CurrFile.FileNo := 0; CurrFile.FileBegin := 0; CurrFile.FileSize := 0; FFileList := nil; FFileCount := 0; FItemIndex := -1; SetLength(FFileList,ArrayStep); FArrCount := ArrayStep; end; Dir := ExtractFilePath(FFileName); if Dir[Length(Dir)] <> '\' then Dir := Dir + '\'; DecodeDate(now(),Y,M,D); DecodeTime(now(),Ch,Mi,S,Ss); FlName := IntToStr(Y)+IntToStr(M)+IntToStr(D)+IntToStr(Ch)+IntToStr(Mi)+IntToStr(S)+IntToStr(Ss)+'.tmp'; fs := TFileStream.Create(FFileName,fmOpenRead); fd := TFileStream.Create(Dir+FlName,fmCreate); temp := AlxStr; fd.Write(temp,SizeOf(AlxStr)); fd.Write(FCountTemp,SizeOf(Integer)); i := 0; While i <= FFileCount-1 do begin if i = FItemIndex then begin inc(i); continue; end; fs.Seek(FFileList[i].FileBegin,soFromBeginning); WriteFlie(fs,fd); inc(i); end; fs.Free; fd.Free; DeleteFile(FFileName); RenameFile(Dir+FlName,FFileName); if FItemIndex = FFileCount-1 then begin Dec(FFileCount); if (FArrCount-FFileCount) >= ArrayStep then begin Dec(FArrCount,ArrayStep); SetLength(FFileList,FArrCount); end; end else begin i := FItemIndex+1; While i <= FFileCount-1 do begin FFileList[i-1] := FFileList[i]; inc(i); end; Dec(FFileCount); if (FArrCount-FFileCount) >= ArrayStep then begin Dec(FArrCount,ArrayStep); SetLength(FFileList,FArrCount); end; end; FItemIndex := 0; CurrFile := FFileList[FItemIndex]; end; procedure TAlxFileMergeStr.Delete(FName: String); var i: Integer; res: Boolean; begin Res := False; if CurrFile.FileName <> FName then begin i := 0; While i <= FFileCount-1 do begin if FFileList[i].FileName = FName then begin SetItemIndex(i); Res := True; Break; end; inc(i); end; end else Res := True; if Res then Delete; end; end.
unit ListGoods; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorDialog, Vcl.ActnList, dsdAction, System.DateUtils, cxClasses, cxPropertiesStore, dsdAddOn, cxGraphics, cxControls, Math, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxTextEdit, Vcl.ExtCtrls, dsdGuides, dsdDB, cxMaskEdit, cxButtonEdit, AncestorBase, dxSkinsCore, dxSkinsDefaultPainters, Data.DB, cxStyles, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, Datasnap.DBClient, cxGridLevel, cxGridCustomView, cxGrid, cxCurrencyEdit, Vcl.ComCtrls, cxCheckBox, cxBlobEdit, dxSkinsdxBarPainter, dxBarExtItems, dxBar, cxNavigator, cxDataControllerConditionalFormattingRulesManagerDialog, DataModul, System.Actions, dxDateRanges, IniUtils; type TListGoodsForm = class(TAncestorBaseForm) ListGoodsGrid: TcxGrid; ListGoodsGridDBTableView: TcxGridDBTableView; ListGoodsGridLevel: TcxGridLevel; ListGoodsDS: TDataSource; colGoodsCode: TcxGridDBColumn; colGoodsName: TcxGridDBColumn; colPrice: TcxGridDBColumn; ListGoodsCDS: TClientDataSet; Timer1: TTimer; pnl1: TPanel; edt1: TEdit; ProgressBar1: TProgressBar; actListDiffAddGoods: TAction; ListDiffDS: TDataSource; ListDiffCDS: TClientDataSet; ListDiffGrid: TcxGrid; ListDiffGridDBTableView: TcxGridDBTableView; colIsSend: TcxGridDBColumn; colCode: TcxGridDBColumn; colName: TcxGridDBColumn; colAmount: TcxGridDBColumn; colPriceDiff: TcxGridDBColumn; colComment: TcxGridDBColumn; colDateInput: TcxGridDBColumn; colUserName: TcxGridDBColumn; ListDiffGridLevel: TcxGridLevel; colAmoutDayUser: TcxGridDBColumn; ListlDiffNoSendCDS: TClientDataSet; colId: TcxGridDBColumn; colAmountDiffPrev: TcxGridDBColumn; colAmountDiff: TcxGridDBColumn; spSelect_CashListDiff: TdsdStoredProc; CashListDiffCDS: TClientDataSet; pnlLocal: TPanel; ListlDiffNoSendCDSID: TIntegerField; ListlDiffNoSendCDSAmoutDiffUser: TCurrencyField; ListlDiffNoSendCDSAmoutDiff: TCurrencyField; ListlDiffNoSendCDSAmountDiffPrev: TCurrencyField; colGoodsNDS: TcxGridDBColumn; colJuridicalPrice: TcxGridDBColumn; colMarginPercent: TcxGridDBColumn; colExpirationDate: TcxGridDBColumn; colIsClose: TcxGridDBColumn; colisFirst: TcxGridDBColumn; colisSecond: TcxGridDBColumn; colJuridicalName: TcxGridDBColumn; colDiffKindId: TcxGridDBColumn; DiffKindCDS: TClientDataSet; actSearchGoods: TdsdOpenForm; BarManager: TdxBarManager; Bar: TdxBar; bbRefresh: TdxBarButton; dxBarStatic: TdxBarStatic; bbGridToExcel: TdxBarButton; bbOpen: TdxBarButton; colContractName: TcxGridDBColumn; colAreaName: TcxGridDBColumn; colisResolution_224: TcxGridDBColumn; colPriceOOC1303: TcxGridDBColumn; colMinimumLot: TcxGridDBColumn; procedure ParentFormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure edt1Exit(Sender: TObject); procedure edt1Change(Sender: TObject); procedure colGoodsNameCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); procedure actListDiffAddGoodsExecute(Sender: TObject); procedure ParentFormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ListGoodsGridDBTableViewDblClick(Sender: TObject); procedure ListGoodsGridDBTableViewFocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure colDiffKindIdGetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: string); procedure mmSearchGoodsClick(Sender: TObject); procedure ListGoodsGridDBTableViewStylesGetContentStyle( Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem; var AStyle: TcxStyle); procedure ParentFormDestroy(Sender: TObject); private { Private declarations } FOldStr : String; FStyle: TcxStyle; procedure FilterRecord(DataSet: TDataSet; var Accept: Boolean); public procedure SetFilter(AText : string); procedure FillingListGoodsCDS(AReLoad : boolean); procedure FillingListlDiffNoSendCDS; end; implementation {$R *.dfm} uses LocalWorkUnit, CommonData, ListDiff, ListDiffAddGoods, MainCash2; procedure TListGoodsForm.FilterRecord(DataSet: TDataSet; var Accept: Boolean); Var S,S1:String; k:integer; F:Boolean; begin S1 := Trim(FOldStr); if S1 = '' then exit; Accept:=true; if ListGoodsCDS.FieldCount < 2 then exit; repeat k:=pos(' ',S1); if K = 0 then k:=length(S1)+1; s := Trim(copy(S1,1,k-1)); S1 := Trim(copy(S1,k,Length(S1))); F := Pos(AnsiUpperCase(s), AnsiUpperCase(DataSet.FieldByName('GoodsName').AsString)) > 0; Accept:=Accept AND F; until (S1='') or (Accept = False); end; procedure TListGoodsForm.ListGoodsGridDBTableViewDblClick(Sender: TObject); begin actListDiffAddGoodsExecute(Sender); end; procedure TListGoodsForm.ListGoodsGridDBTableViewFocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin if not ListDiffCDS.Active then Exit; if not ListGoodsCDS.Eof then ListDiffCDS.Filter := 'Id = ' + ListGoodsCDS.FieldByName('Id').AsString else ListDiffCDS.Filter := 'Id = 0'; end; procedure TListGoodsForm.ListGoodsGridDBTableViewStylesGetContentStyle( Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem; var AStyle: TcxStyle); begin FStyle.Assign(dmMain.cxContentStyle); if (ARecord.Values[colExpirationDate.Index] <> Null) and ((ARecord.Values[colExpirationDate.Index]) < IncYear(Date, 1)) then FStyle.TextColor := clRed; if (ARecord.Values[colPriceOOC1303.Index] <> Null) and (ARecord.Values[colPriceOOC1303.Index] < ARecord.Values[colJuridicalPrice.Index]) and ((ARecord.Values[colJuridicalPrice.Index]/ARecord.Values[colPriceOOC1303.Index] * 100.0 - 100) > MainCashForm.UnitConfigCDS.FindField('DeviationsPrice1303').AsCurrency) then FStyle.Color := TColor($0083D3FA); AStyle := FStyle; end; procedure TListGoodsForm.mmSearchGoodsClick(Sender: TObject); var i : Integer; begin if actSearchGoods.Execute then begin for i := 0 to Screen.ActiveForm.ComponentCount - 1 do if Screen.ActiveForm.Components[I].Name = 'edGoodsSearch' then begin if edt1.Text = '' then begin if not ListGoodsCDS.IsEmpty then TcxTextEdit(Screen.ActiveForm.Components[I]).Text := ListGoodsCDS.FieldByName('GoodsName').AsString; end else TcxTextEdit(Screen.ActiveForm.Components[I]).Text := edt1.Text; end; for i := 0 to Screen.ActiveForm.ComponentCount - 1 do if Screen.ActiveForm.Components[I].Name = 'actRefreshSearch' then begin TdsdExecStoredProc(Screen.ActiveForm.Components[I]).Execute; end; end; end; procedure TListGoodsForm.actListDiffAddGoodsExecute(Sender: TObject); var S: String; nCount : currency; nPos : integer; begin if not ListGoodsCDS.Active then Exit; if ListGoodsCDS.RecordCount < 1 then Exit; with TListDiffAddGoodsForm.Create(nil) do try Price := Self.ListGoodsCDS.FieldByName('Price').AsCurrency; NDS := Self.ListGoodsCDS.FieldByName('NDS').AsCurrency; MCSValue := Self.ListGoodsCDS.FieldByName('MCSValue').AsCurrency; NDSKindId := Self.ListGoodsCDS.FieldByName('NDSKindId').AsInteger; GoodsId := Self.ListGoodsCDS.FieldByName('Id').AsInteger; GoodsCode := Self.ListGoodsCDS.FieldByName('GoodsCode').AsInteger; GoodsName := Self.ListGoodsCDS.FieldByName('GoodsName').AsString; if ShowModal <> mrOk then Exit; finally Free; end; try ListGoodsCDS.DisableControls; ListDiffCDS.Filtered := False; nPos := ListGoodsCDS.RecNo; while ListlDiffNoSendCDS.RecordCount > 0 do ListlDiffNoSendCDS.Delete; FillingListGoodsCDS(True); FillingListlDiffNoSendCDS; finally ListGoodsCDS.RecNo := nPos; ListGoodsCDS.EnableControls; end; if ListDiffCDS.Active then begin ListDiffCDS.Filter := 'Id = ' + ListGoodsCDS.FieldByName('Id').AsString; ListDiffCDS.Filtered := True; end; end; procedure TListGoodsForm.colDiffKindIdGetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: string); var I : Integer; begin if not TryStrToInt(AText, I) then Exit; if not DiffKindCDS.Active then Exit; if DiffKindCDS.Locate('id', I, []) then AText := DiffKindCDS.FieldByName('Name').AsString; end; procedure TListGoodsForm.colGoodsNameCustomDrawCell( Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); var S,S1:string; k: Integer; OldColor:TColor; AText:string; begin S1:=FOldStr; if S1 = '' then exit; AText:=AViewInfo.GridRecord.Values[AViewInfo.Item.Index]; ACanvas.FillRect(AViewInfo.Bounds); ACanvas.TextOut(AViewInfo.Bounds.Left+2,AViewInfo.Bounds.Top+2, AText); repeat k:=pos(' ',S1); if K = 0 then k:=length(S1)+1; s:=copy(S1,1,k-1); delete(S1,1,k); K:=pos(AnsiUpperCase(S),AnsiUpperCase(AText)); if K <> 0 then Begin s:=copy(AText,k,length(s)); OldColor:=ACanvas.Font.Color; ACanvas.Font.Color:=clRed; ACanvas.Font.Style := ACanvas.Font.Style + [fsUnderline]; ACanvas.TextOut(AViewInfo.Bounds.Left+ACanvas.TextWidth(copy(AText,1,K-1))+1,AViewInfo.Bounds.Top+2,S); ACanvas.Font.Style := ACanvas.Font.Style - [fsUnderline]; ACanvas.Font.Color:=OldColor; End; until S1=''; ADone:= True; end; procedure TListGoodsForm.edt1Change(Sender: TObject); begin if Trim(Edt1.text)=FOldStr then exit; FOldStr:=Trim(Edt1.text); Timer1.Enabled:=False; Timer1.Interval:=100; Timer1.Enabled:=True; ProgressBar1.Position:=0; ProgressBar1.Visible:=True; end; procedure TListGoodsForm.edt1Exit(Sender: TObject); begin Timer1.Enabled:=False; ProgressBar1.Position:=0; ProgressBar1.Visible:=False; ListGoodsCDS.DisableControls; try ListGoodsCDS.Filtered:=False; ListGoodsCDS.OnFilterRecord:=Nil; if FOldStr <> '' then begin ListGoodsCDS.OnFilterRecord:=FilterRecord; ListGoodsCDS.Filtered:=True; end; ListGoodsCDS.First; finally ListGoodsCDS.EnableControls end; end; procedure TListGoodsForm.ParentFormCreate(Sender: TObject); procedure SaveLocalGoods; var sp : TdsdStoredProc; ds : TClientDataSet; begin //+ // pr вызывается из обновления остатков // Проверяем обновляли ли сегодня if (MinutesBetween(iniLocalListGoodsDateGet, Now) < 15) then Exit; sp := TdsdStoredProc.Create(nil); try ds := TClientDataSet.Create(nil); try sp.OutputType := otDataSet; sp.DataSet := ds; sp.StoredProcName := 'gpSelect_CashGoods'; sp.Params.Clear; sp.Execute; Add_Log('Start MutexGoods'); WaitForSingleObject(MutexGoods, INFINITE); // только для формы2; защищаем так как есть в приложениее и сервисе try SaveLocalData(ds,Goods_lcl); iniLocalListGoodsDateSave; finally Add_Log('End MutexGoods'); ReleaseMutex(MutexGoods); end; finally ds.free; end; finally freeAndNil(sp); end; end; begin FStyle := TcxStyle.Create(nil); //Получение товаров if not gc_User.Local then SaveLocalGoods; if not gc_User.Local then begin try if CashListDiffCDS.Active then CashListDiffCDS.Close; spSelect_CashListDiff.Execute; except pnlLocal.Visible := True; end; end else pnlLocal.Visible := True; Bar.Visible := not pnlLocal.Visible; while ListlDiffNoSendCDS.RecordCount > 0 do ListlDiffNoSendCDS.Delete; WaitForSingleObject(MutexGoods, INFINITE); try LoadLocalData(ListGoodsCDS, Goods_lcl); if not ListGoodsCDS.Active then ListGoodsCDS.Open; finally ReleaseMutex(MutexGoods); end; try ListGoodsCDS.DisableControls; FillingListGoodsCDS(False); finally ListGoodsCDS.EnableControls; end; WaitForSingleObject(MutexDiffKind, INFINITE); try LoadLocalData(DiffKindCDS,DiffKind_lcl); finally ReleaseMutex(MutexDiffKind); end; WaitForSingleObject(MutexDiffCDS, INFINITE); try CheckListDiffCDS; ListDiffCDS.Filtered := False; if not ListDiffCDS.Active then begin CheckListDiffCDS; LoadLocalData(ListDiffCDS, ListDiff_lcl); end; FillingListlDiffNoSendCDS; finally ReleaseMutex(MutexDiffCDS); end; if ListDiffCDS.Active then begin ListDiffCDS.Filter := 'Id = ' + ListGoodsCDS.FieldByName('Id').AsString; ListDiffCDS.Filtered := True; end; FOldStr := ''; end; procedure TListGoodsForm.ParentFormDestroy(Sender: TObject); begin inherited; FStyle.Free; end; procedure TListGoodsForm.ParentFormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_Return) and (ActiveControl = edt1) then begin Key := 0; ListGoodsGrid.SetFocus; end else if (Key = VK_ADD) or (Key = VK_Return) then Begin Key := 0; actListDiffAddGoodsExecute(Sender); End; end; procedure TListGoodsForm.SetFilter(AText : string); begin edt1.Text := AText; FOldStr := AText; edt1Exit(Nil); edt1.SelStart := Length(AText); end; procedure TListGoodsForm.FillingListGoodsCDS(AReLoad : boolean); begin if AReLoad and not pnlLocal.Visible then try if CashListDiffCDS.Active then CashListDiffCDS.Close; spSelect_CashListDiff.Execute; pnlLocal.Visible := False; except pnlLocal.Visible := True; end; WaitForSingleObject(MutexDiffCDS, INFINITE); try LoadLocalData(ListDiffCDS, ListDiff_lcl); if not ListDiffCDS.Active then begin CheckListDiffCDS; LoadLocalData(ListDiffCDS, ListDiff_lcl); end; finally ReleaseMutex(MutexDiffCDS); end; if not CashListDiffCDS.Active then Exit; CashListDiffCDS.First; while not CashListDiffCDS.Eof do begin if not ListlDiffNoSendCDS.Locate('Id', CashListDiffCDS.FieldByName('Id').AsInteger, []) then begin ListlDiffNoSendCDS.Append; ListlDiffNoSendCDS.FieldByName('Id').AsInteger := CashListDiffCDS.FieldByName('Id').AsInteger; end else ListlDiffNoSendCDS.Edit; ListlDiffNoSendCDS.FieldByName('AmoutDiffUser').AsCurrency := ListlDiffNoSendCDS.FieldByName('AmoutDiffUser').AsCurrency + CashListDiffCDS.FieldByName('AmountDiffUser').AsCurrency; ListlDiffNoSendCDS.FieldByName('AmoutDiff').AsCurrency := ListlDiffNoSendCDS.FieldByName('AmoutDiff').AsCurrency + CashListDiffCDS.FieldByName('AmountDiff').AsCurrency; ListlDiffNoSendCDS.FieldByName('AmountDiffPrev').AsCurrency := ListlDiffNoSendCDS.FieldByName('AmountDiffPrev').AsCurrency + CashListDiffCDS.FieldByName('AmountDiffPrev').AsCurrency; ListlDiffNoSendCDS.Post; CashListDiffCDS.Next; end; ListlDiffNoSendCDS.First; while not ListlDiffNoSendCDS.Eof do begin if ListGoodsCDS.Locate('Id', ListlDiffNoSendCDS.FieldByName('Id').AsInteger, []) then begin ListGoodsCDS.Edit; ListGoodsCDS.FieldByName('AmoutDiffUser').AsCurrency := ListlDiffNoSendCDS.FieldByName('AmoutDiffUser').AsCurrency; ListGoodsCDS.FieldByName('AmoutDiff').AsCurrency := ListlDiffNoSendCDS.FieldByName('AmoutDiff').AsCurrency; ListGoodsCDS.FieldByName('AmountDiffPrev').AsCurrency := ListlDiffNoSendCDS.FieldByName('AmountDiffPrev').AsCurrency; ListGoodsCDS.Post; end; ListlDiffNoSendCDS.Next; end; end; procedure TListGoodsForm.FillingListlDiffNoSendCDS; begin if not ListDiffCDS.Active then Exit; ListDiffCDS.First; while not ListDiffCDS.Eof do begin if (StartOfTheDay(ListDiffCDS.FieldByName('DateInput').AsDateTime) = Date) and (not CashListDiffCDS.Active or not ListDiffCDS.FieldByName('IsSend').AsBoolean) then begin if not ListlDiffNoSendCDS.Locate('Id', ListDiffCDS.FieldByName('Id').AsInteger, []) then begin ListlDiffNoSendCDS.Append; ListlDiffNoSendCDS.FieldByName('Id').AsInteger := ListDiffCDS.FieldByName('Id').AsInteger; end else ListlDiffNoSendCDS.Edit; if (ListDiffCDS.FieldByName('UserID').AsString = gc_User.Session) and (StartOfTheDay(ListDiffCDS.FieldByName('DateInput').AsDateTime) = Date) then ListlDiffNoSendCDS.FieldByName('AmoutDiffUser').AsCurrency := ListlDiffNoSendCDS.FieldByName('AmoutDiffUser').AsCurrency + ListDiffCDS.FieldByName('Amount').AsCurrency; if (StartOfTheDay(ListDiffCDS.FieldByName('DateInput').AsDateTime) = Date) then ListlDiffNoSendCDS.FieldByName('AmoutDiff').AsCurrency := ListlDiffNoSendCDS.FieldByName('AmoutDiff').AsCurrency + ListDiffCDS.FieldByName('Amount').AsCurrency; if (StartOfTheDay(ListDiffCDS.FieldByName('DateInput').AsDateTime) = IncDay(Date, - 1)) then ListlDiffNoSendCDS.FieldByName('AmountDiffPrev').AsCurrency := ListlDiffNoSendCDS.FieldByName('AmountDiffPrev').AsCurrency + ListDiffCDS.FieldByName('Amount').AsCurrency; ListlDiffNoSendCDS.Post; end; ListDiffCDS.Next; end; end; procedure TListGoodsForm.Timer1Timer(Sender: TObject); begin Timer1.Enabled:=False; Timer1.Enabled:=True; ProgressBar1.Position:=ProgressBar1.Position+10; if ProgressBar1.Position=100 then edt1Exit(Sender); end; End.
unit Structs; interface uses Windows, Graphics, SysUtils, Messages; const MESS_REPAINT_VIEW_OK = WM_USER+1; dURightToLeft = 0; dURightSnake = 1; dULeftToRight = 2; dULeftSnake = 3; dLUpToDown = 4; dLUpSnake = 5; dLDownToUp = 6; dLDownSnake = 7; dDLeftToRight = 8; dDLeftSnake = 9; dDRightToLeft = 10; dDRightSnake = 11; dRDownToUp = 12; dRDownSnake = 13; dRUpToDown = 14; dRUpSnake = 15; SizeChipMax = 200; NotSpec: Single=987654321.0; type TOnPaintWafer = procedure(Max: WORD) of object; // Событие - пластина загружена TOnDataTransmit = procedure of object; // Событие - загружаются парамнтры кристаллов TOnChipDlgClose = procedure of object; // Событие - закрытие диалога параметров кристалла ///////////////////////////////////////// TColorParams = packed record Num: WORD; Min: Single; Max: Single; Col: TColor; end; ///////////////////////////////////////// TCadre = record StartX: WORD; StartY: WORD; ScaleX: WORD; ScaleY: WORD; end; ///////////////////////////////////////// TDynArray = array of Single; TChipValues = TDynArray; TChip = packed record ID : DWORD; Status: WORD; Coord : TPoint; Value : TChipValues; ShowGr: WORD; end; PChip = ^TChip; TChips = array of array of TChip; ///////////////////////////////////////// TFail = record Status : WORD; Name : String[40]; Quantity: WORD; Col : TColor; end; TFails = array of TFail; ///////////////////////////////////////// TNorma = record Min: Single; Max: Single; end; TTestParams = record Name : String[40]; Norma : TNorma; Status: WORD; end; TTestsParams = array of TTestParams; PTestsParams = ^TTestsParams; ///////////////////////////////////////// TQuantity = record OK : WORD; Fail: WORD; Meas: Boolean; end; TPD = array of array of TQuantity; ///////////////////////////////////////// TEdgeCoords = record X1: Single; Y1: Single; X2: Single; Y2: Single; X3: Single; Y3: Single; end; ///////////////////////////////////////// var VersionStr: String; deltaW7: byte=0; // Смещение для WinVista, Win7 clRepper : TColor=clPurple; clMRepper : TColor=clFuchsia; clNotTested : TColor=clWhite; clNot4Testing: TColor=clSilver; cl4Mark : TColor=$00000040;//clMaroon; clNotChip : TColor=clGray; clOK : TColor=clLime; clFailNC : TColor=clBlack; clFailSC : TColor=clRed; clFailFC : TColor=clBlue; clBaseChip : TColor=clAqua; clCurChip : TColor=clYellow; function IsChip (const Status: WORD): Boolean; function IsFailChip(const Status: WORD): Boolean; function EqualStatus(const Status1, Status2 : WORD): Boolean; function GetMainColor(const Status: WORD): TColor; function GetPrnColor(const Status: WORD): TColor; function GetStatusString(const Status: WORD): String; function GetWinName: String; procedure ErrMess(Handle: THandle; const ErrMes: String); function QuestMess(Handle: THandle; const QStr: String): Integer; implementation //////////////////////////////////////////////////// function IsChip(const Status: WORD): Boolean; // begin // Result := False; // // case Status of // 0 : Result := True; // 1 : Result := True; // 2 : ; // 3 : ; // 4 : Result := True; // 5 : ; // 7 : Result := True; // 10..1500 : Result := True; // 2000..3000: Result := True; // 3500..4500: Result := True; // end; // end; // //////////////////////////////////////////////////// //////////////////////////////////////////////////// function IsFailChip(const Status: WORD): Boolean; // begin // Result := False; // // case Status of // 0 : ; // 1 : ; // 2 : ; // 3 : ; // 4 : ; // 5 : ; // 7 : ; // 10..1500 : Result := True; // 2000..3000: Result := True; // 3500..4500: Result := True; // end; // end; // //////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// function EqualStatus(const Status1, Status2 : WORD): Boolean; // begin // Result := False; // // if Status1 = Status2 then Result := True // else // if IsFailChip(Status1) and IsFailChip(Status1) then Result := True; // end; // ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////// function GetMainColor(const Status: WORD): TColor; // begin // case Status of // 0 : Result := clNotTested; // 1 : Result := clOK; // 2 : Result := clNotChip; // 3 : Result := clNot4Testing; // 4 : Result := cl4Mark; // 5 : Result := clRepper; // 7 : Result := clMRepper; // 10..1500 : Result := clFailNC; // 2000..3000: Result := clFailSC; // 3500..4500: Result := clFailFC; // else Result := clGray; // end; // end; // ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// function GetPrnColor(const Status: WORD): TColor; // begin // case Status of // 0 : Result := clWhite; // 1 : Result := clWhite; // 2 : Result := clWhite; // 3 : Result := clWhite; // 4 : Result := clBlack; // 5 : Result := clBlack; // 7 : Result := clBlack; // 10..1500 : Result := clBlack; // 2000..3000: Result := clSilver; // 3500..4500: Result := clGray; // else Result := clWhite; // end; // end; // ///////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// function GetStatusString(const Status: WORD): String; // begin // case Status of // 0 : Result := 'Ошибка'; // 1 : Result := 'Кристалл годен'; // 2 : Result := 'Ошибка'; // 3 : Result := 'Ошибка'; // 4 : Result := 'Принудильно маркированный'; // 5 : Result := 'Репер'; // 7 : Result := 'Репер'; // 10..1500 : Result := 'Неконтакт на выводе '+IntToStr(Status-9); // 2000..3000: Result := 'Брак СК'+IntToStr(Status-1999); // 3500..4500: Result := 'Брак ФК'+IntToStr(Status-3499); // else Result := 'Ошибка'; // end; // end; // /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// function GetWinName: String; // var // lpVersionInformation: TOSVersionInfo; // begin // Result := 'Неопределена'; // // lpVersionInformation.dwOSVersionInfoSize := SizeOf(TOSVersionInfo); // if GetVersionEx(lpVersionInformation) then // with lpVersionInformation do // case DwMajorVersion of // 3: if dwMinorVersion = 51 then Result := 'Windows NT 3.51'; // // 4: case dwMinorVersion of // 0 : if dwPlatformId = VER_PLATFORM_WIN32_NT then Result := 'Windows NT 4.0' // else Result := 'Windows 95'; // 10: Result := 'Windows 98'; // 90: Result := 'Windows ME'; // end; // // 5: case dwMinorVersion of // 0: Result := 'Windows 2000'; // 1: Result := 'Windows XP'; // 2: Result := 'Windows 2003'; // end; // // 6: case dwMinorVersion of // 0: Result := 'Windows Vista'; // 1: Result := 'Windows 7'; // end; // end; // end; // /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// procedure ErrMess(Handle: THandle; const ErrMes: String); // begin // MessageBox(Handle, PChar(ErrMes), 'Ошибка!!!', MB_ICONERROR+MB_OK); // end; // /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// function QuestMess(Handle: THandle; const QStr: String): Integer; // begin // Result := MessageBox(Handle, PChar(Qstr), 'Подтверждение!', MB_ICONQUESTION+MB_YESNO); // end; // /////////////////////////////////////////////////////////////////////////////////////////// end.
program mapansi; {$IFNDEF HASAMIGA} {$FATAL This source is compatible with Amiga, AROS and MorphOS only !} {$ENDIF} { Project : mapansi Topic : converts a string to input events using MapANSI() function. Source : RKRM } { This example will also take the created input events and add them to the input stream using the simple commodities.library function AddIEvents(). Alternately, you could open the input.device and use the input device command IND_WRITEEVENT to add events to the input stream. } {$MODE OBJFPC}{$H+}{$HINTS ON} {$UNITPATH ../../../Base/CHelpers} {$UNITPATH ../../../Base/Trinity} {$IFDEF AMIGA} {$UNITPATH ../../../Sys/Amiga} {$ENDIF} {$IFDEF AROS} {$UNITPATH ../../../Sys/AROS} {$ENDIF} {$IFDEF MORPHOS} {$UNITPATH ../../../Sys/MorphOS} {$ENDIF} Uses Exec, AmigaDos, InputEvent, KeyMap, Commodities, Trinity; var InputEvt : PInputEvent = nil; //* we'll allocate this */ //* prototypes for our program functions */ procedure openall; forward; procedure closeall; forward; procedure closeout(errstring: PChar; rc: LONG); forward; function Main(argc: Integer; argv: PPChar): Integer; var str : PChar; tmp1 : PChar; tmp2 : PChar; iebuffer : array[0..Pred(6)] of Char; //* Space for two dead keys */ //* + 1 key + qualifiers */ i : Integer; rc : LONG = 0; begin openall(); str := ';String converted to input events and sent to input device' + LineEnding; InputEvt^.ie_Class := IECLASS_RAWKEY; //* Turn each character into an InputEvent */ tmp1 := str; while (tmp1^ <> #0) do begin //* Convert one character, use default key map */ {$IFDEF MORPHOS} i := KeyMap.MapANSI(PShortInt(tmp1), 1, @iebuffer, 3, nil); {$ELSE} i := KeyMap.MapANSI(tmp1, 1, @iebuffer, 3, nil); {$ENDIF} //* Make sure we start without deadkeys */ InputEvt^.ie_position.ie_dead.ie_Prev1DownCode := 0; InputEvt^.ie_position.ie_dead.ie_Prev1DownQual := 0; InputEvt^.ie_position.ie_dead.ie_Prev2DownCode := 0; InputEvt^.ie_position.ie_dead.ie_Prev2DownQual := 0; tmp2 := iebuffer; case (i) of -2: begin WriteLn('Internal error'); rc := RETURN_FAIL; end; -1: begin WriteLn('Overflow'); rc := RETURN_FAIL; end; 0: begin WriteLn('Can''t generate code'); end; 3,2,1: begin If (i = 3) then begin InputEvt^.ie_position.ie_dead.ie_Prev2DownCode := UBYTE(tmp2^); inc(tmp2); InputEvt^.ie_position.ie_dead.ie_Prev2DownQual := UBYTE(tmp2^); inc(tmp2); end; if ((i = 3) or (i = 2)) then begin InputEvt^.ie_position.ie_dead.ie_Prev1DownCode := UBYTE(tmp2^); inc(tmp2); InputEvt^.ie_position.ie_dead.ie_Prev1DownQual := UBYTE(tmp2^); inc(tmp2); end; if ((i = 3) or (i = 2) or (i = 1)) then begin InputEvt^.ie_Code := UBYTE(tmp2^); inc(tmp2); InputEvt^.ie_Qualifier := UBYTE(tmp2^); end; end; end; if (rc = RETURN_OK) then begin //* Send the key down event */ AddIEvents(InputEvt); //* Create a key up event */ InputEvt^.ie_Code := InputEvt^.ie_Code or IECODE_UP_PREFIX; //* Send the key up event */ AddIEvents(InputEvt); end; if (rc <> RETURN_OK) then break; inc(tmp1); end; closeall(); result := (rc); end; procedure openall; begin {$IF DEFINED(AMIGA) or DEFINED(MORPHOS)} KeymapBase := OpenLibrary('keymap.library', 37); if (KeymapBase = nil) then closeout('Kickstart 2.0 required', RETURN_FAIL); {$ENDIF} {$IF DEFINED(AMIGA) or DEFINED(MORPHOS)} CxBase := OpenLibrary('commodities.library', 37); if (CxBase = nil) then closeout('Kickstart 2.0 required', RETURN_FAIL); {$ENDIF} InputEvt := ExecAllocMem(sizeof(TInputEvent), MEMF_CLEAR); if (InputEvt = nil) then closeout('Can''t allocate input event', RETURN_FAIL); end; procedure closeall; begin if assigned(InputEvt) then ExecFreeMem(InputEvt, sizeof(TInputEvent)); {$IF DEFINED(AMIGA) or DEFINED(MORPHOS)} if assigned(CxBase) then CloseLibrary(CxBase); {$ENDIF} {$IF DEFINED(AMIGA) or DEFINED(MORPHOS)} if assigned(KeymapBase) then CloseLibrary(KeymapBase); {$ENDIF} end; procedure closeout(errstring: PChar; rc: LONG); begin if (errstring^ <> #0) then WriteLn(errstring); closeall; halt(rc); end; begin ExitCode := Main(ArgC, ArgV); end.
unit InfoMoneyDestinationTest; interface uses dbTest, dbObjectTest, TestFramework, ObjectTest; type TInfoMoneyDestinationTest = class(TdbObjectTestNew) published procedure ProcedureLoad; override; procedure Test; override; end; TInfoMoneyDestination = class(TObjectTest) function InsertDefault: integer; override; public function InsertUpdateInfoMoneyDestination(const Id, Code: Integer; Name: string): integer; constructor Create; override; end; implementation uses ZDbcIntfs, SysUtils, Storage, DBClient, XMLDoc, CommonData, Forms, UtilConvert, UtilConst, ZLibEx, zLibUtil, JuridicalTest, DB; { TInfoMoneyDestinationTest } constructor TInfoMoneyDestination.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Object_InfoMoneyDestination'; spSelect := 'gpSelect_Object_InfoMoneyDestination'; spGet := 'gpGet_Object_InfoMoneyDestination'; end; function TInfoMoneyDestination.InsertDefault: integer; begin result := InsertUpdateInfoMoneyDestination(0, -1, 'Управленческие аналитики - назначение'); inherited; end; function TInfoMoneyDestination.InsertUpdateInfoMoneyDestination(const Id, Code: Integer; Name: string): integer; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inCode', ftInteger, ptInput, Code); FParams.AddParam('inName', ftString, ptInput, Name); result := InsertUpdate(FParams); end; procedure TInfoMoneyDestinationTest.ProcedureLoad; begin ScriptDirectory := ProcedurePath + 'OBJECTS\InfoMoneyDestination\'; inherited; end; procedure TInfoMoneyDestinationTest.Test; var Id: integer; RecordCount: Integer; ObjectTest: TInfoMoneyDestination; begin ObjectTest := TInfoMoneyDestination.Create; // Получим список RecordCount := ObjectTest.GetDataSet.RecordCount; // Вставка группы урп.счетов Id := ObjectTest.InsertDefault; try // Получение данных with ObjectTest.GetRecord(Id) do Check((FieldByName('Name').AsString = 'Управленческие аналитики - назначение'), 'Не сходятся данные Id = ' + FieldByName('id').AsString); finally ObjectTest.Delete(Id); end; end; initialization TestFramework.RegisterTest('Объекты', TInfoMoneyDestinationTest.Suite); end.
unit u_LonLatRectByPoint; interface uses t_GeoTypes, i_LonLatRect; type TLonLatRectByPoint = class(TInterfacedObject, ILonLatRect) private FPoint: TDoublePoint; private function GetLeft: Double; function GetTop: Double; function GetRight: Double; function GetBottom: Double; function GetTopLeft: TDoublePoint; function GetBottomRight: TDoublePoint; function GetRect: TDoubleRect; function IsEqual(const ARect: TDoubleRect): Boolean; overload; function IsEqual(const ARect: ILonLatRect): Boolean; overload; function IsPointInRect(const APoint: TDoublePoint): Boolean; function UnionWithRect(const ARect: TDoubleRect): TDoubleRect; overload; function UnionWithRect(const ARect: ILonLatRect): TDoubleRect; overload; function IntersecWithRect( out AResultRect: TDoubleRect; const ARect: TDoubleRect ): Boolean; overload; function IntersecWithRect( out AResultRect: TDoubleRect; const ARect: ILonLatRect ): Boolean; overload; function IsIntersecWithRect(const ARect: TDoubleRect): Boolean; overload; function IsIntersecWithRect(const ARect: ILonLatRect): Boolean; overload; public constructor Create(const APoint: TDoublePoint); end; implementation uses Math, u_GeoFun; { TLonLatRectByPoint } constructor TLonLatRectByPoint.Create(const APoint: TDoublePoint); begin inherited Create; Assert(not IsNan(APoint.X)); Assert(not IsNan(APoint.Y)); FPoint := APoint; end; function TLonLatRectByPoint.GetBottom: Double; begin Result := FPoint.Y; end; function TLonLatRectByPoint.GetBottomRight: TDoublePoint; begin Result := FPoint; end; function TLonLatRectByPoint.GetLeft: Double; begin Result := FPoint.X; end; function TLonLatRectByPoint.GetRect: TDoubleRect; begin Result.TopLeft := FPoint; Result.BottomRight := FPoint; end; function TLonLatRectByPoint.GetRight: Double; begin Result := FPoint.X; end; function TLonLatRectByPoint.GetTop: Double; begin Result := FPoint.Y; end; function TLonLatRectByPoint.GetTopLeft: TDoublePoint; begin Result := FPoint; end; function TLonLatRectByPoint.IntersecWithRect(out AResultRect: TDoubleRect; const ARect: ILonLatRect): Boolean; begin Result := ARect.IsPointInRect(FPoint); if Result then begin AResultRect.TopLeft := FPoint; AResultRect.BottomRight := FPoint; end else begin FillChar(AResultRect, SizeOf(AResultRect), 0); end; end; function TLonLatRectByPoint.IntersecWithRect(out AResultRect: TDoubleRect; const ARect: TDoubleRect): Boolean; begin Result := (FPoint.X <= ARect.Right) and (FPoint.X >= ARect.Left) and (FPoint.Y <= ARect.Top) and (FPoint.Y >= ARect.Bottom); if Result then begin AResultRect.TopLeft := FPoint; AResultRect.BottomRight := FPoint; end else begin FillChar(AResultRect, SizeOf(AResultRect), 0); end; end; function TLonLatRectByPoint.IsEqual(const ARect: ILonLatRect): Boolean; var VRect: TDoubleRect; begin if ARect = nil then begin Result := False; end else if ILonLatRect(Self) = ARect then begin Result := True; end else begin VRect := ARect.Rect; Result := DoublePointsEqual(FPoint, VRect.TopLeft) and DoublePointsEqual(FPoint, VRect.BottomRight); end; end; function TLonLatRectByPoint.IsEqual(const ARect: TDoubleRect): Boolean; begin Result := DoublePointsEqual(FPoint, ARect.TopLeft) and DoublePointsEqual(FPoint, ARect.BottomRight); end; function TLonLatRectByPoint.IsIntersecWithRect( const ARect: TDoubleRect): Boolean; begin Result := (FPoint.X <= ARect.Right) and (FPoint.X >= ARect.Left) and (FPoint.Y <= ARect.Top) and (FPoint.Y >= ARect.Bottom); end; function TLonLatRectByPoint.IsIntersecWithRect( const ARect: ILonLatRect): Boolean; begin if ARect = nil then begin Result := False; end else if ILonLatRect(Self) = ARect then begin Result := True; end else begin Result := ARect.IsPointInRect(FPoint); end; end; function TLonLatRectByPoint.IsPointInRect(const APoint: TDoublePoint): Boolean; begin Result := DoublePointsEqual(FPoint, APoint); end; function TLonLatRectByPoint.UnionWithRect( const ARect: ILonLatRect): TDoubleRect; begin if ARect = nil then begin Result.TopLeft := FPoint; Result.BottomRight := FPoint; end else if ILonLatRect(Self) = ARect then begin Result.TopLeft := FPoint; Result.BottomRight := FPoint; end else begin Result := ARect.Rect; if Result.Left > FPoint.X then begin Result.Left := FPoint.X; end; if Result.Right < FPoint.X then begin Result.Right := FPoint.X; end; if Result.Top < FPoint.Y then begin Result.Top := FPoint.Y; end; if Result.Bottom > FPoint.Y then begin Result.Bottom := FPoint.Y; end; end; end; function TLonLatRectByPoint.UnionWithRect( const ARect: TDoubleRect): TDoubleRect; begin Result := ARect; if Result.Left > FPoint.X then begin Result.Left := FPoint.X; end; if Result.Right < FPoint.X then begin Result.Right := FPoint.X; end; if Result.Top < FPoint.Y then begin Result.Top := FPoint.Y; end; if Result.Bottom > FPoint.Y then begin Result.Bottom := FPoint.Y; end; end; end.
///* // * android-plugin-client-sdk-for-locale https://github.com/twofortyfouram/android-plugin-client-sdk-for-locale // * Copyright 2014 two forty four a.m. LLC // * // * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // * in compliance with the License. You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software distributed under the // * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // * express or implied. See the License for the specific language governing permissions and // * limitations under the License. // */ unit twofortyfouram.Locale.SDK.Client.UI.Activity.InfoActivity; interface //import android.app.Activity; //import android.content.Context; //import android.content.Intent; //import android.content.pm.PackageManager; //import android.net.Uri; //import android.os.Bundle; //import android.support.annotation.NonNull; //import android.support.annotation.Nullable; // //import com.twofortyfouram.locale.sdk.client.R; //import com.twofortyfouram.log.Lumberjack; // //import net.jcip.annotations.NotThreadSafe; // //import static com.twofortyfouram.assertion.Assertions.assertNotNull; // ///** // * If the user tries to launch the plug-in via the app store, // * this will redirect the user to a compatible host app on the device. If a // * compatible host does not exist, this directs the user to download the host // * from the app store. // */ //@NotThreadSafe //public final class InfoActivity extends Activity { // // @Override // public void onCreate(@Nullable final Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // final Intent i = getLaunchIntent(getApplicationContext(), getPackageManager(), // getPackageName()); // // try { // startActivity(i); // } catch (final Exception e) { // Lumberjack.e("Error starting Activity%s", e); //$NON-NLS-1$ // /* // * Catch generic exception to handle all sorts of cases that could // * cause crashes: ActivityNotFoundException, SecurityException, and // * who knows what else. // */ // } // // finish(); // } // // @NonNull // /* package */ static Intent getLaunchIntent(@NonNull final Context context, // @NonNull final PackageManager manager, // @NonNull final String myPackageName) { // assertNotNull(context, "context"); //$NON-NLS-1$ // assertNotNull(manager, "manager"); //$NON-NLS-1$ // assertNotNull(myPackageName, "myPackageName"); //$NON-NLS-1$ // // final String compatiblePackage // = com.twofortyfouram.locale.sdk.client.internal.HostPackageUtil // .getCompatiblePackage(manager, null); // if (null != compatiblePackage) { // final Intent i = manager.getLaunchIntentForPackage(compatiblePackage); // i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // return i; // } else { // return new Intent(Intent.ACTION_VIEW, Uri.parse(context.getString(R.string.com_twofortyfouram_locale_sdk_client_app_store_deep_link_format, // "com.twofortyfouram.locale", myPackageName // ))).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //$NON-NLS-1$ // } // } //} implementation end.
////////////////////////////////////////////////////////////////////////////////// // This source code is provided 'as-is', without any express or implied // // warranty. In no event will Infintuary be held liable for any damages // // arising from the use of this software. // // // // Infintuary does not warrant, that the source code will be free from // // defects in design or workmanship or that operation of the source code // // will be error-free. No implied or statutory warranty of merchantability // // or fitness for a particular purpose shall apply. The entire risk of // // quality and performance is with the user of this source code. // // // // Permission is granted to anyone to use this software for any purpose, // // including commercial applications, and to alter it and redistribute it // // freely, subject to the following restrictions: // // // // 1. The origin of this source code must not be misrepresented; you must // // not claim that you wrote the original source code. // // // // 2. Altered source versions must be plainly marked as such, and must not // // be misrepresented as being the original source code. // // // // 3. This notice may not be removed or altered from any source // // distribution. // ////////////////////////////////////////////////////////////////////////////////// unit MD_Label; // http://www.infintuary.org/stlabel.php (* Mildly bodged by Matthew Hipkin <https://www.matthewhipkin.co.uk> to work properly with Lazarus *) {$IFDEF FPC} {$MODE delphi} {$ELSE} {$DEFINE WINDOWS} {$ENDIF} interface uses {$IFDEF WINDOWS}Windows, Messages, {$ENDIF} {$IFDEF FPC} LMessages, {$ENDIF} SysUtils, Classes, Controls, Graphics; type TOnPaintBackground = procedure(Sender: TObject; Canvas: TCanvas; Width: Integer; Height: Integer) of object; TOnLinkClicked = procedure(Sender: TObject; LinkIndex: Integer; LinkText: WideString) of object; TOnGetLinkStyle = procedure(Sender: TObject; LinkIndex: Integer; LinkText: string; var FontNormal, FontHover: TFont) of object; TLink = class FLinkID: Integer; FLinkText: WideString; FLinkRef: WideString; FFont: TFont; FFontHover: TFont; constructor Create(ALinkID: Integer; LinkRef: string; AFont, AFontHover: TFont); destructor Destroy; override; end; TMDLabel = class (TCustomControl) private {$IFNDEF UNICODE} FCaptionW: WideString; FCaptionUTF8: UTF8String; {$ENDIF} FLinkFontNormal: TFont; FLinkFontHover: TFont; FAutoSizeWidth: Boolean; FAutoSizeHeight: Boolean; FTextAlignment: TAlignment; FCompressSpaces: Boolean; FTabWidth: Integer; FInitialized: Boolean; FTextHeight: Integer; FMaxWidth: Integer; FLastID: Integer; FDefaultCursor: TCursor; FParsingText: Boolean; FBuildingLines: Boolean; FRebuildLines: Boolean; FOnHeightChanged: TNotifyEvent; FOnWidthChanged: TNotifyEvent; FOnPaintBackground: TOnPaintBackground; FOnLinkClicked: TOnLinkClicked; FOnGetLinkStyle: TOnGetLinkStyle; FOnMouseLeave: TNotifyEvent; FLines: TList; FWords: TList; FLinkRCs: TList; FLinkList: TList; FMouseDownMove: Boolean; FMouseDownIndex: Integer; FMouseWasDown: Boolean; {$IFNDEF UNICODE} procedure SetCaptionW(Value: WideString); procedure SetCaptionUTF8(Value: UTF8String); {$ENDIF} procedure SetAutoSizeWidth(Value: Boolean); procedure SetAutoSizeHeight(Value: Boolean); procedure SetTextAlignment(Value: TAlignment); procedure SetCompressSpaces(Value: Boolean); procedure SetTabWidth(Value: Integer); procedure SetMaxWidth(Value: Integer); procedure WMEraseBkgnd(var Msg: TWmEraseBkgnd); message WM_ERASEBKGND; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure DoFontChange(Sender: TObject); function TextHeightW(ws: WideString): Integer; function TextWidthW(ws: WideString): Integer; procedure TextSizeW(ws: WideString; out RC: TRect); procedure SetFont(Index: Integer; Value: TFont); procedure SetHeight(Value: Integer); function IsMouseOverLink(LinkID: Integer): Boolean; procedure ParseText; procedure BuildLines; procedure TextToWords; function GetLinesCount: Integer; procedure AddToLinkList(LinkID: Integer; Text: WideString); function GetLink(LinkID: Integer): TLink; protected procedure Paint; override; procedure CreateWnd; override; procedure Loaded; override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseLeave(var { %H- } Msg: TMessage); message CM_MOUSELEAVE; {$IFDEF UNICODE} procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; {$ENDIF} {$IFNDEF LCL} procedure CreateWindowHandle(const Params: TCreateParams); override; {$ENDIF} public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; procedure ForceUpdateSize; property LinesCount: Integer read GetLinesCount; published property Align; property AutoSizeHeight: Boolean read FAutoSizeHeight write SetAutoSizeHeight; property AutoSizeWidth: Boolean read FAutoSizeWidth write SetAutoSizeWidth; {$IFNDEF UNICODE} property Caption: WideString read FCaptionW write SetCaptionW stored False; property CaptionUTF8: UTF8String read FCaptionUTF8 write SetCaptionUTF8; {$ELSE} property Caption; {$ENDIF} property Color; property CompressSpaces: Boolean read FCompressSpaces write SetCompressSpaces; property Height; property Left; property Font; property LinkFontNormal: TFont index 1 read FLinkFontNormal write SetFont; property LinkFontHover: TFont index 2 read FLinkFontHover write SetFont; property MaxWidth: Integer read FMaxWidth write SetMaxWidth; property ParentColor; property ParentFont; property TabWidth: Integer read FTabWidth write SetTabWidth; property TextAlignment: TAlignment read FTextAlignment write SetTextAlignment; property TextHeight: Integer read FTextHeight; property Top; property Visible; property Width; property OnClick; property OnDblClick; property OnGetLinkStyle: TOnGetLinkStyle read FOnGetLinkStyle write FOnGetLinkStyle; property OnHeightChanged: TNotifyEvent read FOnHeightChanged write FOnHeightChanged; property OnLinkClicked: TOnLinkClicked read FOnLinkClicked write FOnLinkClicked; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseLeave read FOnMouseLeave write FOnMouseLeave; property OnPaintBackground: TOnPaintBackground read FOnPaintBackground write FOnPaintBackground; property OnResize; property OnStartDock; property OnStartDrag; property OnWidthChanged: TNotifyEvent read FOnWidthChanged write FOnWidthChanged; end; procedure Register; implementation procedure Register; begin RegisterComponents('MDR', [TMDLabel]); end; type TToken = record Kind: Integer; Text: WideString; Value: Integer; end; TWordInfo = class protected FText: WideString; FRect: TRect; FFontStyle: TFontStyles; FLinkID: Integer; FUseDefaultLinkColor: Boolean; FFontColor: TColor; FBackColor: TColor; FSize: Integer; FWordHeight: Integer; FWordWidth: Integer; FDescent: Integer; public constructor Create(AText: WideString; AFontStyle: TFontStyles; AFontColor: TColor; AFontSize: Integer; ABackColor: TColor; ALinkID: Integer); procedure SetWidth(XPos: Integer; TextRC: TRect; Descent: Integer); procedure AdjustWidth(XPos: Integer); procedure SetLineHeight(LineTop, LineHeight, MaxDescent: Integer); procedure SetXOffset(Offset: Integer); procedure Add(ws: WideString); end; TSpaceInfo = class(TWordInfo) end; TDefaultFormatInfo = class(TWordInfo) public constructor Create; end; TBreakInfo = class(TDefaultFormatInfo) end; TTabInfo = class(TDefaultFormatInfo) public FTabPos: Integer; FTabBreak: Boolean; constructor Create(TabPos: Integer; TabBreak: Boolean); end; TDSPInfo = class(TWordInfo) end; TLineInfo = class FWords: TList; FLineWidth: Integer; FLineHeight: Integer; FMaxDescent: Integer; constructor Create; destructor Destroy; override; end; TLinkRect = class FRect: TRect; FMouseOver: Boolean; FLinkID: Integer; procedure SetData(ARect: TRect; ALinkID: Integer); constructor Create(ALinkID: Integer); end; constructor TLink.Create(ALinkID: Integer; LinkRef: string; AFont, AFontHover: TFont); begin FLinkID := ALinkID; FLinkText := ''; FLinkRef := LinkRef; FFont := TFont.Create; FFontHover := TFont.Create; FFont.Assign(AFont); FFontHover.Assign(AFontHover); end; destructor TLink.Destroy; begin FFont.Free; FFontHover.Free; inherited; end; constructor TWordInfo.Create(AText: WideString; AFontStyle: TFontStyles; AFontColor: TColor; AFontSize: Integer; ABackColor: TColor; ALinkID: Integer); begin FText := AText; FRect := Rect(0, 0, 0, 0); FFontStyle := AFontStyle; FLinkID := ALinkID; FFontColor := AFontColor; FSize := AFontSize; FBackColor := ABackColor; FUseDefaultLinkColor := True; FDescent := 0; end; procedure TWordInfo.SetWidth(XPos: Integer; TextRC: TRect; Descent: Integer); begin FWordWidth := TextRC.Right - TextRC.Left; FRect.Left := XPos; FRect.Right := XPos + FWordWidth; FRect.Top := 0; FRect.Bottom := TextRC.Bottom; FWordHeight := TextRC.Bottom; if Descent >= 0 then FDescent := Descent; end; procedure TWordInfo.AdjustWidth(XPos: Integer); begin FWordWidth := FRect.Right - FRect.Left; FRect.Left := XPos; FRect.Right := XPos + FWordWidth; FRect.Top := 0; end; procedure TWordInfo.SetLineHeight(LineTop, LineHeight, MaxDescent: Integer); begin FRect.Bottom := LineTop + LineHeight - (MaxDescent - FDescent); FRect.Top := FRect.Bottom - FWordHeight; end; procedure TWordInfo.SetXOffset(Offset: Integer); begin FRect.Left := FRect.Left + Offset; FRect.Right := FRect.Left + FWordWidth; end; procedure TWordInfo.Add(ws: WideString); begin FText := FText + ws; end; constructor TDefaultFormatInfo.Create; begin inherited Create('', [], clBlack, 0, clNone, 0); end; constructor TTabInfo.Create(TabPos: Integer; TabBreak: Boolean); begin inherited Create; FTabPos := TabPos; FTabBreak := TabBreak; end; constructor TLineInfo.Create; begin FWords := TList.Create; FLineWidth := 0; FLineHeight := 0; FMaxDescent := 0; end; destructor TLineInfo.Destroy; begin FWords.Free; inherited; end; constructor TLinkRect.Create(ALinkID: Integer); begin FRect := Rect(0, 0, 0, 0); FMouseOver := False; FLinkID := ALinkID; end; procedure TLinkRect.SetData(ARect: TRect; ALinkID: Integer); begin FRect := ARect; FLinkID := ALinkID; end; function GetSpaces(Count: Integer): WideString; var i: Integer; begin Result := ''; for i := 1 to Count do Result := Result + ' '; end; {$IFNDEF UNICODE} type TCharSet = set of char; function CharInSet(c: char; TheSet: TCharSet): Boolean; begin Result := (c in TheSet); end; function UTF8ToWideString(s8: UTF8String): WideString; begin Result := UTF8Decode(s8); end; {$ENDIF} const TOKEN_UNKNOWN = 0; TOKEN_TEXT = 1; TOKEN_B_ON = 2; TOKEN_B_OFF = 3; TOKEN_I_ON = 4; TOKEN_I_OFF = 5; TOKEN_U_ON = 6; TOKEN_U_OFF = 7; TOKEN_S_ON = 8; TOKEN_S_OFF = 9; TOKEN_FC_ON = 10; TOKEN_FC_OFF = 11; TOKEN_A_ON = 12; TOKEN_A_OFF = 13; TOKEN_SPACE = 14; TOKEN_BREAK = 15; TOKEN_TAB = 16; TOKEN_TABF = 17; TOKEN_DSP = 18; TOKEN_FS_ON = 19; TOKEN_FS_OFF = 20; TOKEN_BC_ON = 21; TOKEN_BC_OFF = 22; function HexStringToBuffer(const HexString: string): TBytes; function HexDigitToByte(HexDigit: char): Byte; begin case HexDigit of '0' .. '9': Result := Byte(HexDigit) - Byte('0'); 'A' .. 'F': Result := Byte(HexDigit) - Byte('A') + 10; else Result := 0; end; end; const HexChars = ['0' .. '9', 'A' .. 'F', 'a' .. 'f']; var i: Integer; sHex: string; begin sHex := ''; for i := 1 to length(HexString) do if (CharInSet(HexString[i], HexChars)) then sHex := sHex + UpCase(HexString[i]); if length(sHex) mod 2 <> 0 then sHex := '0' + sHex; SetLength(Result, (length(sHex) div 2)); for i := 0 to length(Result) - 1 do Result[i] := (HexDigitToByte(sHex[2 * i + 1]) * 16) + HexDigitToByte(sHex[2 * i + 2]); end; function HexStringToColor(HexString: string; var Color: Integer): Boolean; var Buffer: TBytes; begin Result := False; Color := 0; if length(HexString) > 6 then Exit; if length(HexString) < 1 then Exit; Buffer := HexStringToBuffer(HexString); Color := Integer(Buffer[length(Buffer) - 1]); if length(Buffer) > 1 then Color := Color or Integer(Buffer[length(Buffer) - 2]) shl 8; if length(Buffer) > 2 then Color := Color or Integer(Buffer[length(Buffer) - 3]) shl 16; Result := True; end; function DecStringToColor(DecString: string; var Color: Integer): Boolean; begin Result := False; Color := 0; if length(DecString) > 8 then Exit; Result := TryStrToInt(DecString, Color); Color := Color and $FFFFFF; end; function NameStringToColor(NameString: string; var Color: Integer): Boolean; begin Result := True; NameString := LowerCase(NameString); if NameString = 'clblack' then Color := clBlack else if NameString = 'clmaroon' then Color := clMaroon else if NameString = 'clgreen' then Color := clGreen else if NameString = 'clolive' then Color := clOlive else if NameString = 'clnavy' then Color := clNavy else if NameString = 'clpurple' then Color := clPurple else if NameString = 'clteal' then Color := clTeal else if NameString = 'clgray' then Color := clGray else if NameString = 'clsilver' then Color := clSilver else if NameString = 'clred' then Color := clRed else if NameString = 'cllime' then Color := clLime else if NameString = 'clyellow' then Color := clYellow else if NameString = 'clblue' then Color := clBlue else if NameString = 'clfuchsia' then Color := clFuchsia else if NameString = 'clmagenta' then Color := clFuchsia else if NameString = 'claqua' then Color := clAqua else if NameString = 'clltgray' then Color := clLtGray else if NameString = 'cldkgray' then Color := clDkGray else if NameString = 'clwhite' then Color := clWhite else if NameString = 'clmoneygreen' then Color := clMoneyGreen else if NameString = 'clskyblue' then Color := clSkyBlue else if NameString = 'clcream' then Color := clCream else if NameString = 'clmedgray' then Color := clMedGray else if NameString = 'clbrown' then Color := $17335C else if NameString = 'clorange' then Color := $008CFF else if NameString = 'clpink' then Color := $9314FF else Result := False; end; function EntityToString(ws: WideString): WideString; begin Result := ws; case ws[1] of 'a': if ws = 'amp' then Result := '&'; 'b': if ws = 'bull' then Result := UTF8ToWideString(AnsiString(#$e2#$80#$a2)); 'c': if ws = 'cent' then Result := UTF8ToWideString(AnsiString(#$C2#$A2)) else if ws = 'copy' then Result := UTF8ToWideString(AnsiString(#$C2#$A9)); 'e': if ws = 'euro' then Result := '€'; 'g': if ws = 'gt' then Result := '>'; 'l': if ws = 'lt' then Result := '<'; 'n': if ws = 'nbsp' then Result := ' ' else if ws = 'ndash' then Result := UTF8ToWideString(AnsiString(#$e2#$80#$93)); 'r': if ws = 'reg' then Result := UTF8ToWideString(AnsiString(#$C2#$AE)); 't': if ws = 'trade' then Result := UTF8ToWideString(AnsiString(#$e2#$84#$a2)); end; end; function ReplaceHTMLEntities(ws: WideString): WideString; var p, i, j: Integer; c, c2: WideChar; Entity: WideString; begin p := pos('&', ws); if p < 1 then Result := ws else begin Result := copy(ws, 1, p - 1); i := p; while i <= length(ws) do begin c := ws[i]; if c = '&' then begin j := i + 1; while j <= length(ws) do begin c2 := ws[j]; if c2 = ';' then begin Entity := copy(ws, i + 1, j - i - 1); if Entity <> '' then Result := Result + EntityToString(LowerCase(Entity)); i := j; Break; end else if c2 = '&' then begin Result := Result + copy(ws, i, j - i); i := j - 1; Break; end; inc(j); end; if j > length(ws) then begin Result := Result + copy(ws, i, length(ws)); Exit; end; end else Result := Result + c; inc(i); end; end; end; function GetToken(Line: WideString; var Index: Integer; out Token: TToken): Boolean; type TIntType = (ctUnknown, ctHex, ctDec, ctName); const WhiteSpace = [' ', #9]; LineBreak = [#10, #13]; Space = WhiteSpace + LineBreak; Digits = ['0' .. '9']; HexDigits = ['0' .. '9', 'a' .. 'f', 'A' .. 'F']; Letters = ['a' .. 'z', 'A' .. 'Z']; ST_START = 0; ST_TAG_START = 1; ST_TAG_BOLD = 2; ST_TAG_ITALIC = 3; ST_TAG_UNDERLINE = 4; ST_TAG_STRIKEOUT = 5; ST_TAG_COLOR = 6; ST_COL_HEX = 7; ST_COL_DEC = 8; ST_COL_END = 9; ST_COL_NAME = 10; ST_COLOR = 11; ST_COLOR_END = 12; ST_ENDTAG = 15; ST_ENDTAG_BOLD = 16; ST_ENDTAG_ITALIC = 17; ST_ENDTAG_UNDERLINE = 18; ST_ENDTAG_STRIKEOUT = 19; ST_ENDTAG_COLOR = 20; ST_TAG_LINK = 21; ST_ENDTAG_LINK = 22; ST_SPACE = 23; ST_TAG_BREAK = 24; ST_TAG_TAB = 25; ST_TAB = 26; ST_TABF = 27; ST_TAB_DEC = 28; ST_TAB_HEX = 29; ST_TAB2_END = 30; ST_TAB_END = 31; ST_TAG_DSP = 36; ST_TAG_DSP2 = 37; ST_TAG_DSP3 = 38; ST_DSP_END = 39; ST_FONT_SIZE = 40; ST_SIZE_DEC = 41; ST_SIZE_END2 = 42; ST_SIZE_END = 43; ST_TAG_FONT = 44; ST_TAG_FONT_SIZE = 45; ST_ENDTAG_FONT = 47; ST_ENDTAG_FONT_SIZE = 48; ST_ENDTAG_FONT_COLOR = 49; ST_ENDTAG_BACK_COLOR = 50; ST_LINK_REF = 51; var c: char; State: Integer; StartIndex: Integer; IntType: TIntType; IntValue: string; BoolValue: Boolean; begin Token.Kind := TOKEN_UNKNOWN; Token.Text := ''; Token.Value := 0; IntValue := ''; IntType := ctUnknown; BoolValue := False; State := ST_START; StartIndex := Index; c := #0; while True do begin if Index <= length(Line) then begin if Integer(Line[Index]) < 256 then c := char(Line[Index]) else c := 'a'; // use dummy character for all wide characters end else begin Result := (Token.Kind <> TOKEN_UNKNOWN); if Result then begin Token.Text := (copy(Line, StartIndex, Index - StartIndex)); if Token.Kind = TOKEN_TEXT then Token.Text := ReplaceHTMLEntities(Token.Text); end; Exit; end; case State of ST_START: begin if c = '<' then begin if Token.Kind = TOKEN_TEXT then begin Token.Text := ReplaceHTMLEntities(copy(Line, StartIndex, Index - StartIndex)); Result := True; Exit; end else State := ST_TAG_START; end else if CharInSet(c, Space) then begin if Token.Kind = TOKEN_TEXT then begin Token.Text := ReplaceHTMLEntities(copy(Line, StartIndex, Index - StartIndex)); Result := True; Exit; end else begin State := ST_SPACE; Token.Kind := TOKEN_SPACE; if CharInSet(c, WhiteSpace) then Token.Text := c else if (c = #10) then Token.Text := ' ' else Token.Text := ''; end; end else begin Token.Kind := TOKEN_TEXT; end end; ST_SPACE: begin if CharInSet(c, Space) then begin if CharInSet(c, WhiteSpace) then Token.Text := Token.Text + c else if (c = #10) then Token.Text := Token.Text + ' '; end else begin Result := True; Exit; end; end; ST_TAG_START: if CharInSet(c, Space) then State := ST_TAG_START else if CharInSet(c, ['B', 'b']) then State := ST_TAG_BOLD else if CharInSet(c, ['F', 'f']) then State := ST_TAG_FONT else if CharInSet(c, ['I', 'i']) then State := ST_TAG_ITALIC else if CharInSet(c, ['U', 'u']) then State := ST_TAG_UNDERLINE else if CharInSet(c, ['S', 's']) then State := ST_TAG_STRIKEOUT else if CharInSet(c, ['C', 'c']) then State := ST_TAG_COLOR else if CharInSet(c, ['A', 'a']) then State := ST_TAG_LINK else if CharInSet(c, ['T', 't']) then State := ST_TAG_TAB else if CharInSet(c, ['D', 'd']) then State := ST_TAG_DSP else if c = '/' then State := ST_ENDTAG else if c <> '<' then begin Token.Kind := TOKEN_TEXT; State := ST_START; end; ST_TAG_BOLD: if c = '>' then begin Token.Kind := TOKEN_B_ON; inc(Index); Result := True; Exit; end else if CharInSet(c, ['R', 'r']) then State := ST_TAG_BREAK else if CharInSet(c, ['C', 'c']) then begin State := ST_TAG_COLOR; BoolValue := True; end else State := ST_START; ST_TAG_BREAK: if c = '>' then begin Token.Kind := TOKEN_BREAK; inc(Index); Result := True; Exit; end else State := ST_START; ST_TAG_LINK: if c = '>' then begin Token.Kind := TOKEN_A_ON; inc(Index); Result := True; Exit; end else if c = ':' then State := ST_LINK_REF else State := ST_START; ST_LINK_REF: if c = '>' then begin Token.Kind := TOKEN_A_ON; Token.Text := trim(Token.Text); inc(Index); Result := True; Exit; end else Token.Text := Token.Text + c; ST_TAG_ITALIC: if c = '>' then begin Token.Kind := TOKEN_I_ON; inc(Index); Result := True; Exit; end else State := ST_START; ST_TAG_UNDERLINE: if c = '>' then begin Token.Kind := TOKEN_U_ON; inc(Index); Result := True; Exit; end else State := ST_START; ST_TAG_STRIKEOUT: if c = '>' then begin Token.Kind := TOKEN_S_ON; inc(Index); Result := True; Exit; end else State := ST_START; ST_TAG_FONT: if CharInSet(c, ['S', 's']) then State := ST_TAG_FONT_SIZE else if CharInSet(c, ['C', 'c']) then State := ST_TAG_COLOR else State := ST_START; ST_TAG_FONT_SIZE: if c = ':' then State := ST_FONT_SIZE else State := ST_START; ST_FONT_SIZE: if CharInSet(c, Digits) then begin State := ST_SIZE_DEC; IntValue := IntValue + c; end else State := ST_START; ST_SIZE_DEC: if CharInSet(c, Digits) then IntValue := IntValue + c else if CharInSet(c, Space) then State := ST_SIZE_END2 else if c = '>' then State := ST_SIZE_END else State := ST_START; ST_SIZE_END2: if c = '>' then State := ST_SIZE_END else State := ST_START; ST_SIZE_END: begin Token.Kind := TOKEN_TEXT; Result := True; if length(IntValue) <= 3 then begin if TryStrToInt(IntValue, Token.Value) then Token.Kind := TOKEN_FS_ON; end; Exit; end; ST_TAG_TAB: if c = ':' then State := ST_TAB else if c = 'f' then begin BoolValue := True; State := ST_TABF; end else if c = '>' then State := ST_TAB_END else State := ST_START; ST_TABF: if c = ':' then State := ST_TAB else State := ST_START; ST_TAB: if c = '$' then begin State := ST_TAB_HEX; end else if CharInSet(c, Digits) then begin State := ST_TAB_DEC; IntValue := IntValue + c; end else State := ST_START; ST_TAB_HEX: if CharInSet(c, HexDigits) then IntValue := IntValue + c else if CharInSet(c, Space) then State := ST_TAB2_END else if c = '>' then State := ST_TAB_END else State := ST_START; ST_TAB_DEC: if CharInSet(c, Digits) then IntValue := IntValue + c else if CharInSet(c, Space) then State := ST_TAB2_END else if c = '>' then State := ST_TAB_END else State := ST_START; ST_TAB2_END: if c = '>' then State := ST_TAB_END else State := ST_START; ST_TAB_END: begin Token.Kind := TOKEN_TEXT; Result := True; if IntValue = '' then Token.Kind := TOKEN_TAB else if length(IntValue) <= 4 then begin if TryStrToInt(IntValue, Token.Value) then begin if BoolValue then Token.Kind := TOKEN_TABF else Token.Kind := TOKEN_TAB; end; end; Exit; end; ST_TAG_DSP: if CharInSet(c, ['s', 'S']) then State := ST_TAG_DSP2 else State := ST_START; ST_TAG_DSP2: if CharInSet(c, ['p', 'P']) then State := ST_TAG_DSP3 else State := ST_START; ST_TAG_DSP3: if c = '>' then State := ST_DSP_END else State := ST_START; ST_DSP_END: begin Token.Kind := TOKEN_DSP; Result := True; Exit; end; ST_TAG_COLOR: if c = ':' then State := ST_COLOR else State := ST_START; ST_COLOR: if c = '$' then begin State := ST_COL_HEX; IntType := ctHex; end else if CharInSet(c, Digits) then begin State := ST_COL_DEC; IntValue := IntValue + c; IntType := ctDec; end else if CharInSet(c, ['C', 'c']) then begin State := ST_COL_NAME; IntValue := IntValue + c; IntType := ctName; end else State := ST_START; ST_COL_HEX: if CharInSet(c, HexDigits) then IntValue := IntValue + c else if CharInSet(c, Space) then State := ST_COL_END else if c = '>' then State := ST_COLOR_END else State := ST_START; ST_COL_DEC: if CharInSet(c, Digits) then IntValue := IntValue + c else if CharInSet(c, Space) then State := ST_COL_END else if c = '>' then State := ST_COLOR_END else State := ST_START; ST_COL_NAME: if CharInSet(c, Letters) then IntValue := IntValue + c else if CharInSet(c, Space) then State := ST_COL_END else if c = '>' then State := ST_COLOR_END else State := ST_START; ST_COL_END: if c = '>' then State := ST_COLOR_END else State := ST_START; ST_COLOR_END: begin Token.Kind := TOKEN_TEXT; Result := True; if BoolValue then begin case IntType of ctHex: if HexStringToColor(IntValue, Token.Value) then Token.Kind := TOKEN_BC_ON; ctDec: if DecStringToColor(IntValue, Token.Value) then Token.Kind := TOKEN_BC_ON; ctName: if NameStringToColor(IntValue, Token.Value) then Token.Kind := TOKEN_BC_ON; end; end else begin case IntType of ctHex: if HexStringToColor(IntValue, Token.Value) then Token.Kind := TOKEN_FC_ON; ctDec: if DecStringToColor(IntValue, Token.Value) then Token.Kind := TOKEN_FC_ON; ctName: if NameStringToColor(IntValue, Token.Value) then Token.Kind := TOKEN_FC_ON; end; end; Exit; end; ST_ENDTAG: if CharInSet(c, Space) then State := ST_ENDTAG else if CharInSet(c, ['B', 'b']) then State := ST_ENDTAG_BOLD else if CharInSet(c, ['I', 'i']) then State := ST_ENDTAG_ITALIC else if CharInSet(c, ['U', 'u']) then State := ST_ENDTAG_UNDERLINE else if CharInSet(c, ['S', 's']) then State := ST_ENDTAG_STRIKEOUT else if CharInSet(c, ['C', 'c']) then State := ST_ENDTAG_FONT_COLOR else if CharInSet(c, ['A', 'a']) then State := ST_ENDTAG_LINK else if CharInSet(c, ['F', 'f']) then State := ST_ENDTAG_FONT else begin Token.Kind := TOKEN_TEXT; State := ST_START; end; ST_ENDTAG_BOLD: if c = '>' then begin Token.Kind := TOKEN_B_OFF; inc(Index); Result := True; Exit; end else if CharInSet(c, ['C', 'c']) then State := ST_ENDTAG_BACK_COLOR else State := ST_START; ST_ENDTAG_LINK: if c = '>' then begin Token.Kind := TOKEN_A_OFF; inc(Index); Result := True; Exit; end else State := ST_START; ST_ENDTAG_FONT: if CharInSet(c, ['S', 's']) then State := ST_ENDTAG_FONT_SIZE else if CharInSet(c, ['C', 'c']) then State := ST_ENDTAG_FONT_COLOR else State := ST_START; ST_ENDTAG_FONT_SIZE: if c = '>' then begin Token.Kind := TOKEN_FS_OFF; inc(Index); Result := True; Exit; end else State := ST_START; ST_ENDTAG_ITALIC: if c = '>' then begin Token.Kind := TOKEN_I_OFF; inc(Index); Result := True; Exit; end else State := ST_START; ST_ENDTAG_UNDERLINE: if c = '>' then begin Token.Kind := TOKEN_U_OFF; inc(Index); Result := True; Exit; end else State := ST_START; ST_ENDTAG_STRIKEOUT: if c = '>' then begin Token.Kind := TOKEN_S_OFF; inc(Index); Result := True; Exit; end else State := ST_START; ST_ENDTAG_FONT_COLOR: if c = '>' then begin Token.Kind := TOKEN_FC_OFF; inc(Index); Result := True; Exit; end else State := ST_START; ST_ENDTAG_BACK_COLOR: if c = '>' then begin Token.Kind := TOKEN_BC_OFF; inc(Index); Result := True; Exit; end else State := ST_START; end; inc(Index); end; end; procedure TMDLabel.TextToWords; var Token: TToken; i, Index: Integer; ws: WideString; CurrentStyle: TFontStyles; FontColorStack: TList; BackColorStack: TList; SizeStack: TList; LinkID, CurLinkID: Integer; InLink: Boolean; FontSize: Integer; FontColor: TColor; BackColor: TColor; begin if (csLoading in ComponentState) or not FInitialized then Exit; for i := 0 to FWords.Count - 1 do if Assigned(FWords[i]) then TWordInfo(FWords[i]).Free; FWords.Clear; {$IFNDEF UNICODE} ws := FCaptionW; {$ELSE} ws := inherited Caption; {$ENDIF} if ws = '' then Exit; FontColorStack := TList.Create; BackColorStack := TList.Create; SizeStack := TList.Create; try FontColorStack.Add(Pointer(Font.Color)); BackColorStack.Add(Pointer(clNone)); SizeStack.Add(Pointer(Font.Size)); CurLinkID := 0; InLink := False; CurrentStyle := Font.Style; Index := 1; while GetToken(ws, Index, Token) do begin if InLink then LinkID := CurLinkID else LinkID := 0; FontSize := Integer(SizeStack[SizeStack.Count - 1]); FontColor := TColor(FontColorStack[FontColorStack.Count - 1]); BackColor := TColor(BackColorStack[BackColorStack.Count - 1]); case Token.Kind of TOKEN_TEXT: FWords.Add(TWordInfo.Create(Token.Text, CurrentStyle, FontColor, FontSize, BackColor, LinkID)); TOKEN_A_ON: begin inc(CurLinkID); InLink := True; FLinkList.Add(TLink.Create(CurLinkID, Token.Text, FLinkFontNormal, FLinkFontHover)); end; TOKEN_A_OFF: InLink := False; TOKEN_B_ON: CurrentStyle := CurrentStyle + [fsBold]; TOKEN_B_OFF: CurrentStyle := CurrentStyle - [fsBold]; TOKEN_I_ON: CurrentStyle := CurrentStyle + [fsItalic]; TOKEN_I_OFF: CurrentStyle := CurrentStyle - [fsItalic]; TOKEN_U_ON: CurrentStyle := CurrentStyle + [fsUnderline]; TOKEN_U_OFF: CurrentStyle := CurrentStyle - [fsUnderline]; TOKEN_S_ON: CurrentStyle := CurrentStyle + [fsStrikeOut]; TOKEN_S_OFF: CurrentStyle := CurrentStyle - [fsStrikeOut]; TOKEN_FC_ON: FontColorStack.Add(Pointer(Token.Value)); TOKEN_FC_OFF: if FontColorStack.Count > 1 then FontColorStack.Delete(FontColorStack.Count - 1); TOKEN_BC_ON: BackColorStack.Add(Pointer(Token.Value)); TOKEN_BC_OFF: if BackColorStack.Count > 1 then BackColorStack.Delete(BackColorStack.Count - 1); TOKEN_SPACE: FWords.Add(TSpaceInfo.Create(Token.Text, CurrentStyle, FontColor, FontSize, BackColor, LinkID)); TOKEN_BREAK: FWords.Add(TBreakInfo.Create); TOKEN_TAB: FWords.Add(TTabInfo.Create(Token.Value, False)); TOKEN_TABF: FWords.Add(TTabInfo.Create(Token.Value, True)); TOKEN_FS_ON: SizeStack.Add(Pointer(Token.Value)); TOKEN_FS_OFF: if SizeStack.Count > 1 then SizeStack.Delete(SizeStack.Count - 1); TOKEN_DSP: FWords.Add(TDSPInfo.Create(' ', CurrentStyle, FontColor, FontSize, BackColor, LinkID)); end; end; finally FontColorStack.Free; BackColorStack.Free; SizeStack.Free; end; end; procedure TMDLabel.AddToLinkList(LinkID: Integer; Text: WideString); var i: Integer; begin if (FLastID >= 0) and (FLastID < FLinkList.Count) then begin if TLink(FLinkList[FLastID]).FLinkID = LinkID then begin TLink(FLinkList[FLastID]).FLinkText := TLink(FLinkList[FLastID]).FLinkText + Text; Exit; end; end; for i := 0 to FLinkList.Count - 1 do begin if TLink(FLinkList[i]).FLinkID = LinkID then begin TLink(FLinkList[i]).FLinkText := TLink(FLinkList[i]).FLinkText + Text; FLastID := i; Exit; end; end; end; function TMDLabel.GetLink(LinkID: Integer): TLink; var i: Integer; begin Result := nil; if (LinkID >= 1) and (LinkID <= FLinkList.Count) then begin if TLink(FLinkList[LinkID - 1]).FLinkID = LinkID then begin Result := TLink(FLinkList[LinkID - 1]); Exit; end; for i := 0 to FLinkList.Count - 1 do begin if TLink(FLinkList[i]).FLinkID = LinkID then begin Result := TLink(FLinkList[i]); Exit; end; end; end; end; procedure TMDLabel.ParseText; var i: Integer; Link: TLink; begin if not Assigned(Parent) then exit; if (csLoading in ComponentState) or not FInitialized then Exit; if FParsingText then Exit; FParsingText := True; try for i := 0 to FLinkRCs.Count - 1 do if Assigned(FLinkRCs[i]) then TLinkRect(FLinkRCs[i]).Free; FLinkRCs.Clear; TextToWords; for i := 0 to FWords.Count - 1 do begin if TWordInfo(FWords[i]).FLinkID > 0 then begin FLinkRCs.Add(TLinkRect.Create(TWordInfo(FWords[i]).FLinkID)); AddToLinkList(TWordInfo(FWords[i]).FLinkID, TWordInfo(FWords[i]).FText); end; end; if Assigned(FOnGetLinkStyle) then begin for i := 0 to FLinkList.Count - 1 do begin Link := TLink(FLinkList[i]); FOnGetLinkStyle(self, Link.FLinkID, Link.FLinkText, Link.FFont, Link.FFontHover); end; end; BuildLines; finally FParsingText := False; end; end; procedure TMDLabel.BuildLines; var i, j: Integer; ws: WideString; LineTop: Integer; WordInfo: TWordInfo; LineInfo: TLineInfo; tmpWordInfo: TWordInfo; LineWidth: Integer; MaxLineWidth: Integer; TabSpaces: WideString; TextRC: TRect; DefaultLineHeight: Integer; Offset: Integer; TabPos: Integer; TabBreak: Integer; tmpWords: TList; WordLeft, WordLen: Integer; Link: TLink; TM: TEXTMETRIC; const _TABWIDTH = 50; begin if (csLoading in ComponentState) or not FInitialized then Exit; if FBuildingLines then begin FRebuildLines := True; Exit; end; FBuildingLines := True; try for i := 0 to FLines.Count - 1 do if Assigned(FLines[i]) then TLineInfo(FLines[i]).Free; FLines.Clear; LineInfo := TLineInfo.Create; FLines.Add(LineInfo); LineWidth := 0; TabBreak := 0; TabSpaces := GetSpaces(FTabWidth); Canvas.Font.Assign(Font); DefaultLineHeight := TextHeightW(' '); for i := 0 to FWords.Count - 1 do begin WordInfo := TWordInfo(FWords[i]); if (WordInfo is TSpaceInfo) or (WordInfo is TDSPInfo) then begin if FCompressSpaces then begin if LineInfo.FWords.Count = 0 then ws := '' // ignore leading spaces else ws := ' '; end else begin ws := ''; for j := 1 to length(WordInfo.FText) do begin if WordInfo.FText[j] = ' ' then ws := ws + ' ' else if WordInfo.FText[i] = #9 then ws := ws + TabSpaces; end; end; end else ws := WordInfo.FText; if WordInfo is TBreakInfo then begin LineInfo.FLineWidth := LineWidth; LineInfo := TLineInfo.Create; FLines.Add(LineInfo); LineWidth := 0; TabBreak := 0; end else if WordInfo is TTabInfo then begin if TTabInfo(WordInfo).FTabPos = 0 then TabPos := ((LineWidth div _TABWIDTH) + 1) * _TABWIDTH else begin TabPos := TTabInfo(WordInfo).FTabPos; if TTabInfo(WordInfo).FTabBreak then TabBreak := TabPos; end; if LineWidth < TabPos then begin if (TabPos <= Width) or FAutoSizeWidth then begin WordInfo.SetWidth(LineWidth, Rect(0, 0, TabPos - LineWidth, 0), 0); LineWidth := TabPos; LineInfo.FWords.Add(WordInfo); end; end; end else if ws <> '' then begin if WordInfo.FLinkID = 0 then begin Canvas.Font.Assign(Font); Canvas.Font.Color := WordInfo.FFontColor; Canvas.Font.Style := WordInfo.FFontStyle; Canvas.Font.Size := WordInfo.FSize; end else begin Link := GetLink(WordInfo.FLinkID); if Assigned(Link) then begin if IsMouseOverLink(WordInfo.FLinkID) then Canvas.Font.Assign(Link.FFontHover) else Canvas.Font.Assign(Link.FFont); end else begin if IsMouseOverLink(WordInfo.FLinkID) then Canvas.Font.Assign(FLinkFontHover) else Canvas.Font.Assign(FLinkFontNormal); end; end; if WordInfo is TDSPInfo then TextSizeW('0', TextRC) else TextSizeW(ws, TextRC); GetTextMetrics(Canvas.Handle, TM); WordInfo.SetWidth(LineWidth, TextRC, TM.tmDescent); if (WordInfo.FRect.Right <= Width) or (FAutoSizeWidth and ((WordInfo.FRect.Right <= FMaxWidth) or (FMaxWidth = 0))) then begin LineInfo.FWords.Add(WordInfo); LineWidth := WordInfo.FRect.Right; end else begin // word wrap tmpWords := TList.Create; try // remove all spaces from the right while LineInfo.FWords.Count > 0 do begin tmpWordInfo := TWordInfo(LineInfo.FWords[LineInfo.FWords.Count - 1]); if (tmpWordInfo is TSpaceInfo) or (tmpWordInfo is TTabInfo) or (tmpWordInfo is TDSPInfo) then begin LineInfo.FWords.Delete(LineInfo.FWords.Count - 1); end else Break; end; if (trim(ws) <> '') or (tmpWords.Count > 0) then tmpWords.Add(WordInfo); if LineInfo.FWords.Count > 0 then begin LineInfo.FLineWidth := TWordInfo(LineInfo.FWords[LineInfo.FWords.Count - 1]).FRect.Right; if (tmpWords.Count > 0) then begin LineInfo := TLineInfo.Create; FLines.Add(LineInfo); end; end else LineInfo.FLineWidth := 0; if (tmpWords.Count > 0) then begin if (LineInfo.FWords.Count = 0) then LineWidth := TabBreak else LineWidth := 0; for j := 0 to tmpWords.Count - 1 do begin WordInfo := TWordInfo(tmpWords[j]); LineInfo.FWords.Add(WordInfo); WordInfo.AdjustWidth(LineWidth); LineWidth := WordInfo.FRect.Right; end; if FAutoSizeWidth and (FMaxWidth <> 0) and (LineWidth > FMaxWidth) then begin WordInfo := TWordInfo(LineInfo.FWords[LineInfo.FWords.Count - 1]); if Assigned(WordInfo) then begin LineWidth := WordInfo.FRect.Left; ws := WordInfo.FText; WordLeft := WordInfo.FRect.Left; WordLen := length(ws); while WordLeft + TextWidthW(ws + '...') > FMaxWidth do begin dec(WordLen); ws := copy(ws, 1, WordLen); end; WordInfo.FText := ws + '...'; TextSizeW(WordInfo.FText, TextRC); WordInfo.SetWidth(LineWidth, TextRC, -1); LineWidth := WordInfo.FRect.Right; end; end; end; finally tmpWords.Free; end; end; end; end; LineInfo.FLineWidth := LineWidth; MaxLineWidth := 0; LineTop := 0; for i := 0 to FLines.Count - 1 do begin LineInfo := TLineInfo(FLines[i]); if LineInfo.FLineWidth > MaxLineWidth then MaxLineWidth := LineInfo.FLineWidth; LineInfo.FLineHeight := 0; LineInfo.FMaxDescent := 0; for j := 0 to LineInfo.FWords.Count - 1 do begin if TWordInfo(LineInfo.FWords[j]).FWordHeight > LineInfo.FLineHeight then LineInfo.FLineHeight := TWordInfo(LineInfo.FWords[j]).FWordHeight; if TWordInfo(LineInfo.FWords[j]).FDescent > LineInfo.FMaxDescent then LineInfo.FMaxDescent := TWordInfo(LineInfo.FWords[j]).FDescent; end; if LineInfo.FLineHeight = 0 then LineInfo.FLineHeight := DefaultLineHeight; for j := 0 to LineInfo.FWords.Count - 1 do begin TWordInfo(LineInfo.FWords[j]).SetLineHeight(LineTop, LineInfo.FLineHeight, LineInfo.FMaxDescent); end; LineTop := LineTop + LineInfo.FLineHeight; end; if FAutoSizeWidth and (MaxLineWidth <> Width) then begin if (MaxLineWidth > FMaxWidth) and (FMaxWidth <> 0) then MaxLineWidth := FMaxWidth; Width := MaxLineWidth; if Assigned(FOnWidthChanged) then FOnWidthChanged(self); end; SetHeight(LineTop); if FAutoSizeHeight and (LineTop <> Height) then begin Height := LineTop; FTextHeight := LineTop; if Assigned(FOnHeightChanged) then FOnHeightChanged(self); end; for i := 0 to FLines.Count - 1 do begin LineInfo := TLineInfo(FLines[i]); case FTextAlignment of taRightJustify: Offset := Width - LineInfo.FLineWidth; taCenter: Offset := (Width - LineInfo.FLineWidth) div 2; else Offset := 0; end; if Offset <> 0 then begin for j := 0 to LineInfo.FWords.Count - 1 do begin TWordInfo(LineInfo.FWords[j]).SetXOffset(Offset); end; end; end; finally FBuildingLines := False; end; end; constructor TMDLabel.Create(AOwner: TComponent); begin FInitialized := False; // required for runtime creation of MDLabel inherited; ControlStyle := [csOpaque, csCaptureMouse, csClickEvents, csSetCaption]; Width := 100; Height := 13; FLinkFontNormal := TFont.Create; FLinkFontNormal.Assign(Font); FLinkFontNormal.Color := clBlue; FLinkFontNormal.Style := []; FLinkFontHover := TFont.Create; FLinkFontHover.Assign(Font); FLinkFontHover.Color := clRed; FLinkFontHover.Style := [fsUnderline]; FAutoSizeWidth := True; FAutoSizeHeight := True; FTextAlignment := taLeftJustify; FCompressSpaces := False; FTabWidth := 8; FParsingText := False; FBuildingLines := False; FRebuildLines := False; FMaxWidth := 0; FLastID := -1; FTextHeight := 0; Cursor := crArrow; TabStop := False; DoubleBuffered := True; FLinkFontNormal.OnChange := DoFontChange; FLinkFontHover.OnChange := DoFontChange; FOnLinkClicked := nil; FOnPaintBackground := nil; FOnHeightChanged := nil; FOnWidthChanged := nil; FOnGetLinkStyle := nil; FOnMouseLeave := nil; FLines := TList.Create; FWords := TList.Create; FLinkRCs := TList.Create; FLinkList := TList.Create; FMouseDownMove := False; FMouseWasDown := False; FMouseDownIndex := -1; {$IFDEF LCL} FDefaultCursor := Cursor; FInitialized := True; ParseText; {$ENDIF} end; procedure TMDLabel.CreateWnd; begin inherited CreateWnd; {$IFNDEF UNICODE} if (inherited Caption <> '') and (FCaptionUTF8 = '') then CaptionUTF8 := inherited Caption; {$ENDIF} end; {$IFNDEF LCL} procedure TMDLabel.CreateWindowHandle(const Params: TCreateParams); begin inherited CreateWindowHandle(Params); FDefaultCursor := Cursor; FInitialized := True; ParseText; end; {$ENDIF} procedure TMDLabel.Loaded; begin inherited; ParseText; end; destructor TMDLabel.Destroy; var i: Integer; begin FLinkFontNormal.Free; FLinkFontHover.Free; for i := 0 to FLines.Count - 1 do if Assigned(FLines[i]) then TLineInfo(FLines[i]).Free; FLines.Free; for i := 0 to FWords.Count - 1 do if Assigned(FWords[i]) then TWordInfo(FWords[i]).Free; FWords.Free; for i := 0 to FLinkRCs.Count - 1 do if Assigned(FLinkRCs[i]) then TLinkRect(FLinkRCs[i]).Free; FLinkRCs.Free; for i := 0 to FLinkList.Count - 1 do if Assigned(FLinkList[i]) then TLink(FLinkList[i]).Free; FLinkList.Free; inherited; end; procedure TMDLabel.WMEraseBkgnd(var Msg: TWmEraseBkgnd); begin Msg.Result := 1; end; {$IFNDEF UNICODE} procedure TMDLabel.SetCaptionW(Value: WideString); begin if FCaptionW = Value then Exit; FCaptionW := Value; FCaptionUTF8 := UTF8Encode(Value); ParseText; Invalidate; end; procedure TMDLabel.SetCaptionUTF8(Value: UTF8String); begin if FCaptionUTF8 = Value then Exit; FCaptionUTF8 := Value; FCaptionW := UTF8Decode(FCaptionUTF8); if (FCaptionW = '') and (FCaptionUTF8 <> '') then FCaptionW := 'invalid UTF8'; ParseText; Invalidate; end; {$ELSE} procedure TMDLabel.CMTextChanged(var Message: TMessage); begin inherited; ParseText; Invalidate; end; {$ENDIF} procedure TMDLabel.ForceUpdateSize; begin FInitialized := True; ParseText; end; procedure TMDLabel.SetFont(Index: Integer; Value: TFont); begin case Index of 1: FLinkFontNormal.Assign(Value); 2: FLinkFontHover.Assign(Value); end; end; procedure TMDLabel.SetHeight(Value: Integer); begin if FAutoSizeHeight then Exit; if Height = Value then Exit; Height := Value; if Assigned(FOnHeightChanged) then FOnHeightChanged(self); end; procedure TMDLabel.SetAutoSizeWidth(Value: Boolean); begin if FAutoSizeWidth = Value then Exit; FAutoSizeWidth := Value; BuildLines; Invalidate; end; procedure TMDLabel.SetAutoSizeHeight(Value: Boolean); begin if FAutoSizeHeight = Value then Exit; FAutoSizeHeight := Value; BuildLines; Invalidate; end; procedure TMDLabel.SetCompressSpaces(Value: Boolean); begin if FCompressSpaces = Value then Exit; FCompressSpaces := Value; BuildLines; Invalidate; end; procedure TMDLabel.SetTextAlignment(Value: TAlignment); begin if FTextAlignment = Value then Exit; FTextAlignment := Value; BuildLines; Invalidate; end; procedure TMDLabel.TextSizeW(ws: WideString; out RC: TRect); begin RC := Rect(0, 0, 0, 0); DrawTextW(Canvas.Handle, PWideChar(ws), length(ws), RC, DT_CALCRECT or DT_NOPREFIX or DT_LEFT or DT_SINGLELINE or DT_NOCLIP); end; function TMDLabel.TextHeightW(ws: WideString): Integer; var RC: TRect; begin RC := Rect(0, 0, 0, 0); DrawTextW(Canvas.Handle, PWideChar(ws), length(ws), RC, DT_CALCRECT or DT_NOPREFIX or DT_LEFT or DT_SINGLELINE or DT_NOCLIP); Result := RC.Bottom - RC.Top; end; function TMDLabel.TextWidthW(ws: WideString): Integer; var RC: TRect; begin RC := Rect(0, 0, 0, 0); DrawTextW(Canvas.Handle, PWideChar(ws), length(ws), RC, DT_CALCRECT or DT_NOPREFIX or DT_LEFT or DT_SINGLELINE or DT_NOCLIP); Result := RC.Right - RC.Left; end; procedure TMDLabel.SetTabWidth(Value: Integer); begin if FTabWidth = Value then Exit; FTabWidth := Value; BuildLines; Invalidate; end; procedure TMDLabel.SetMaxWidth(Value: Integer); begin if FMaxWidth = Value then Exit; FMaxWidth := Value; BuildLines; Invalidate; end; procedure TMDLabel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var RC: TRect; i: Integer; Link: TLink; LinkRect: TLinkRect; LinkText: WideString; begin try if Button <> mbLeft then Exit; for i := 0 to FLinkRCs.Count - 1 do begin LinkRect := TLinkRect(FLinkRCs[i]); RC := LinkRect.FRect; if (X >= RC.Left) and (X <= RC.Right) and (Y >= RC.Top) and (Y <= RC.Bottom) then begin if FMouseDownIndex = i then begin FMouseWasDown := False; Link := GetLink(LinkRect.FLinkID); if Link.FLinkRef <> '' then LinkText := Link.FLinkRef else LinkText := Link.FLinkText; if Assigned(FOnLinkClicked) then FOnLinkClicked(self, Link.FLinkID, LinkText); Exit; end; end; end; finally FMouseDownIndex := -1; inherited; end; end; procedure TMDLabel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var RC: TRect; i: Integer; LinkRect: TLinkRect; begin FMouseWasDown := True; FMouseDownIndex := -1; try if Button <> mbLeft then Exit; for i := 0 to FLinkRCs.Count - 1 do begin LinkRect := TLinkRect(FLinkRCs[i]); RC := LinkRect.FRect; if (X >= RC.Left) and (X <= RC.Right) and (Y >= RC.Top) and (Y <= RC.Bottom) then FMouseDownIndex := i; end; finally inherited; end; end; procedure TMDLabel.MouseMove(Shift: TShiftState; X, Y: Integer); var Msg: TMessage; RC: TRect; i: Integer; LinkRect: TLinkRect; CursorHand: Boolean; TrackMouseEv: TTrackMouseEvent; begin if (csDesigning in ComponentState) or (csDestroying in ComponentState) then Exit; try TrackMouseEv.cbSize := sizeof(TrackMouseEv); TrackMouseEv.hwndTrack := Handle; TrackMouseEv.dwFlags := TME_LEAVE; TrackMouseEvent(TrackMouseEv); FMouseDownMove := FMouseWasDown; if (Y > Height) or (Y < 0) or (X > Width) or (X < 0) then begin MouseLeave(Msg { %H- } ); Exit; end; CursorHand := False; for i := 0 to FLinkRCs.Count - 1 do begin LinkRect := TLinkRect(FLinkRCs[i]); RC := LinkRect.FRect; if (X >= RC.Left) and (X <= RC.Right) and (Y > RC.Top) and (Y < RC.Bottom) then begin CursorHand := True; if not LinkRect.FMouseOver then begin LinkRect.FMouseOver := True; BuildLines; Invalidate; end; end else begin if LinkRect.FMouseOver then begin LinkRect.FMouseOver := False; BuildLines; Invalidate; end; end; end; if CursorHand then begin if Cursor <> crHandPoint then Cursor := crHandPoint; end else if Cursor <> FDefaultCursor then Cursor := FDefaultCursor; finally inherited MouseMove(Shift, X, Y); end; end; procedure TMDLabel.MouseLeave(var Msg: TMessage); var i: Integer; LinkRect: TLinkRect; begin FMouseDownMove := False; FMouseWasDown := False; if (csDesigning in ComponentState) or (csDestroying in ComponentState) then Exit; for i := 0 to FLinkRCs.Count - 1 do begin LinkRect := TLinkRect(FLinkRCs[i]); if LinkRect.FMouseOver then begin LinkRect.FMouseOver := False; Cursor := FDefaultCursor; BuildLines; Invalidate; end; end; if Assigned(FOnMouseLeave) then FOnMouseLeave(self); end; function TMDLabel.IsMouseOverLink(LinkID: Integer): Boolean; var i: Integer; LinkRect: TLinkRect; begin Result := False; if (csDesigning in ComponentState) or (csDestroying in ComponentState) then Exit; for i := 0 to FLinkRCs.Count - 1 do begin LinkRect := TLinkRect(FLinkRCs[i]); if LinkRect.FLinkID = LinkID then begin if LinkRect.FMouseOver then begin Result := True; Exit; end; end; end; end; procedure TMDLabel.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); var OldWidth: Integer; begin OldWidth := Width; inherited; if (csDesigning in ComponentState) or (csDestroying in ComponentState) or (csLoading in ComponentState) or not FInitialized then Exit; if FBuildingLines then begin FRebuildLines := True; Exit; end; if OldWidth <> AWidth then begin BuildLines; Invalidate; if Assigned(FOnWidthChanged) then FOnWidthChanged(self); end; end; function TMDLabel.GetLinesCount: Integer; begin Result := 0; if Assigned(FLines) then Result := FLines.Count; end; procedure TMDLabel.CMFontChanged(var Message: TMessage); begin DoFontChange(nil); end; procedure TMDLabel.DoFontChange(Sender: TObject); begin ParseText; Invalidate; end; procedure TMDLabel.Paint; var ws: WideString; i, Line: Integer; WordInfo: TWordInfo; LineInfo: TLineInfo; LinkIndex: Integer; Link: TLink; begin if not(csDesigning in ComponentState) and not Visible then Exit; if FParsingText or FBuildingLines then Exit; if FRebuildLines then begin FRebuildLines := False; BuildLines; end; if Assigned(FOnPaintBackground) then FOnPaintBackground(self, self.Canvas, Width, Height) else begin Canvas.Pen.Width := 0; Canvas.Brush.Style := bsSolid; Canvas.Brush.Color := Color; Canvas.Pen.Color := Canvas.Brush.Color; Canvas.Rectangle(ClientRect); Canvas.Brush.Style := bsClear; end; LinkIndex := 0; for Line := 0 to FLines.Count - 1 do begin LineInfo := TLineInfo(FLines[Line]); for i := 0 to LineInfo.FWords.Count - 1 do begin WordInfo := TWordInfo(LineInfo.FWords[i]); ws := WordInfo.FText; if ws <> '' then begin if WordInfo.FBackColor = clNone then Canvas.Brush.Style := bsClear else begin Canvas.Brush.Color := WordInfo.FBackColor; Canvas.Brush.Style := bsSolid; // required for Lazarus end; if WordInfo.FLinkID = 0 then begin Canvas.Font.Assign(self.Font); Canvas.Font.Color := WordInfo.FFontColor; Canvas.Font.Style := WordInfo.FFontStyle; Canvas.Font.Size := WordInfo.FSize; end else begin Link := GetLink(WordInfo.FLinkID); if Assigned(Link) then begin if IsMouseOverLink(WordInfo.FLinkID) then Canvas.Font.Assign(Link.FFontHover) else Canvas.Font.Assign(Link.FFont); end else begin if IsMouseOverLink(WordInfo.FLinkID) then Canvas.Font.Assign(FLinkFontHover) else Canvas.Font.Assign(FLinkFontNormal); end; end; if WordInfo.FLinkID > 0 then begin TLinkRect(FLinkRCs[LinkIndex]).SetData(WordInfo.FRect, WordInfo.FLinkID); inc(LinkIndex); end; DrawTextW(Canvas.Handle, PWideChar(ws), length(ws), WordInfo.FRect, DT_NOPREFIX or DT_LEFT or DT_SINGLELINE); end; end; end; end; end.
{*! * Fano Web Framework (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano * @copyright Copyright (c) 2018 Zamrony P. Juhara * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) *} unit IniConfigImpl; interface {$MODE OBJFPC} {$H+} uses IniFiles, DependencyIntf, ConfigIntf; type (*!------------------------------------------------------------ * Application configuration base class that load data from INI * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-------------------------------------------------------------*) TIniConfig = class(TInterfacedObject, IAppConfiguration, IDependency) private fDefaultSection : string; procedure getSectionIdentFromConfigName( const configName : string; var section : string; var ident : string ); protected FIniConfig :TIniFile; function buildIniData() : TIniFile; virtual; abstract; public constructor create(const defaultSection : string); destructor destroy(); override; function getString(const configName : string; const defaultValue : string = '') : string; function getInt(const configName : string; const defaultValue : integer = 0) : integer; function getBool(const configName : string; const defaultValue : boolean = false) : boolean; end; implementation uses sysutils, classes; constructor TIniConfig.create(const defaultSection : string); begin fDefaultSection := defaultSection; fIniConfig := buildIniData(); end; destructor TIniConfig.destroy(); begin fIniConfig.free(); inherited destroy(); end; procedure TIniConfig.getSectionIdentFromConfigName( const configName : string; var section : string; var ident : string ); var sectionPos : integer; begin sectionPos := pos('.', configName); if sectionPos = 0 then begin //no section found, use default section section := fDefaultSection; ident := configName; end else begin section := copy(configName, 1, sectionPos - 1); ident := copy(configName, sectionPos + 1, length(configName) - sectionPos); end; end; function TIniConfig.getString(const configName : string; const defaultValue : string = '') : string; var section, ident : string; begin getSectionIdentFromConfigName(configName, section, ident); result := fIniConfig.readString(section, ident, defaultValue); end; function TIniConfig.getInt(const configName : string; const defaultValue : integer = 0) : integer; var section, ident : string; begin getSectionIdentFromConfigName(configName, section, ident); result := fIniConfig.readInteger(section, ident, defaultValue); end; function TIniConfig.getBool(const configName : string; const defaultValue : boolean = false) : boolean; var section, ident : string; begin getSectionIdentFromConfigName(configName, section, ident); result := fIniConfig.readBool(section, ident, defaultValue); end; end.
unit uframe; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Windows, uModbus, uBase; type { TFrame } TFrame = class(TPriorityItem, IFrame) private fSlaveId: byte; fRequestCount: longint; fResponseCount: longint; fRequestPdu: TPdu; fResponsePdu: TPdu; fTimeout: dword; fResponseEvent: THandle; fString: string; protected function GetSlaveId: byte; procedure SetSlaveId(const aSlaveId: byte); function GetRequestCount: Longint; procedure SetRequestCount(const aCount: longint); function GetResponseCount: Longint; procedure SetResponseCount(const aCount: longint); function GetRequestPdu: PPdu; function GetResponsePdu: PPdu; function GetTimeout: dword; procedure SetTimeout(const aTimeout: dword); function GetResponded: boolean; procedure SetResponded(const aResponded: boolean); public constructor Create; destructor Destroy; override; public function ToString: string; reintroduce; property SlaveId: byte read GetSlaveId write SetSlaveId; property RequestCount: longint read GetRequestCount write SetRequestCount; property ResponseCount: longint read GetResponseCount write SetResponseCount; property RequestPdu: PPdu read GetRequestPdu; property ResponsePdu: PPdu read GetResponsePdu; property Timeout: dword read GetTimeout write SetTimeout; property Responded: boolean read GetResponded write SetResponded; end; implementation { TFrame } constructor TFrame.Create; begin inherited Create; fResponseEvent := CreateEvent(nil, false, false, ''); end; destructor TFrame.Destroy; begin CloseHandle(fResponseEvent); inherited Destroy; end; function TFrame.ToString: string; var RequestStr: String; ResponseStr: String; I: Integer; begin RequestStr := ''; if fRequestCount > 0 then for I := 0 to fRequestCount - 1 do RequestStr := RequestStr + IntToHex(fRequestPdu[I], 2) + ' '; ResponseStr := ''; if fResponseCount > 0 then for I := 0 to fResponseCount - 1 do ResponseStr := ResponseStr + IntToHex(fResponsePdu[I], 2) + ' '; fString := ''; fString := fString + Format('Адрес устройства: %d', [fSlaveId]) + #13#10; fString := fString + Format('Запрос: %s', [RequestStr]) + #13#10; fString := fString + Format('Ответ: %s', [ResponseStr]) + #13#10; Result := fString; end; function TFrame.GetSlaveId: byte; begin Result := fSlaveId; end; procedure TFrame.SetSlaveId(const aSlaveId: byte); begin if fSlaveId <> aSlaveId then fSlaveId := aSlaveId; end; function TFrame.GetRequestCount: Longint; begin Result := fRequestCount; end; procedure TFrame.SetRequestCount(const aCount: longint); begin if fRequestCount <> aCount then fRequestCount := aCount; end; function TFrame.GetResponseCount: Longint; begin Result := fResponseCount; end; procedure TFrame.SetResponseCount(const aCount: longint); begin if fResponseCount <> aCount then fResponseCount := aCount; end; function TFrame.GetRequestPdu: PPdu; begin Result := @fRequestPdu; end; function TFrame.GetResponsePdu: PPdu; begin Result := @fResponsePdu end; function TFrame.GetTimeout: dword; begin Result := fTimeout; end; procedure TFrame.SetTimeout(const aTimeout: dword); begin if fTimeout <> aTimeout then fTimeout := aTimeout; end; function TFrame.GetResponded: boolean; begin Result := WaitForSingleObject(fResponseEvent, 3 * fTimeout) = WAIT_OBJECT_0; end; procedure TFrame.SetResponded(const aResponded: boolean); begin case aResponded of true: SetEvent(fResponseEvent); false: ResetEvent(fResponseEvent); end; end; end.
unit Crud.Resource.Conexao; interface uses FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MySQLDef, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Phys.MySQL, Data.DB, FireDAC.Comp.Client, Crud.Resource.Interfaces; type TConexao = class(TInterfacedObject, iConexao) private FConn : TFDConnection; public constructor Create; destructor Destroy; override; class function New: iConexao; function Connect : TCustomConnection; end; implementation { TConexao } function TConexao.Connect: TCustomConnection; begin Result := FConn; end; constructor TConexao.Create; begin FConn := TFDConnection.Create(nil); FConn.Params.Add('DriverID=MySQL'); FConn.Params.Add('Database=db_crud'); FConn.Params.Add('User_Name=root'); FConn.Params.Add('Password=toor'); FConn.Params.Add('Server=localhost'); FConn.Params.Add('Port=3306'); FConn.Params.Add('CharacterSet=utf8'); FConn.Params.Add('Compress=True'); FConn.Params.Add('UseSSL=True'); FConn.Connected := True; end; destructor TConexao.Destroy; begin FConn.DisposeOf; inherited; end; class function TConexao.New: iConexao; begin Result := Self.Create; end; end.
unit CustomPatchFrm; interface uses dmImage, TSTOProject.Xml, TSTOCustomPatches.IO, TSTOHackSettings, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, VirtualTrees, {$If CompilerVersion = 18.5}VirtualTrees.D2007Types,{$EndIf} Dialogs, ComCtrls, ToolWin, StdCtrls, ExtCtrls, Menus, Tabs, SpTBXExControls, TB2Dock, TB2Toolbar, SpTBXItem, TB2Item, SpTBXControls, SpTBXDkPanels, SpTBXTabs, SciScintillaBase, SciScintillaMemo, SciScintilla, SciScintillaNPP, SciLanguageManager, SciActions, System.Actions, Vcl.ActnList; type TFrmCustomPatches = class(TForm) PanInfo: TPanel; PanTreeView: TPanel; vstPatchData: TSpTBXVirtualStringTree; dckTbMain: TSpTBXDock; tbMainV2: TSpTBXToolbar; tbSave: TSpTBXItem; SplitterV2: TSpTBXSplitter; gbPatchInfoV2: TSpTBXGroupBox; tsXmlV2: TSpTBXTabSet; tsOutput: TSpTBXTabItem; tsXPathResult: TSpTBXTabItem; tsInput: TSpTBXTabItem; vstCustomPacthes: TSpTBXVirtualStringTree; lblPatchName: TLabel; EditPatchName: TEdit; lblPatchDesc: TLabel; EditPatchDesc: TEdit; lblPatchFileName: TLabel; EditPatchFileName: TEdit; EditXml: TScintillaNPP; popVSTCustomPatches: TSpTBXPopupMenu; popDeletePatch: TSpTBXItem; popAddPatch: TSpTBXItem; actlstScintilla: TActionList; SciToggleBookMark1: TSciToggleBookMark; SciNextBookmark1: TSciNextBookmark; SciPrevBookmark1: TSciPrevBookmark; SciFoldAll1: TSciFoldAll; SciUnFoldAll1: TSciUnFoldAll; SciCollapseCurrentLevel1: TSciCollapseCurrentLevel; SciUnCollapseCurrentLevel1: TSciUnCollapseCurrentLevel; SciCollapseLevel11: TSciCollapseLevel1; SciCollapseLevel21: TSciCollapseLevel2; SciCollapseLevel31: TSciCollapseLevel3; SciCollapseLevel41: TSciCollapseLevel4; SciExpandLevel11: TSciExpandLevel1; SciExpandLevel21: TSciExpandLevel2; SciExpandLevel31: TSciExpandLevel3; SciExpandLevel41: TSciExpandLevel4; popVSTPatchData: TSpTBXPopupMenu; popAddPatchData: TSpTBXItem; popDeletePatchData: TSpTBXItem; procedure FormCreate(Sender: TObject); procedure tbSaveOldClick(Sender: TObject); procedure tsXmlV1Change(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); procedure vstCustomPacthesInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure vstCustomPacthesFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); procedure vstPatchDataInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure vstPatchDataCreateEditor(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink); procedure vstPatchDataFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); procedure vstPatchDataKeyAction(Sender: TBaseVirtualTree; var CharCode: Word; var Shift: TShiftState; var DoDefault: Boolean); procedure vstPatchDataAfterCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellRect: TRect); procedure tsXmlV2ActiveTabChange(Sender: TObject; TabIndex: Integer); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure vstPatchDataGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure vstCustomPacthesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure FormActivate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure EditPatchNameExit(Sender: TObject); procedure EditPatchDescExit(Sender: TObject); procedure EditPatchFileNameExit(Sender: TObject); procedure popAddPatchClick(Sender: TObject); procedure popAddPatchDataClick(Sender: TObject); procedure popDeletePatchClick(Sender: TObject); procedure popDeletePatchDataClick(Sender: TObject); Private FProject : ITSTOXMLProject; FHackSettings : ITSTOHackSettings; FCustomPatches : ITSTOCustomPatchesIO; FFormSettings : ITSTOXMLFormSetting; FPrevPatch : PVirtualNode; FPrevPatchData : PVirtualNode; Procedure SetProject(AProject : ITSTOXMLProject); Procedure SetHackSettings(AHackSettings : ITSTOHackSettings); Function GetLangMgr() : TSciLanguageManager; Procedure SetLangMgr(ALangMgr : TSciLanguageManager); Procedure SetNodeData(ANode : PVirtualNode; ANodeData : IInterface); Function GetNodeData(ANode : PVirtualNode; AId : TGUID; Var ANodeData) : Boolean; OverLoad; Procedure DisplayXml(APatch : ITSTOCustomPatchIO; AIndex : Integer = -1); Procedure DoOnPatchesChanged(Sender : TObject); Published Property ProjectFile : ITSTOXMLProject Read FProject Write SetProject; Property HackSettings : ITSTOHackSettings Read FHackSettings Write SetHackSettings; Property LangMgr : TSciLanguageManager Read GetLangMgr Write SetLangMgr; end; implementation Uses SpTBXSkins, RTTI, TypInfo, XmlDoc, HsFunctionsEx, HsXmlDocEx, HsStreamEx, VTEditors, VTCombos, TSTOPatches; {$R *.dfm} procedure TFrmCustomPatches.FormActivate(Sender: TObject); Var X : Integer; begin WindowState := TRttiEnumerationType.GetValue<TWindowState>(FFormSettings.WindowState); If WindowState = wsNormal Then Begin Left := FFormSettings.X; Top := FFormSettings.Y; Height := FFormSettings.H; Width := FFormSettings.W; End; For X := 0 To FFormSettings.Count - 1 Do If SameText(FFormSettings[X].SettingName, 'SplitTvsLeft') Then PanTreeView.Width := FFormSettings[X].SettingValue; end; procedure TFrmCustomPatches.FormCloseQuery(Sender: TObject; var CanClose: Boolean); Var lSetting : ITSTOXmlCustomFormSetting; X : Integer; begin CanClose := True; If FCustomPatches.Modified Then Case MessageDlg('Save changes to Custom patches ?', mtInformation, [mbYes, mbNo, mbCancel], 0) Of mrYes : tbSaveOldClick(Self); mrCancel : CanClose := False; End; If CanClose Then Begin FFormSettings.WindowState := TRttiEnumerationType.GetName(WindowState); If WindowState <> wsMaximized Then Begin FFormSettings.X := Left; FFormSettings.Y := Top; FFormSettings.H := Height; FFormSettings.W := Width; End; lSetting := Nil; For X := 0 To FFormSettings.Count - 1 Do If SameText(FFormSettings[X].SettingName, 'SplitTvsLeft') Then Begin lSetting := FFormSettings[X]; End; If Not Assigned(lSetting) Then lSetting := FFormSettings.Add(); lSetting.SettingName := 'SplitTvsLeft'; lSetting.SettingValue := PanTreeView.Width; End; end; procedure TFrmCustomPatches.FormCreate(Sender: TObject); Var lTop, lLeft : Integer; X : Integer; lControl : TControl; begin FPrevPatch := Nil; FPrevPatchData := Nil; If SameText(SkinManager.CurrentSkin.SkinName, 'WMP11') Then Begin vstCustomPacthes.Color := $00262525; vstCustomPacthes.Font.Color := $00F1F1F1; vstPatchData.Color := $00262525; vstPatchData.Font.Color := $00F1F1F1; PanTreeView.Color := $00262525; PanInfo.Color := $00262525; End; end; procedure TFrmCustomPatches.FormKeyPress(Sender: TObject; var Key: Char); begin If Key = #27 Then Begin Key := #0; Close; End; end; Procedure TFrmCustomPatches.SetProject(AProject : ITSTOXMLProject); Var lXml : IXmlDocumentEx; X : Integer; Begin lXml := LoadXmlData(AProject.OwnerDocument.Xml.Text); Try FProject := TTSTOXmlTSTOProject.GetTSTOProject(lXml); For X := 0 To AProject.Settings.FormPos.Count - 1 Do If SameText(AProject.Settings.FormPos[X].Name, Self.ClassName) Then Begin FFormSettings := AProject.Settings.FormPos[X]; Break; End; If Not Assigned(FFormSettings) Then Begin FFormSettings := AProject.Settings.FormPos.Add(); FFormSettings.Name := Self.ClassName; FFormSettings.WindowState := TRttiEnumerationType.GetName(WindowState); FFormSettings.X := Left; FFormSettings.Y := Top; FFormSettings.H := Height; FFormSettings.W := Width; With FFormSettings.Add() Do Begin SettingName := 'SplitTvsLeft'; SettingValue := PanTreeView.Width; End; End; // vstCustomPacthes.RootNodeCount := FProject.CustomPatches.Patches.Count; Finally lXml := Nil; End; End; Procedure TFrmCustomPatches.SetHackSettings(AHackSettings : ITSTOHackSettings); Begin FHackSettings := AHackSettings; If Assigned(FHackSettings) Then Begin FCustomPatches := TTSTOCustomPatchesIO.CreateCustomPatchIO(); FCustomPatches.Assign(FHackSettings.CustomPatches); FCustomPatches.OnChange := DoOnPatchesChanged; vstCustomPacthes.RootNodeCount := FCustomPatches.Patches.Count; End; End; Function TFrmCustomPatches.GetLangMgr() : TSciLanguageManager; Begin Result := EditXml.LanguageManager; End; Procedure TFrmCustomPatches.SetLangMgr(ALangMgr : TSciLanguageManager); Begin EditXml.LanguageManager := ALangMgr; EditXml.SelectedLanguage := 'XML'; EditXml.Folding := EditXml.Folding + [foldFold]; End; Procedure TFrmCustomPatches.DoOnPatchesChanged(Sender : TObject); Begin tbSave.Enabled := FCustomPatches.Modified; End; procedure TFrmCustomPatches.EditPatchDescExit(Sender: TObject); Var lPatch : ITSTOCustomPatchIO; begin If GetNodeData(FPrevPatch, ITSTOCustomPatchIO, lPatch) Then lPatch.PatchDesc := EditPatchDesc.Text; end; procedure TFrmCustomPatches.EditPatchFileNameExit(Sender: TObject); Var lPatch : ITSTOCustomPatchIO; begin If GetNodeData(FPrevPatch, ITSTOCustomPatchIO, lPatch) Then lPatch.FileName := EditPatchFileName.Text; end; procedure TFrmCustomPatches.EditPatchNameExit(Sender: TObject); Var lPatch : ITSTOCustomPatchIO; begin If GetNodeData(FPrevPatch, ITSTOCustomPatchIO, lPatch) Then lPatch.PatchName := EditPatchName.Text; end; procedure TFrmCustomPatches.tbSaveOldClick(Sender: TObject); Var lStrStream : IStringStreamEx; lMem : IMemoryStreamEx; begin If FCustomPatches.Modified Then Begin FHackSettings.CustomPatches.Assign(FCustomPatches); FHackSettings.CustomPatches.ForceChanged(); FCustomPatches.ClearChanges(); End; ModalResult := mrOk; end; procedure TFrmCustomPatches.tsXmlV1Change(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); Var lPatch : ITSTOCustomPatchIO; begin If GetNodeData(FPrevPatch, ITSTOCustomPatchIO, lPatch) Then DisplayXml(lPatch, NewTab); end; procedure TFrmCustomPatches.tsXmlV2ActiveTabChange(Sender: TObject; TabIndex: Integer); Var lPatch : ITSTOCustomPatchIO; begin If GetNodeData(FPrevPatch, ITSTOCustomPatchIO, lPatch) Then DisplayXml(lPatch, TabIndex); end; Function TFrmCustomPatches.GetNodeData(ANode : PVirtualNode; AId : TGUID; Var ANodeData) : Boolean; Var lNodeData : PPointer; Begin If Assigned(ANode) Then Begin lNodeData := TreeFromNode(ANode).GetNodeData(ANode); Result := Assigned(lNodeData^) And Supports(IInterface(lNodeData^), AId, ANodeData); End Else Result := False; End; procedure TFrmCustomPatches.popAddPatchClick(Sender: TObject); begin FCustomPatches.Patches.Add().PatchName := '<NewPatch>'; With vstCustomPacthes Do ReinitNode(AddChild(Nil), False); end; procedure TFrmCustomPatches.popAddPatchDataClick(Sender: TObject); Var lPatch : ITSTOCustomPatchIO; begin If GetNodeData(FPrevPatch, ITSTOCustomPatchIO, lPatch) Then Begin lPatch.PatchData.Add(); With vstPatchData Do ReinitNode(AddChild(Nil), False); End; end; procedure TFrmCustomPatches.popDeletePatchClick(Sender: TObject); Var lNode : PVirtualNode; lPatch : ITSTOCustomPatchIO; begin If MessageConfirm('Do you want to delete this patch?') Then With vstCustomPacthes Do Begin lNode := GetFirstSelected(); If Self.GetNodeData(lNode, ITSTOCustomPatchIO, lPatch) Then Begin FCustomPatches.Patches.Remove(lPatch); DeleteNode(lNode); End; End; end; procedure TFrmCustomPatches.popDeletePatchDataClick(Sender: TObject); Var lNode : PVirtualNode; lPatch : ITSTOCustomPatchIO; lPatchData : ITSTOPatchDataIO; begin If MessageConfirm('Do you want to delete this patch item?') Then With vstPatchData Do Begin lNode := GetFirstSelected(); If Self.GetNodeData(FPrevPatch, ITSTOCustomPatchIO, lPatch) And Self.GetNodeData(lNode, ITSTOPatchDataIO, lPatchData) Then Begin DeleteNode(lNode); lPatch.PatchData.Remove(lPatchData); End; End; end; Procedure TFrmCustomPatches.SetNodeData(ANode : PVirtualNode; ANodeData : IInterface); Var lNodeData : PPointer; Begin lNodeData := TreeFromNode(ANode).GetNodeData(ANode); lNodeData^ := Pointer(ANodeData); End; Procedure TFrmCustomPatches.DisplayXml(APatch : ITSTOCustomPatchIO; AIndex : Integer = -1); Var lXml : IXmlDocumentEx; lNodes : IXmlNodeListEx; X : Integer; lModder : ITSTOModder; Begin EditXml.Lines.Text := ''; If AIndex = -1 Then AIndex := tsXmlV2.ActiveTabIndex; If FileExists(FProject.Settings.SourcePath + APatch.FileName) Then Case AIndex Of 0 : Begin With TStringList.Create() Do Try LoadFromFile(FProject.Settings.SourcePath + APatch.FileName); If Copy(Text, 1, 3) = #$EF#$BB#$BF Then Text := Copy(Text, 4, Length(Text)); EditXml.Lines.Text := FormatXmlData(Text); Finally Free(); End; End; 1 : Begin //EditXml.BeginUpdate(); lXml := LoadXMLDocument(FProject.Settings.SourcePath + APatch.FileName); Try EditXml.Lines.Text := ''; For X := 0 To APatch.PatchData.Count - 1 Do Begin If APatch.PatchData[X].PatchPath <> '' Then Begin lNodes := lXml.SelectNodes(APatch.PatchData[X].PatchPath); If Assigned(lNodes) Then With lNodes.Enumerator Do While MoveNext() Do With EditXml.Lines Do Text := Text + FormatXmlData(Current.Xml); End; End; Finally lXml := Nil; //EditXml.EndUpdate(); End; End; 2 : Begin //EditXml.BeginUpdate(); lXml := LoadXMLDocument(FProject.Settings.SourcePath + APatch.FileName); lModder := TTSTOModder.Create(); Try lModder.PreviewCustomPatches(lXml, APatch.PatchData); EditXml.Lines.Text := FormatXmlData(lXml.Xml.Text); Finally lModder := Nil; lXml := Nil; // EditXml.EndUpdate(); End; End; End; End; procedure TFrmCustomPatches.vstCustomPacthesFocusChanged( Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); Var lPatch : ITSTOCustomPatchIO; lPatchData : ITSTOPatchDataIO; begin If GetNodeData(FPrevPatch, ITSTOCustomPatchIO, lPatch) Then Try lPatch.PatchName := EditPatchName.Text; lPatch.PatchDesc := EditPatchDesc.Text; lPatch.FileName := EditPatchFileName.Text; If GetNodeData(FPrevPatchData, ITSTOPatchDataIO, lPatchData) Then Try Finally lPatchData := Nil; End; Finally lPatch := Nil; End; FPrevPatch := Node; If GetNodeData(FPrevPatch, ITSTOCustomPatchIO, lPatch) Then Try EditPatchName.Text := lPatch.PatchName; EditPatchDesc.Text := lPatch.PatchDesc; EditPatchFileName.Text := lPatch.FileName; DisplayXml(lPatch); vstPatchData.BeginUpdate(); Try If vstPatchData.IsEditing Then vstPatchData.EndEditNode(); vstPatchData.Clear(); vstPatchData.RootNodeCount := lPatch.PatchData.Count; Finally vstPatchData.EndUpdate(); End; FPrevPatchData := Nil; Finally lPatch := Nil; End; end; procedure TFrmCustomPatches.vstCustomPacthesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); Var lNodeData : ITSTOCustomPatchIO; begin If GetNodeData(Node, ITSTOCustomPatchIO, lNodeData) Then CellText := lNodeData.PatchName Else CellText := ''; end; procedure TFrmCustomPatches.vstCustomPacthesInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); begin SetNodeData(Node, FCustomPatches.Patches[Node.Index]); //FProject.CustomPatches.Patches[Node.Index]); end; (******************************************************************************) Type TVTPatchDataEditor = Class(TInterfacedObject, IVTEditLink) Private FEdit : TWinControl; FTree : TCustomVirtualStringTree;//TVirtualStringTree; FNode : PVirtualNode; FColumn : Integer; Procedure EditKeyDown(Sender : TObject; Var Key : Word; Shift : TShiftState); Procedure EditKeyUp(Sender : TObject; Var Key : Word; Shift : TShiftState); Protected Function BeginEdit() : Boolean; StdCall; Function CancelEdit() : Boolean; StdCall; Function EndEdit() : Boolean; StdCall; Function GetBounds() : TRect; StdCall; Procedure SetBounds(R : TRect); StdCall; Function PrepareEdit(Tree : TBaseVirtualTree; Node : PVirtualNode; Column : TColumnIndex): Boolean; StdCall; Procedure ProcessMessage(Var Message: TMessage); StdCall; Public Destructor Destroy(); OverRide; End; Const _PATCH_TYPE : Array[0..3] Of String = ( 'Add Attributes', 'Delete Attributes', 'Add Nodes', 'Delete Nodes' ); Destructor TVTPatchDataEditor.Destroy(); Begin If Assigned(FEdit) And FEdit.HandleAllocated Then PostMessage(FEdit.Handle, CM_RELEASE, 0, 0); InHerited Destroy(); End; Procedure TVTPatchDataEditor.EditKeyDown(Sender : TObject; Var Key : Word; Shift : TShiftState); Var CanAdvance : Boolean; Begin Case Key Of VK_ESCAPE : Key := 0; VK_RETURN : Begin FTree.EndEditNode(); Key := 0; End; VK_UP, VK_DOWN : Begin CanAdvance := Shift = []; If FEdit Is TVirtualStringTreeDropDown Then CanAdvance := CanAdvance And Not TVirtualStringTreeDropDown(FEdit).DroppedDown; If CanAdvance Then Begin PostMessage(FTree.Handle, WM_KEYDOWN, Key, 0); Key := 0; End; End; End; End; Procedure TVTPatchDataEditor.EditKeyUp(Sender : TObject; Var Key : Word; Shift : TShiftState); Begin Case Key Of VK_ESCAPE : Begin FTree.CancelEditNode(); Key := 0; End; End; End; Function TVTPatchDataEditor.BeginEdit() : Boolean; Begin Result := True; FEdit.Show(); FEdit.SetFocus(); End; Function TVTPatchDataEditor.CancelEdit() : Boolean; Begin Result := True; FEdit.Hide(); FTree.SetFocus(); End; Function TVTPatchDataEditor.EndEdit() : Boolean; Var lPatch : PPointer; lPatchData : ITSTOPatchDataIO; Begin Result := True; lPatch := FTree.GetNodeData(FNode); If Assigned(lPatch) And Supports(IInterface(lPatch^), ITSTOPatchDataIO, lPatchData) Then Case FColumn Of 0 : lPatchData.PatchType := TVirtualStringTreeDropDown(FEdit).ItemIndex + 1; 1 : lPatchData.PatchPath := THsVTEdit(FEdit).Text; 2 : lPatchData.Code := TMemo(FEdit).Lines.Text; End; FEdit.Hide(); FTree.SetFocus(); End; Function TVTPatchDataEditor.GetBounds() : TRect; Begin Result := FEdit.BoundsRect; End; Type TVSTreeAccess = Class(TCustomVirtualStringTree); Procedure TVTPatchDataEditor.SetBounds(R : TRect); Var Dummy : Integer; Begin TVSTreeAccess(FTree).Header.Columns.GetColumnBounds(FColumn, Dummy, R.Right); If FEdit Is TMemo Then R.Bottom := FTree.Height - TVSTreeAccess(FTree).Header.Height; FEdit.BoundsRect := R; End; Function TVTPatchDataEditor.PrepareEdit(Tree : TBaseVirtualTree; Node : PVirtualNode; Column : TColumnIndex): Boolean; Function CreateEdit() : TWinControl; Begin Result := THsVTEdit.Create(Nil); With Result As THsVTEdit Do Begin Visible := False; Parent := Tree; OnKeyDown := EditKeyDown; OnKeyUp := EditKeyUp; End; End; Function CreateComboBox() : TWinControl; Begin Result := TVirtualStringTreeDropDown.Create(Nil); With Result As TVirtualStringTreeDropDown Do Begin Visible := False; Parent := Tree; OnKeyDown := EditKeyDown; OnKeyUp := EditKeyUp; End; End; Function CreateMemo() : TWinControl; Begin Result := TMemo.Create(Nil); With Result As TMemo Do Begin Visible := False; Parent := Tree; ScrollBars := ssVertical; End; End; Var lNodeData : PPointer; lPatchData : ITSTOPatchDataIO; X : Integer; Begin Result := True; FTree := Tree As TCustomVirtualStringTree;//TVirtualStringTree; FNode := Node; FColumn := Column; If Assigned(FEdit) Then FreeAndNil(FEdit); lNodeData := FTree.GetNodeData(Node); If Assigned(lNodeData) And Supports(IInterface(lNodeData^), ITSTOPatchDataIO, lPatchData) Then Case Column Of 0 : Begin FEdit := CreateComboBox(); With FEdit As TVirtualStringTreeDropDown Do Begin For X := Low(_PATCH_TYPE) To High(_PATCH_TYPE) Do Items.Add(_PATCH_TYPE[X]); ItemIndex := lPatchData.PatchType - 1; End; End; 1 : Begin FEdit := CreateEdit(); With FEdit As THsVTEdit Do Text := lPatchData.PatchPath; End; 2 : Begin FEdit := CreateMemo(); With FEdit As TMemo Do Lines.Text := lPatchData.Code; (*## FEdit := CreateMemo(); With FEdit As TMemo Do For X := 0 To lPatchData.Code.ChildNodes.Count - 1 Do Lines.Add(lPatchData.Code.ChildNodes[X].Xml); *) End; End; End; Procedure TVTPatchDataEditor.ProcessMessage(Var Message: TMessage); Begin FEdit.WindowProc(Message); End; (******************************************************************************) procedure TFrmCustomPatches.vstPatchDataAfterCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellRect: TRect); Function MouseInCell() : Boolean; Var lRect : TRect; lPt : TPoint; lParent : TWinControl; Begin lRect := TVirtualStringTree(Sender).Header.Columns[Column].GetRect(); lPt := Mouse.CursorPos; lParent := Sender; While Assigned(lParent) Do Begin Dec(lPt.X, lParent.Left); lParent := lParent.Parent; End; Result := (lPt.X >= lRect.Left) And (lPt.X <= lRect.Right); End; Var lRect : TRect; lCurState : TSpTBXSkinStatesType; lCellText : String; lPatchData : ITSTOPatchDataIO; begin lRect := TVirtualStringTree(Sender).Header.Columns[Column].GetRect(); TargetCanvas.Brush.Color := TVirtualStringTree(Sender).Color; TargetCanvas.Pen.Color := TargetCanvas.Brush.Color; TargetCanvas.Rectangle(CellRect); lRect.Top := CellRect.Top; lRect.Bottom := CellRect.Bottom; With TVirtualStringTree(Sender), TreeOptions Do If (Node = FocusedNode) And ((Column = Sender.FocusedColumn) Or (toFullRowSelect In SelectionOptions)) Then Begin If CurrentSkin.Options(skncListItem, sknsChecked).IsEmpty Then lCurState := sknsHotTrack Else lCurState := sknsChecked; End Else If (Node = HotNode) And (MouseInCell() Or (toFullRowSelect In SelectionOptions)) Then lCurState := sknsHotTrack Else lCurState := sknsNormal; If (lCurState <> sknsNormal) And Not CurrentSkin.Options(skncListItem, lCurState).IsEmpty Then CurrentSkin.PaintBackground( TargetCanvas, lRect, skncListItem, lCurState, True, True ); TargetCanvas.Brush.Style := bsClear; TargetCanvas.Font.Assign(Sender.Font); If Sender.Font.Color = clNone Then If CurrentSkin.Options(skncListItem, lCurState).TextColor <> clNone Then TargetCanvas.Font.Color := CurrentSkin.Options(skncListItem, lCurState).TextColor; lRect.Left := lRect.Left + 8; lRect.Top := (lRect.Bottom - lRect.Top - TargetCanvas.TextHeight('XXX')) Div 2; lCellText := ''; If GetNodeData(Node, ITSTOPatchDataIO, lPatchData) Then Case Column Of 0 : lCellText := _PATCH_TYPE[lPatchData.PatchType - 1]; 1 : lCellText := lPatchData.PatchPath; 2 : lCellText := lPatchData.Code; (*## 2 : Begin If lPatchData.Code.ChildNodes.Count > 0 Then lCellText := lPatchData.Code.ChildNodes[0].Xml; End; *) End; TargetCanvas.TextOut( lRect.Left, lRect.Top, lCellText ); end; procedure TFrmCustomPatches.vstPatchDataCreateEditor(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink); begin EditLink := TVTPatchDataEditor.Create(); end; procedure TFrmCustomPatches.vstPatchDataFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); begin If Sender.IsEditing Then Sender.EndEditNode(); If Assigned(Node) Then Sender.EditNode(Node, Column); FPrevPatchData := Node; end; procedure TFrmCustomPatches.vstPatchDataGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); Var lPatchData : ITSTOPatchDataIO; begin CellText := ''; If GetNodeData(Node, ITSTOPatchDataIO, lPatchData) Then Case Column Of 0 : CellText := _PATCH_TYPE[lPatchData.PatchType - 1]; 1 : CellText := lPatchData.PatchPath; 2 : CellText := lPatchData.Code; (*## 2 : Begin If lPatchData.Code.ChildNodes.Count > 0 Then CellText := lPatchData.Code.ChildNodes[0].Xml; End; *) End; end; procedure TFrmCustomPatches.vstPatchDataInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); Var lPatch : ITSTOCustomPatchIO; begin If GetNodeData(FPrevPatch, ITSTOCustomPatchIO, lPatch) Then SetNodeData(Node, lPatch.PatchData[Node.Index]); end; procedure TFrmCustomPatches.vstPatchDataKeyAction(Sender: TBaseVirtualTree; var CharCode: Word; var Shift: TShiftState; var DoDefault: Boolean); Var lPatch : ITSTOCustomPatchIO; lPatchData : ITSTOPatchDataIO; begin If CharCode = VK_DOWN Then Begin If Not Assigned(FPrevPatchData.NextSibling) And GetNodeData(FPrevPatch, ITSTOCustomPatchIO, lPatch) Then Begin lPatchData := lPatch.PatchData.Add(); lPatchData.PatchType := 1; Sender.AddChild(Nil, Pointer(lPatchData)); End; End Else If (ssCtrl In Shift) And (CharCode = VK_DELETE) And GetNodeData(FPrevPatch, ITSTOCustomPatchIO, lPatch) And GetNodeData(FPrevPatchData, ITSTOPatchDataIO, lPatchData) And (MessageDlg('Do you want to delete this patch?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) Then Begin Sender.DeleteNode(FPrevPatchData); lPatch.PatchData.Remove(lPatchData); FPrevPatchData := Nil; End; end; //http://www.xnxx.com/video-16n3p42/geile_stiefelschlampen_ficken_sich_gegenseitig //http://www.xnxx.com/video-611oyc9/two_lesbians_teens_licking_pussy_and_fuck_with_a_dildo end.
unit UtilString; interface uses Classes; procedure Split(const Delimiter: Char; const Input: string; const Destination: TStrings); function FormatCurr(const Curr: currency): string; function CreateName(const seed: string): string; procedure ReplaceLastChar(var s: string; const oldChar, newChar: char); implementation uses SysUtils, StrUtils; procedure ReplaceLastChar(var s: string; const oldChar, newChar: char); var i: Integer; begin for i := length(s) downto 1 do begin if s[i] = oldChar then begin s[i] := newChar; exit; end; end; end; function CreateName(const seed: string): string; var i, num, count: integer; c: char; begin num := length(seed); SetLength(result, num); count := 0; for i := 1 to num do begin c := seed[i]; if c in ['A'..'Z', 'a'..'z'] then begin inc(count); result[count] := c; end; end; SetLength(result, count); end; function FormatCurr(const Curr: currency): string; begin result := FloatToStrF(Curr, ffCurrency, 10, CurrencyDecimals); end; procedure Split(const Delimiter: Char; const Input: string; const Destination: TStrings); var i, j: integer; cad: string; begin Assert(Assigned(Destination)); Destination.Clear; i := 1; j := Pos(Delimiter, Input); if j = 0 then begin cad := Input; if cad <> '' then Destination.Add(cad); end else begin repeat cad := Copy(Input, i, j - i); if cad <> '' then Destination.Add(cad); i := j + 1; j := PosEx(Delimiter, Input, i); until j = 0; if i < length(Input) then begin cad := Copy(Input, i, length(Input)); Destination.Add(cad); end; end; end; end.
// Редактирование текущих настроек контроллера unit uModbusFormData; {$mode objfpc}{$H+} interface uses Classes, SysUtils, uCustomEditor, upropertyeditor, uConfiguratorData, uModbus; type { TModbusBaseData } TModbusBaseData = class(TPropertyData) private fModbusData: TModbusData; fReadOnly: Boolean; public constructor Create(const aCaption: string; const aModbusData: TModbusData); reintroduce; property ReadOnly: Boolean read fReadOnly write fReadOnly; end; { TCommaTextData } TCommaTextData = class(TModbusBaseData) public constructor Create(const aCaption: String; const aCommaText: String; const aModbusData: TModbusData); reintroduce; end; { TBaudRate } TBaudRate = class(TCommaTextData) protected procedure SetValue(const aValue: string); override; function GetValue: string; override; public constructor Create(const aModbusData: TModbusData); reintroduce; end; { TParity } TParity = class(TCommaTextData) protected procedure SetValue(const aValue: string); override; function GetValue: string; override; public constructor Create(const aModbusData: TModbusData); reintroduce; end; { TStopBits } TStopBits = class(TCommaTextData) protected procedure SetValue(const aValue: string); override; function GetValue: string; override; public constructor Create(const aModbusData: TModbusData); reintroduce; end; { TByteSize } TByteSize = class(TCommaTextData) protected procedure SetValue(const aValue: string); override; function GetValue: string; override; public constructor Create(const aModbusData: TModbusData); reintroduce; end; { TThreeAndHalf } TThreeAndHalf = class(TModbusBaseData) protected procedure SetValue(const aValue: string); override; function GetValue: string; override; public constructor Create(const aModbusData: TModbusData); reintroduce; end; { TIpAddress } TIpAddress = class(TModbusBaseData) protected procedure SetValue(const aValue: string); override; function GetValue: string; override; public constructor Create(const aModbusData: TModbusData); reintroduce; end; { TPort } TPort = class(TModbusBaseData) protected procedure SetValue(const aValue: string); override; function GetValue: string; override; public constructor Create(const aModbusData: TModbusData); reintroduce; end; implementation { TModbusBaseData } constructor TModbusBaseData.Create(const aCaption: string; const aModbusData: TModbusData); begin inherited Create(aCaption); fModbusData := aModbusData; fReadOnly := False; end; { TCommaTextData } constructor TCommaTextData.Create(const aCaption: String; const aCommaText: String; const aModbusData: TModbusData); begin inherited Create(aCaption, aModbusData); TypeEditor := TTypeEditor.teComboBox; Strings.CommaText := aCommaText; end; { TPort } constructor TPort.Create(const aModbusData: TModbusData); begin inherited Create('Порт', aModbusData); TypeEditor := TBaseData.TTypeEditor.teSpinEdit; end; function TPort.GetValue: string; var Port: Word; begin Port := (fModbusData.Controller.Transaction.Communication as ITcpCommunication).TcpConnection.Port; Result := IntToStr(Port); end; procedure TPort.SetValue(const aValue: string); var Port: word; Flag: Boolean; begin Port := StrToInt(aValue); Flag := fModbusData.Controller.IsOpen; if Flag then fModbusData.Controller.Close; (fModbusData.Controller.Transaction.Communication as ITcpCommunication).TcpConnection.Port := Port; if Flag then fModbusData.Controller.Open; end; { TIpAddress } constructor TIpAddress.Create(const aModbusData: TModbusData); begin inherited Create('IP-адрес', aModbusData); TypeEditor := TBaseData.TTypeEditor.teEdit; end; function TIpAddress.GetValue: string; begin Result := (fModbusData.Controller.Transaction.Communication as ITcpCommunication).TcpConnection.Ip; end; procedure TIpAddress.SetValue(const aValue: string); var Flag: Boolean; begin Flag := fModbusData.Controller.IsOpen; if Flag then fModbusData.Controller.Close; (fModbusData.Controller.Transaction.Communication as ITcpCommunication).TcpConnection.Ip := aValue; if Flag then fModbusData.Controller.Open; end; { TThreeAndHalf } constructor TThreeAndHalf.Create(const aModbusData: TModbusData); begin inherited Create('Таймаут в 3,5 байта', aModbusData); TypeEditor := TTypeEditor.teSpinEdit; end; function TThreeAndHalf.GetValue: string; var ThreeAndHalf: Dword; begin ThreeAndHalf := (fModbusData.Controller.Transaction.Communication as IRtuCommunication).RtuConnection.ThreeAndHalf; Result := IntToStr(ThreeAndHalf); end; procedure TThreeAndHalf.SetValue(const aValue: string); var ThreeAndHalf: Integer; Flag: Boolean; begin ThreeAndHalf := StrToInt(aValue); Flag := fModbusData.Controller.IsOpen; if Flag then fModbusData.Controller.Close; (fModbusData.Controller.Transaction.Communication as IRtuCommunication).RtuConnection.ThreeAndHalf := ThreeAndHalf; if Flag then fModbusData.Controller.Open; end; { TByteSize } constructor TByteSize.Create(const aModbusData: TModbusData); begin inherited Create( 'Число бит в байте', '6,7,8', aModbusData); end; function TByteSize.GetValue: string; var ByteSize: Dword; begin ByteSize := (fModbusData.Controller.Transaction.Communication as IRtuCommunication).RtuConnection.ByteSize; Result := IntToStr(ByteSize); end; procedure TByteSize.SetValue(const aValue: string); var ByteSize: Dword; Flag: Boolean; begin ByteSize := StrToInt(aValue); Flag := fModbusData.Controller.IsOpen; if Flag then fModbusData.Controller.Close; (fModbusData.Controller.Transaction.Communication as IRtuCommunication).RtuConnection.ByteSize := ByteSize; if Flag then fModbusData.Controller.Open; end; { TStopBits } constructor TStopBits.Create(const aModbusData: TModbusData); begin inherited Create( 'Количество стоповых бит', '0,1,2', aModbusData); end; function TStopBits.GetValue: string; var StopBits: Dword; begin StopBits := (fModbusData.Controller.Transaction.Communication as IRtuCommunication).RtuConnection.StopBits; Result := IntToStr(StopBits); end; procedure TStopBits.SetValue(const aValue: string); var StopBits: Dword; Flag: Boolean; begin StopBits := StrToInt(aValue); Flag := fModbusData.Controller.IsOpen; if Flag then fModbusData.Controller.Close; (fModbusData.Controller.Transaction.Communication as IRtuCommunication).RtuConnection.StopBits := StopBits; if Flag then fModbusData.Controller.Open; end; { TParity } constructor TParity.Create(const aModbusData: TModbusData); begin inherited Create( 'Режим проверки четности', '0,1,2,3', aModBusData); end; function TParity.GetValue: string; var Parity: Dword; begin Parity := (fModbusData.Controller.Transaction.Communication as IRtuCommunication).RtuConnection.Parity; Result := IntToStr(Parity); end; procedure TParity.SetValue(const aValue: string); var Parity: Dword; Flag: Boolean; begin Parity := StrToInt(aValue); Flag := fModbusData.Controller.IsOpen; if Flag then fModbusData.Controller.Close; (fModbusData.Controller.Transaction.Communication as IRtuCommunication).RtuConnection.Parity := Parity; if Flag then fModbusData.Controller.Open; end; { TBaudRate } constructor TBaudRate.Create(const aModbusData: TModbusData); begin inherited Create( 'Скорость передачи данных', '1200,2400,4800,9600,14400,19200,38400,56000,57600,115200,128000,256000', aModbusData); end; function TBaudRate.GetValue: string; var BaudRate: Dword; begin BaudRate := (fModbusData.Controller.Transaction.Communication as IRtuCommunication).RtuConnection.BaudRate; Result := IntToStr(BaudRate); end; procedure TBaudRate.SetValue(const aValue: string); var BaudRate: Dword; Flag: Boolean; begin BaudRate := StrToInt(aValue); Flag := fModbusData.Controller.IsOpen; if Flag then fModbusData.Controller.Close; (fModbusData.Controller.Transaction.Communication as IRtuCommunication).RtuConnection.BaudRate := BaudRate; if Flag then fModbusData.Controller.Open; end; end.
unit cPessoa; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TPessoa = class //Nome da classe que instanciará o objeto private // atributos e métodos privados Fcodigo :Integer; //Variáveis para uso interno da classe (Fields) Fnome :String; Fidade :Integer; protected //Métodos protegigdos Public //Métodos públicos constructor Create(nome: string); //Contrutor destructor Destroy; override; //Destructor function saberIdade(qtdAnos: Integer): Integer; //As propriedades são declaradas em public, para ficarem disponíveis property codigo :Integer read Fcodigo write Fcodigo; property nome :String read Fnome write Fnome; property idade :Integer read Fidade write Fidade; end; implementation constructor TPessoa.Create(nome: string);; begin Fnome:=nome; end; destructor TPessoa.Destroy; begin inherited; end; function TPessoa.saberIdade(qtdAnos: Integer): Integer; begin Result := Fidade + qtdAnos; end; end.
unit ServerContainerUnit; interface uses System.SysUtils, System.Classes, Vcl.SvcMgr, Datasnap.DSTCPServerTransport, Datasnap.DSServer, Datasnap.DSCommonServer, Datasnap.DSAuth, IPPeerServer; type TServerContainer1 = class(TService) DSServer1: TDSServer; DSTCPServerTransport1: TDSTCPServerTransport; DSServerClass1: TDSServerClass; procedure DSServerClass1GetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); procedure ServiceStart(Sender: TService; var Started: Boolean); private { Private declarations } protected function DoStop: Boolean; override; function DoPause: Boolean; override; function DoContinue: Boolean; override; procedure DoInterrogate; override; public function GetServiceController: TServiceController; override; end; var ServerContainer1: TServerContainer1; implementation uses Winapi.Windows, ServerMethodsUnit; {$R *.dfm} procedure TServerContainer1.DSServerClass1GetClass( DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); begin PersistentClass := ServerMethodsUnit.TServerMethodsFiltro; end; procedure ServiceController(CtrlCode: DWord); stdcall; begin ServerContainer1.Controller(CtrlCode); end; function TServerContainer1.GetServiceController: TServiceController; begin Result := ServiceController; end; function TServerContainer1.DoContinue: Boolean; begin Result := inherited; DSServer1.Start; end; procedure TServerContainer1.DoInterrogate; begin inherited; end; function TServerContainer1.DoPause: Boolean; begin DSServer1.Stop; Result := inherited; end; function TServerContainer1.DoStop: Boolean; begin DSServer1.Stop; Result := inherited; end; procedure TServerContainer1.ServiceStart(Sender: TService; var Started: Boolean); begin DSServer1.Start; end; end.
unit ACarregaDado; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ToolWin, Vcl.ComCtrls, APrincipal, Vcl.ExtCtrls, Vcl.StdCtrls; type TFCarregaDado = class(TForm) HTela: THeaderControl; Panel1: TPanel; Panel2: TPanel; PCarregaStatus: TProgressBar; MCarregaDado: TMemo; procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } Function CarregaDadoAtualiza(PpDescricao:String; PpProcesso:Integer) : String; end; var FCarregaDado: TFCarregaDado; implementation {$R *.dfm} function TFCarregaDado.CarregaDadoAtualiza(PpDescricao: String; PpProcesso: Integer): String; begin MCarregaDado.Lines.Add(PpDescricao); PCarregaStatus.Position := PpProcesso; end; procedure TFCarregaDado.FormClose(Sender: TObject; var Action: TCloseAction); begin if (PCarregaStatus.Position.MaxValue < PCarregaStatus.Position) and (PCarregaStatus.Position.MinValue > PCarregaStatus.Position) then begin ShowMessage('Processo não foi encerrado.'); Abort; end; end; end.
uses classifica, Classes, sysutils; const MAX_IN_BUF = 4096 * 4; var total_bytes_read, bytes_read : int64; input_buffer : array[0..MAX_IN_BUF-1] of char; idx_input_buffer : longint; input_stream : TFileStream; function fast_read_next_char(): Char; begin (* Take one char out of the buffer *) fast_read_next_char := input_buffer[idx_input_buffer]; inc(idx_input_buffer); if idx_input_buffer = MAX_IN_BUF then (* I'm at the end of the buffer, read another buffer *) begin if total_bytes_read <= input_stream.Size then (* We haven't reached EOF *) begin bytes_read := input_stream.Read(input_buffer, sizeof(input_buffer)); inc(total_bytes_read, bytes_read); end; idx_input_buffer := 0; end; end; (* Returns first non whitespace character *) function fast_read_char() : char; var c: Char; begin c := fast_read_next_char(); while (ord(c) = $0020) or (ord(c) = $0009) or (ord(c) = $000a) or (ord(c) = $000b) or (ord(c) = $000c) or (ord(c) = $000d) do c := fast_read_next_char(); fast_read_char := c; end; function fast_read_int() : longint; var res : longint; c : char; negative : boolean; begin res := 0; negative := False; repeat c := fast_read_next_char(); until (c = '-') or (('0' <= c) and (c <= '9')); if c = '-' then begin negative := True; c := fast_read_next_char(); end; repeat res := res * 10 + ord(c) - ord('0'); c := fast_read_next_char(); until not (('0' <= c) and (c <= '9')); if negative then fast_read_int := -res else fast_read_int := res; end; function fast_read_longint() : int64; var res : int64; c : char; negative : boolean; begin res := 0; negative := False; repeat c := fast_read_next_char(); until (c = '-') or (('0' <= c) and (c <= '9')); if c = '-' then begin negative := True; c := fast_read_next_char(); end; repeat res := res * 10 + ord(c) - ord('0'); c := fast_read_next_char(); until not (('0' <= c) and (c <= '9')); if negative then fast_read_longint := -res else fast_read_longint := res; end; function fast_read_real() : double; begin (* TODO *) fast_read_real := 42.0; end; procedure init_fast_input(file_name : string); begin input_stream := TFileStream.Create(file_name, fmOpenRead); input_stream.Position := 0; bytes_read := input_stream.Read(input_buffer, sizeof(input_buffer)); inc(total_bytes_read, bytes_read); idx_input_buffer := 0; end; procedure close_fast_input; begin input_stream.Free; end; const MAX_OUT_BUF = 4096 * 4; var output_buffer : array[0..MAX_OUT_BUF-1] of char; idx_output_buffer : longint; output_stream : TFileStream; procedure fast_write_char(x : char); begin (* Write one char onto the buffer *) output_buffer[idx_output_buffer] := x; inc(idx_output_buffer); if idx_output_buffer = MAX_OUT_BUF then (* I'm at the end of the buffer, flush it *) begin output_stream.WriteBuffer(output_buffer, sizeof(output_buffer)); idx_output_buffer := 0; end; end; procedure fast_write_int(x : longint); begin if x < 0 then (* Write the sign, then the number *) begin fast_write_char('-'); fast_write_int(-x); end else (* Write the number recursively *) begin if x >= 10 then fast_write_int(x div 10); fast_write_char(chr(ord('0') + x mod 10)); end; end; procedure fast_write_longint(x : int64); begin if x < 0 then (* Write the sign, then the number *) begin fast_write_char('-'); fast_write_longint(-x); end else (* Write the number recursively *) begin if x >= 10 then fast_write_longint(x div 10); fast_write_char(chr(ord('0') + x mod 10)); end; end; procedure fast_write_real(x : double); begin (* TODO *) fast_write_char('4'); fast_write_char('2'); fast_write_char('.'); fast_write_char('0'); end; procedure init_fast_output(file_name : string); var open_flag: word; begin open_flag := fmCreate; if FileExists(file_name) then open_flag := fmOpenWrite; output_stream := TFileStream.Create(file_name, open_flag); output_stream.size := 0; idx_output_buffer := 0; end; procedure close_fast_output; begin if idx_output_buffer > 0 then (* Gotta flush them bytez *) begin (* TODO: check if this is OK also when using unicode data *) output_stream.Write(output_buffer, idx_output_buffer * sizeof(output_buffer[0])) end; output_stream.Free; end; var { Declaring variables } N : longint; Q : longint; ids : array of longint; types : array of char; params : array of longint; answers : array of longint; { Declaring iterators used in for loops } i0: longint; { Functions ad-hoc for this grader } procedure make_calls(var Q: longint; types: array of char; params: array of longint; var answers: array of longint); var i, cnt: longint; begin cnt := 0; for i := 0 to Q-1 do begin answers[i] := 0; if types[i] = 's' then supera(params[i]) else if types[i] = 'x' then squalifica(params[i]) else if types[i] = 'p' then begin answers[cnt] := partecipante(params[i]); cnt := cnt + 1; end; end; Q := cnt; end; begin init_fast_input('input.txt'); init_fast_output('output.txt'); { Reading input } N := fast_read_int(); Q := fast_read_int(); Setlength(ids, N); for i0 := 0 to N-1 do begin ids[i0] := fast_read_int(); end; Setlength(types, Q); Setlength(params, Q); for i0 := 0 to Q-1 do begin types[i0] := fast_read_char(); params[i0] := fast_read_int(); end; { Calling functions } inizia(N, ids); Setlength(answers, Q); make_calls(Q, types, params, answers); { Writing output } for i0 := 0 to Q-1 do begin fast_write_int(answers[i0]); fast_write_char(' '); end; fast_write_char(chr(10)); close_fast_input(); close_fast_output(); end.
unit LoteValidade; interface uses SysUtils, Contnrs, ProdutoValidade, Generics.Collections; type TLoteValidade = class private Fcodigo :Integer; Fcriacao :TDateTime; Fnumero_doc :Integer; Fnumero_nota :Integer; FItensDoLote :TObjectList<TProdutoValidade>; Fmovimentar_estoque: boolean; function getItensDoLote: TObjectList<TProdutoValidade>; public property movimentar_estoque :boolean read Fmovimentar_estoque write Fmovimentar_estoque; public property codigo :Integer read Fcodigo write Fcodigo; property criacao :TDateTime read Fcriacao write Fcriacao; property numero_doc :Integer read Fnumero_doc write Fnumero_doc; property numero_nota :Integer read Fnumero_nota write Fnumero_nota; property ItensDoLote :TObjectList<TProdutoValidade> read getItensDoLote write FItensDoLote; public destructor Destroy;override; constructor Create; end; implementation uses repositorio, fabricaRepositorio, EspecificacaoItensDoLoteValidade; { TLoteValidade } constructor TLoteValidade.Create; begin Fmovimentar_estoque := false; end; destructor TLoteValidade.Destroy; begin if assigned(FItensDoLote) then FreeAndNil(FItensDoLote); inherited; end; function TLoteValidade.getItensDoLote: TObjectList<TProdutoValidade>; var repositorio :TRepositorio; especificacao :TEspecificacaoItensDoLoteValidade; begin if not assigned(FItensDoLote) then begin try repositorio := TFabricaRepositorio.GetRepositorio(TProdutoValidade.ClassName); especificacao := TEspecificacaoItensDoLoteValidade.Create(self); FItensDoLote := repositorio.GetListaPorEspecificacao<TProdutoValidade>(especificacao, intToStr(Fcodigo)); finally FreeAndNil(repositorio); FreeAndNil(especificacao); end; end; result := FItensDoLote; end; end.
unit Calculate; {$mode objfpc}{$H+} interface uses Classes, Math, SysUtils, DryConversion; { ГОСТ 23360-78 От - включительно До - включительно Свыше - НЕвключительно } type TParallelKey = record MaxDiameter: Extended; Width: Extended; Height: Extended; ShaftDepth: Extended; BushingDepth: Extended; MinRadius: Extended; MaxRadius: Extended; Tolerance: Extended; end; const ParallelKeysTableCount = 26; ParallelKeysTable: array [0..ParallelKeysTableCount - 1] of TParallelKey = ( (MaxDiameter: 0.008; Width: 0.002; Height: 0.002; ShaftDepth: 0.0012; BushingDepth: 0.001; MinRadius: 0.00008; MaxRadius: 0.00016; Tolerance: 0.0001), (MaxDiameter: 0.01; Width: 0.003; Height: 0.003; ShaftDepth: 0.0018; BushingDepth: 0.0014; MinRadius: 0.00008; MaxRadius: 0.00016; Tolerance: 0.0001), (MaxDiameter: 0.012; Width: 0.004; Height: 0.004; ShaftDepth: 0.0025; BushingDepth: 0.0018; MinRadius: 0.00008; MaxRadius: 0.00016; Tolerance: 0.0001), (MaxDiameter: 0.017; Width: 0.005; Height: 0.005; ShaftDepth: 0.003; BushingDepth: 0.0023; MinRadius: 0.00016; MaxRadius: 0.00025; Tolerance: 0.0001), (MaxDiameter: 0.022; Width: 0.006; Height: 0.006; ShaftDepth: 0.0035; BushingDepth: 0.0028; MinRadius: 0.00016; MaxRadius: 0.00025; Tolerance: 0.0001), (MaxDiameter: 0.03; Width: 0.008; Height: 0.007; ShaftDepth: 0.004; BushingDepth: 0.0033; MinRadius: 0.00016; MaxRadius: 0.00025; Tolerance: 0.0002), (MaxDiameter: 0.038; Width: 0.01; Height: 0.008; ShaftDepth: 0.005; BushingDepth: 0.0033; MinRadius: 0.00025; MaxRadius: 0.0004; Tolerance: 0.0002), (MaxDiameter: 0.044; Width: 0.012; Height: 0.008; ShaftDepth: 0.005; BushingDepth: 0.0033; MinRadius: 0.00025; MaxRadius: 0.0004; Tolerance: 0.0002), (MaxDiameter: 0.05; Width: 0.014; Height: 0.009; ShaftDepth: 0.0055; BushingDepth: 0.0038; MinRadius: 0.00025; MaxRadius: 0.0004; Tolerance: 0.0002), (MaxDiameter: 0.058; Width: 0.016; Height: 0.01; ShaftDepth: 0.006; BushingDepth: 0.0043; MinRadius: 0.00025; MaxRadius: 0.0004; Tolerance: 0.0002), (MaxDiameter: 0.065; Width: 0.018; Height: 0.011; ShaftDepth: 0.007; BushingDepth: 0.0044; MinRadius: 0.00025; MaxRadius: 0.0004; Tolerance: 0.0002), (MaxDiameter: 0.075; Width: 0.02; Height: 0.012; ShaftDepth: 0.0075; BushingDepth: 0.0049; MinRadius: 0.0004; MaxRadius: 0.0006; Tolerance: 0.0002), (MaxDiameter: 0.085; Width: 0.022; Height: 0.014; ShaftDepth: 0.009; BushingDepth: 0.0054; MinRadius: 0.0004; MaxRadius: 0.0006; Tolerance: 0.0002), (MaxDiameter: 0.095; Width: 0.025; Height: 0.014; ShaftDepth: 0.009; BushingDepth: 0.0054; MinRadius: 0.0004; MaxRadius: 0.0006; Tolerance: 0.0002), (MaxDiameter: 0.11; Width: 0.028; Height: 0.016; ShaftDepth: 0.01; BushingDepth: 0.0064; MinRadius: 0.0004; MaxRadius: 0.0006; Tolerance: 0.0002), (MaxDiameter: 0.13; Width: 0.032; Height: 0.018; ShaftDepth: 0.011; BushingDepth: 0.0074; MinRadius: 0.0004; MaxRadius: 0.0006; Tolerance: 0.0002), (MaxDiameter: 0.15; Width: 0.036; Height: 0.02; ShaftDepth: 0.012; BushingDepth: 0.0084; MinRadius: 0.0007; MaxRadius: 0.001; Tolerance: 0.0003), (MaxDiameter: 0.17; Width: 0.04; Height: 0.022; ShaftDepth: 0.013; BushingDepth: 0.0094; MinRadius: 0.0007; MaxRadius: 0.001; Tolerance: 0.0003), (MaxDiameter: 0.2; Width: 0.045; Height: 0.025; ShaftDepth: 0.015; BushingDepth: 0.01; MinRadius: 0.0007; MaxRadius: 0.001; Tolerance: 0.0003), (MaxDiameter: 0.23; Width: 0.05; Height: 0.028; ShaftDepth: 0.017; BushingDepth: 0.0114; MinRadius: 0.0007; MaxRadius: 0.001; Tolerance: 0.0003), (MaxDiameter: 0.26; Width: 0.056; Height: 0.032; ShaftDepth: 0.02; BushingDepth: 0.0124; MinRadius: 0.0012; MaxRadius: 0.0016; Tolerance: 0.0003), (MaxDiameter: 0.29; Width: 0.063; Height: 0.032; ShaftDepth: 0.02; BushingDepth: 0.0124; MinRadius: 0.0012; MaxRadius: 0.0016; Tolerance: 0.0003), (MaxDiameter: 0.33; Width: 0.07; Height: 0.036; ShaftDepth: 0.022; BushingDepth: 0.0144; MinRadius: 0.0012; MaxRadius: 0.0016; Tolerance: 0.0003), (MaxDiameter: 0.38; Width: 0.08; Height: 0.04; ShaftDepth: 0.025; BushingDepth: 0.0154; MinRadius: 0.002; MaxRadius: 0.0025; Tolerance: 0.0003), (MaxDiameter: 0.44; Width: 0.09; Height: 0.045; ShaftDepth: 0.028; BushingDepth: 0.0174; MinRadius: 0.002; MaxRadius: 0.0025; Tolerance: 0.0003), (MaxDiameter: 0.5; Width: 0.1; Height: 0.05; ShaftDepth: 0.031; BushingDepth: 0.0195; MinRadius: 0.002; MaxRadius: 0.0025; Tolerance: 0.0003) { Альтернативные типоразмеры: (0.03, 0.007, 0.007, 0.004, 0.0033, 0.00025) (0.095, 0.024, 0.014, 0.009, 0.0054, 0.0006) } ); KeyLengthCount = 36; KeyLength: array [0..KeyLengthCount - 1] of Extended = ( 0.006, 0.008, 0.01, 0.012, 0.014, 0.016, 0.018, 0.02, 0.022, 0.025, 0.028, 0.032, 0.036, 0.04, 0.045, 0.05, 0.056, 0.063, 0.07, 0.08, 0.09, 0.1, 0.11, 0.125, 0.14, 0.16, 0.18, 0.2, 0.22, 0.25, 0.28, 0.32, 0.36, 0.4, 0.45, 0.5); function CreateOutputFromForce(const BearingForce, ShearForce: Extended; const Key: TParallelKey; const MaxBearingStress, MaxShearStress: Extended): string; function CreateOutputFromTorque( const Torque, ShaftDiam, MaxBearingStress, MaxShearStress: Extended): string; implementation { Выступ шпонки над пазом } function CalcKeyAboveShaft(const Key: TParallelKey): Extended; begin Result := Key.Height - Key.ShaftDepth; end; { Сила смятия } function CalcBearingForce(const Torque, ShaftDiam: Extended): Extended; begin Result := 2 * Torque / ShaftDiam; end; { Сила среза } function CalcShearForce( const Torque, ShaftDiam, KeyAboveShaft: Extended): Extended; begin Result := 2 * Torque / (ShaftDiam + KeyAboveShaft); end; { Рабочая длина шпонки (смятие) } function CalcWorkingLengthFromBearing( const BearingForce, KeyAboveShaft, MaxBearingStress: Extended): Extended; begin Result := BearingForce / KeyAboveShaft / MaxBearingStress; end; { Рабочая длина шпонки (срез) } function CalcWorkingLengthFromShear( const ShearForce, KeyWidth, MaxShearStress: Extended): Extended; begin Result := ShearForce / KeyWidth / MaxShearStress; end; { Рабочая длина шпонки (максимальная) } function CalcWorkingLength(const BearingForce, ShearForce: Extended; const Key: TParallelKey; const MaxBearingStress, MaxShearStress: Extended): Extended; var KeyAboveShaft: Extended; begin KeyAboveShaft := CalcKeyAboveShaft(Key); Result := Max( CalcWorkingLengthFromBearing(BearingForce, KeyAboveShaft, MaxBearingStress), CalcWorkingLengthFromShear(ShearForce, Key.Width, MaxShearStress)); end; { Полная длина шпонки } function CalcFullLength(const WorkingLength, KeyWidth: Extended): Extended; var I: Integer = 0; begin Result := WorkingLength + KeyWidth; if Result < KeyLength[KeyLengthCount - 1] then begin while Result > KeyLength[I] do Inc(I); Result := KeyLength[I]; end; end; function CreateOutputFromForce(const BearingForce, ShearForce: Extended; const Key: TParallelKey; const MaxBearingStress, MaxShearStress: Extended): string; const RatioForDouble = 0.5; var SingleWorkingLength, SingleFullLength: Extended; DoubleWorkingLength, DoubleFullLength: Extended; begin SingleWorkingLength := CalcWorkingLength(BearingForce, ShearForce, Key, MaxBearingStress, MaxShearStress); DoubleWorkingLength := CalcWorkingLength(BearingForce * RatioForDouble, ShearForce * RatioForDouble, Key, MaxBearingStress, MaxShearStress); SingleFullLength := CalcFullLength(SingleWorkingLength, Key.Width); DoubleFullLength := CalcFullLength(DoubleWorkingLength, Key.Width); Result := 'Шпонка ' + FormatFloat(',0.#', ToMm(Key.Width)) + 'x' + FormatFloat(',0.#', ToMm(Key.Height)) + sLineBreak + sLineBreak + 'Длина 1 шпонки:'#9'Lр = ' + FormatFloat(',0.0', ToMm(SingleWorkingLength)) + ' min → L = ' + FormatFloat(',0.#', ToMm(SingleFullLength)) + sLineBreak + 'Длина 2 шпонок:'#9'Lр = ' + FormatFloat(',0.0', ToMm(DoubleWorkingLength)) + ' min → L = ' + FormatFloat(',0.#', ToMm(DoubleFullLength)) + sLineBreak + sLineBreak + 'Глубина паза на валу:'#9 + FormatFloat(',0.0#', ToMm(Key.ShaftDepth)) + ' (+' + FormatFloat(',0.0#', ToMm(Key.Tolerance)) + ')' + sLineBreak + 'Глубина паза втулки: '#9 + FormatFloat(',0.0#', ToMm(Key.BushingDepth)) + ' (+' + FormatFloat(',0.0#', ToMm(Key.Tolerance)) + ')' + sLineBreak + 'Радиус закругления: '#9 + FormatFloat(',0.0#', ToMm(Key.MinRadius)) + '...' + FormatFloat(',0.0#', ToMm(Key.MaxRadius)); end; function CreateOutputFromTorque( const Torque, ShaftDiam, MaxBearingStress, MaxShearStress: Extended): string; var Key: TParallelKey; I: Integer = 0; BearingForce, ShearForce: Extended; begin while ParallelKeysTable[I].MaxDiameter < ShaftDiam do Inc(I); Key := ParallelKeysTable[I]; BearingForce := CalcBearingForce(Torque, ShaftDiam); ShearForce := CalcShearForce(Torque, ShaftDiam, CalcKeyAboveShaft(Key)); Result := CreateOutputFromForce(BearingForce, ShearForce, Key, MaxBearingStress, MaxShearStress); end; end.
unit CellOutlineEditor; interface uses Grids, Windows, Messages, Classes, Controls, CelledOutlines, ExceptSafe; type ESafeCelledOutlineEditor = class( ESafe ); type TCellOutlneEditor = class(TCustomControl) protected FOutline : TveCellOutline; FOnChanged : TNotifyEvent; FColCount : integer; FRowCount : integer; FRowHeight : integer; FColWidth : integer; FLineWidth : integer; FTopRow : integer; FLeftCol : integer; FCol, FRow : integer; // buffered access to pin names NewOutline : boolean; EditX, EditY : integer; EditText : string; // buffered access to pin names function GetPinName( x, y : integer ) : string; procedure SetPinName( x, y : integer; value : string ); procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL; procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL; procedure CreateParams(var Params: TCreateParams); override; procedure WMGetDlgCode(var message: TMessage); message WM_GETDLGCODE; procedure KeyPress(var Key: Char); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; function ColsAcross : integer; function RowsDown : integer; procedure PaintHeadings; procedure PaintCell( ACol, ARow : integer ); procedure Paint; override; procedure SetHorzScroll; procedure SetVertScroll; procedure Changed; procedure SetOutline( value : TveCellOutline ) ; public constructor Create(AOwner: TComponent); override; property Outline : TveCellOutline read FOutline write SetOutline; property Align; property Color; property Ctl3D; property Enabled; property Font; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property OnEnter; property OnExit; property OnChanged : TNotifyEvent read FOnChanged write FOnChanged; property RowHeight : integer read FRowHeight write FRowHeight; property ColWidth : integer read FColWidth write FColWidth; property LineWidth : integer read FLineWidth write FLineWidth; end; implementation uses SysUtils, Graphics, Outlines, Forms; //(forms added during debug) // ********************************* // TCellOutlineEditor // ********************************* constructor TCellOutlneEditor.Create(AOwner: TComponent); begin inherited Create(AOwner); FColCount := 7; FRowCount := 7; // these values will need initialising depending on Screen.PixelsPerInch FRowHeight := 15; FColWidth := 30; FLineWidth := 1; // initialise here - may need different code later FColCount := TveCellOutline_MaxWidth; FRowCount := TveCellOutline_MaxHeight; end; procedure TCellOutlneEditor.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.Style := Params.Style or WS_VSCROLL or WS_HSCROLL {or WS_BORDER}; end; procedure TCellOutlneEditor.Changed; begin if Assigned( FOnChanged ) then begin FOnChanged( self ); end; end; // Handle a Windows Message to request arrow key messages sent to this // TWinControl as well as ordinary key messages. Plus, DLGC_WANTCHARS // stops the containing form from stealing accelerator keys when ALT is not // pressed - Delphi forms behave like that. This message is sent on every // keystroke received when this control has the focus. procedure TCellOutlneEditor.WMGetDlgCode(var message: TMessage); begin message.Result := DLGC_WANTARROWS or DLGC_WANTCHARS; end; // *** UTILITY FUNCTION BUFFERS PIN NAMES *** // Call this to read value of a pin // Once user edits a pin name, we use a buffered value of Name, so as to allow // user to add spaces - however the Name saved into the TveCellOutline has // leading/trailing spaces removed. function TCellOutlneEditor.GetPinName( x, y : integer ) : string; begin // in newly editing this cell, load from outline if NewOutline or (EditX <> x) or (EditY <> y) then begin NewOutline := False; EditX := x; EditY := y; EditText := FOutline.CellPinNames[FCol,FRow]; end; result := EditText; end; // *** UTILITY FUNCTION BUFFERS PIN NAMES *** // Call this to set value of a pin procedure TCellOutlneEditor.SetPinName( x, y : integer; value : string ); begin // in newly editing this cell remember it! if NewOutline or (EditX <> x) or (EditY <> y) then begin NewOutline := False; EditX := x; EditY := y; end; // buffered value allows editing with spaces EditText := value; // outline value must not begin/end with a space FOutline.CellPinNames[FCol,FRow] := trim( value ); end; procedure TCellOutlneEditor.KeyDown(var Key: Word; Shift: TShiftState); var OldCellX, OldCellY : integer; begin // do nothing if no outline or wrong type of outline if not Assigned(FOutline) then begin exit; end; // will repaint previous selected cell to remove highlight OldCellX := FCol; OldCellY := FRow; // act on key case Key of VK_LEFT : begin dec( FCol ); if FCol < 0 then begin FCol := 0; end; if FCol < FLeftCol then begin FLeftCol := FCol; SetHorzScroll; Paint; exit; end; end; VK_RIGHT : begin inc( FCol ); if FCol >= FColCount then begin FCol := FColCount -1; end; if FCol >= FLeftCol + ColsAcross then begin FLeftCol := FCol - ColsAcross +1; SetHorzScroll; Paint; exit; end; end; VK_UP : begin dec( FRow ); if FRow < 0 then begin FRow := 0 end; if FRow < FTopRow then begin FTopRow := FRow; SetVertScroll; Paint; exit; end; end; VK_DOWN : begin inc( FRow ); if FRow >= FRowCount then begin FRow := FRowCount -1; end; if FRow >= FTopRow + RowsDown then begin FTopRow := FRow - RowsDown +1; SetVertScroll; Paint; exit; end; end; VK_HOME : begin FCol := 0; FRow := 0; FLeftCol := 0; FTopRow := 0; SetVertScroll; SetHorzScroll; Paint; exit; end; VK_END : begin FCol := FOutline.Width -1; FRow := FOutline.Height -1; FTopRow := 0; FLeftCol := 0; if FRow >= FTopRow + RowsDown then begin FTopRow := FRow - RowsDown +1; end; if FCol >= FLeftCol + ColsAcross then begin FLeftCol := FCol - ColsAcross +1; end; SetVertScroll; SetHorzScroll; Paint; exit; end; VK_PRIOR : begin SendMessage( handle, WM_VSCROLL, SB_PAGEUP, 0 ); end; VK_NEXT : begin SendMessage( handle, WM_VSCROLL, SB_PAGEDOWN, 0 ); end; { VK_SPACE : begin if FOutline.CellTypes[FCol,FRow] = ctFree then begin FOutline.CellTypes[FCol,FRow] := ctBody; end else begin FOutline.CellTypes[FCol,FRow] := ctFree; end; Changed; end; } VK_DELETE : begin if FOutline.CellTypes[FCol,FRow] = ctPin then begin FOutline.CellTypes[FCol,FRow] := ctBody; end else if FOutline.CellTypes[FCol,FRow] = ctBody then begin FOutline.CellTypes[FCol,FRow] := ctFree; end else begin FOutline.CellTypes[FCol,FRow] := ctBody; end; Changed; end; VK_RETURN : begin if FOutline.CellTypes[FCol,FRow] = ctPin then begin end else if FOutline.CellTypes[FCol,FRow] = ctBody then begin FOutline.CellTypes[FCol,FRow] := ctFree; end else begin FOutline.CellTypes[FCol,FRow] := ctBody; end; Changed; end; // ignore other keys else begin // swallow every other key unless it is an Accelerator, otherwise // The parent form may swallow it - Delphi forms will act // accelerator keys *even if the ALT key is not pressed* { if not( ssAlt in Shift) then begin Key := 0; end; } exit; end; end; // paint previously selected cell PaintCell( OldCellX, OldCellY ); // paint new selected cell to show highlight PaintCell( FCol, FRow ); end; procedure TCellOutlneEditor.KeyPress(var Key: Char); var // CellType : TCellType; Value : string; PinName : string; begin // inherited KeyPress( Key ); // do nothing if no outline or wrong type of outline if not Assigned(FOutline) then begin exit; end; // we respond to number keys here in KeyPress, because main & keypad // number keys get converted to a single ASCII value. In OnKeyDown, // these keys are not combined and possibly may even be different for // different language keyboards. case Key of char(VK_BACK) : begin // if cell is pin, then use key value to alter existing PinNo if FOutline.CellTypes[FCol,FRow] = ctPin then begin PinName := GetPinName( FCol, FRow ); PinName := Trim( Copy( PinName, 1, Length(PinName)-1 ) ); // blank pin names are not allowed - turn into body cell if PinName = '' then begin FOutline.CellTypes[FCol,FRow] := ctBody; end // show edited pin else begin SetPinName( FCol, FRow, PinName ); end; // paint selected cell to show change PaintCell( FCol, FRow ); Changed; end end; else begin Value := Key; Key := Char(0); // if cell is a pin, retrieve its PinName if FOutline.CellTypes[FCol,FRow] = ctPin then begin PinName := GetPinName( FCol, FRow ); end // if cell is not pin, make it a pin & give it key value as PinNo else begin // too many pins? if FOutline.PinCount > TveMaxPinIndex then begin raise ESafeCelledOutlineEditor.Create( 'Too many pins' ); end; FOutline.CellTypes[FCol,FRow] := ctPin; SetPinName( FCol, FRow, '' ); PinName := ''; end; // use key value to alter existing PinNo // Trim means no spaces will ever appear in pin name, because // the only way to add a space is to type it on the end of the // string PinName := PinName + Value; // blank pin names are not allowed - turn into body cell if PinName = '' then begin FOutline.CellTypes[FCol,FRow] := ctBody; end // show edited pin else begin SetPinName( FCol, FRow, PinName ); end; // paint selected cell to show change PaintCell( FCol, FRow ); Changed; end; end end; procedure TCellOutlneEditor.MouseDown( Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var NewCellX, NewCellY : integer; OldCellX, OldCellY : integer; begin // do nothing if no outline or wrong type of outline if not Assigned(FOutline) then begin exit; end; // calculate X, Y or clicked cell NewCellX := FLeftCol + (X div (FColWidth + FLineWidth)) -1; NewCellY := FTopRow + (Y div (FRowHeight +FLineWidth)) -1; // if clicked position doesn not map to a visible cell if (NewCellX < FLeftCol) or (NewCellX >= FLeftCol + ColsAcross) or (NewCellY < FTopRow) or (NewCellY >= FTopRow + RowsDown) then begin exit; end; // will repaint previous selected cell to remove highlight OldCellX := FCol; OldCellY := FRow; // move selection to new cell selected FCol := NewCellX; FRow := NewCellY; // if a right-click, toggle cell state between blank and body if Shift = [ssRight] then begin if FOutline.CellTypes[FCol,FRow] = ctFree then begin FOutline.CellTypes[FCol,FRow] := ctBody; end else begin FOutline.CellTypes[FCol,FRow] := ctFree; end; Changed; end; // paint previously selected cell PaintCell( OldCellX, OldCellY ); // paint new selected cell to show highlight PaintCell( FCol, FRow ); // focus means Windows will direct keystrokes to this control SetFocus; end; const CellSelectedColor = clLtGray; // clGray; //clBtnFace; procedure TCellOutlneEditor.PaintCell( ACol, ARow : integer ); var X1, Y1 : integer; X2, Y2 : integer; ARect : TRect; TheText : string; PenWidth : integer; OldWidth : integer; begin // no data if not Assigned( FOutline ) then begin Canvas.Brush.Color := clWindow; Canvas.FillRect( ARect ); exit; end; // nothing to do if outside display window if (ACol < FLeftCol) or (ACol > FLeftCol + ColsAcross +1) or (ARow < FTopRow) or (ARow > FTopRow + RowsDown +1) then begin exit; end; Canvas.Font := Font; // calculate cell bounding rectangle X1 := FLineWidth + ((ACol+1-FLeftCol)* (FColWidth + FLineWidth)); X2 := X1 + FColWidth {+ FLineWidth}; Y1 := FLineWidth + ((ARow+1-FTopRow) * (FRowHeight + FLineWidth)); Y2 := Y1 + FRowHeight {+ FLineWidth}; ARect := Rect(X1, Y1, X2, Y2); case FOutline.CellTypes[ACol,ARow] of ctFree : begin // leave blank Canvas.Brush.Color := clWindow; Canvas.FillRect( ARect ); end; ctBody : begin // draw rectangle Canvas.Brush.Color := CellSelectedColor; Canvas.FillRect( ARect ); end; ctPin : begin // draw pin number Canvas.Brush.Color := CellSelectedColor; Canvas.Pen.Color := clWindowText; TheText := FOutline.CellPinNames[ACol,ARow]; with ARect, Canvas do TextRect(ARect, Left + (Right - Left - TextWidth(TheText)) div 2, Top + (Bottom - Top - TextHeight(TheText)) div 2, TheText); end; end; // if cell is selected, highlight it if (ACol = FCol) and (ARow = FRow) then begin PenWidth := (ARect.Right - ARect.Left) div 12; Canvas.Pen.Color := clHighLight; OldWidth := Canvas.Pen.Width; Canvas.Pen.Width := PenWidth; Canvas.Brush.Style := bsClear; Canvas.MoveTo( ARect.Right-1, ARect.Top + 1); Canvas.LineTo( ARect.Right-1, ARect.Bottom-1); Canvas.LineTo( ARect.Left + 1, ARect.Bottom-1); Canvas.Pen.Width := OldWidth; end; end; function TCellOutlneEditor.ColsAcross : integer; begin result := (Width - FLineWidth - FLineWidth - FColWidth - GetSystemMetrics(SM_CXVSCROLL)) div (FColWidth + FLineWidth); end; function TCellOutlneEditor.RowsDown : integer; begin result := (Height - FLineWidth - FLineWidth - FRowHeight - GetSystemMetrics(SM_CYHSCROLL)) div (FRowHeight + FLineWidth); end; procedure TCellOutlneEditor.PaintHeadings; var i : integer; TheText : string; ARect : TRect; X1, Y1 : integer; X2, Y2 : integer; begin Canvas.Font := Font; Canvas.Brush.Color := clBtnFace; Canvas.Pen.Color := clWindowText; // top row contains col headings Y1 := FLineWidth; Y2 := Y1 + FRowHeight; for i := 1 to ColsAcross do begin // cell dimensions X1 := FLineWidth + (i * (FColWidth + FLineWidth)); X2 := X1 + FColWidth {+ FLineWidth}; ARect := Rect(X1, Y1, X2, Y2); // text inside cell TheText := IntToStr( i + FLeftCol ); Canvas.TextRect(ARect, X1 + (X2 - X1 - Canvas.TextWidth(TheText)) div 2, Y1 + (Y2 - Y1 - Canvas.TextHeight(TheText)) div 2, TheText); // line around cell Canvas.MoveTo( X1-1, Y1-1 ); Canvas.LineTo( X2, Y1-1 ); Canvas.LineTo( X2, Y2 ); Canvas.LineTo( X1-1, Y2 ); Canvas.LineTo( X1-1, Y1-1 ); end; // left col contains row of headings X1 := FLineWidth; X2 := X1 + FColWidth; for i := 1 to RowsDown do begin // cell dimensions Y1 := FLineWidth + (i * (FRowHeight + FLineWidth)); Y2 := Y1 + FRowHeight; ARect := Rect(X1, Y1, X2, Y2); // text inside cell TheText := IntToStr( i + FTopRow ); Canvas.TextRect(ARect, X1 + (X2 - X1 - Canvas.TextWidth(TheText)) div 2, Y1 + (Y2 - Y1 - Canvas.TextHeight(TheText)) div 2, TheText); // line around cell Canvas.MoveTo( X1 -1, Y1-1 ); Canvas.LineTo( X2, Y1-1 ); Canvas.LineTo( X2, Y2 ); Canvas.LineTo( X1-1, Y2 ); Canvas.LineTo( X1-1, Y1-1 ); end; end; procedure TCellOutlneEditor.Paint; var i , j : integer; begin PaintHeadings; // paint cells for i := 0 to FColCount -1 do begin for j := 0 to FRowCount -1 do begin PaintCell( i, j ); end; end; end; procedure TCellOutlneEditor.SetHorzScroll; var ScrollInfo : TScrollInfo; begin ScrollInfo.cbSize := sizeof(TScrollInfo); ScrollInfo.fMask := SIF_POS or SIF_RANGE or SIF_PAGE; ScrollInfo.nMin := 0; ScrollInfo.nMax := FColCount - 1; ScrollInfo.nPage := ColsAcross; ScrollInfo.nPos := FLeftCol; ScrollInfo.nTrackPos := 0; SetScrollInfo( handle, SB_HORZ, ScrollInfo, TRUE ); end; procedure TCellOutlneEditor.SetVertScroll; var ScrollInfo : TScrollInfo; begin ScrollInfo.cbSize := sizeof(TScrollInfo); ScrollInfo.fMask := SIF_POS or SIF_RANGE or SIF_PAGE; ScrollInfo.nMin := 0; ScrollInfo.nMax := FRowCount -1; ScrollInfo.nPage := RowsDown; ScrollInfo.nPos := FTopRow; ScrollInfo.nTrackPos := 0; SetScrollInfo( handle, SB_VERT, ScrollInfo, TRUE ); end; procedure TCellOutlneEditor.WMVScroll(var Msg: TWMVScroll); begin case Msg.ScrollCode of SB_THUMBPOSITION, SB_THUMBTRACK : begin FTopRow := Msg.Pos; end; SB_LINEDOWN : begin Inc( FTopRow ); if FTopRow > FRowCount - RowsDown then begin FTopRow := FRowCount - RowsDown; end; end; SB_LINEUP : begin Dec( FTopRow ); if FTopRow < 0 then begin FTopRow := 0; end; end; SB_PAGEDOWN : begin Inc( FTopRow, RowsDown -1 ); if FTopRow > FRowCount - RowsDown then begin FTopRow := FRowCount - RowsDown; end; end; SB_PAGEUP : begin Dec( FTopRow, RowsDown -1 ); if FTopRow < 0 then begin FTopRow := 0; end; end else begin exit; end; end; SetVertScroll; Paint; { TWMScroll = packed record Msg: Cardinal; ScrollCode: Smallint; // SB_xxxx Pos: Smallint; ScrollBar: HWND; Result: Longint; end; } end; procedure TCellOutlneEditor.WMHScroll(var Msg: TWMHScroll); begin case Msg.ScrollCode of SB_THUMBPOSITION, SB_THUMBTRACK : begin FLeftCol := Msg.Pos; end; SB_LINERIGHT : begin Inc( FLeftCol ); if FLeftCol > FColCount - ColsAcross then begin FLeftCol := FColCount - ColsAcross; end; end; SB_LINELEFT : begin Dec( FLeftCol ); if FLeftCol < 0 then begin FLeftCol := 0; end; end; SB_PAGERIGHT : begin Inc( FLeftCol, ColsAcross -1 ); if FLeftCol > FColCount - ColsAcross then begin FLeftCol := FColCount - ColsAcross; end; end; SB_PAGELEFT : begin Dec( FLeftCol, ColsAcross -1 ); if FLeftCol < 0 then begin FLeftCol := 0; end; end else begin exit; end; end; SetHorzScroll; Paint; end; procedure TCellOutlneEditor.SetOutline( value : TveCellOutline ) ; begin FOutline := value; FRow := 0; FCol := 0; FTopRow := 0; FLeftCol := 0; SetVertScroll; SetHorzScroll; Paint; NewOutline := True; end; end.
unit p_main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls; type Tfrm_ConvertColor = class(TForm) pnl_total: TPanel; lbl_title: TLabel; btn_convert: TBitBtn; edt_HTML: TEdit; edt_dephiHEX: TEdit; edt_delphiInt: TEdit; shp_colorPicker: TShape; dlgColor_picker: TColorDialog; edt_delphiNorm: TEdit; rb_Html: TRadioButton; rb_delphiInt: TRadioButton; rb_delphiHex: TRadioButton; rb_delphiNorm: TRadioButton; procedure btn_convertClick(Sender: TObject); procedure shp_colorPickerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private { Private declarations } function IntColorToHtmlColor(c: Integer): string; function HexColorToHtmlColor(s: string): string; function HtmlColorToHexColor(s: string): string; function TColorToHex(c: TColor): string; procedure Convert; public { Public declarations } end; var frm_ConvertColor: Tfrm_ConvertColor; cPicked, cTemp : TColor; cHtml, cInt, cHex, cNorm: string; implementation {$R *.dfm} {由 Delphi 的颜色常数转换到 Html 颜色} function Tfrm_ConvertColor.IntColorToHtmlColor(c: Integer): string; var R,G,B: Byte; begin R := c and $FF; G := (c shr 8) and $FF; B := (c shr 16) and $FF; Result := #35 + Format('%.2x%.2x%.2x',[R,G,B]); end; {HexString to HtmlColor} function Tfrm_ConvertColor.HexColorToHtmlColor(s: string): string; var i: Integer; R,G,B: Byte; begin i := StrToInt(s); R := i and $FF; G := (i shr 8) and $FF; B := (i shr 16) and $FF; Result := #35 + Format('%.2x%.2x%.2x',[R,G,B]); end; {从HtmlColor to HexColor} function Tfrm_ConvertColor.HtmlColorToHexColor(s: string): string; var R, G, B: string; begin s := Copy(s,2,6); R := Copy(s,1,2); G := Copy(s,3,2); B := Copy(s,5,2); Result := '$' + B + G + R; end; {DelphiColor 转换 为 十六进制字符串的颜色} function Tfrm_ConvertColor.TColorToHex(c: TColor): string; begin Result:= '$' + IntToHex(c,6); end; procedure Tfrm_ConvertColor.Convert; begin edt_HTML.Text := cHtml; edt_delphiInt.Text := cInt; edt_dephiHEX.Text := cHex; edt_delphiNorm.Text := cNorm; end; procedure Tfrm_ConvertColor.btn_convertClick(Sender: TObject); begin try if rb_Html.Checked then begin cHtml := Trim(edt_HTML.Text); cHex := HtmlColorToHexColor(cHtml); cInt := IntToStr(ColorToRGB(StringToColor(cHex))); cNorm := ColorToString(StringToColor(cInt)); end else if rb_delphiInt.Checked then begin cInt := Trim(edt_delphiInt.Text); cHtml := IntColorToHtmlColor(StrToInt(cInt)); cHex := TColorToHex(StrToInt(cInt)); end else if rb_delphiHex.Checked then begin cHex := Trim(edt_dephiHEX.Text); cHtml := HexColorToHtmlColor(cHex); cInt := IntToStr(ColorToRGB(StringToColor(cHex))); end; if cInt <> '' then begin shp_colorPicker.Brush.Color := StringToColor(cInt); lbl_title.Font.Color := StringToColor(cInt); end; except Application.MessageBox('录入数据有误!','提示', MB_OK); end; Convert; end; procedure Tfrm_ConvertColor.shp_colorPickerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if dlgColor_picker.Execute() then begin cPicked := dlgColor_picker.Color; shp_colorPicker.Brush.Color := cPicked; lbl_title.Font.Color := cPicked; cHtml := IntColorToHtmlColor(cPicked); cHex := TColorToHex(cPicked); cInt := IntToStr(ColorToRGB(cPicked)); cNorm := ColorToString(cPicked); Convert; end; end; end.
unit AqDrop.Core.Types; interface {$I 'AqDrop.Core.Defines.inc'} uses System.TypInfo; type TAqID = type NativeUInt; TAqIDHelper = record helper for TAqID strict private function VerifyIfIsEmpty: Boolean; inline; public function ToString: string; class function GetEmptyID: TAqID; static; inline; property IsEmpty: Boolean read VerifyIfIsEmpty; end; {$IFNDEF AQMOBILE} TAqAnsiCharSet = set of AnsiChar; {$ENDIF} TAqDataType = ( adtUnknown, adtBoolean, adtEnumerated, adtUInt8, adtInt8, adtUInt16, adtInt16, adtUInt32, adtInt32, adtUInt64, adtInt64, adtCurrency, adtDouble, adtSingle, adtDatetime, adtDate, adtTime, adtAnsiChar, adtChar, adtAnsiString, adtString, adtWideString, adtSet, adtClass, adtMethod, adtVariant, adtRecord, adtInterface, adtGUID); TAqDataTypeHelper = record helper for TAqDataType function ToString: string; class function FromTypeInfo(const pType: PTypeInfo): TAqDataType; static; class function FromType<T>: TAqDataType; static; end; const adtIntTypes = [adtUInt8..adtInt64]; adtCharTypes = [adtAnsiChar, adtChar]; adtStringTypes = [adtAnsiString, adtString, adtWideString]; type TAqEntityID = type Int64; TAqUnixDateTime = type Int64; TAqGenericEvent<T> = procedure(pArg: T) of object; implementation uses System.SysUtils, AqDrop.Core.Helpers, AqDrop.Core.Exceptions; { TAqDataTypeHelper } class function TAqDataTypeHelper.FromType<T>: TAqDataType; begin Result := FromTypeInfo(TypeInfo(T)); end; class function TAqDataTypeHelper.FromTypeInfo(const pType: PTypeInfo): TAqDataType; begin case pType^.Kind of tkUnknown: Result := TAqDataType.adtUnknown; tkInteger: Result := TAqDataType.adtInt32; tkChar: Result := TAqDataType.adtAnsiChar; tkEnumeration: begin if pType = TypeInfo(Boolean) then begin Result := TAqDataType.adtBoolean; end else begin Result := TAqDataType.adtEnumerated; end; end; tkFloat: begin if pType = TypeInfo(TDateTime) then begin Result := TAqDataType.adtDatetime; end else if pType = TypeInfo(TDate) then begin Result := TAqDataType.adtDate; end else if pType = TypeInfo(TTime) then begin Result := TAqDataType.adtTime; end else if pType = TypeInfo(Currency) then begin Result := TAqDataType.adtCurrency; end else begin Result := TAqDataType.adtDouble; end; end; tkSet: Result := TAqDataType.adtSet; tkClass: Result := TAqDataType.adtClass; tkMethod: Result := TAqDataType.adtMethod; tkWChar: Result := TAqDataType.adtChar; tkLString: Result := TAqDataType.adtAnsiString; tkWString: Result := TAqDataType.adtWideString; tkVariant: Result := TAqDataType.adtVariant; tkRecord: begin if pType = TypeInfo(TGUID) then begin Result := TAqDataType.adtGUID; end else begin Result := TAqDataType.adtRecord; end; end; tkInterface: Result := TAqDataType.adtInterface; tkInt64: Result := TAqDataType.adtInt64; tkUString: Result := TAqDataType.adtString; else raise EAqInternal.CreateFmt('Unexpected data type while getting the AqDataType (%s - %s)', [pType^.Name, GetEnumName(TypeInfo(TTypeKind), Integer(pType^.Kind))]); end; end; function TAqDataTypeHelper.ToString: string; begin Result := GetEnumName(TypeInfo(TAqDataType), Integer(Self)); end; { TAqIDHelper } class function TAqIDHelper.GetEmptyID: TAqID; begin Result := 0; end; function TAqIDHelper.ToString: string; begin Result := NativeInt(Self).ToString; end; function TAqIDHelper.VerifyIfIsEmpty: Boolean; begin Result := Self = GetEmptyID; end; end.