text
stringlengths
14
6.51M
unit uMessageSlot; interface uses Classes, StdCtrls, ExtCtrls, Controls, Graphics, SysUtils, Buttons, Forms; type TMessageSlot = class(TPanel) constructor Create(AOwner: TComponent); override; private IsNewMessage: Boolean; imgImage: TImage; pnlCentral, pnlTop, pnlMiddle, pnlBottom: TPanel; txtTitle, txtOrigin, txtContent, txtTimestamp: TLabel; btnClose: TSpeedButton; procedure InitializeComponents; procedure PanelOnMouseOver(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure PanelOnMouseLeave(Sender: TObject); procedure DescartarMensagem(Sender: TObject); private function GetMessage: string; function GetOrigin: string; function GetTimestamp: string; function GetTitle: string; procedure SetMessage(const Value: string); procedure SetOrigin(const Value: string); procedure SetTimestamp(const Value: string); procedure SetTitle(const Value: string); published procedure NewMessage(aTitle, aOrigin, aMessage, aTimestamp: string); property Title: string read GetTitle write SetTitle; property Origin: string read GetOrigin write SetOrigin; property Message: string read GetMessage write SetMessage; property Timestamp: string read GetTimestamp write SetTimestamp; end; TMessageSlotList = class(TScrollBox) published procedure AddNewMessage(aTitle, aOrigin, aMessage, aTimestamp: String); end; procedure Register; implementation procedure TMessageSlot.PanelOnMouseLeave(Sender: TObject); begin btnClose.Visible := False; end; procedure TMessageSlot.PanelOnMouseOver(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if IsNewMessage then Color := clWhite; btnClose.Visible := True; end; constructor TMessageSlot.Create(AOwner: TComponent); begin inherited; InitializeComponents; end; procedure TMessageSlot.DescartarMensagem(Sender: TObject); begin Self.Free; end; function TMessageSlot.GetMessage: string; begin Result := txtContent.Caption; end; function TMessageSlot.GetOrigin: string; begin Result := txtOrigin.Caption; end; function TMessageSlot.GetTimestamp: string; begin Result := txtTimestamp.Caption; end; function TMessageSlot.GetTitle: string; begin Result := txtTitle.Caption; end; procedure TMessageSlot.InitializeComponents; begin IsNewMessage := False; {$REGION 'Ajustes no painel'} Height := 150; Width := 700; Color := clWhite; Font.Name := 'Segoe UI'; Font.Size := 12; OnMouseMove := PanelOnMouseOver; OnMouseLeave := PanelOnMouseLeave; {$ENDREGION} {$REGION 'Imagem'} imgImage := TImage.Create(Self); with imgImage do begin Parent := Self; Anchors := [akBottom, akLeft, akTop]; Left := 10; Top := 10; Height := Self.Height - 10 - 10; Width := Height; Center := True; OnMouseMove := Self.OnMouseMove; end; {$ENDREGION} {$REGION 'Painéis'} // Painel central pnlCentral := TPanel.Create(Self); with pnlCentral do begin Parent := Self; Anchors := [akBottom, akLeft, akRight, akTop]; BevelOuter := bvNone; Top := 10; Left := imgImage.Left + imgImage.Width + 10; Height := imgImage.Height; Width := Self.Width - Left - 10; OnMouseMove := Self.OnMouseMove; end; // Painel no topo pnlTop := TPanel.Create(pnlCentral); with pnlTop do begin Parent := pnlCentral; BevelOuter := bvNone; Align := alTop; Height := 23; OnMouseMove := Self.OnMouseMove; end; // Painel na base pnlBottom := TPanel.Create(pnlCentral); with pnlBottom do begin Parent := pnlCentral; BevelOuter := bvNone; Align := alBottom; Height := 23; OnMouseMove := Self.OnMouseMove; end; // Painel de conteúdo central pnlMiddle := TPanel.Create(pnlCentral); with pnlMiddle do begin Parent := pnlCentral; BevelOuter := bvNone; Align := alClient; OnMouseMove := Self.OnMouseMove; end; {$ENDREGION} {$REGION 'Etiquetas'} // Etiqueta de título txtTitle := TLabel.Create(pnlTop); with txtTitle do begin Parent := pnlTop; Align := alLeft; Margins.Left := 5; Margins.Top := 0; Margins.Bottom := 0; AlignWithMargins := True; Layout := tlCenter; Font.Color := clTeal; Font.Size := 8; Font.Style := Font.Style + [fsBold]; end; // Etiqueta de origem txtOrigin := TLabel.Create(pnlTop); with txtOrigin do begin Parent := pnlTop; Align := alLeft; Margins.Left := 5; Margins.Top := 0; Margins.Bottom := 0; AlignWithMargins := True; Layout := tlCenter; Font.Color := clSilver; Font.Size := 8; end; // Etiqueta de conteúdo txtContent := TLabel.Create(pnlMiddle); with txtContent do begin Parent := pnlMiddle; Align := alClient; Margins.Left := 5; Margins.Top := 0; Margins.Bottom := 0; AlignWithMargins := True; Font.Size := 10; WordWrap := True; end; // Etiqueta de estampa de tempo txtTimestamp := TLabel.Create(pnlBottom); with txtTimestamp do begin Parent := pnlBottom; Align := alLeft; Margins.Left := 5; Margins.Top := 0; Margins.Bottom := 0; AlignWithMargins := True; Layout := tlCenter; Font.Color := clSilver; Font.Size := 8; end; {$ENDREGION} {$REGION 'Botão para fechar'} btnClose := TSpeedButton.Create(pnlTop); with btnClose do begin Parent := pnlTop; Align := alRight; Height := 21; Flat := True; Caption := 'X'; Font.Color := TColor($00804000); Font.Style := Font.Style + [fsBold]; Visible := False; OnClick := DescartarMensagem; end; {$ENDREGION} Caption := ''; Title := 'Title'; Origin := 'Origin'; Message := 'Message'; Timestamp := 'Timestamp'; end; procedure TMessageSlot.NewMessage(aTitle, aOrigin, aMessage, aTimestamp: string); begin Caption := ''; txtTitle.Caption := aTitle; txtOrigin.Caption := aOrigin; txtContent.Caption := aMessage; txtTimestamp.Caption := aTimestamp; Color := TColor($00C8FFFF); IsNewMessage := True; end; procedure TMessageSlot.SetMessage(const Value: string); begin txtContent.Caption := Value; end; procedure TMessageSlot.SetOrigin(const Value: string); begin txtOrigin.Caption := Value; end; procedure TMessageSlot.SetTimestamp(const Value: string); begin txtTimestamp.Caption := Value; end; procedure TMessageSlot.SetTitle(const Value: string); begin txtTitle.Caption := Value; end; procedure Register; begin RegisterComponents('Samples', [TMessageSlot, TMessageSlotList]); end; procedure TMessageSlotList.AddNewMessage(aTitle, aOrigin, aMessage, aTimestamp: String); var NewMessage: TMessageSlot; begin NewMessage := TMessageSlot.Create(Self); NewMessage.Align := alTop; NewMessage.Parent := Self; NewMessage.Title := aTitle; NewMessage.Origin := aOrigin; NewMessage.Message := aMessage; NewMessage.Timestamp := aTimestamp; end; end.
unit testodesolverunit; interface uses Math, Sysutils, Ap, odesolver; function TestODESolver(Silent : Boolean):Boolean; function testodesolverunit_test_silent():Boolean; function testodesolverunit_test():Boolean; implementation procedure Unset2D(var X : TReal2DArray);forward; procedure Unset1D(var X : TReal1DArray);forward; procedure UnsetRep(var Rep : ODESolverReport);forward; (************************************************************************* Test *************************************************************************) function TestODESolver(Silent : Boolean):Boolean; var PassCount : AlglibInteger; CurErrors : Boolean; RKCKErrors : Boolean; WasErrors : Boolean; XTbl : TReal1DArray; YTbl : TReal2DArray; Rep : ODESolverReport; XG : TReal1DArray; Y : TReal1DArray; H : Double; Eps : Double; Solver : AlglibInteger; Pass : AlglibInteger; MyNFEV : AlglibInteger; V : Double; N : AlglibInteger; M : AlglibInteger; M2 : AlglibInteger; I : AlglibInteger; Err : Double; State : ODESolverState; begin RKCKErrors := False; WasErrors := False; PassCount := 10; // // simple test: just A*sin(x)+B*cos(x) // Assert(PassCount>=2); Pass:=0; while Pass<=PassCount-1 do begin Solver:=0; while Solver<=0 do begin // // prepare // H := 1.0E-2; Eps := 1.0E-5; if Pass mod 2=0 then begin Eps := -Eps; end; SetLength(Y, 2); I:=0; while I<=1 do begin Y[I] := 2*RandomReal-1; Inc(I); end; M := 2+RandomInteger(10); SetLength(XG, M); XG[0] := (M-1)*RandomReal; I:=1; while I<=M-1 do begin XG[I] := XG[I-1]+RandomReal; Inc(I); end; V := 2*Pi/(XG[M-1]-XG[0]); APVMul(@XG[0], 0, M-1, V); if AP_FP_Greater(RandomReal,0.5) then begin APVMul(@XG[0], 0, M-1, -1); end; MyNFEV := 0; // // choose solver // if Solver=0 then begin ODESolverRKCK(Y, 2, XG, M, Eps, H, State); end; // // solve // while ODESolverIteration(State) do begin State.DY[0] := State.Y[1]; State.DY[1] := -State.Y[0]; MyNFEV := MyNFEV+1; end; ODESolverResults(State, M2, XTbl, YTbl, Rep); // // check results // CurErrors := False; if Rep.TerminationType<=0 then begin CurErrors := True; end else begin CurErrors := CurErrors or (M2<>M); Err := 0; I:=0; while I<=M-1 do begin Err := Max(Err, AbsReal(YTbl[I,0]-(+Y[0]*Cos(XTbl[I]-XTbl[0])+Y[1]*Sin(XTbl[I]-XTbl[0])))); Err := Max(Err, AbsReal(YTbl[I,1]-(-Y[0]*Sin(XTbl[I]-XTbl[0])+Y[1]*Cos(XTbl[I]-XTbl[0])))); Inc(I); end; CurErrors := CurErrors or AP_FP_Greater(Err,10*AbsReal(Eps)); CurErrors := CurErrors or (MyNFEV<>Rep.NFEV); end; if Solver=0 then begin RKCKErrors := RKCKErrors or CurErrors; end; Inc(Solver); end; Inc(Pass); end; // // another test: // // y(0) = 0 // dy/dx = f(x,y) // f(x,y) = 0, x<1 // x-1, x>=1 // // with BOTH absolute and fractional tolerances. // Starting from zero will be real challenge for // fractional tolerance. // Assert(PassCount>=2); Pass:=0; while Pass<=PassCount-1 do begin H := 1.0E-4; Eps := 1.0E-4; if Pass mod 2=0 then begin Eps := -Eps; end; SetLength(Y, 1); Y[0] := 0; M := 21; SetLength(XG, M); I:=0; while I<=M-1 do begin XG[I] := AP_Double(2*I)/(M-1); Inc(I); end; MyNFEV := 0; ODESolverRKCK(Y, 1, XG, M, Eps, H, State); while ODESolverIteration(State) do begin State.DY[0] := Max(State.X-1, 0); MyNFEV := MyNFEV+1; end; ODESolverResults(State, M2, XTbl, YTbl, Rep); if Rep.TerminationType<=0 then begin RKCKErrors := True; end else begin RKCKErrors := RKCKErrors or (M2<>M); Err := 0; I:=0; while I<=M-1 do begin Err := Max(Err, AbsReal(YTbl[I,0]-AP_Sqr(Max(XG[I]-1, 0))/2)); Inc(I); end; RKCKErrors := RKCKErrors or AP_FP_Greater(Err,AbsReal(Eps)); RKCKErrors := RKCKErrors or (MyNFEV<>Rep.NFEV); end; Inc(Pass); end; // // end // WasErrors := RKCKErrors; if not Silent then begin Write(Format('TESTING ODE SOLVER'#13#10'',[])); Write(Format('* RK CASH-KARP: ',[])); if RKCKErrors then begin Write(Format('FAILED'#13#10'',[])); end else begin Write(Format('OK'#13#10'',[])); end; if WasErrors then begin Write(Format('TEST FAILED'#13#10'',[])); end else begin Write(Format('TEST PASSED'#13#10'',[])); end; end; Result := not WasErrors; end; (************************************************************************* Unsets real matrix *************************************************************************) procedure Unset2D(var X : TReal2DArray); begin SetLength(X, 1, 1); X[0,0] := 2*RandomReal-1; end; (************************************************************************* Unsets real vector *************************************************************************) procedure Unset1D(var X : TReal1DArray); begin SetLength(X, 1); X[0] := 2*RandomReal-1; end; (************************************************************************* Unsets report *************************************************************************) procedure UnsetRep(var Rep : ODESolverReport); begin Rep.NFEV := 0; end; (************************************************************************* Silent unit test *************************************************************************) function testodesolverunit_test_silent():Boolean; begin Result := TestODESolver(True); end; (************************************************************************* Unit test *************************************************************************) function testodesolverunit_test():Boolean; begin Result := TestODESolver(False); end; end.
{ LibXml2-XmlTextReader wrapper class for Delphi Copyright (c) 2010 Tobias Grimm Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit XmlTextReaderTest; interface uses libxml2, XmlTextReader, TestFrameWork, Classes, Windows, SysUtils; type TXmlTextReaderTest = class(TTestCase) private FXmlTextReader: TXmlTextReader; FDataStream: TStringStream; private procedure SetXmlData(const Data: string); protected procedure SetUp; override; procedure TearDown; override; published procedure TestCreateFromStream; procedure TestCreateFromNonExistingFile; procedure TestCreateFromFile; procedure TestMultipleThreads; procedure TestReset; procedure TestRead; procedure TestReadOuterXml; procedure TestReadInnerXml; procedure TestSkip; procedure TestReadString; procedure TestReadInvalidXml; procedure TestReadInvalidXmlFile; procedure TestNodeType; procedure TestAttributeProperties; procedure TestElementProperties; procedure TestNameSpaceProperties; procedure TestGetAttributeMethods; procedure TestMoveMethods; procedure TestLookupNamespace; procedure TestParserProp; procedure TestReadmeSample; end; TTestThread = class(TThread) private FFileName: string; protected procedure Execute; override; public constructor Create(const fileName: string); virtual; end; implementation { TXmlreaderTest } procedure TXmlTextReaderTest.SetUp; begin inherited; FDataStream := TStringStream.Create(''); FXmlTextReader := TXmlTextReader.Create(FDataStream); end; procedure TXmlTextReaderTest.SetXmlData(const Data: string); begin FDataStream.Size := 0; FDataStream.WriteString(Data); FDataStream.Seek(0, soFromBeginning); FXmlTextReader.Reset; end; procedure TXmlTextReaderTest.TearDown; begin FXmlTextReader.Free; FDataStream.Free; inherited; end; procedure TXmlTextReaderTest.TestCreateFromStream; begin try TXmlTextReader.Create(nil).Free; Fail('Expected EArgumentNullException'); except on E: EArgumentNullException do ; end; TXmlTextReader.Create(FDataStream).Free; Check(True, 'Construction from stream'); end; procedure TXmlTextReaderTest.TestElementProperties; begin SetXmlData('<?xml version="1.0"?>' + '<root>' + '<first>' + 'value' + '<empty/>' + '</first>' + '</root>'); FXmlTextReader.Read; CheckEquals('root', FXmlTextReader.Name, 'Name property'); CheckEquals(0, FXmlTextReader.Depth, 'property Depth'); Check(not FXmlTextReader.HasValue, 'property HasValue'); Check(not FXmlTextReader.IsEmptyElement, 'property IsEmptyElement'); FXmlTextReader.Read; CheckEquals('first', FXmlTextReader.Name, 'Name property'); CheckEquals(1, FXmlTextReader.Depth, 'property Depth'); Check(not FXmlTextReader.HasValue, 'property HasValue'); Check(not FXmlTextReader.IsEmptyElement, 'property IsEmptyElement'); FXmlTextReader.Read; CheckEquals('#text', FXmlTextReader.Name, 'Name property'); Check(FXmlTextReader.HasValue, 'property HasValue'); CheckEquals('value', FXmlTextReader.Value, 'property Value'); Check(not FXmlTextReader.IsEmptyElement, 'property IsEmptyElement'); FXmlTextReader.Read; Check(FXmlTextReader.IsEmptyElement, 'property IsEmptyElement'); end; procedure TXmlTextReaderTest.TestNameSpaceProperties; begin SetXmlData('<?xml version="1.0"?>' + '<root xmlns:test="http://e-tobi.net">' + '<test:node/>' + '</root>'); FXmlTextReader.Read; FXmlTextReader.Read; CheckEquals('test', FXmlTextReader.Prefix, 'Prefix property'); CheckEquals('test:node', FXmlTextReader.Name, 'Name property'); CheckEquals('node', FXmlTextReader.LocalName, 'LocalName property'); CheckEquals('test', FXmlTextReader.Prefix, 'Prefix property'); CheckEquals('http://e-tobi.net', FXmlTextReader.NameSpaceUri, 'NameSpaceUri property'); end; procedure TXmlTextReaderTest.TestAttributeProperties; begin SetXmlData('<?xml version="1.0"?>' + '<root>' + '<first a1="1" a2="2"/>' + '</root>'); while FXmlTextReader.Read and (FXmlTextReader.Name <> 'root') do ; CheckEquals(0, FXmlTextReader.AttributeCount, 'property AttributeCount'); Check(not FXmlTextReader.HasAttributes, 'property HasAttributes'); FXmlTextReader.Read; CheckEquals(2, FXmlTextReader.AttributeCount, 'property AttributeCount'); Check(FXmlTextReader.HasAttributes, 'property HasAttributes'); end; procedure TXmlTextReaderTest.TestReadInvalidXml; begin // document = '' try FXmlTextReader.Read; Fail('Expected EXmlException'); except on E: EXmlException do ; end; // document = invalid SetXmlData('<?xml version="1.0"?><x></y>'); try FXmlTextReader.Read; // reads <x> FXmlTextReader.Read; // reads </y> Fail('Expected EXmlException'); except on E: EXmlException do ; end; end; procedure TXmlTextReaderTest.TestReset; begin SetXmlData('<?xml version="1.0"?><first_doc/>'); // reset called within SetXmlData FXmlTextReader.Read; CheckEquals('first_doc', FXmlTextReader.Name, 'Reading first doc'); SetXmlData('<?xml version="1.0"?><second_doc/>'); // reset called within SetXmlData FXmlTextReader.Read; CheckEquals('second_doc', FXmlTextReader.Name, 'Reading second doc with same XmlTextReader'); end; procedure TXmlTextReaderTest.TestGetAttributeMethods; begin SetXmlData('<?xml version="1.0"?>' + '<root xmlns:test="http://e-tobi.net">' + '<first a="1" b="2" test:a="3"/>' + '</root>'); FXmlTextReader.Read; FXmlTextReader.Read; CheckEquals('1', FXmlTextReader.GetAttribute('a'), 'attribute by name'); CheckEquals('2', FXmlTextReader.GetAttribute('b'), 'attribute by name'); CheckEquals('1', FXmlTextReader.GetAttribute(0), 'attribute by number'); CheckEquals('2', FXmlTextReader.GetAttribute(1), 'attribute by number'); CheckEquals('3', FXmlTextReader.GetAttribute('a', 'http://e-tobi.net'), 'attribute by namespace'); end; procedure TXmlTextReaderTest.TestMoveMethods; begin SetXmlData('<?xml version="1.0"?>' + '<root xmlns:test="http://e-tobi.net" a="2" test:a="3">' + '<first/>' + '</root>'); FXmlTextReader.Read; Check(not FXmlTextReader.MoveToAttribute('x'), 'move to non existing attribute by name returned true'); Check(FXmlTextReader.MoveToAttribute('a'), 'move to attribute returned false'); CheckEquals('2', FXmlTextReader.Value, 'moved to wrong attribute by name'); Check(not FXmlTextReader.MoveToAttribute('x', 'http://e-tobi.net'), 'move to non existing attribute by namespace returned true'); Check(not FXmlTextReader.MoveToAttribute('a', 'http://foo'), 'move to attribute by non existing namespace returned true'); Check(FXmlTextReader.MoveToAttribute('a', 'http://e-tobi.net'), 'move to attribute returned false'); CheckEquals('3', FXmlTextReader.Value, 'moved to wrong attribute by namespac'); try FXmlTextReader.MoveToAttribute(4); Fail('Expected EArgumentOutOfRangeException'); except on E: EArgumentOutOfRangeException do ; end; FXmlTextReader.MoveToAttribute(1); CheckEquals('2', FXmlTextReader.Value, 'moved to wrong attribute by number'); Check(FXmlTextReader.MoveToFirstAttribute, 'moved to first attribute failed'); CheckEquals('http://e-tobi.net', FXmlTextReader.Value, 'moved not to first attribute'); Check(FXmlTextReader.MoveToNextAttribute, 'moved to next attribute failed'); CheckEquals('2', FXmlTextReader.Value, 'moved not to next attribute'); Check(FXmlTextReader.MoveToNextAttribute, 'moved to next attribute failed'); CheckEquals('3', FXmlTextReader.Value, 'moved not to next attribute'); Check(not FXmlTextReader.MoveToNextAttribute, 'moved to last + 1 attribute returned true'); Check(FXmlTextReader.MoveToElement, 'move from attribute to element failed'); CheckEquals('root', FXmlTextReader.Name, 'moved back - wrong element'); Check(not FXmlTextReader.MoveToElement, 'move from attribute to element should fail'); FXmlTextReader.Read; Check(not FXmlTextReader.MoveToFirstAttribute, 'moved to first attribute, where no attribute exists'); end; procedure TXmlTextReaderTest.TestLookupNamespace; begin SetXmlData('<?xml version="1.0"?>' + '<root xmlns:ns1="http://e-tobi.net" xmlns:ns2="foo"/>'); FXmlTextReader.Read; CheckEquals('http://e-tobi.net', FXmlTextReader.LookupNamespace('ns1'), 'wrong namespace returned'); CheckEquals('foo', FXmlTextReader.LookupNamespace('ns2'), 'wrong namespace returned'); end; procedure TXmlTextReaderTest.TestReadOuterXml; begin SetXmlData( '<?xml version="1.0" encoding="iso-8859-1"?><root><first>äöüß</first></root>'); CheckEquals('', FXmlTextReader.ReadOuterXml); FXmlTextReader.Read; CheckEquals('<root><first>äöüß</first></root>', FXmlTextReader.ReadOuterXml); end; procedure TXmlTextReaderTest.TestReadString; begin SetXmlData('<?xml version="1.0"?><root>contents</root>'); FXmlTextReader.Read; CheckEquals('contents', FXmlTextReader.ReadString, 'ReadString failed'); end; procedure TXmlTextReaderTest.TestParserProp; begin SetXmlData('<?xml version="1.0"?><root>contents</root>'); FXmlTextReader.ParserProperties := []; Check([] = FXmlTextReader.ParserProperties, 'no ParserProperties should be set'); FXmlTextReader.ParserProperties := [XML_PARSER_LOADDTD]; Check([XML_PARSER_LOADDTD] = FXmlTextReader.ParserProperties, 'XML_PARSER_LOADDTD should be set'); FXmlTextReader.ParserProperties := [XML_PARSER_DEFAULTATTRS]; Check([XML_PARSER_LOADDTD] = FXmlTextReader.ParserProperties, 'XML_PARSER_DEFAULTATTRS should be set'); // XML_PARSER_LOADDTD, // = 1 // XML_PARSER_DEFAULTATTRS, // = 2 // XML_PARSER_VALIDATE, // = 3 // XML_PARSER_SUBST_ENTITIES // = 4 end; procedure TXmlTextReaderTest.TestCreateFromFile; var fileName: string; xmlData: AnsiString; fileStream: TFileStream; begin xmlData := '<?xml version="1.0"?><root />'; fileName := '.\temp.xml'; fileStream := TFileStream.Create(fileName, fmCreate); try fileStream.Write(PAnsiString(xmlData)^, length(xmlData)); finally fileStream.Free; end; try TXmlTextReader.Create(fileName).Free; Check(True, 'Construction from file'); finally DeleteFile(fileName); end; end; procedure TXmlTextReaderTest.TestMultipleThreads; var fileName: string; fileStream: TFileStream; thread1, thread2: TTestThread; begin SetXmlData('<?xml version="1.0"?><root />'); fileName := '.\temp.xml'; fileStream := TFileStream.Create(fileName, fmCreate); FDataStream.Seek(0, soFromBeginning); try fileStream.CopyFrom(FDataStream, FDataStream.Size); finally fileStream.Free; end; thread1 := TTestThread.Create(fileName); thread2 := TTestThread.Create(fileName); try thread1.Start; thread2.Start; thread1.WaitFor; thread2.WaitFor; Check(True, 'Construction from file twice'); finally thread1.Free; thread2.Free; DeleteFile(fileName); end; end; procedure TXmlTextReaderTest.TestCreateFromNonExistingFile; begin try TXmlTextReader.Create('does not exist').Free; Fail('Expected EXmlException'); except on E: EXmlException do ; end; end; procedure TXmlTextReaderTest.TestNodeType; begin SetXmlData('<?xml version="1.0"?>' + '<!DOCTYPE root [' + '<!ELEMENT first EMPTY>' + '<!ATTLIST first a1 CDATA #IMPLIED>' + '<!ATTLIST first a2 CDATA #IMPLIED>' + '<!ATTLIST first a3 CDATA "3">' + ']>' + '<root>' + '<first a1="1" a2="2"/>' + '</root>'); Check(ntNone = FXmlTextReader.NodeType, 'NodeType should be None'); FXmlTextReader.Read; Check(ntDocumentType = FXmlTextReader.NodeType, 'NodeType should be DocumentType'); FXmlTextReader.Read; Check(ntElement = FXmlTextReader.NodeType, 'NodeType should be Element'); end; procedure TXmlTextReaderTest.TestSkip; begin SetXmlData('<?xml version="1.0"?><root><a><c/></a><b><c/></b></root>'); FXmlTextReader.Read; FXmlTextReader.Read; CheckEquals('a', FXmlTextReader.Name); FXmlTextReader.Skip; CheckEquals('b', FXmlTextReader.Name); end; procedure TXmlTextReaderTest.TestReadInvalidXmlFile; var xmlFile: TFileStream; xmlData: AnsiString; xmlreader: TXmlTextReader; begin xmlData := '<?xml version="1.0"?><root><a></b></root>'; xmlFile := TFileStream.Create('temp.xml', fmCreate); try xmlFile.Write(PAnsiString(xmlData)^, length(xmlData)); FreeAndNil(xmlFile); try xmlreader := TXmlTextReader.Create('temp.xml'); try xmlreader.Read; Fail('Expected EXmlException'); finally xmlreader.Free; end; except on E: EXmlException do ; end; finally xmlFile.Free; DeleteFile('tem.xml'); end; end; procedure TXmlTextReaderTest.TestReadmeSample; var xmlFile: TFileStream; xmlData: AnsiString; reader: TXmlTextReader; begin xmlData := '<root>' + ' <first something="foo" somethingElse="bar" />' + ' <second>Baz</second>' + '</root>'; xmlFile := TFileStream.Create('temp.xml', fmCreate); try xmlFile.WriteBuffer(PAnsiChar(xmlData)^, length(xmlData)); FreeAndNil(xmlFile); reader := TXmlTextReader.Create('temp.xml'); try reader.Read; CheckEquals('root', reader.Name); reader.Read; // #text because of indentation reader.Read; CheckEquals('first', reader.Name); CheckEquals('foo', reader.GetAttribute('something')); CheckEquals('bar', reader.GetAttribute('somethingElse')); reader.Read; // #text because of indentation reader.Read; CheckEquals('second', reader.Name); CheckEquals('Baz', reader.ReadString); // read 'ahead' element content reader.Read; // #text CheckEquals('Baz', reader.Value); reader.Read; reader.Read; CheckFalse(reader.Read); // EOF! finally xmlFile.Free; end; finally xmlFile.Free; DeleteFile('tem.xml'); end; end; procedure TXmlTextReaderTest.TestRead; begin SetXmlData('<?xml version="1.0" encoding="iso-8859-1"?><äöüß>äöüß</äöüß>'); CheckEquals(True, FXmlTextReader.Read); CheckEquals('äöüß', FXmlTextReader.Name); CheckEquals(True, FXmlTextReader.Read); CheckEquals('#text', FXmlTextReader.Name); CheckEquals('äöüß', FXmlTextReader.Value); CheckEquals(True, FXmlTextReader.Read); CheckEquals('äöüß', FXmlTextReader.Name); CheckEquals(false, FXmlTextReader.Read); CheckEquals(false, FXmlTextReader.Read); end; procedure TXmlTextReaderTest.TestReadInnerXml; begin SetXmlData( '<?xml version="1.0" encoding="iso-8859-1"?><root><first>äöüß</first></root>'); CheckEquals('', FXmlTextReader.ReadOuterXml); FXmlTextReader.Read; CheckEquals('<first>äöüß</first>', FXmlTextReader.ReadInnerXml); end; { TTestThread } constructor TTestThread.Create(const fileName: string); begin inherited Create(True); FFileName := fileName; end; procedure TTestThread.Execute; var x: TXmlTextReader; i: Integer; begin inherited; for i := 1 to 1 do begin x := TXmlTextReader.Create(FFileName); x.Read; x.Free; end; end; initialization RegisterTest('Constructors', TXmlTextReaderTest.Suite); end.
{***********************************<_INFO>************************************} { <Проект> VScreen } { } { <Область> 16:Медиа-контроль } { } { <Задача> Форма для проверки соединения с устройством. Открывает } { соединение с указанным каналом и отображает видеопоток на } { экране. } { } { <Автор> Фадеев Р.В. } { } { <Дата> 10.09.2007 } { } { <Примечание> Нет примечаний } { } { <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" } { } {***********************************</_INFO>***********************************} unit MediaStream.PreviewForm.MediaServer; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ufmForm_B, StdCtrls, ExtendControls, ExtCtrls,VideoPane.Control, Buttons, MediaServer.Net.Mscp.Client,MediaServer.Net.Definitions, ComCtrls, MediaStream.PtzControl; type TfmMediaStreamPreviewMediaServer = class(TfmForm_B) paScreen: TPanel; Panel2: TPanel; paMonitor: TPanel; Bevel1: TBevel; Panel1: TPanel; edProperties: TExtendMemo; paPtz: TfrmPtzControl; paArchive: TGroupBox; buGetArchive: TButton; dtArchiveFrom: TDateTimePicker; dtArchiveTo: TDateTimePicker; ckPtzViaMscp: TExtendCheckBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ckUseMscpClick(Sender: TObject); procedure buGetArchiveClick(Sender: TObject); private FPane : TVideoPane; FMscpClient: TMscpClient; FServerIp: string; FServerPort: Word; FSourceName: string; FUserName: string; FUserPassword: string; procedure OnVideoPaneError(aSender: TVideoPane; aError: Exception); procedure OnVideoPaneConnected(Sender: TVideoPane); procedure OnVideoPaneDisconnected(Sender: TVideoPane); procedure OnPtzControlError(aSender: TfrmPtzControl; aError: Exception); procedure OnPtzControlCommandExecuting(aSender: TfrmPtzControl; aCommand: TPtzCommand; var aSpeed: TPtzSpeed); procedure SendPtzCommandViaMscp(const aCommand: string; aSpeed: integer); protected procedure DoClose(var Action: TCloseAction); override; public constructor Create(AOwner : TComponent);override; destructor Destroy; override; class procedure Run(const aServerIP: string; aServerPort: Word; const aSourceName: string; const aUserName,aPassword: string; aCustomSettings: TBytes); end; implementation uses MediaStream.DataSource.Ms3s,Player.VideoOutput.Base, Player.VideoOutput.AllTypes,Player.AudioOutput.AllTypes; {$R *.DFM} { TfmMediaStreamPreviewMediaServer } procedure TfmMediaStreamPreviewMediaServer.buGetArchiveClick(Sender: TObject); var aSourceName: string; begin inherited; if FMscpClient=nil then FMscpClient:=TMscpClient.Create(FServerIp,icMSCPServerPort); FMscpClient.SendCommandHistoryView(FSourceName,'',dtArchiveFrom.DateTime,dtArchiveTo.DateTime,aSourceName); TfmMediaStreamPreviewMediaServer.Create(nil).Run(FServerIp, FServerPort, aSourceName,'root','',nil); end; procedure TfmMediaStreamPreviewMediaServer.ckUseMscpClick(Sender: TObject); begin inherited; FreeAndNil(FMscpClient); if ckPtzViaMscp.Checked then try FMscpClient:=TMscpClient.Create(FServerIp,icMSCPServerPort); except ckPtzViaMscp.Checked:=false; raise; end; end; constructor TfmMediaStreamPreviewMediaServer.Create(AOwner: TComponent); begin inherited; dtArchiveTo.DateTime:=Now; dtArchiveFrom.DateTime:=dtArchiveTo.DateTime-7; end; destructor TfmMediaStreamPreviewMediaServer.Destroy; begin FreeAndNil(FMscpClient); FreeAndNil(FPane); inherited; end; procedure TfmMediaStreamPreviewMediaServer.DoClose(var Action: TCloseAction); begin inherited; Action:=caFree; end; procedure TfmMediaStreamPreviewMediaServer.SendPtzCommandViaMscp(const aCommand: string; aSpeed: integer); begin Assert(FMscpClient<>nil); FMscpClient.SendCommandPtzExecute(FSourceName,FUserName,FUserPassword, aCommand,'',0,aSpeed,true); end; class procedure TfmMediaStreamPreviewMediaServer.Run(const aServerIP: string; aServerPort: Word; const aSourceName: string; const aUserName,aPassword: string; aCustomSettings: TBytes); var aConnectionParams_MediaServer: TMediaStreamDataSourceConnectParams_Ms3s; begin with TfmMediaStreamPreviewMediaServer.Create(nil) do begin FServerIp:=aServerIP; FServerPort:=aServerPort; FSourceName:=aSourceName; FUserName:=aUserName; FUserPassword:=aPassword; FPane:=TVideoPane.Create(paScreen, TPlayerVideoOutput_AllTypes,TPlayerAudioOutput_AllTypes); FPane.SynchronousDisplay:=true; // For Debugging Caption:=Format('Просмотр: %s:%d/%s',[aServerIP,aServerPort,aSourceName]); Color:=clBlack; ParentBackground:=false; edProperties.Lines.Clear; edProperties.Lines.Add('Свойства соединения:'); edProperties.Lines.Add(' Имя = '+aSourceName); edProperties.Lines.Add(' IP = '+aServerIP); edProperties.Lines.Add(' Порт = '+IntToStr(aServerPort)); edProperties.Lines.Add(' Протокол = '+'3S'); edProperties.Lines.Add(' Пользователь = '+aUserName); paPtz.Visible:=false; paArchive.Visible:=false; Show; FPane.Parent:=paScreen; FPane.Align:=alClient; FPane.Visible:=true; FPane.OnConnectFailed:=OnVideoPaneError; FPane.OnConnectSucceed:=OnVideoPaneConnected; FPane.OnDisconnected:=OnVideoPaneDisconnected; FPane.AudioEnabled:=true; FPane.KeepAspectRatio:=true; FPane.ShowMonitor(paMonitor); paMonitor.AutoSize:=true; paPtz.OnError:=OnPtzControlError; paPtz.OnCommandExecuting:=OnPtzControlCommandExecuting; aConnectionParams_MediaServer:=TMediaStreamDataSourceConnectParams_Ms3s.Create( aServerIP,aServerPort, aSourceName,aUserName,aPassword,aCustomSettings,INFINITE); try FPane.Connect(TMediaStreamDataSource_Ms3s,aConnectionParams_MediaServer); finally FreeAndNil(aConnectionParams_MediaServer); end; end; end; procedure TfmMediaStreamPreviewMediaServer.OnPtzControlCommandExecuting(aSender: TfrmPtzControl; aCommand: TPtzCommand; var aSpeed: TPtzSpeed); begin inherited; if ckPtzViaMscp.Checked then begin case aCommand of pmLeft: begin SendPtzCommandViaMscp('Left',aSpeed) end; pmUp: begin SendPtzCommandViaMscp('Up',aSpeed) end; pmRight:begin SendPtzCommandViaMscp('Right',aSpeed) end; pmDown: begin SendPtzCommandViaMscp('Down',aSpeed) end; pcZoomIn: begin SendPtzCommandViaMscp('ZoomIn',0) end; pcZoomOut: begin SendPtzCommandViaMscp('ZoomOut',0) end; pcFocusIn: begin SendPtzCommandViaMscp('FocusIn',0) end; pcFocusOut: begin SendPtzCommandViaMscp('FocusOut',0) end; pcApertureInc: begin SendPtzCommandViaMscp('ApertureInc',0) end; pcApertureDec: begin SendPtzCommandViaMscp('ApertureDec',0) end; end; aSpeed:=0; end; end; procedure TfmMediaStreamPreviewMediaServer.OnPtzControlError(aSender: TfrmPtzControl; aError: Exception); begin OnVideoPaneError(nil,aError); end; procedure TfmMediaStreamPreviewMediaServer.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action:=caFree; FreeAndNil(FMscpClient); FreeAndNil(FPane); end; procedure TfmMediaStreamPreviewMediaServer.OnVideoPaneConnected(Sender: TVideoPane); begin paPtz.Visible:=FPane.DataSource.PtzSupported; paPtz.DataSource:=FPane.DataSource; if FPane.DataSource.PtzSupported then FPane.DataSource.PtzInit; paArchive.Visible:=MediaStream.DataSource.Ms3s.TMediaStreamDataSource_Ms3s(FPane.DataSource).Channel.ArchiveSupported; end; procedure TfmMediaStreamPreviewMediaServer.OnVideoPaneDisconnected(Sender: TVideoPane); begin paPtz.DataSource:=nil; end; procedure TfmMediaStreamPreviewMediaServer.OnVideoPaneError(aSender: TVideoPane; aError: Exception); begin edProperties.Lines.Add('** ОШИБКА: '+aError.Message); end; end.
PROGRAM MODE; VAR num: INTEGER; BEGIN WRITE ('Type a number : '); READ (num); IF ( (num mod 2) = 0 ) THEN WRITE ('The number is even') ELSE WRITE ('The number is odd'); END.
(* * Chhom Seng * 2015/05/03 * * WIMInfo * * Command-line tool to modify custom XML information in a WIM file. This tool * supports embed, extract, and remove. * * Embed: The user can specify an XML that is to be embedded into the WIM. An * optional image index parameter can be given to indicate which image * should be modified. * * Extract: The user can use an XPath expression to indicate information * to be extracted from the WIM file. When extracting, the output is * written to standard out. * * Remove: The user can use an XPath expression to indicate nodes to remove * from the WIM file. * * The XPath expression must be in absolute addressing. * * TODO: Implement WIMContainer class to handle common WIM tasks. *) program wiminfo; {$mode objfpc}{$H+} uses {$IFDEF UNIX} {$IFDEF UseCThreads} cthreads, {$ENDIF} {$ENDIF} Classes, SysUtils, CustApp, wimgapi, Windows, Dialogs, DOM, XMLRead, XMLWrite, XPath, XMLUtils; const { The WIMGet/WIMSet information functions work with a string buffer that is preceded by $FEFF. Without this marker, both functions fail. } WIM_INFO_MARKER = widechar($FEFF); type { Handles WIM files. Currently unimplemented } WIMContainer = class(TObject) FHandle: THandle; FFilePath: string; FDesiredAccess, FDisposition, FFlagsAndAttributes, FCompressionType: DWORD; public { Return value of WIMCreateFile. 0 is an invalid value } property Handle: THandle read FHandle; {property FilePath: string read FFilePath write SetFilePath; } end; { TWIMInfo } TWIMInfo = class(TCustomApplication) protected WIM: WIMContainer; WIMFile, XMLFile: string; Index: integer; procedure DoRun; override; { Copies an XML document into the specified image } procedure Embed(XMLPath: string; ImageIndex: integer = 0); { Extracts the specified node (using XPath) } procedure Extract(XPathExp: string = ''); { Removes the specified node (using XPath) } procedure Remove(XPathExp: string); public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; end; { TWIMInfo } procedure TWIMInfo.DoRun; var ErrorMsg, XPathExp: string; begin // quick check parameters ErrorMsg := CheckOptions('hiexr', ['help', 'index', 'embed', 'extract', 'remove']); if ErrorMsg <> '' then begin ShowException(Exception.Create(ErrorMsg)); Terminate; Exit; end; // parse parameters if HasOption('h', 'help') then begin WriteHelp; Terminate; Exit; end; { The first parameter must always be a WIM file } WIMFile := GetParams(1); if not FileExists(WIMFile) then begin ShowException(Exception.Create('The given WIM file was not found.')); Terminate; Exit; end else begin { Remember to initialize the WIMGAPI unit } InitWIMGAPI(); //WIM := WIMContainer.Create(WIMFile); if ParamCount = 1 then begin Extract('//WIM'); end; if HasOption('e', 'embed') then begin XMLFile := GetOptionValue('e', 'embed'); if HasOption('i', 'index') then Index := StrToInt(GetOptionValue('i', 'index')) else Index := 0; Embed(XMLFile, Index); end else if HasOption('x', 'extract') then begin XPathExp := GetOptionValue('x', 'extract'); Extract(XPathExp); end else if HasOption('r', 'remove') then begin XPathExp := GetOptionValue('r', 'remove'); Remove(XPathExp); end else begin { Default handling } end; end; // stop program loop Terminate; end; { XMLPath is the path to an XML file } { ImageIndex is the specified image. Indices start at 1 } procedure TWIMInfo.Embed(XMLPath: string = ''; ImageIndex: integer = 0); var { WIMHandle is the handle to the WIM file InfoHandle is the handle to use for retrieving information } WIMHandle, InfoHandle: THandle; OperationResult: boolean; OldInfoBuffer, NewInfoBuffer: PWideChar; BufferSize, dwResult: DWord; // Temporary directory needed for WIM modification TempDir: string; XMLDataString: TStringStream; XMLDoc, ImageXML: TXMLDocument; NewNode, ExistingNode: TDOMNode; begin if not FileExists(XMLPath) then begin raise Exception.Create('The given XML was not found'); end; WIMHandle := 0; InfoHandle := 0; OldInfoBuffer := nil; NewInfoBuffer := nil; BufferSize := 0; dwResult := 0; XMLDataString := nil; XMLDoc := nil; ImageXML := nil; NewNode := nil; ExistingNode := nil; ReadXMLFile(XMLDoc, XMLPath); if XMLDoc = nil then raise Exception.Create('Failed to initialize XML'); WIMHandle := WIMCreateFile(StringToOleStr(WIMFile), WIM_GENERIC_WRITE, WIM_OPEN_EXISTING, WIM_FLAG_VERIFY, 0, @dwResult); if WIMHandle = 0 then raise Exception.Create('Failed to open the WIM'); { Must always set temporary path or modifications will fail } TempDir := WIMFile + '_temp'; if not DirectoryExists(TempDir) then CreateDir(Tempdir); OperationResult := WIMSetTemporaryPath(WIMHandle, StringToOleStr(TempDir)); if not OperationResult = True then raise Exception.Create('Failed to set temporary path with error: ' + IntToStr(GetLastError())); if (ImageIndex > 0) and (ImageIndex <= WIMGetImageCount(WIMHandle)) then begin InfoHandle := WIMLoadImage(WIMHandle, ImageIndex); end else begin InfoHandle := WIMHandle; end; OperationResult := WIMGetImageInformation(InfoHandle, @OldInfoBuffer, @BufferSize); if not OperationResult = True then raise Exception.Create('Failed to get image information'); { Skip the first character or XML creation fails } XMLDataString := TStringStream.Create(WideCharToString(@OldInfoBuffer[1])); ReadXMLFile(ImageXML, XMLDataString); XMLDataString.Free; NewNode := ImageXML.ImportNode(TDOMNode(XMLDoc.DocumentElement), True); { Determine whether the node already exists. If it does, replace it } ExistingNode := ImageXML.DocumentElement.FindNode(NewNode.NodeName); if Assigned(ExistingNode) then begin ImageXML.DocumentElement.ReplaceChild(NewNode, ExistingNode); end else begin ImageXML.DocumentElement.AppendChild(NewNode); end; XMLDataString := TStringStream.Create(''); WriteXML(ImageXML.DocumentElement, XMLDataString); NewInfoBuffer := AllocMem(Length(XMLDataString.DataString) * SizeOf(PWideChar)); { Skip over the first element (the Header); don't overwrite it or WIMSetImageInformation will fail } NewInfoBuffer^ := WIM_INFO_MARKER; StrCopy(@NewInfoBuffer[1], StringToOleStr(XMLDataString.DataString)); OperationResult := WIMSetImageInformation(InfoHandle, NewInfoBuffer, StrLen(NewInfoBuffer) * SizeOf(NewInfoBuffer)); if not OperationResult = True then raise Exception.Create('Failed to set new information'); Freememory(NewInfoBuffer); if not (OldInfoBuffer = nil) then LocalFree(HLOCAL(OldInfoBuffer)); ExistingNode.Free; NewNode.Free; XMLDataString.Free; ImageXML.Free; XMLDoc.Free; { Will need to check whether WIMHandle are the same because of the current implementation } if WIMHandle = InfoHandle then begin OperationResult := WIMCloseHandle(WIMHandle); end else begin if InfoHandle <> 0 then WIMCloseHandle(InfoHandle); if WIMHandle <> 0 then OperationResult := WIMCloseHandle(WIMHandle); end; if DirectoryExists(TempDir) then RemoveDir(TempDir); if not OperationResult = True then raise Exception.Create('Failed to close WIM with error: ' + IntToStr(GetLastError())); end; procedure TWIMInfo.Extract(XPathExp: string); var Handle: THandle; InfoBuffer: PWideChar; OperationResult: boolean; dwResult, BufferSize: DWord; XML, OutputXML: TXMLDocument; TempNode: TDOMNode; NodePtr: Pointer; XMLString: TStringStream; TempDir: string; FoundNodes: TXPathVariable; begin if not FileExists(WIMFile) then begin raise Exception.Create('The specified WIM file was not found'); end; Handle := 0; InfoBuffer := nil; OperationResult := False; dwResult := 0; BufferSize := 0; XML := nil; Handle := WIMCreateFile(StringToOleStr(WIMFile), WIM_GENERIC_READ, WIM_OPEN_EXISTING, 0, 0, @dwResult); { dwResult indicates whether it opened new or existing } if Handle = 0 then begin raise Exception.Create('Unable to open the specified WIM with error: ' + IntToStr(GetLastError())); end; { Must always set temporary path or modifications will fail } TempDir := WIMFile + '_temp'; if not DirectoryExists(TempDir) then CreateDir(Tempdir); OperationResult := WIMSetTemporaryPath(Handle, StringToOleStr(TempDir)); if not OperationResult = True then raise Exception.Create('Failed to set temporary path with error: ' + IntToStr(GetLastError())); OperationResult := WIMGetImageInformation(Handle, @InfoBuffer, @BufferSize); if not OperationResult = True then begin raise Exception.Create('Failed to get the image information'); end; { Need to skip the first character in the buffer or XML won't initialize } XMLString := TStringStream.Create(WideCharToString(@InfoBuffer[1])); ReadXMLFile(XML, XMLString); XMLString.Free; { The XPath expression should strip out the root node since it is interpreted incorrectly } if XPathExp = '' then XPathExp := '/'; FoundNodes := EvaluateXPathExpression(XPathExp, XML.DocumentElement); if FoundNodes = nil then begin raise Exception.Create('Failed to evaluate the XPath expression'); end; OutputXML := TXMLDocument.Create(); for NodePtr in FoundNodes.AsNodeSet() do begin TempNode := TDOMNode(NodePtr); XMLString := TStringStream.Create(''); WriteXML(TempNode, XMLString); Write(XMLString.DataString); XMLString.Free; end; FoundNodes.Free; XML.Free; OutputXML.Free; if DirectoryExists(TempDir) then RemoveDir(TempDir); if not (InfoBuffer = nil) then begin LocalFree(HLOCAL(InfoBuffer)); end; OperationResult := WIMCloseHandle(Handle); if not OperationResult = True then begin raise Exception.Create('Failed to close the handle with error: ' + IntToStr(GetLastError())); end; end; procedure TWIMInfo.Remove(XPathExp: string); var Handle: THandle; OldInfoBuffer, NewInfoBuffer: PWideChar; BufferSize, dwResult: DWord; OperationResult: boolean; XMLDoc: TXMLDocument; XMLDataString: TStringStream; FoundNodes: TXPathVariable; TempNode: TDOMNode; TempPtr: Pointer; TempDir: string; begin Handle := 0; OldInfoBuffer := nil; BufferSize := 0; dwResult := 0; OperationResult := False; XMLDoc := nil; XMLDataString := nil; TempNode := nil; { Modify the WIM, so open write } Handle := WIMCreateFile(StringToOleStr(WIMFile), WIM_GENERIC_WRITE, WIM_OPEN_EXISTING, 0, 0, @dwResult); if Handle = 0 then begin raise Exception.Create('Failed to open the specified WIM with error: ' + IntToStr(GetLastError())); end; { Must always set temporary path or modifications will fail } TempDir := WIMFile + '_temp'; if not DirectoryExists(TempDir) then CreateDir(Tempdir); OperationResult := WIMSetTemporaryPath(Handle, StringToOleStr(TempDir)); if not OperationResult = True then raise Exception.Create('Failed to set temporary path with error: ' + IntToStr(GetLastError())); OperationResult := WIMGetImageInformation(Handle, @OldInfoBuffer, @dwResult); if OperationResult = False then begin raise Exception.Create('Failed to get image information with error: ' + IntToStr(GetLastError())); end; { $FEFF precedes OldInfoBuffer. Must skip it for successful XML initialization } XMLDataString := TStringStream.Create(WideCharToString(@OldInfoBuffer[1])); ReadXMLFile(XMLDoc, XMLDataString); XMLDataString.Free; if not Assigned(XMLDoc) then begin raise Exception.Create('Failed to create XML document'); end; { Should ensure that XPath like //WIM/IMAGE are not accepted } FoundNodes := EvaluateXPathExpression(XPathExp, XMLDoc.DocumentElement); for TempPtr in FoundNodes.AsNodeSet do begin TempNode := TDOMNode(TempPtr); TempNode.ParentNode.RemoveChild(TempNode); end; XMLDataString := TStringStream.Create(''); WriteXML(XMLDoc.DocumentElement, XMLDataString); NewInfoBuffer := AllocMem(Length(XMLDataString.DataString) * SizeOf(PWideChar)); { Skip over the first element (the Header); don't overwrite it or WIMSetImageInformation will fail } NewInfoBuffer^ := WIM_INFO_MARKER; StrCopy(@NewInfoBuffer[1], StringToOleStr(XMLDataString.DataString)); XMLDataString.Free; OperationResult := WIMSetImageInformation(Handle, NewInfoBuffer, StrLen(NewInfoBuffer) * SizeOf(NewInfoBuffer)); if not OperationResult = True then raise Exception.Create('Failed to set new information with error: ' + IntToStr(GetLastError())); FoundNodes.Free; XMLDoc.Free; Freememory(NewInfoBuffer); if not (OldInfoBuffer = nil) then LocalFree(HLOCAL(OldInfoBuffer)); if Handle <> 0 then WIMCloseHandle(Handle); if DirectoryExists(TempDir) then RemoveDir(TempDir); end; constructor TWIMInfo.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException := True; end; destructor TWIMInfo.Destroy; begin inherited Destroy; end; procedure TWIMInfo.WriteHelp; begin { add your help code here } WriteLn('Usage: ', 'wiminfo', ' -h'); WriteLn('wiminfo', ' <path_to_wim_file> Display the XML information in the WIM.'); WriteLn; WriteLn('wiminfo', ' <path_to_wim_file> [-i index] [-e <path_to_xml_file>] Embed the given XML file into the specified image.'); WriteLn; WriteLn('wiminfo', ' <path_to_wim_file> [-i index] [-x <xpath>] Display information with the specified XPath expression.'); WriteLn; WriteLn('wiminfo', ' <path_to_wim_file> [-i index] [-r <xpath>] Remove the information from the WIM with the XPath expression.'); WriteLn; WriteLn('Press any key to continue...'); ReadLn; end; var Application: TWIMInfo; {$R *.res} begin Application := TWIMInfo.Create(nil); Application.Title := 'WIMInfo'; Application.Run; Application.Free; end.
/// ///////////////////////////////////////// // Журнал запросов по СОМ-порту /// ///////////////////////////////////////// unit ComLog; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, GMGlobals, StdCtrls, Clipbrd, GMConst, ExtCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxScrollBox, dxSkinsCore, cxLabel, cxTextEdit, cxMaskEdit, cxSplitter, cxColorComboBox, cxMemo, cxProgressBar, cxDropDownEdit, cxCalendar, dxSkinscxPCPainter, dxBarBuiltInMenu, cxPC, cxTimeEdit, cxRadioGroup, cxGroupBox, cxSpinEdit, cxCheckBox, cxButtonEdit, cxButtons, cxCheckListBox, cxListBox, cxListView, cxImage, Vcl.Menus; type TComLogFrm = class(TForm) mCOMLog: TcxMemo; Panel1: TcxGroupBox; btnCopy: TcxButton; Timer1: TTimer; procedure mCOMLogKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnCopyClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { Private declarations } slBuffer: TSTringList; tLastRefrMemo, tLastRefrBuffer: int64; synch: TMultiReadExclusiveWriteSynchronizer; procedure WMUpdateCOMLog(var Msg: TMessage); message WM_UPDATE_COM_LOG; public { Public declarations } end; var ComLogFrm: TComLogFrm; implementation {$R *.dfm} uses ProgramLogFile; { TComLogFrm } procedure TComLogFrm.WMUpdateCOMLog(var Msg: TMessage); var s: string; begin synch.BeginWrite(); try while slBuffer.Count > 1000 do slBuffer.Delete(0); try s := FormatDateTime('hh:nn:ss.zzz ', Now()) + #9 + TStringClass(Msg.WParam).s; except on e: Exception do ProgramLog.AddException('WMUpdateCOMLog - ' + e.Message); end; slBuffer.Add(s); finally synch.EndWrite(); try TStringClass(Msg.WParam).Free(); except end; tLastRefrBuffer := GetTickCount(); end; end; procedure TComLogFrm.mCOMLogKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl, ssAlt]) and (Key = Ord('C')) then Clipboard().SetTextBuf(PChar(mCOMLog.Text)); end; procedure TComLogFrm.btnCopyClick(Sender: TObject); begin mCOMLog.SelectAll(); mCOMLog.CopyToClipboard(); end; procedure TComLogFrm.FormCreate(Sender: TObject); begin slBuffer := TSTringList.Create(); tLastRefrMemo := 0; tLastRefrBuffer := 0; synch := TMultiReadExclusiveWriteSynchronizer.Create(); end; procedure TComLogFrm.FormDestroy(Sender: TObject); begin slBuffer.Free(); synch.Free(); end; procedure TComLogFrm.Timer1Timer(Sender: TObject); begin if not Visible or (tLastRefrMemo > tLastRefrBuffer) then Exit; synch.BeginRead(); try tLastRefrMemo := GetTickCount(); mCOMLog.Lines.Assign(slBuffer); finally synch.EndRead(); end; mCOMLog.SelStart := mCOMLog.Perform(EM_LINEINDEX, mCOMLog.Lines.Count, 0); mCOMLog.Perform(EM_SCROLLCARET, 0, 0); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995-2001 Borland Software Corporation } { } {*******************************************************} unit IStreams; interface uses Windows, ActiveX, SysUtils, Classes, VirtIntf, AxCtrls; type { TIStreamAdapter } TIStreamAdapter = class(TStreamAdapter, IStreamModifyTime) protected FModifyTime: Longint; public constructor Create(Stream: TStream; Ownership: TStreamOwnership = soReference); function Write(pv: Pointer; cb: Longint; pcbWritten: PLongint): HResult; override; function Stat(out statstg: TStatStg; grfStatFlag: Longint): HResult; override; function GetModifyTime: Longint; virtual; stdcall; procedure SetModifyTime(Value: Longint); virtual; stdcall; end; { TIMemoryStream } TIMemoryStream = class(TIStreamAdapter) private function GetMemoryStream: TMemoryStream; public constructor Create(Stream: TMemoryStream; Ownership: TStreamOwnership = soReference); property MemoryStream: TMemoryStream read GetMemoryStream; end; { TIFileStream } TIFileStream = class(TStreamAdapter, IStreamModifyTime) private function GetFileStream: TFileStream; public constructor Create(const FileName: string; Mode: Word); function Commit(grfCommitFlags: Longint): HResult; override; function Stat(out statstg: TStatStg; grfStatFlag: Longint): HResult; override; function GetModifyTime: Longint; stdcall; procedure SetModifyTime(Time: Longint); stdcall; property FileStream: TFileStream read GetFileStream; end; { TVirtualStream } TVirtualStream = class(TOleStream) private FStreamModifyTime: IStreamModifyTime; public constructor Create(AStream: IStream); function GetModifyTime: Longint; procedure SetModifyTime(Time: Longint); end; TExceptionHandler = procedure; const ExceptionHandler: TExceptionHandler = nil; implementation {$IFDEF LINUX} uses Libc; {$ENDIF} { TIStreamAdapter } constructor TIStreamAdapter.Create(Stream: TStream; Ownership: TStreamOwnership); begin inherited Create(Stream, Ownership); FModifyTime := DateTimeToFileDate(Now); end; function TIStreamAdapter.Write(pv: Pointer; cb: Longint; pcbWritten: PLongint): HResult; begin Result := inherited Write(pv, cb, pcbWritten); FModifyTime := DateTimeToFileDate(Now); end; function TIStreamAdapter.Stat(out statstg: TStatStg; grfStatFlag: Longint): HResult; var DosFileTime: Longint; LocalFileTime: TFileTime; begin Result := inherited Stat(statstg, grfStatFlag); if Result <> 0 then Exit; DosFileTime := GetModifyTime; DosDateTimeToFileTime(LongRec(DosFileTime).Hi, LongRec(DosFileTime).Lo, LocalFileTime); LocalFileTimeToFileTime(LocalFileTime, statstg.mtime); end; function TIStreamAdapter.GetModifyTime: Longint; begin Result := FModifyTime; end; procedure TIStreamAdapter.SetModifyTime(Value: Longint); begin FModifyTime := Value; end; { TIMemoryStream } constructor TIMemoryStream.Create(Stream: TMemoryStream; Ownership: TStreamOwnership); begin if Stream = nil then begin Ownership := soOwned; Stream := TMemoryStream.Create; end; inherited Create(Stream, Ownership); end; function TIMemoryStream.GetMemoryStream: TMemoryStream; begin Result := TMemoryStream(Stream); end; { TIFileStream } constructor TIFileStream.Create(const FileName: string; Mode: Word); begin {$IFDEF LINUX} if Mode = fmCreate then unlink(PChar(FileName)); {$ENDIF} inherited Create(TFileStream.Create(FileName, Mode), soOwned); end; function TIFileStream.GetFileStream: TFileStream; begin Result := TFileStream(Stream); end; function TIFileStream.Stat(out statstg: TStatStg; grfStatFlag: Longint): HResult; begin Result := inherited Stat(statstg, grfStatFlag); if Result <> 0 then Exit; GetFileTime(TFileStream(Stream).Handle, @statstg.ctime, @statstg.atime, @statstg.mtime); end; function TIFileStream.GetModifyTime: Longint; begin Result := FileGetDate(FileStream.Handle); end; procedure TIFileStream.SetModifyTime(Time: Longint); begin {$IFDEF MSWINDOWS} FileSetDate(FileStream.Handle, Time); {$ELSE} {$ENDIF} end; function TIFileStream.Commit(grfCommitFlags: Longint): HResult; begin FlushFileBuffers(FileStream.Handle); Result := inherited Commit(grfCommitFlags); end; { TVirtualStream } constructor TVirtualStream.Create(AStream: IStream); begin inherited Create(AStream); if AStream.QueryInterface(IStreamModifyTime, FStreamModifyTime) <> 0 then FStreamModifyTime := nil; end; function TVirtualStream.GetModifyTime: Longint; begin if FStreamModifyTime <> nil then Result := FStreamModifyTime.GetModifyTime else Result := 0; end; procedure TVirtualStream.SetModifyTime(Time: Longint); begin if FStreamModifyTime <> nil then FStreamModifyTime.SetModifyTime(Time); end; end.
unit diocp_ex_httpClient; interface uses Classes {$IFDEF POSIX} , diocp.core.rawPosixSocket {$ELSE} , diocp.core.rawWinSocket , diocp.winapi.winsock2 , SysConst {$ENDIF} , SysUtils, utils_URL, utils.strings, diocp_ex_http_common; const HTTP_HEADER_END :array[0..3] of Byte=(13,10,13,10); type //2007以上直接=TBytes {$if CompilerVersion< 18.5} TBytes = array of Byte; {$IFEND} TDiocpHttpClient = class(TComponent) private FStringBuilder:TDStringBuilder; FCustomeHeader: TStrings; FURL: TURL; FRawSocket: TRawSocket; FRequestAccept: String; FRequestAcceptEncoding: String; FRawCookie:String; FRequestBody: TMemoryStream; FRequestContentType: String; FRequestHeader: TStringList; FReponseBuilder: TDBufferBuilder; FResponseBody: TMemoryStream; FResponseContentType: String; FResponseContentEncoding:String; FResponseHeader: TStringList; FTimeOut: Integer; /// <summary> /// CheckRecv buffer /// </summary> procedure CheckRecv(buf: Pointer; len: cardinal); procedure CheckSocketResult(pvSocketResult:Integer); procedure InnerExecuteRecvResponse(); procedure Close; procedure DoAfterResponse; public procedure Cleaup; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Post(pvURL:String); procedure Get(pvURL:String); /// <summary> /// 关闭Socket,异步操作时,关闭Socket会使正在进行的阻塞操作抛出异常从而中断 /// </summary> procedure CloseSocket; procedure SetRequestBodyAsString(pvRequestData: string; pvConvert2Utf8: Boolean); property CustomeHeader: TStrings read FCustomeHeader; /// <summary> /// 请求参数: /// 接受数据的编码类型 /// Accept-Encoding:gzip,deflate /// </summary> property RequestAcceptEncoding: String read FRequestAcceptEncoding write FRequestAcceptEncoding; /// <summary> /// 请求参数: /// 接受数据类型 /// Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 /// </summary> property RequestAccept: String read FRequestAccept write FRequestAccept; /// <summary> /// POST请求时, 内容数据类型 /// </summary> property RequestContentType: String read FRequestContentType write FRequestContentType; property RequestBody: TMemoryStream read FRequestBody; property RequestHeader: TStringList read FRequestHeader; property ResponseBody: TMemoryStream read FResponseBody; property ResponseHeader: TStringList read FResponseHeader; /// <summary> /// 响应得到的头信息 /// 返回的数据类型 /// Content-Type:image/png /// Content-Type:text/html; charset=utf-8 /// </summary> property ResponseContentType: String read FResponseContentType; property TimeOut: Integer read FTimeOut write FTimeOut; end; procedure WriteStringToStream(pvStream: TStream; pvDataString: string; pvConvert2Utf8: Boolean = true); function ReadStringFromStream(pvStream: TStream; pvIsUtf8Raw:Boolean): String; implementation { TDiocpHttpClient } resourcestring STRING_E_RECV_ZERO = '服务端主动断开关闭'; STRING_E_TIMEOUT = '服务端响应超时'; {$IFDEF POSIX} {$ELSE} // <2007版本的Windows平台使用 // SOSError = 'System Error. Code: %d.'+sLineBreak+'%s'; procedure RaiseLastOSErrorException(LastError: Integer); var // 高版本的 SOSError带3个参数 Error: EOSError; begin if LastError <> 0 then Error := EOSError.CreateResFmt(@SOSError, [LastError, SysErrorMessage(LastError)]) else Error := EOSError.CreateRes(@SUnkOSError); Error.ErrorCode := LastError; raise Error; end; {$ENDIF} procedure WriteStringToStream(pvStream: TStream; pvDataString: string; pvConvert2Utf8: Boolean = true); {$IFDEF UNICODE} var lvRawData:TBytes; {$ELSE} var lvRawStr:AnsiString; {$ENDIF} begin {$IFDEF UNICODE} if pvConvert2Utf8 then begin lvRawData := TEncoding.UTF8.GetBytes(pvDataString); end else begin lvRawData := TEncoding.Default.GetBytes(pvDataString); end; pvStream.Write(lvRawData[0], Length(lvRawData)); {$ELSE} if pvConvert2Utf8 then begin lvRawStr := UTF8Encode(pvDataString); end else begin lvRawStr := AnsiString(pvDataString); end; pvStream.WriteBuffer(PAnsiChar(lvRawStr)^, length(lvRawStr)); {$ENDIF} end; function ReadStringFromStream(pvStream: TStream; pvIsUtf8Raw:Boolean): String; {$IFDEF UNICODE} var lvRawData:TBytes; {$ELSE} var lvRawStr:AnsiString; {$ENDIF} begin {$IFDEF UNICODE} SetLength(lvRawData, pvStream.Size); pvStream.Position := 0; pvStream.Read(lvRawData[0], pvStream.Size); if pvIsUtf8Raw then begin Result := TEncoding.UTF8.GetString(lvRawData); end else begin Result := TEncoding.Default.GetString(lvRawData); end; {$ELSE} SetLength(lvRawStr, pvStream.Size); pvStream.Position := 0; pvStream.Read(PAnsiChar(lvRawStr)^, pvStream.Size); if pvIsUtf8Raw then begin Result := UTF8Decode(lvRawStr); end else begin Result := AnsiString(lvRawStr); end; {$ENDIF} end; constructor TDiocpHttpClient.Create(AOwner: TComponent); begin inherited; FStringBuilder := TDStringBuilder.Create; FRawSocket := TRawSocket.Create; FRequestBody := TMemoryStream.Create; FRequestHeader := TStringList.Create; FCustomeHeader := TStringList.Create; FReponseBuilder := TDBufferBuilder.Create; FCustomeHeader.NameValueSeparator := ':'; FResponseBody := TMemoryStream.Create; FResponseHeader := TStringList.Create; FTimeOut := 300000; FURL := TURL.Create; {$if CompilerVersion >= 18.5} FRequestHeader.LineBreak := #13#10; FResponseHeader.LineBreak := #13#10; {$IFEND} end; destructor TDiocpHttpClient.Destroy; begin FRawSocket.Free; FResponseHeader.Free; FResponseBody.Free; FRequestHeader.Free; FCustomeHeader.Free; FRequestBody.Free; FReponseBuilder.Free; FURL.Free; FStringBuilder.Free; inherited; end; procedure TDiocpHttpClient.CheckSocketResult(pvSocketResult: Integer); var lvErrorCode:Integer; begin if pvSocketResult = -2 then begin self.Close; raise Exception.Create(STRING_E_TIMEOUT); end; {$IFDEF POSIX} if (pvSocketResult = -1) or (pvSocketResult = 0) then begin try RaiseLastOSError; except FRawSocket.Close; raise; end; end; {$ELSE} if (pvSocketResult = SOCKET_ERROR) then begin lvErrorCode := GetLastError; FRawSocket.Close; // 出现异常后断开连接 {$if CompilerVersion < 23} RaiseLastOSErrorException(lvErrorCode); {$ELSE} RaiseLastOSError(lvErrorCode); {$ifend} end; {$ENDIF} end; procedure TDiocpHttpClient.Cleaup; begin FRequestBody.Clear; FResponseBody.Clear; end; procedure TDiocpHttpClient.Close; begin FRawSocket.Close(); end; procedure TDiocpHttpClient.Get(pvURL: String); var r, len:Integer; lvIpAddr:string; {$IFDEF UNICODE} lvRawHeader:TBytes; {$ELSE} lvRawHeader:AnsiString; {$ENDIF} begin FURL.SetURL(pvURL); FRequestHeader.Clear; if FURL.ParamStr = '' then begin FRequestHeader.Add(Format('GET %s HTTP/1.1', [FURL.URI])); end else begin FRequestHeader.Add(Format('GET %s HTTP/1.1', [FURL.URI + '?' + FURL.ParamStr])); end; FRequestHeader.Add(Format('Host: %s', [FURL.RawHostStr])); if FRawCookie <> '' then begin FRequestHeader.Add('Cookie:' + FRawCookie); end; FRequestHeader.Add(''); // 添加一个回车符 FRawSocket.CreateTcpSocket; try // 进行域名解析 lvIpAddr := FRawSocket.GetIpAddrByName(FURL.Host); if not FRawSocket.Connect(lvIpAddr,StrToIntDef(FURL.Port, 80)) then begin RaiseLastOSError; end; FStringBuilder.Clear; FStringBuilder.Append(FRequestHeader.Text); if FCustomeHeader.Count > 0 then begin FStringBuilder.Append(FCustomeHeader.Text); end; FStringBuilder.Append(FStringBuilder.LineBreak); {$IFDEF UNICODE} lvRawHeader := TEncoding.Default.GetBytes(FStringBuilder.ToString()); len := Length(lvRawHeader); r := FRawSocket.SendBuf(PByte(lvRawHeader)^, len); CheckSocketResult(r); if r <> len then begin raise Exception.Create(Format('指定发送的数据长度:%d, 实际发送长度:%d', [len, r])); end; {$ELSE} lvRawHeader := FStringBuilder.ToString(); len := Length(lvRawHeader); r := FRawSocket.SendBuf(PAnsiChar(lvRawHeader)^, len); CheckSocketResult(r); if r <> len then begin raise Exception.Create(Format('指定发送的数据长度:%d, 实际发送长度:%d', [len, r])); end; {$ENDIF} // //{$IFDEF UNICODE} // lvRawHeader := TEncoding.Default.GetBytes(FRequestHeader.Text); // len := Length(lvRawHeader); // r := FRawSocket.SendBuf(PByte(lvRawHeader)^, len); // CheckSocketResult(r); // if r <> len then // begin // raise Exception.Create(Format('指定发送的数据长度:%d, 实际发送长度:%d', [len, r])); // end; //{$ELSE} // lvRawHeader := FRequestHeader.Text; // len := Length(lvRawHeader); // r := FRawSocket.SendBuf(PAnsiChar(lvRawHeader)^, len); // CheckSocketResult(r); // if r <> len then // begin // raise Exception.Create(Format('指定发送的数据长度:%d, 实际发送长度:%d', [len, r])); // end; //{$ENDIF} InnerExecuteRecvResponse(); finally FRawSocket.Close(False); end; end; procedure TDiocpHttpClient.InnerExecuteRecvResponse; var lvRawHeader, lvBytes:TBytes; r, l:Integer; lvTempStr, lvRawHeaderStr:String; lvBuffer:PByte; begin FReponseBuilder.Clear; // 超过2048以外的长度,认为是错误的 SetLength(lvRawHeader, 2048); FillChar(lvRawHeader[0], 2048, 0); r := FRawSocket.RecvBufEnd(@lvRawHeader[0], 2048, @HTTP_HEADER_END[0], 4, FTimeOut); if r = 0 then begin // 对方被关闭 Close; raise Exception.Create('与服务器断开连接!'); end; // 检测是否有错误 CheckSocketResult(r); {$IFDEF UNICODE} lvRawHeaderStr := TEncoding.Default.GetString(lvRawHeader); {$ELSE} lvRawHeaderStr := StrPas(@lvRawHeader[0]); {$ENDIF} FResponseHeader.Text := lvRawHeaderStr; FResponseContentType := StringsValueOfName(FResponseHeader, 'Content-Type', [':'], True); lvTempStr := StringsValueOfName(FResponseHeader, 'Content-Length', [':'], True); FResponseContentEncoding :=StringsValueOfName(FResponseHeader, 'Content-Encoding', [':'], True); l := StrToIntDef(lvTempStr, 0); if l > 0 then begin lvBuffer := FReponseBuilder.GetLockBuffer(l); try CheckRecv(lvBuffer, l); finally FReponseBuilder.ReleaseLockBuffer(l); end; if FResponseContentEncoding = 'zlib' then begin ZDecompressBufferBuilder(FReponseBuilder); end {$IFDEF MSWINDOWS} else if FResponseContentEncoding = 'gzip' then begin GZDecompressBufferBuilder(FReponseBuilder); end {$ENDIF} ; l:= FReponseBuilder.Length; FResponseBody.Size := l; Move(FReponseBuilder.Memory^, FResponseBody.Memory^, l); end; lvTempStr := StringsValueOfName(FResponseHeader, 'Set-Cookie', [':'], True); if lvTempStr <> '' then begin FRawCookie := lvTempStr; end; DoAfterResponse; end; procedure TDiocpHttpClient.Post(pvURL: String); var r, len:Integer; lvIpAddr:string; {$IFDEF UNICODE} lvRawHeader:TBytes; {$ELSE} lvRawHeader:AnsiString; {$ENDIF} begin FURL.SetURL(pvURL); FRequestHeader.Clear; if FURL.ParamStr = '' then begin FRequestHeader.Add(Format('POST %s HTTP/1.1', [FURL.URI])); end else begin FRequestHeader.Add(Format('POST %s HTTP/1.1', [FURL.URI + '?' + FURL.ParamStr])); end; if FRawCookie <> '' then begin FRequestHeader.Add('Cookie:' + FRawCookie); end; FRequestHeader.Add(Format('Host: %s', [FURL.RawHostStr])); FRequestHeader.Add(Format('Content-Length: %d', [self.FRequestBody.Size])); if FRequestContentType = '' then begin FRequestContentType := 'application/x-www-form-urlencoded'; end; FRequestHeader.Add(Format('Content-Type: %s', [FRequestContentType])); if FRequestAcceptEncoding <> '' then begin FRequestHeader.Add(Format('Accept-Encoding: %s', [FRequestAcceptEncoding])); end; //FRequestHeader.Add(''); // 添加一个回车符 FRawSocket.CreateTcpSocket; try // 进行域名解析 lvIpAddr := FRawSocket.GetIpAddrByName(FURL.Host); if not FRawSocket.Connect(lvIpAddr,StrToIntDef(FURL.Port, 80)) then begin RaiseLastOSError; end; FStringBuilder.Clear; FStringBuilder.Append(FRequestHeader.Text); if FCustomeHeader.Count > 0 then begin FStringBuilder.Append(FCustomeHeader.Text); end; FStringBuilder.Append(FStringBuilder.LineBreak); {$IFDEF UNICODE} lvRawHeader := TEncoding.Default.GetBytes(FStringBuilder.ToString()); len := Length(lvRawHeader); r := FRawSocket.SendBuf(PByte(lvRawHeader)^, len); CheckSocketResult(r); if r <> len then begin raise Exception.Create(Format('指定发送的数据长度:%d, 实际发送长度:%d', [len, r])); end; {$ELSE} lvRawHeader := FStringBuilder.ToString(); len := Length(lvRawHeader); r := FRawSocket.SendBuf(PAnsiChar(lvRawHeader)^, len); CheckSocketResult(r); if r <> len then begin raise Exception.Create(Format('指定发送的数据长度:%d, 实际发送长度:%d', [len, r])); end; {$ENDIF} // 发送请求数据体 if FRequestBody.Size > 0 then begin len := FRequestBody.Size; r := FRawSocket.SendBuf(FRequestBody.Memory^, len); CheckSocketResult(r); if r <> len then begin raise Exception.Create(Format('指定发送的数据长度:%d, 实际发送长度:%d', [len, r])); end; end; InnerExecuteRecvResponse(); finally FRawSocket.Close(False); end; end; procedure TDiocpHttpClient.CheckRecv(buf: Pointer; len: cardinal); var lvTempL :Integer; lvReadL :Cardinal; lvPBuf:Pointer; begin lvReadL := 0; lvPBuf := buf; while lvReadL < len do begin lvTempL := FRawSocket.RecvBuf(lvPBuf^, len - lvReadL); if lvTempL = 0 then begin self.Close; raise Exception.Create('与服务器断开连接!'); end; CheckSocketResult(lvTempL); lvPBuf := Pointer(IntPtr(lvPBuf) + Cardinal(lvTempL)); lvReadL := lvReadL + Cardinal(lvTempL); end; end; procedure TDiocpHttpClient.CloseSocket; begin self.FRawSocket.Close; end; procedure TDiocpHttpClient.DoAfterResponse; begin end; procedure TDiocpHttpClient.SetRequestBodyAsString(pvRequestData: string; pvConvert2Utf8: Boolean); begin FRequestBody.Clear; WriteStringToStream(FRequestBody, pvRequestData, pvConvert2Utf8); end; end.
{$INCLUDE ..\cDefines.inc} unit cInternetUtils; { } { Internet Utilities 3.04 } { } { This unit is copyright © 2000-2004 by David J Butler } { } { This unit is part of Delphi Fundamentals. } { Its original file name is cInternetUtils.pas } { The latest version is available from the Fundamentals home page } { http://fundementals.sourceforge.net/ } { } { I invite you to use this unit, free of charge. } { I invite you to distibute this unit, but it must be for free. } { I also invite you to contribute to its development, } { but do not distribute a modified copy of this file. } { } { A forum is available on SourceForge for general discussion } { http://sourceforge.net/forum/forum.php?forum_id=2117 } { } { References: } { RFC 2045 (MIME) } { } { Revision history: } { 17/10/2000 1.01 Unit cInternetStandards. } { 22/12/2001 1.02 Unit cMIME. } { 12/12/2002 3.03 Unit cInternetUtils. } { 05/03/2004 3.04 Moved URL function to unit cURL. } { } interface uses { Fundamentals } cUtils, cStrings, cReaders, cStreams; { } { Constants } { } const SPACE = csAsciiCtl + [asciiSP]; { } { MIME Content Types } { } const ctHTML = 'text/html'; ctText = 'text/plain'; ctXML = 'text/xml'; ctJPG = 'image/jpeg'; ctGIF = 'image/gif'; ctBMP = 'image/bmp'; ctPNG = 'image/png'; ctTIFF = 'image/tiff'; ctMPG = 'video/mpeg'; ctAVI = 'video/avi'; ctQT = 'video/quicktime'; ctBinary = 'application/binary'; ctPDF = 'application/pdf'; ctPostscript = 'application/postscript'; ctBasicAudio = 'audio/basic'; ctMP3 = 'audio/mpeg'; ctRA = 'audio/x-realaudio'; ctURLEncoded = 'application/x-www-form-urlencoded'; ctZIP = 'application/zip'; ctJavaScript = 'application/javascript'; ctPascal = 'text/x-source-pascal'; ctCPP = 'text/x-source-cpp'; ctINI = 'text/x-windows-ini'; ctBAT = 'text/x-windows-bat'; function MIMEContentTypeFromExtention(const Extention: String): String; { } { Multi-Line encodings } { } function EncodeDotLineTerminated(const S: AnsiString): AnsiString; function EncodeEmptyLineTerminated(const S: AnsiString): AnsiString; function DecodeDotLineTerminated(const S: AnsiString): AnsiString; function DecodeEmptyLineTerminated(const S: AnsiString): AnsiString; procedure StreamDotLineTerminated(const Source, Destination: AStream; const ProgressCallback: TCopyProgressProcedure = nil); overload; procedure StreamDotLineTerminated(const Source: String; const Destination: AStream; const ProgressCallback: TCopyProgressProcedure = nil); overload; { } { HTML } { } function htmlCharRef(const CharVal: LongWord; const UseHex: Boolean = False): String; function htmlSafeAsciiText(const S: String): String; procedure htmlSafeWideText(var S: WideString); function htmlSafeQuotedText(const S: String): String; { } { Header field } { } function EncodeHeaderField(const Name, Body: String): String; function DecodeHeaderField(const S: String; var Name, Body: String): Boolean; { } { E-mail address } { } procedure DecodeEMailAddress(const S: String; var User, Domain: String); procedure DecodeEMailField(const S: String; var EMailAddress, Name: String); { } { Host } { } procedure DecodeHost(const Address: String; var Host, Port: String; const DefaultPort: String = ''); { } { Date } { } function DateFieldBody: String; function DateField: String; { } { Other header fields } { } function MessageIDFieldBody(const ID: String = ''; const Host: String = ''): String; { } { THeader class } { } type { AHeaderField } AHeaderField = class protected function GetName: String; virtual; abstract; procedure SetName(const Name: String); virtual; abstract; function GetBody: String; virtual; abstract; procedure SetBody(const Body: String); virtual; abstract; function GetBodyAsInteger: Int64; virtual; procedure SetBodyAsInteger(const Value: Int64); virtual; function GetBodyAsFloat: Extended; virtual; procedure SetBodyAsFloat(const Value: Extended); virtual; function GetAsString: String; virtual; procedure SetAsString(const Value: String); virtual; public constructor Create(const Body: String); reintroduce; overload; constructor Create(const Name, Body: String); reintroduce; overload; function Duplicate: AHeaderField; virtual; procedure Prepare; virtual; property Name: String read GetName write SetName; property Body: String read GetBody write SetBody; property BodyAsInteger: Int64 read GetBodyAsInteger write SetBodyAsInteger; property BodyAsFloat: Extended read GetBodyAsFloat write SetBodyAsFloat; property AsString: String read GetAsString write SetAsString; end; AHeaderFieldClass = class of AHeaderField; AHeaderFieldArray = Array of AHeaderField; { THeader } THeader = class protected FFields : AHeaderFieldArray; function GetFieldCount: Integer; function GetFieldByIndex(const Idx: Integer): AHeaderField; procedure SetFieldByIndex(const Idx: Integer; const Field: AHeaderField); function GetField(const Name: String): AHeaderField; procedure SetField(const Name: String; const Field: AHeaderField); function GetFieldBody(const Name: String): String; procedure SetFieldBody(const Name: String; const Body: String); function GetAsString: String; virtual; procedure SetAsString(const Header: String); virtual; public constructor Create(const Header: String); reintroduce; overload; constructor Create(const HeaderReader: AReaderEx; const Tolerant: Boolean = True; const MaxHeaderSize: Integer = -1); reintroduce; overload; destructor Destroy; override; function Duplicate: THeader; virtual; procedure ReadFromStream(const HeaderReader: AReaderEx; const Tolerant: Boolean = True; const MaxHeaderSize: Integer = -1); virtual; procedure Prepare; virtual; property AsString: String read GetAsString write SetAsString; property FieldCount: Integer read GetFieldCount; property FieldByIndex[const Idx: Integer]: AHeaderField read GetFieldByIndex write SetFieldByIndex; function GetFieldIndex(const Name: String): Integer; function HasField(const Name: String): Boolean; property Field[const Name: String]: AHeaderField read GetField write SetField; default; property FieldBody[const Name: String]: String read GetFieldBody write SetFieldBody; function GetFieldNames: StringArray; virtual; procedure Clear; virtual; procedure DeleteFieldByIndex(const Idx: Integer); function DeleteField(const Name: String): Boolean; procedure AddField(const Field: AHeaderField); overload; procedure AddField(const Name, Body: String); overload; virtual; procedure AddField(const FieldLine: String); overload; virtual; end; THeaderClass = class of THeader; THeaderArray = array of THeader; { } { AHeaderField implementations } { } type { THeaderField } THeaderField = class(AHeaderField) protected FName : String; FBody : String; function GetName: String; override; procedure SetName(const Name: String); override; function GetBody: String; override; procedure SetBody(const Body: String); override; public function Duplicate: AHeaderField; override; end; { TInvalidField } TInvalidField = class(AHeaderField) protected FRawLine : String; function GetName: String; override; procedure SetName(const Name: String); override; function GetBody: String; override; procedure SetBody(const Body: String); override; function GetAsString: String; override; procedure SetAsString(const Value: String); override; public constructor Create(const RawLine: String); function Duplicate: AHeaderField; override; end; { TDateField } TDateField = class(AHeaderField) protected FGMTDateTime : TDateTime; function GetName: String; override; procedure SetName(const Name: String); override; function GetBody: String; override; procedure SetBody(const Body: String); override; public constructor CreateNow; constructor Create(const LocalTime: TDateTime); reintroduce; overload; function Duplicate: AHeaderField; override; property GMTDateTime: TDateTime read FGMTDateTime write FGMTDateTime; end; { TEMailField } TEMailField = class(THeaderField) protected FAddress : String; FName : String; function GetBody: String; override; procedure SetBody(const Body: String); override; public property Address: String read FAddress; property Name: String read FName; end; { } { Self-testing code } { } procedure SelfTest; implementation uses { Delphi } Windows, SysUtils, { Fundamentals } cRandom, cDateTime, cUnicode, cWriters, cWindows; { } { MIME Content Type } { } type TContentTypeDef = record Ext : String; CT : String; end; const PredefinedContentTypes = 28; PredefinedContentType: Array[1..PredefinedContentTypes] of TContentTypeDef = ( (Ext: '.htm'; CT: ctHTML), (Ext: '.html'; CT: ctHTML), (Ext: '.jpg'; CT: ctJPG), (Ext: '.jpeg'; CT: ctJPG), (Ext: '.gif'; CT: ctGIF), (Ext: '.png'; CT: ctPNG), (Ext: '.bmp'; CT: ctBMP), (Ext: '.txt'; CT: ctText), (Ext: '.mpeg'; CT: ctMPG), (Ext: '.mpg'; CT: ctMPG), (Ext: '.pdf'; CT: ctPDF), (Ext: '.exe'; CT: ctBinary), (Ext: '.ps'; CT: ctPostScript), (Ext: '.avi'; CT: ctAVI), (Ext: '.qt'; CT: ctQT), (Ext: '.mov'; CT: ctQT), (Ext: '.au'; CT: ctBasicAudio), (Ext: '.wav'; CT: ctBasicAudio), (Ext: '.mp3'; CT: ctMP3), (Ext: '.mp2'; CT: ctMP3), (Ext: '.pdf'; CT: ctPDF), (Ext: '.ra'; CT: ctRA), (Ext: '.tif'; CT: ctTIFF), (Ext: '.tiff'; CT: ctTIFF), (Ext: '.zip'; CT: ctZIP), (Ext: '.ini'; CT: ctINI), (Ext: '.bat'; CT: ctBAT), (Ext: '.js'; CT: ctJavaScript)); function MIMEContentTypeFromExtention(const Extention: String): String; var I : Integer; begin // pre-defined types For I := 1 to PredefinedContentTypes do if StrEqualNoCase(Extention, PredefinedContentType[I].Ext) then begin Result := PredefinedContentType[I].CT; exit; end; // check OS Result := ContentTypeFromExtention(Extention); end; { } { Multi-Line encodings } { } function EncodeDotLineTerminated(const S: AnsiString): AnsiString; begin Result := S; if (Length(Result) >= 1) and (Result[1] = '.') then Insert('.', Result, 1); Result := StrReplace(CRLF + '.', CRLF + '..', Result) + '.' + CRLF; end; function DecodeDotLineTerminated(const S: AnsiString): AnsiString; begin if not StrMatchRight(S, '.' + CRLF) then raise EConvertError.Create('Not dot line terminated'); Result := StrReplace(CRLF + '.', CRLF, S); Delete(Result, Length(Result) - 1, 2); if (Length(Result) >= 1) and (Result[1] = '.') then Delete(Result, 1, 1); end; function EncodeEmptyLineTerminated(const S: AnsiString): AnsiString; begin Result := StrInclSuffix(S, CRLF); if (Length(Result) >= 2) and (Result[1] = asciiCR) and (Result[2] = asciiLF) then Insert('.', Result, 1); Result := StrReplace(CRLF + CRLF, CRLF + '.' + CRLF, Result) + CRLF; end; function DecodeEmptyLineTerminated(const S: AnsiString): AnsiString; begin if not StrMatchRight(S, CRLF) then raise EConvertError.Create('Not dot line terminated'); Result := StrReplace(CRLF + '.', CRLF, CopyLeft(S, Length(S) - 2)); if (Length(Result) >= 1) and (Result[1] = '.') then Delete(Result, 1, 1); end; procedure StreamDotLineTerminated(const Source, Destination: AStream; const ProgressCallback: TCopyProgressProcedure); var R : AReaderEx; W : AWriterEx; P : Int64; A : Boolean; S : String; begin R := Source.Reader; W := Destination.Writer; P := R.Position; A := False; While not R.EOF do begin S := R.ExtractLine(-1, [eolCRLF, eolEOF]); if (S <> '') and (S[1] = '.') then S := '.' + S; W.WriteLine(S, nlCRLF); if Assigned(ProgressCallback) then begin ProgressCallback(Source, Destination, R.Position - P, A); if A then raise EStreamOperationAborted.Create; end; end; W.WriteLine('.', nlCRLF); end; procedure StreamDotLineTerminated(const Source: String; const Destination: AStream; const ProgressCallback: TCopyProgressProcedure); var R : StringArray; W : AWriterEx; A : Boolean; S : String; I : Integer; P : Int64; begin R := StrSplit(Source, CRLF); W := Destination.Writer; A := False; P := 0; For I := 0 to Length(R) - 1 do begin S := R[I]; Inc(P, Length(S) + 2); if (S <> '') and (S[1] = '.') then S := '.' + S; W.WriteLine(S, nlCRLF); if Assigned(ProgressCallback) then begin ProgressCallback(nil, Destination, P, A); if A then raise EStreamOperationAborted.Create; end; end; W.WriteLine('.', nlCRLF); end; { } { HTML } { } function htmlCharRef(const CharVal: LongWord; const UseHex: Boolean): String; begin if UseHex then if CharVal <= $FF then Result := '#x' + LongWordToHex(CharVal, 2) + ';' else if CharVal <= $FFFF then Result := '#x' + LongWordToHex(CharVal, 4) + ';' else Result := '#x' + LongWordToHex(CharVal, 6) + ';' else Result := '#' + LongWordToStr(CharVal) + ';'; end; function htmlSafeAsciiText(const S: String): String; begin Result := S; // Check for unsafe characters if PosChar(['&', '<', '>', '"', #39], S) = 0 then exit; // Replace unsafe characters with entity references Result := StrReplace('&', '&amp;', Result); Result := StrReplace('<', '&lt;', Result); Result := StrReplace('>', '&gt;', Result); Result := StrReplace('"', '&quot;', Result); Result := StrReplace(#39, '&apos;', Result); end; procedure htmlSafeWideText(var S: WideString); begin WideReplaceChar('&', '&amp;', S); WideReplaceChar('<', '&lt;', S); WideReplaceChar('>', '&gt;', S); WideReplaceChar('"', '&quot;', S); WideReplaceChar(#39, '&apos;', S); end; function htmlSafeQuotedText(const S: String): String; begin Result := '"' + htmlSafeAsciiText(S) + '"'; end; { } { Header fields } { } function EncodeHeaderField(const Name, Body: String): String; begin Result := cStrings.Trim(Name, SPACE) + ': ' + cStrings.Trim(Body, SPACE); end; function DecodeHeaderField(const S: String; var Name, Body: String): Boolean; begin Result := StrSplitAtChar(S, ':', Name, Body); if not Result then exit; TrimInPlace(Name, SPACE); TrimInPlace(Body, SPACE); end; { } { E-mail address } { } procedure DecodeEMailAddress(const S: String; var User, Domain: String); begin if not StrSplitAtChar(S, '@', User, Domain) then begin User := S; Domain := ''; end; TrimInPlace(User, SPACE); TrimInPlace(Domain, SPACE); end; { Recognised e-mail formats: } { fundamentals@eternallines.com (Fundamentals Project) } { Fundamentals Project <fundamentals@eternallines.com> } { <fundamentals@eternallines.com> Fundamentals Project } { "Fundamentals Project" fundamentals@eternallines.com } { fundamentals@eternallines.com "Fundamentals Project" } procedure DecodeEMailField(const S: String; var EMailAddress, Name: String); var T, U : String; I : Integer; begin EMailAddress := ''; Name := ''; T := cStrings.Trim(S, SPACE); if T = '' then exit; EMailAddress := cStrings.Trim(StrRemoveCharDelimited(T, '<', '>'), SPACE); Name := cStrings.Trim(StrRemoveCharDelimited(T, '"', '"'), SPACE); U := cStrings.Trim(StrRemoveCharDelimited(T, '(', ')'), SPACE); if (U <> '') and (Name = '') then Name := U; TrimInPlace(T, SPACE); I := PosChar([';', ':', ',', '"', '(', '<'], T); if I > 0 then begin SetLength(T, I - 1); TrimInPlace(T, SPACE); end; if T <> '' then if EMailAddress = '' then EMailAddress := T else if Name = '' then Name := T; end; { } { Host } { } procedure DecodeHost(const Address: String; var Host, Port: String; const DefaultPort: String); begin if not StrSplitAtChar(Address, ':', Host, Port) then begin Host := Address; Port := ''; end; TrimInPlace(Host, SPACE); TrimInPlace(Port, SPACE); if Port = '' then Port := DefaultPort; end; { } { Date } { } function DateFieldBody: String; begin Result := NowAsRFCDateTime; end; function DateField: String; begin Result := EncodeHeaderField('Date', DateFieldBody); end; { } { Miscellaneous } { } function MessageIDFieldBody(const ID: String; const Host: String): String; var S, T: String; begin if ID = '' then S := RandomHex(24) + LongWordToHex(GetTickCount, 8) else S := ID; ConvertLower(S); if Host = '' then T := RandomPseudoWord(12) else T := Host; ConvertLower(T); Result := '<' + S + '@' + T + '>'; end; { } { AHeaderField } { } constructor AHeaderField.Create(const Body: String); begin inherited Create; SetBody(Body); end; constructor AHeaderField.Create(const Name, Body: String); begin inherited Create; SetName(Name); SetBody(Body); end; function AHeaderField.Duplicate: AHeaderField; begin Result := AHeaderFieldClass(ClassType).Create(GetName, GetBody); end; procedure AHeaderField.Prepare; begin end; function AHeaderField.GetBodyAsInteger: Int64; begin Result := StrToInt64Def(GetBody, -1); end; procedure AHeaderField.SetBodyAsInteger(const Value: Int64); begin SetBody(IntToStr(Value)); end; function AHeaderField.GetBodyAsFloat: Extended; begin Result := StrToFloatDef(GetBody, -1.0); end; procedure AHeaderField.SetBodyAsFloat(const Value: Extended); begin SetBody(FloatToStr(Value)); end; function AHeaderField.GetAsString: String; begin Result := EncodeHeaderField(GetName, GetBody); end; procedure AHeaderField.SetAsString(const Value: String); var N, B: String; begin DecodeHeaderField(Value, N, B); SetName(N); SetBody(B); end; { } { THeader } { } constructor THeader.Create(const Header: String); begin inherited Create; SetAsString(Header); end; constructor THeader.Create(const HeaderReader: AReaderEx; const Tolerant: Boolean; const MaxHeaderSize: Integer); begin inherited Create; ReadFromStream(HeaderReader, Tolerant, MaxHeaderSize); end; procedure THeader.ReadFromStream(const HeaderReader: AReaderEx; const Tolerant: Boolean; const MaxHeaderSize: Integer); var I : Integer; S : String; begin I := HeaderReader.LocateStr(CRLF, MaxHeaderSize); if I = 0 then begin HeaderReader.Skip(2); SetAsString(''); exit; end; if Tolerant then Repeat S := HeaderReader.ExtractLine(MaxHeaderSize, [eolCRLF]); if S <> '' then AddField(S); Until S = '' else begin I := HeaderReader.LocateStr(CRLF + CRLF, MaxHeaderSize); if I = -1 then exit; SetAsString(HeaderReader.ReadStr(I)); HeaderReader.Skip(4); end; end; function THeader.Duplicate: THeader; var I : Integer; begin Result := THeaderClass(ClassType).Create; For I := 0 to Length(FFields) - 1 do Result.AddField(FFields[I].Duplicate); end; function THeader.GetFieldNames: StringArray; var I, L : Integer; begin L := Length(FFields); SetLength(Result, L); For I := 0 to L - 1 do Result[I] := FFields[I].Name; end; function THeader.GetFieldIndex(const Name: String): Integer; var I : Integer; S : String; begin S := cStrings.Trim(Name, SPACE); For I := 0 to Length(FFields) - 1 do if StrEqualNoCase(S, FFields[I].Name) then begin Result := I; exit; end; Result := -1; end; function THeader.DeleteField(const Name: String): Boolean; var I : Integer; begin Result := False; Repeat I := GetFieldIndex(Name); if I < 0 then break; Result := True; DeleteFieldByIndex(I); Until False; end; procedure THeader.Clear; var L : Integer; Begin Repeat L := Length(FFields); if L = 0 then break; DeleteFieldByIndex(L - 1); Until False; End; function THeader.GetField(const Name: String): AHeaderField; var I : Integer; begin I := GetFieldIndex(Name); if I = -1 then Result := nil else Result := GetFieldByIndex(I); end; procedure THeader.SetField(const Name: String; const Field: AHeaderField); var I : Integer; begin if Assigned(Field) and not StrEqualNoCase(Field.Name, Name) then Field.Name := Name; I := GetFieldIndex(Name); if I = -1 then begin if Assigned(Field) then AddField(Field); end else if not Assigned(Field) then DeleteFieldByIndex(I) else FieldByIndex[I] := Field; end; function THeader.GetFieldBody(const Name: String): String; var F : AHeaderField; begin F := GetField(Name); if not Assigned(F) then Result := '' else Result := F.Body; end; procedure THeader.SetFieldBody(const Name: String; const Body: String); var F : AHeaderField; begin F := GetField(Name); if not Assigned(F) then AddField(Name, Body) else F.Body := Body; end; function THeader.HasField(const Name: String): Boolean; begin Result := GetFieldIndex(Name) >= 0; end; procedure THeader.AddField(const FieldLine: String); var N, B: String; begin if DecodeHeaderField(FieldLine, N, B) then AddField(N, B) else AddField(TInvalidField.Create(FieldLine)); end; function THeader.GetAsString: String; var I : Integer; begin Result := ''; For I := 0 to FieldCount - 1 do Result := Result + FieldByIndex[I].GetAsString + CRLF; Result := Result + CRLF; end; procedure THeader.SetAsString(const Header: String); var S : StringArray; I, J : Integer; Name : String; Body : String; begin S := StrSplit(Header, CRLF); Name := ''; For I := 0 to Length(S) - 1 do begin J := Pos(':', S[I]); if J > 0 then // header-field begin if Name <> '' then AddField(Name, Body); Name := cStrings.Trim(CopyLeft(S[I], J - 1), SPACE); Body := cStrings.Trim(CopyFrom(S[I], J + 1), SPACE); end else if (Name <> '') and (S[I] <> '') and (S[I][1] in SPACE) then // header-line continuation Body := Body + S[I] else begin if Name <> '' then AddField(Name, Body); Name := ''; if S[I] <> '' then AddField(TInvalidField.Create(S[I])); end; end; if Name <> '' then AddField(Name, Body); end; procedure THeader.Prepare; var I : Integer; begin For I := 0 to Length(FFields) - 1 do FFields[I].Prepare; end; destructor THeader.Destroy; var I : Integer; begin For I := Length(FFields) - 1 downto 0 do FreeAndNil(FFields[I]); FFields := nil; inherited Destroy; end; procedure THeader.AddField(const Field: AHeaderField); begin Append(ObjectArray(FFields), Field); end; procedure THeader.AddField(const Name, Body: String); begin AddField(THeaderField.Create(Name, Body)); end; function THeader.GetFieldCount: Integer; begin Result := Length(FFields); end; function THeader.GetFieldByIndex(const Idx: Integer): AHeaderField; begin Result := FFields[Idx]; end; procedure THeader.SetFieldByIndex(const Idx: Integer; const Field: AHeaderField); begin FreeAndNil(FFields[Idx]); FFields[Idx] := Field; end; procedure THeader.DeleteFieldByIndex(const Idx: Integer); begin Remove(ObjectArray(FFields), Idx, 1, True); end; { } { THeaderField } { } function THeaderField.GetName: String; begin Result := FName; end; procedure THeaderField.SetName(const Name: String); begin FName := Name; end; function THeaderField.GetBody: String; begin Result := FBody; end; procedure THeaderField.SetBody(const Body: String); begin FBody := Body; end; function THeaderField.Duplicate: AHeaderField; begin Result := THeaderField.Create(FName, FBody); end; { } { TInvalidField } { } constructor TInvalidField.Create(const RawLine: String); begin inherited Create; FRawLine := RawLine; end; function TInvalidField.Duplicate: AHeaderField; begin Result := TInvalidField.Create(FRawLine); end; function TInvalidField.GetName: String; begin Result := ''; end; function TInvalidField.GetBody: String; begin Result := ''; end; procedure TInvalidField.SetBody(const Body: String); begin end; procedure TInvalidField.SetName(const Name: String); begin end; function TInvalidField.GetAsString: String; begin Result := FRawLine; end; procedure TInvalidField.SetAsString(const Value: String); begin FRawLine := Value; end; { } { TDateField } { } constructor TDateField.CreateNow; begin inherited Create; GMTDateTime := LocalTimeToGMTTime(Now); end; constructor TDateField.Create(const LocalTime: TDateTime); begin inherited Create; GMTDateTime := LocalTimeToGMTTime(LocalTime); end; function TDateField.Duplicate: AHeaderField; begin Result := TDateField.Create; TDateField(Result).FGMTDateTime := FGMTDateTime; end; function TDateField.GetBody: String; begin Result := GMTDateTimeToRFC1123DateTime(GMTDateTime); end; procedure TDateField.SetBody(const Body: String); begin GMTDateTime := RFCDateTimeToGMTDateTime(Body); end; procedure TDateField.SetName(const Name: String); begin end; function TDateField.GetName: String; begin Result := 'Date'; end; { } { TEMailField } { } function TEMailField.GetBody: String; begin if FName <> '' then Result := '<' + Address + '> (' + FName + ')' else Result := Address; end; procedure TEMailField.SetBody(const Body: String); begin DecodeEMailField(Body, FAddress, FName); end; { } { Self-testing code } { } {$ASSERTIONS ON} procedure SelfTest; var A, B : String; begin { EncodeHeaderField } Assert(EncodeHeaderField('Xyz', 'Abcd') = 'Xyz: Abcd', 'EncodeHeaderField'); DecodeHeaderField('Xyz: Abcd', A, B); Assert((A = 'Xyz') and (B = 'Abcd'), 'DecodeHeaderField'); DecodeHeaderField(' X : A ', A, B); Assert((A = 'X') and (B = 'A'), 'DecodeHeaderField'); { DecodeEMailField } DecodeEMailField('a@b.com', A, B); Assert((A = 'a@b.com') and (B = ''), 'DecodeEmailField'); DecodeEMailField('a@b.c "D"', A, B); Assert((A = 'a@b.c') and (B = 'D'), 'DecodeEmailField'); DecodeEMailField('<a@b.c> Koos', A, B); Assert((A = 'a@b.c') and (B = 'Koos'), 'DecodeEmailField'); DecodeEMailField('Koos <a>', A, B); Assert((A = 'a') and (B = 'Koos'), 'DecodeEmailField'); end; end.
// ################################## // # TPLVisor - Michel Kunkler 2013 # // ################################## (* Magnetband *) unit TPLMagnetband; interface uses Windows, Messages, Variants, Classes, Graphics, Controls, Forms, StdCtrls, ExtCtrls, Menus, Dialogs, // Show Message SysUtils, // Format TPLZeichen; type TMagnetband = class private Form : TObject; public ErstesZeichen : TZeichenKette; // Performance LetztesZeichen : TZeichenKette; Position : TZeichenKette; Padding : integer; Laenge : integer; // Performance procedure ErweitereLinks; procedure ErweitereRechts; procedure ZeigeLinks; procedure ZeigeRechts; procedure links; procedure rechts; procedure schreibe(wert : char); function hole : char; //View function GetRechtsMax : integer; //constructor / destructor constructor Create(Form : TObject); destructor Destroy; Reintroduce; end; CMagnetband = class of TMagnetband; implementation uses TPLVisorMain; { TMagnetband } constructor TMagnetband.Create(Form : TObject); begin self.Form := TTPLVisorForm(Form); self.Position := TZeichenKette.Create; self.ErstesZeichen := self.Position; self.LetztesZeichen := self.Position; self.Padding := TTPLVisorForm(self.Form).Padding; self.Position.Zeichen.Anzeigen(self.Form, 0); self.Laenge := 1; self.Position.Zeichen.ZEdit.Color := clRed; end; destructor TMagnetband.Destroy; var Zeichen : TZeichenKette; begin Zeichen := self.ErstesZeichen; while Zeichen <> self.LetztesZeichen do begin Zeichen := TZeichenKette(Zeichen.Naechstes); TZeichenKette(Zeichen.Vorheriges).Destroy; end; Zeichen.Destroy; end; procedure TMagnetband.ErweitereLinks; var Zeichen : TZeichenKette; begin Zeichen := TZeichenKette.Create; self.ErstesZeichen.Vorheriges := TZeichenKette(Zeichen); Zeichen.Naechstes := self.ErstesZeichen; Zeichen.Zeichen.Anzeigen(self.Form, self.ErstesZeichen.Zeichen.ZShape.Left - self.ErstesZeichen.Zeichen.ZShape.Width - self.Padding); self.ErstesZeichen := Zeichen; self.Laenge := self.Laenge+1; end; procedure TMagnetband.ErweitereRechts; var Zeichen : TZeichenKette; begin Zeichen := TZeichenKette.Create; self.LetztesZeichen.Naechstes := TZeichenKette(Zeichen); Zeichen.Vorheriges := self.LetztesZeichen; Zeichen.Zeichen.Anzeigen(self.Form, self.LetztesZeichen.Zeichen.ZShape.Left + self.LetztesZeichen.Zeichen.ZShape.Width + self.Padding); self.LetztesZeichen := Zeichen; self.Laenge := self.Laenge+1; end; procedure TMagnetband.ZeigeLinks; var Zeichen : TZeichenKette; begin Zeichen := self.ErstesZeichen; while Zeichen <> nil do begin TTPLVisorForm(self.Form).VerschiebeZeichen(Zeichen.Zeichen, TTPLVisorForm(self.Form).Schritt); Zeichen := TZeichenKette(Zeichen.Naechstes); end; while self.ErstesZeichen.Zeichen.ZShape.Left > 0 do self.ErweitereLinks; end; procedure TMagnetband.ZeigeRechts; var Zeichen : TZeichenKette; begin Zeichen := self.ErstesZeichen; while Zeichen <> nil do begin TTPLVisorForm(self.Form).VerschiebeZeichen(Zeichen.Zeichen, -TTPLVisorForm(self.Form).Schritt); Zeichen := TZeichenKette(Zeichen.Naechstes); end; while self.GetRechtsMax < TTPLVisorForm(self.Form).Band.Width do self.ErweitereRechts; end; procedure TMagnetband.Links; begin self.Position.Zeichen.ZEdit.Color := clWhite; if self.Position.Vorheriges = nil then self.ErweitereLinks else self.Position := TZeichenKette(self.Position.Vorheriges); self.Position.Zeichen.ZEdit.Color := clRed; end; procedure TMagnetband.Rechts; begin self.Position.Zeichen.ZEdit.Color := clWhite; if self.Position.Naechstes = nil then self.ErweitereRechts; self.Position := TZeichenKette(self.Position.Naechstes); self.Position.Zeichen.ZEdit.Color := clRed; end; procedure TMagnetband.Schreibe(Wert : char); begin self.Position.Zeichen.ZEdit.Text := Wert; end; function TMagnetband.Hole : char; begin Result := self.Position.Zeichen.ZEdit.Text[1]; end; function TMagnetband.GetRechtsMax : integer; begin Result := self.LetztesZeichen.Zeichen.ZShape.Left + self.LetztesZeichen.Zeichen.ZShape.Width + self.Padding; end; end.
unit UIntComAtualizacaoTabPreco; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, FireDAC.Stan.Error, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, DateUtils, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.ExtCtrls, UDBCampoCodigo, MemDS, VirtualTable, StrUtils, Vcl.Menus; type TFIntComAtualizacaoTabPreco = class(TForm) btAtualizar: TBitBtn; btFechar: TBitBtn; qyItensVarPadrao: TFDQuery; qyVarItemFaltante: TFDQuery; lbcdVariavel: TLabel; edcdVariavel: TDBCampoCodigo; qyVariavelItens: TFDQuery; mLog: TMemo; lbcdItem: TLabel; edcdItem: TDBCampoCodigo; btSalvarItemEsc: TBitBtn; btExluirItemEsc: TBitBtn; grItensEscolhidos: TDBGrid; lbLog: TLabel; vtItensEscolhidos: TVirtualTable; vtItensEscolhidoscdItem: TStringField; vtItensEscolhidosdeItem: TStringField; dsItensEscolhidos: TDataSource; qyTamItemFaltante: TFDQuery; mRefsImg: TMemo; lbTabPreco: TLabel; edcdTabPreco: TDBCampoCodigo; procedure btFecharClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btAtualizarClick(Sender: TObject); procedure btSalvarItemEscClick(Sender: TObject); procedure btExluirItemEscClick(Sender: TObject); procedure FormShow(Sender: TObject); private procedure FecharConexaoIntegracao; function ListaItensEsc : String; procedure AtualizarTabPreco; procedure AtualizarTabPrecoTam; procedure AtualizarTabPrecoCor; procedure AtualizarTabPrecoImagem; public { Public declarations } end; var FIntComAtualizacaoTabPreco: TFIntComAtualizacaoTabPreco; implementation {$R *.dfm} {$R Icones.res} uses uDmIntegracao, uDmERP, UTelaInicial, uFuncoes; procedure TFIntComAtualizacaoTabPreco.btFecharClick(Sender: TObject); var Tab : TTabSheet; begin FecharConexaoIntegracao; Tab := FTelaInicial.pcTelas.ActivePage; if Assigned(Tab) then begin Tab.Parent := nil; Tab.PageControl := nil; FreeAndNil(Tab); end; FTelaInicial.pcTelas.Visible := FTelaInicial.pcTelas.PageCount > 0; FTelaInicial.imLogoERP.Visible := not FTelaInicial.pcTelas.Visible; end; procedure TFIntComAtualizacaoTabPreco.btSalvarItemEscClick(Sender: TObject); begin if edcdItem.ERPValorValido then begin vtItensEscolhidos.Append; vtItensEscolhidos.FieldByName('cdItem').AsString := edcdItem.ERPEdCampoChaveText; vtItensEscolhidos.FieldByName('deItem').AsString := edcdItem.ERPLbDescricaoCaption; vtItensEscolhidos.Post; edcdItem.ERPEdCampoChaveText := ''; edcdItem.ERPEdCampoChaveSetFocus; end; end; procedure TFIntComAtualizacaoTabPreco.btAtualizarClick(Sender: TObject); begin if not edcdVariavel.ERPValorValido then Aviso('Escolha uma variável antes de atualizar os preços.') else if Pergunta('Confirma a atualização dos preços para a variável escolhida?') then begin if StrToIntDef(edcdVariavel.ERPEdCampoChaveText, 0) = 5 then AtualizarTabPrecoTam else if StrToIntDef(edcdVariavel.ERPEdCampoChaveText, 0) = 10 then AtualizarTabPrecoCor else if StrToIntDef(edcdVariavel.ERPEdCampoChaveText, 0) = 30 then AtualizarTabPrecoImagem else AtualizarTabPreco; end; end; procedure TFIntComAtualizacaoTabPreco.btExluirItemEscClick(Sender: TObject); begin if not vtItensEscolhidos.IsEmpty then vtItensEscolhidos.Delete; end; procedure TFIntComAtualizacaoTabPreco.FecharConexaoIntegracao; begin if qyVarItemFaltante.Active then qyVarItemFaltante.Close; if qyTamItemFaltante.Active then qyTamItemFaltante.Close; DmIntegracao.fdConnInteg.Connected := False; end; procedure TFIntComAtualizacaoTabPreco.FormCreate(Sender: TObject); begin btAtualizar.Glyph.LoadFromResourceName(HInstance, 'IMGBTSALVAR_32X32'); btFechar.Glyph.LoadFromResourceName(HInstance, 'IMGBTFECHAR_32X32'); btSalvarItemEsc.Glyph.LoadFromResourceName(HInstance, 'IMGBTSALVAR_16X16'); btExluirItemEsc.Glyph.LoadFromResourceName(HInstance, 'IMGBTEXCLUIR_16X16'); vtItensEscolhidos.Open; end; procedure TFIntComAtualizacaoTabPreco.FormShow(Sender: TObject); begin edcdVariavel.ERPEdCampoChaveSetFocus; end; function TFIntComAtualizacaoTabPreco.ListaItensEsc : String; begin Result := ''; if not vtItensEscolhidos.IsEmpty then begin vtItensEscolhidos.DisableControls; try vtItensEscolhidos.First; while not vtItensEscolhidos.Eof do begin if Trim(Result) = '' then Result := QuotedStr(vtItensEscolhidos.FieldByName('cdItem').AsString) else Result := Result + ', ' + QuotedStr(vtItensEscolhidos.FieldByName('cdItem').AsString); vtItensEscolhidos.Next; end; finally vtItensEscolhidos.EnableControls; end; end; end; procedure TFIntComAtualizacaoTabPreco.AtualizarTabPreco; var sCondTabPreco, sAux, sUsuPC, sSql, snmFieldPrecoVar, snmVarSeqPadrao : String; stDados : TStringList; begin sCondTabPreco := ''; if (Trim(edcdTabPreco.ERPEdCampoChaveText) <> '') and (edcdTabPreco.ERPValorValido) then sCondTabPreco := ' AND codigo_tab = ' + QuotedStr(edcdTabPreco.ERPEdCampoChaveText); stDados := TStringList.Create; snmVarSeqPadrao := ''; snmFieldPrecoVar := ''; case StrToIntDef(edcdVariavel.ERPEdCampoChaveText, 0) of 15: begin snmVarSeqPadrao := 'cdTipoAlcaSeq'; snmFieldPrecoVar := 'vlPrecoPadAlca'; end; 19: begin snmVarSeqPadrao := 'cdAdornoSeq'; snmFieldPrecoVar := 'vlPrecoPadAdorno'; end; 20: begin snmVarSeqPadrao := 'cdChavetaSeq'; snmFieldPrecoVar := 'vlPrecoPadChaveta'; end; 25: begin snmVarSeqPadrao := 'cdForracaoSeq'; snmFieldPrecoVar := 'vlPrecoPadForracao'; end; end; DmIntegracao.fdConnInteg.Connected := True; if qyItensVarPadrao.Active then qyItensVarPadrao.Close; qyItensVarPadrao.MacroByName('filtro').Clear; sAux := ListaItensEsc; if Trim(sAux) <> '' then qyItensVarPadrao.MacroByName('filtro').Value := ' WHERE a.cdItem IN(' + sAux + ')'; qyItensVarPadrao.Open(); try qyItensVarPadrao.DisableControls; qyVariavelItens.DisableControls; qyItensVarPadrao.First; while not qyItensVarPadrao.Eof do begin if (qyItensVarPadrao.FieldByName(snmVarSeqPadrao).AsInteger > 0) then begin ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'UPDATE vlVarItb vv ' + ' SET preco_agregar = 0 ' + ' WHERE vv.codigo_variavel = ' + edcdVariavel.ERPEdCampoChaveText + ' AND vv.item IN(' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') + ')' + ' AND vv.valorVar = ' + qyItensVarPadrao.FieldByName(snmVarSeqPadrao).AsString + sCondTabPreco ); if qyVariavelItens.Active then qyVariavelItens.Close; qyVariavelItens.ParamByName('cdVariavel').AsInteger := StrToIntDef(edcdVariavel.ERPEdCampoChaveText, 0); qyVariavelItens.ParamByName('cdVariavelItem').AsInteger := qyItensVarPadrao.FieldByName(snmVarSeqPadrao).AsInteger; qyVariavelItens.Open(); qyVariavelItens.First; while not qyVariavelItens.Eof do begin if //(qyItensVarPadrao.FieldByName(snmFieldPrecoVar).AsFloat > 0) and (qyVariavelItens.FieldByName('vlPrecoPadrao').AsFloat > qyItensVarPadrao.FieldByName(snmFieldPrecoVar).AsFloat) then begin if qyVarItemFaltante.Active then qyVarItemFaltante.Close; qyVarItemFaltante.ParamByName('vlPreco').AsFloat := qyVariavelItens.FieldByName('vlPrecoPadrao').AsFloat; qyVarItemFaltante.ParamByName('cdVariavel').AsInteger := StrToIntDef(edcdVariavel.ERPEdCampoChaveText, 0); qyVarItemFaltante.ParamByName('cdVariavelItem').AsInteger := qyVariavelItens.FieldByName('cdVariavelItem').AsInteger; qyVarItemFaltante.MacroByName('itens').Clear; qyVarItemFaltante.MacroByName('itens').Value := QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12'); qyVarItemFaltante.MacroByName('codTab').Clear; if Trim(sCondTabPreco) <> '' then qyVarItemFaltante.MacroByName('codTab').Value := sCondTabPreco; qyVarItemFaltante.Open(); if (not qyVarItemFaltante.IsEmpty) then begin sSql := qyVarItemFaltante.SQL.Text; sSql := AnsiReplaceStr(sSql, ':vlPreco', AnsiReplaceStr(qyVariavelItens.FieldByName('vlPrecoPadrao').AsString, ',', '.')); sSql := AnsiReplaceStr(sSql, ':cdVariavelItem', qyVariavelItens.FieldByName('cdVariavelItem').AsString); sSql := AnsiReplaceStr(sSql, ':cdVariavel', qyVariavelItens.FieldByName('cdVariavel').AsString); sSql := AnsiReplaceStr(sSql, '&itens', QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') ); sSql := AnsiReplaceStr(sSql, '&codTab', sCondTabPreco); sSql := 'INSERT INTO vlVarItb (recnum, codigo_tab, item, codigo_variavel, valorvar, preco_agregar) ' + sSql; ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, sSql); ExecuteSimplesSql(DmIntegracao.fdConnInteg, 'SELECT MAX(recnum) AS ultRec FROM vlVarItb', 'ultRec', stDados ); ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'ALTER TABLE vlVarItb ALTER COLUMN recNum RESTART WITH ' + IntToStr(StrToIntDef(stDados.Strings[0], 0) + 1)); end else ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'UPDATE vlVarItb vv ' + ' SET preco_agregar = ' + AnsiReplaceStr(qyVariavelItens.FieldByName('vlPrecoPadrao').AsString, ',', '.') + ' WHERE vv.codigo_variavel = ' + qyVariavelItens.FieldByName('cdVariavel').AsString + ' AND vv.item IN(' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') + ')' + ' AND vv.valorVar = ' + qyVariavelItens.FieldByName('cdVariavelItem').AsString + sCondTabPreco ); end else ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'UPDATE vlVarItb vv ' + ' SET preco_agregar = 0 ' + ' WHERE vv.codigo_variavel = ' + qyVariavelItens.FieldByName('cdVariavel').AsString + ' AND vv.item IN(' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') + ')' + ' AND vv.valorVar = ' + qyVariavelItens.FieldByName('cdVariavelItem').AsString + sCondTabPreco ); qyVariavelItens.Next; end; end else mLog.Lines.Add('Opção padrão da variável ' + edcdVariavel.ERPLbDescricaoCaption + ' não definida para o item ' + Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) ); qyItensVarPadrao.Next; end; finally qyItensVarPadrao.EnableControls; qyVariavelItens.EnableControls; end; sUsuPC := QuotedStr(RetornaNomeComputador); sUsuPC := sUsuPC + ',' + QuotedStr(RetornaIpComputador); ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'DELETE FROM vlVarItb_log b ' + ' WHERE EXISTS (SELECT a.operlog_id ' + ' FROM operlog a ' + ' WHERE a.operlog_id = b.operlog_id ' + ' AND a.usuario_windows IN(' + sUsuPC + ')' + ' )' ); ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'DELETE FROM operlog ' + ' WHERE usuario_windows IN(' + sUsuPC + ') ' + ' AND UPPER(tabela) = ''VLVARITB'' ' ); if Assigned(stDados) then FreeAndNil(stDados); FecharConexaoIntegracao; Aviso('Atualização dos preços das opções de ' + edcdVariavel.ERPLbDescricaoCaption + ' finalizado com sucesso.'); end; procedure TFIntComAtualizacaoTabPreco.AtualizarTabPrecoTam; var sCondTabPreco, sAux, sUsuPC, sSql : String; stDados : TStringList; begin sCondTabPreco := ''; if (Trim(edcdTabPreco.ERPEdCampoChaveText) <> '') and (edcdTabPreco.ERPValorValido) then sCondTabPreco := ' AND codigo_tab = ' + QuotedStr(edcdTabPreco.ERPEdCampoChaveText); stDados := TStringList.Create; DmIntegracao.fdConnInteg.Connected := True; if qyItensVarPadrao.Active then qyItensVarPadrao.Close; qyItensVarPadrao.MacroByName('filtro').Clear; sAux := ListaItensEsc; if Trim(sAux) <> '' then qyItensVarPadrao.MacroByName('filtro').Value := ' WHERE a.cdItem IN(' + sAux + ')'; qyItensVarPadrao.Open(); try qyItensVarPadrao.DisableControls; qyTamItemFaltante.DisableControls; qyItensVarPadrao.First; while not qyItensVarPadrao.Eof do begin if qyTamItemFaltante.Active then qyTamItemFaltante.Close; qyTamItemFaltante.MacroByName('filtro').Clear; sAux := ' AND it.item IN(' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') + ')'; if Trim(sCondTabPreco) <> '' then sAux := sAux + sCondTabPreco; qyTamItemFaltante.MacroByName('filtro').Value := sAux; qyTamItemFaltante.Open(); if (not qyTamItemFaltante.IsEmpty) then begin sSql := qyTamItemFaltante.SQL.Text; sSql := AnsiReplaceStr(sSql, '&filtro', ' AND it.item IN(' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') + ')' + sCondTabPreco ); sSql := 'INSERT INTO vlVarItb (recnum, codigo_tab, item, codigo_variavel, valorvar, preco_agregar) ' + sSql; ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, sSql); ExecuteSimplesSql(DmIntegracao.fdConnInteg, 'SELECT MAX(recnum) AS ultRec FROM vlVarItb', 'ultRec', stDados ); ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'ALTER TABLE vlVarItb ALTER COLUMN recNum RESTART WITH ' + IntToStr(StrToIntDef(stDados.Strings[0], 0) + 1)); end else ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'UPDATE vlVarItb a ' + ' SET preco_agregar = ( ' + ' COALESCE( ' + ' ( ' + ' SELECT b.vl ' + ' FROM itemTab b ' + ' WHERE b.codigo_tab = a.codigo_tab ' + ' AND b.item = a.item ' + ' ), ' + ' 0 ' + ' ) * ' + ' CAST( ' + ' CASE ' + ' WHEN CAST(a.valorVar AS INTEGER) IN(51, 52) THEN ' + // 1,90 Gordo, Semi Gordo ' 30 / 100.0000 ' + ' WHEN CAST(a.valorVar AS INTEGER) IN(53, 70) THEN ' + // 1,90 Super Gordo | 1,90 CREMACAO ' 50 / 100.0000 ' + ' WHEN CAST(a.valorVar AS INTEGER) = 54 THEN ' + // 1,90 Extra Gordo ' 90 / 100.0000 ' + ' WHEN CAST(a.valorVar AS INTEGER) IN (55, 60, 65) THEN ' + // 2,00 | 2,10 | 2,20 ' 15 / 100.0000 ' + ' WHEN CAST(a.valorVar AS INTEGER) IN (56, 57, 61, 62, 66, 67) THEN ' + // 2,00 Gordo, Semi Gordo ' 45 / 100.0000 ' + ' WHEN CAST(a.valorVar AS INTEGER) IN (58, 63, 68) THEN ' + // 2,00 Super Gordo ' 65 / 100.0000 ' + ' WHEN CAST(a.valorVar AS INTEGER) IN (59, 64, 69) THEN ' + // 2,00 Extra Gordo ' 105 / 100.0000 ' + ' WHEN CAST(a.valorVar AS INTEGER) IN(71, 72) THEN ' + // 1,90 Gordo Cremação, Semi Gordo Cremação ' 80 / 100.0000 ' + ' WHEN CAST(a.valorVar AS INTEGER) = 73 THEN ' + // 1,90 Super Gordo Cremação ' 1 ' + ' WHEN CAST(a.valorVar AS INTEGER) = 74 THEN ' + // 1,90 Extra Gordo Cremação ' 140 / 100.0000 ' + ' ELSE ' + ' 0.0000 ' + ' END AS NUMERIC(15, 4) ' + ' ) ' + ' ) ' + ' WHERE a.codigo_variavel = 5 ' + ' AND COALESCE( ' + ' ( ' + ' SELECT b.vl ' + ' FROM itemTab b ' + ' WHERE b.codigo_tab = a.codigo_tab ' + ' AND b.item = a.item ' + ' ), ' + ' 0 ' + ' ) > 0 ' + ' AND a.item IN(' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') + ')' + sCondTabPreco ); qyItensVarPadrao.Next; end; finally qyItensVarPadrao.EnableControls; qyTamItemFaltante.EnableControls; end; sUsuPC := QuotedStr(RetornaNomeComputador); sUsuPC := sUsuPC + ',' + QuotedStr(RetornaIpComputador); ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'DELETE FROM vlVarItb_log b ' + ' WHERE EXISTS (SELECT a.operlog_id ' + ' FROM operlog a ' + ' WHERE a.operlog_id = b.operlog_id ' + ' AND a.usuario_windows IN(' + sUsuPC + ')' + ' )' ); ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'DELETE FROM operlog ' + ' WHERE usuario_windows IN(' + sUsuPC + ') ' + ' AND UPPER(tabela) = ''VLVARITB'' ' ); if Assigned(stDados) then FreeAndNil(stDados); FecharConexaoIntegracao; Aviso('Atualização dos preços das opções de ' + edcdVariavel.ERPLbDescricaoCaption + ' finalizado com sucesso.'); end; procedure TFIntComAtualizacaoTabPreco.AtualizarTabPrecoCor; var sCondTabPreco, sAux, sUsuPC, sSql : String; stDados : TStringList; begin sCondTabPreco := ''; if (Trim(edcdTabPreco.ERPEdCampoChaveText) <> '') and (edcdTabPreco.ERPValorValido) then sCondTabPreco := ' AND codigo_tab = ' + QuotedStr(edcdTabPreco.ERPEdCampoChaveText); stDados := TStringList.Create; DmIntegracao.fdConnInteg.Connected := True; if qyItensVarPadrao.Active then qyItensVarPadrao.Close; qyItensVarPadrao.MacroByName('filtro').Clear; sAux := ListaItensEsc; if Trim(sAux) <> '' then qyItensVarPadrao.MacroByName('filtro').Value := ' WHERE a.cdItem IN(' + sAux + ')'; qyItensVarPadrao.Open(); try qyItensVarPadrao.DisableControls; qyTamItemFaltante.DisableControls; qyItensVarPadrao.First; while not qyItensVarPadrao.Eof do begin { ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'UPDATE vlVarItb vv ' + ' SET preco_agregar = 0 ' + ' WHERE vv.codigo_variavel = ' + edcdVariavel.ERPEdCampoChaveText + ' AND vv.item IN(' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') + ')' + ' AND vv.valorVar = ' + qyItensVarPadrao.FieldByName(snmVarSeqPadrao).AsString + sCondTabPreco ); } if qyVariavelItens.Active then qyVariavelItens.Close; qyVariavelItens.ParamByName('cdVariavel').AsInteger := StrToIntDef(edcdVariavel.ERPEdCampoChaveText, 0); qyVariavelItens.ParamByName('cdVariavelItem').AsInteger := 0; qyVariavelItens.Open(); qyVariavelItens.First; while not qyVariavelItens.Eof do begin if (qyItensVarPadrao.FieldByName('flCobrarCor').AsString = 'S') and (qyVariavelItens.FieldByName('vlPrecoPadrao').AsFloat > 0) then begin if qyVarItemFaltante.Active then qyVarItemFaltante.Close; qyVarItemFaltante.ParamByName('vlPreco').AsFloat := qyVariavelItens.FieldByName('vlPrecoPadrao').AsFloat; qyVarItemFaltante.ParamByName('cdVariavel').AsInteger := StrToIntDef(edcdVariavel.ERPEdCampoChaveText, 0); qyVarItemFaltante.ParamByName('cdVariavelItem').AsInteger := qyVariavelItens.FieldByName('cdVariavelItem').AsInteger; qyVarItemFaltante.MacroByName('itens').Clear; qyVarItemFaltante.MacroByName('itens').Value := QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12'); qyVarItemFaltante.MacroByName('codTab').Clear; if Trim(sCondTabPreco) <> '' then qyVarItemFaltante.MacroByName('codTab').Value := sCondTabPreco; qyVarItemFaltante.Open(); if (not qyVarItemFaltante.IsEmpty) then begin sSql := qyVarItemFaltante.SQL.Text; sSql := AnsiReplaceStr(sSql, ':vlPreco', AnsiReplaceStr(qyVariavelItens.FieldByName('vlPrecoPadrao').AsString, ',', '.')); sSql := AnsiReplaceStr(sSql, ':cdVariavelItem', qyVariavelItens.FieldByName('cdVariavelItem').AsString); sSql := AnsiReplaceStr(sSql, ':cdVariavel', qyVariavelItens.FieldByName('cdVariavel').AsString); sSql := AnsiReplaceStr(sSql, '&itens', QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') ); sSql := AnsiReplaceStr(sSql, '&codTab', sCondTabPreco); sSql := 'INSERT INTO vlVarItb (recnum, codigo_tab, item, codigo_variavel, valorvar, preco_agregar) ' + sSql; ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, sSql); ExecuteSimplesSql(DmIntegracao.fdConnInteg, 'SELECT MAX(recnum) AS ultRec FROM vlVarItb', 'ultRec', stDados ); ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'ALTER TABLE vlVarItb ALTER COLUMN recNum RESTART WITH ' + IntToStr(StrToIntDef(stDados.Strings[0], 0) + 1)); end else ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'UPDATE vlVarItb vv ' + ' SET preco_agregar = ' + AnsiReplaceStr(qyVariavelItens.FieldByName('vlPrecoPadrao').AsString, ',', '.') + ' WHERE vv.codigo_variavel = ' + qyVariavelItens.FieldByName('cdVariavel').AsString + ' AND vv.item IN(' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') + ')' + ' AND vv.valorVar = ' + qyVariavelItens.FieldByName('cdVariavelItem').AsString + sCondTabPreco ); end else ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'UPDATE vlVarItb vv ' + ' SET preco_agregar = 0 ' + ' WHERE vv.codigo_variavel = ' + qyVariavelItens.FieldByName('cdVariavel').AsString + ' AND vv.item IN(' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') + ')' + ' AND vv.valorVar = ' + qyVariavelItens.FieldByName('cdVariavelItem').AsString + sCondTabPreco ); qyVariavelItens.Next; end; qyItensVarPadrao.Next; end; finally qyItensVarPadrao.EnableControls; qyTamItemFaltante.EnableControls; end; sUsuPC := QuotedStr(RetornaNomeComputador); sUsuPC := sUsuPC + ',' + QuotedStr(RetornaIpComputador); ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'DELETE FROM vlVarItb_log b ' + ' WHERE EXISTS (SELECT a.operlog_id ' + ' FROM operlog a ' + ' WHERE a.operlog_id = b.operlog_id ' + ' AND a.usuario_windows IN(' + sUsuPC + ')' + ' )' ); ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'DELETE FROM operlog ' + ' WHERE usuario_windows IN(' + sUsuPC + ') ' + ' AND UPPER(tabela) = ''VLVARITB'' ' ); if Assigned(stDados) then FreeAndNil(stDados); FecharConexaoIntegracao; Aviso('Atualização dos preços das opções de ' + edcdVariavel.ERPLbDescricaoCaption + ' finalizado com sucesso.'); end; procedure TFIntComAtualizacaoTabPreco.AtualizarTabPrecoImagem; var i : Integer; sCondTabPreco, sAux, sUsuPC, sSql : String; stDados : TStringList; begin sCondTabPreco := ''; if (Trim(edcdTabPreco.ERPEdCampoChaveText) <> '') and (edcdTabPreco.ERPValorValido) then sCondTabPreco := ' AND codigo_tab = ' + QuotedStr(edcdTabPreco.ERPEdCampoChaveText); stDados := TStringList.Create; DmIntegracao.fdConnInteg.Connected := True; if qyItensVarPadrao.Active then qyItensVarPadrao.Close; qyItensVarPadrao.MacroByName('filtro').Clear; sAux := ListaItensEsc; if mRefsImg.Lines.Count > 0 then begin i := 0; while i < mRefsImg.Lines.Count do begin if sAux = '' then sAux := QuotedStr(mRefsImg.Lines.Strings[i]) else sAux := sAux + ',' + QuotedStr(mRefsImg.Lines.Strings[i]); Inc(i); end; end; if Trim(sAux) <> '' then qyItensVarPadrao.MacroByName('filtro').Value := ' WHERE a.cdItem IN(' + sAux + ')'; qyItensVarPadrao.Open(); try qyItensVarPadrao.DisableControls; qyTamItemFaltante.DisableControls; qyItensVarPadrao.First; while not qyItensVarPadrao.Eof do begin { ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'UPDATE vlVarItb vv ' + ' SET preco_agregar = 0 ' + ' WHERE vv.codigo_variavel = ' + edcdVariavel.ERPEdCampoChaveText + ' AND vv.item IN(' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') + ')' + ' AND vv.valorVar = ' + qyItensVarPadrao.FieldByName(snmVarSeqPadrao).AsString + sCondTabPreco ); } if qyVariavelItens.Active then qyVariavelItens.Close; qyVariavelItens.ParamByName('cdVariavel').AsInteger := StrToIntDef(edcdVariavel.ERPEdCampoChaveText, 0); qyVariavelItens.ParamByName('cdVariavelItem').AsInteger := 0; qyVariavelItens.Open(); qyVariavelItens.First; while not qyVariavelItens.Eof do begin if (qyVariavelItens.FieldByName('vlPrecoPadrao').AsFloat > 0) then begin if qyVarItemFaltante.Active then qyVarItemFaltante.Close; qyVarItemFaltante.ParamByName('vlPreco').AsFloat := qyVariavelItens.FieldByName('vlPrecoPadrao').AsFloat; qyVarItemFaltante.ParamByName('cdVariavel').AsInteger := StrToIntDef(edcdVariavel.ERPEdCampoChaveText, 0); qyVarItemFaltante.ParamByName('cdVariavelItem').AsInteger := qyVariavelItens.FieldByName('cdVariavelItem').AsInteger; qyVarItemFaltante.MacroByName('itens').Clear; qyVarItemFaltante.MacroByName('itens').Value := QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12'); qyVarItemFaltante.MacroByName('codTab').Clear; if Trim(sCondTabPreco) <> '' then qyVarItemFaltante.MacroByName('codTab').Value := sCondTabPreco; qyVarItemFaltante.Open(); if (not qyVarItemFaltante.IsEmpty) then begin sSql := qyVarItemFaltante.SQL.Text; sSql := AnsiReplaceStr(sSql, ':vlPreco', AnsiReplaceStr(qyVariavelItens.FieldByName('vlPrecoPadrao').AsString, ',', '.')); sSql := AnsiReplaceStr(sSql, ':cdVariavelItem', qyVariavelItens.FieldByName('cdVariavelItem').AsString); sSql := AnsiReplaceStr(sSql, ':cdVariavel', qyVariavelItens.FieldByName('cdVariavel').AsString); sSql := AnsiReplaceStr(sSql, '&itens', QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') ); sSql := AnsiReplaceStr(sSql, '&codTab', sCondTabPreco); sSql := 'INSERT INTO vlVarItb (recnum, codigo_tab, item, codigo_variavel, valorvar, preco_agregar) ' + sSql; ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, sSql); ExecuteSimplesSql(DmIntegracao.fdConnInteg, 'SELECT MAX(recnum) AS ultRec FROM vlVarItb', 'ultRec', stDados ); ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'ALTER TABLE vlVarItb ALTER COLUMN recNum RESTART WITH ' + IntToStr(StrToIntDef(stDados.Strings[0], 0) + 1)); end else ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'UPDATE vlVarItb vv ' + ' SET preco_agregar = ' + AnsiReplaceStr(qyVariavelItens.FieldByName('vlPrecoPadrao').AsString, ',', '.') + ' WHERE vv.codigo_variavel = ' + qyVariavelItens.FieldByName('cdVariavel').AsString + ' AND vv.item IN(' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') + ')' + ' AND vv.valorVar = ' + qyVariavelItens.FieldByName('cdVariavelItem').AsString + sCondTabPreco ); end else ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'UPDATE vlVarItb vv ' + ' SET preco_agregar = 0 ' + ' WHERE vv.codigo_variavel = ' + qyVariavelItens.FieldByName('cdVariavel').AsString + ' AND vv.item IN(' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString)) + ',' + QuotedStr(Trim(qyItensVarPadrao.FieldByName('cdItem').AsString) + '.12') + ')' + ' AND vv.valorVar = ' + qyVariavelItens.FieldByName('cdVariavelItem').AsString + sCondTabPreco ); qyVariavelItens.Next; end; qyItensVarPadrao.Next; end; finally qyItensVarPadrao.EnableControls; qyTamItemFaltante.EnableControls; end; sUsuPC := QuotedStr(RetornaNomeComputador); sUsuPC := sUsuPC + ',' + QuotedStr(RetornaIpComputador); ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'DELETE FROM vlVarItb_log b ' + ' WHERE EXISTS (SELECT a.operlog_id ' + ' FROM operlog a ' + ' WHERE a.operlog_id = b.operlog_id ' + ' AND a.usuario_windows IN(' + sUsuPC + ')' + ' )' ); ExecuteInstrucaoSql(DmIntegracao.fdConnInteg, 'DELETE FROM operlog ' + ' WHERE usuario_windows IN(' + sUsuPC + ') ' + ' AND UPPER(tabela) = ''VLVARITB'' ' ); if Assigned(stDados) then FreeAndNil(stDados); FecharConexaoIntegracao; Aviso('Atualização dos preços das opções de ' + edcdVariavel.ERPLbDescricaoCaption + ' finalizado com sucesso.'); end; initialization RegisterClass(TFIntComAtualizacaoTabPreco); finalization UnRegisterClass(TFIntComAtualizacaoTabPreco); end.
{*******************************************************} { } { Delphi Visual Component Library } { TStrings property editor dialog } { } { Copyright (c) 1999 Borland International } { } {*******************************************************} unit StrEdit; interface uses Windows, Classes, Graphics, Forms, Controls, Buttons, Dialogs, DesignEditors, DesignIntf, StdCtrls, ExtCtrls, ComCtrls, Menus, ActnPopup; type TStrEditDlg = class(TForm) OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; StringEditorMenu: TPopupActionBar; LoadItem: TMenuItem; SaveItem: TMenuItem; CodeEditorItem: TMenuItem; CodeWndBtn: TButton; OKButton: TButton; CancelButton: TButton; HelpButton: TButton; procedure FileOpen(Sender: TObject); procedure FileSave(Sender: TObject); procedure HelpButtonClick(Sender: TObject); procedure CodeWndBtnClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); private protected FModified: Boolean; function GetLines: TStrings; virtual; abstract; procedure SetLines(const Value: TStrings); virtual; abstract; function GetLinesControl: TWinControl; virtual; abstract; public property Lines: TStrings read GetLines write SetLines; end; {$IFDEF NEWNEWDESIGNER} type TStringListProperty = class(TClassProperty) protected function EditDialog: TStrEditDlg; virtual; function GetStrings: TStrings; virtual; procedure SetStrings(const Value: TStrings); virtual; public function GetAttributes: TPropertyAttributes; override; procedure Edit; override; end; TValueListProperty = class(TStringListProperty) protected function EditDialog: TStrEditDlg; override; end; {$ENDIF} implementation {$R *.dfm} uses ActiveX, SysUtils, DesignConst, ToolsAPI, IStreams, StFilSys, TypInfo {$IFDEF NEWNEWDESIGNER} , StringsEdit, ValueEdit {$ENDIF} ; type TStringsModuleCreator = class(TInterfacedObject, IOTACreator, IOTAModuleCreator) private FFileName: string; FStream: TStringStream; FAge: TDateTime; public constructor Create(const FileName: string; Stream: TStringStream; Age: TDateTime); destructor Destroy; override; { IOTACreator } function GetCreatorType: string; function GetExisting: Boolean; function GetFileSystem: string; function GetOwner: IOTAModule; function GetUnnamed: Boolean; { IOTAModuleCreator } function GetAncestorName: string; function GetImplFileName: string; function GetIntfFileName: string; function GetFormName: string; function GetMainForm: Boolean; function GetShowForm: Boolean; function GetShowSource: Boolean; function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; procedure FormCreated(const FormEditor: IOTAFormEditor); end; TOTAFile = class(TInterfacedObject, IOTAFile) private FSource: string; FAge: TDateTime; public constructor Create(const ASource: string; AAge: TDateTime); { IOTAFile } function GetSource: string; function GetAge: TDateTime; end; { TOTAFile } constructor TOTAFile.Create(const ASource: string; AAge: TDateTime); begin inherited Create; FSource := ASource; FAge := AAge; end; function TOTAFile.GetAge: TDateTime; begin Result := FAge; end; function TOTAFile.GetSource: string; begin Result := FSource; end; { TStringsModuleCreator } constructor TStringsModuleCreator.Create(const FileName: string; Stream: TStringStream; Age: TDateTime); begin inherited Create; FFileName := FileName; FStream := Stream; FAge := Age; end; destructor TStringsModuleCreator.Destroy; begin FStream.Free; inherited; end; procedure TStringsModuleCreator.FormCreated(const FormEditor: IOTAFormEditor); begin { Nothing to do } end; function TStringsModuleCreator.GetAncestorName: string; begin Result := ''; end; function TStringsModuleCreator.GetCreatorType: string; begin Result := sText; end; function TStringsModuleCreator.GetExisting: Boolean; begin Result := True; end; function TStringsModuleCreator.GetFileSystem: string; begin Result := sTStringsFileSystem; end; function TStringsModuleCreator.GetFormName: string; begin Result := ''; end; function TStringsModuleCreator.GetImplFileName: string; begin Result := FFileName; end; function TStringsModuleCreator.GetIntfFileName: string; begin Result := ''; end; function TStringsModuleCreator.GetMainForm: Boolean; begin Result := False; end; function TStringsModuleCreator.GetOwner: IOTAModule; begin Result := nil; end; function TStringsModuleCreator.GetShowForm: Boolean; begin Result := False; end; function TStringsModuleCreator.GetShowSource: Boolean; begin Result := True; end; function TStringsModuleCreator.GetUnnamed: Boolean; begin Result := False; end; function TStringsModuleCreator.NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; begin Result := nil; end; function TStringsModuleCreator.NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin Result := TOTAFile.Create(FStream.DataString, FAge); end; function TStringsModuleCreator.NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin Result := nil; end; { TStrEditDlg } procedure TStrEditDlg.FileOpen(Sender: TObject); begin with OpenDialog do if Execute then Lines.LoadFromFile(FileName); end; procedure TStrEditDlg.FileSave(Sender: TObject); begin SaveDialog.FileName := OpenDialog.FileName; with SaveDialog do if Execute then Lines.SaveToFile(FileName); end; {$IFDEF NEWNEWDESIGNER} { TStringListProperty } function TStringListProperty.EditDialog: TStrEditDlg; begin Result := TStringsEditDlg.Create(Application); end; function TStringListProperty.GetAttributes: TPropertyAttributes; begin Result := inherited GetAttributes + [paDialog] - [paSubProperties]; end; function TStringListProperty.GetStrings: TStrings; begin Result := TStrings(GetOrdValue); end; procedure TStringListProperty.SetStrings(const Value: TStrings); begin SetOrdValue(Longint(Value)); end; procedure TStringListProperty.Edit; var Ident: string; Component: TComponent; Module: IOTAModule; Editor: IOTAEditor; ModuleServices: IOTAModuleServices; Stream: TStringStream; Age: TDateTime; begin Component := TComponent(GetComponent(0)); ModuleServices := BorlandIDEServices as IOTAModuleServices; if (TObject(Component) is TComponent) and (Component.Owner = Self.Designer.GetRoot) and (Self.Designer.GetRoot.Name <> '') then begin Ident := Self.Designer.GetRoot.Name + DotSep + Component.Name + DotSep + GetName; Module := ModuleServices.FindModule(Ident); end else Module := nil; if (Module <> nil) and (Module.GetModuleFileCount > 0) then Module.GetModuleFileEditor(0).Show else with EditDialog do try Lines := GetStrings; // UpdateStatus(nil); FModified := False; ActiveControl := GetLinesControl; CodeEditorItem.Enabled := Ident <> ''; CodeWndBtn.Enabled := Ident <> ''; case ShowModal of mrOk: SetStrings(Lines); mrYes: begin // this used to be done in LibMain's TLibrary.Create but now its done here // the unregister is done over in ComponentDesigner's finalization StFilSys.Register; Stream := TStringStream.Create(''); Lines.SaveToStream(Stream); Stream.Position := 0; Age := Now; Module := ModuleServices.CreateModule( TStringsModuleCreator.Create(Ident, Stream, Age)); if Module <> nil then begin with StringsFileSystem.GetTStringsProperty(Ident, Component, GetName) do DiskAge := DateTimeToFileDate(Age); Editor := Module.GetModuleFileEditor(0); if FModified then Editor.MarkModified; Editor.Show; end; end; end; finally Free; end; end; {$ENDIF} procedure TStrEditDlg.HelpButtonClick(Sender: TObject); begin Application.HelpContext(HelpContext); end; procedure TStrEditDlg.CodeWndBtnClick(Sender: TObject); begin ModalResult := mrYes; end; {$IFDEF NEWNEWDESIGNER} { TValueListProperty } function TValueListProperty.EditDialog: TStrEditDlg; begin Result := TValueEditDlg.Create(Application); end; {$ENDIF} var StoredWidth, StoredHeight, StoredLeft, StoredTop: Integer; procedure TStrEditDlg.FormDestroy(Sender: TObject); begin StoredWidth := Width; StoredHeight := Height; StoredLeft := Left; StoredTop := Top; end; procedure TStrEditDlg.FormShow(Sender: TObject); begin if StoredWidth <> 0 then Width := StoredWidth; if StoredHeight <> 0 then Height := StoredHeight; if StoredLeft <> 0 then Left := StoredLeft else Left := (Screen.Width - Width) div 2; if StoredTop <> 0 then Top := StoredTop else Top := (Screen.Height - Height) div 2; end; end.
{ girerrors.pas Copyright (C) 2011 Andrew Haines andrewd207@aol.com 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. } unit girErrors; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TGirError = (geError, geWarn, geInfo, geDebug, geFatal, geFuzzy); TgirErrorFunc = procedure(UserData: Pointer; AType: TgirError; AMsg: String); const geUnhandledNode = 'Unhandled node [%s] "%s"'; geUnexpectedNodeType = 'Unexpected node [%s] type: found "%s" expected "%s"'; geMissingNode = '[%s] Could not find child node "%s" while looking in node "%s"'; geAddingErrorNode = '%s %s throws an error but is not included as a param. Adding...'; var girErrorName: array[TGirError] of String =( 'Error', 'Warning', 'Info', 'Debug', 'Fatal', 'Fuzzy' ); procedure girError(AType: TgirError; AMsg: String); //returns old handler function girSetErrorHandler(AHandler: TgirErrorFunc; AUserData: Pointer): TgirErrorFunc; implementation var UserData: Pointer; InternalHandler: TgirErrorFunc; procedure girError(AType: TgirError; AMsg: String); begin if InternalHandler <> nil then begin InternalHandler(UserData, AType, AMsg); Exit; end; // if AType = geDebug then WriteLn(girErrorName[AType],': ', AMsg); end; function girSetErrorHandler(AHandler: TgirErrorFunc; AUserData: Pointer ): TgirErrorFunc; begin Result := InternalHandler; InternalHandler:=AHandler; UserData:=AUserData; end; end.
unit utils_queueTask; interface uses utils.queues, Classes, SysUtils, {$IFDEF MSWINDOWS} Windows, Messages, ActiveX, {$ENDIF} SyncObjs; type TDTaskWorker = class; TDQueueTask = class; TQueueTaskNotifyEvent = procedure(pSender: TDQueueTask; pvTaskData: Pointer) of object; TDQueueTask = class(TObject) private FLocker:TCriticalSection; FWorker: TDTaskWorker; FDebugInfo: String; FDataQueue: TSafeQueue; FEnable: Boolean; FOnExecute: TQueueTaskNotifyEvent; FWorkerAlive: Boolean; FCommEvent: TEvent; FDataPtr: Pointer; FLastErrorMessage: String; {$IFDEF MSWINDOWS} FNeedCoInitialize: Boolean; {$ENDIF} FOnCancelTask: TQueueTaskNotifyEvent; procedure NotifyDestroyWorker; protected procedure CheckForWorker; procedure DoTask(pvData: Pointer); virtual; property CommEvent: TEvent read FCommEvent; /// <summary> /// 执行取消队列任务 /// </summary> procedure DoCancelTask(); public constructor Create; destructor Destroy; override; /// <summary> /// 投递一个任务, 触发工作线程工作 /// </summary> procedure PostATask(pvData:Pointer); /// <summary> /// 停止工作(设置等待当前工作停止超时(单位ms)) /// 停止工作线程, 取消剩余任务(清空数据队列) /// </summary> /// <returns>成功停止返回true</returns> function StopWorker(pvTimeOut: Cardinal): Boolean; /// <summary> /// 存放额外数据 /// </summary> property DataPtr: Pointer read FDataPtr write FDataPtr; /// <summary> /// 是否允许执行任务(不停止工作线程) /// </summary> property Enable: Boolean read FEnable write FEnable; /// <summary> /// 任务数据队列 /// </summary> property DataQueue: TSafeQueue read FDataQueue; /// <summary> /// 最后抛出的一个错误信息 /// </summary> property LastErrorMessage: String read FLastErrorMessage; {$IFDEF MSWINDOWS} /// <summary> /// 线程中是否需要执行CoInitlize /// Windows系统有效 /// </summary> property NeedCoInitialize: Boolean read FNeedCoInitialize write FNeedCoInitialize; {$ENDIF} /// <summary> /// 取消任务通知 /// </summary> property OnCancelTask: TQueueTaskNotifyEvent read FOnCancelTask write FOnCancelTask; /// <summary> /// 任务回调函数 /// </summary> property OnExecute: TQueueTaskNotifyEvent read FOnExecute write FOnExecute; end; TDTaskWorker = class(TThread) private FOwner: TDQueueTask; FNotify: TEvent; {$IFDEF MSWINDOWS} FCoInitialized:Boolean; {$ENDIF} public constructor Create(AOwner: TDQueueTask); destructor Destroy; override; {$IFDEF MSWINDOWS} /// <summary> /// current worker invoke /// </summary> procedure CheckCoInitializeEx(pvReserved: Pointer = nil; coInit: Longint = 0); {$ENDIF} procedure Execute; override; end; implementation function tick_diff(tick_start, tick_end: Cardinal): Cardinal; begin if tick_end >= tick_start then result := tick_end - tick_start else result := High(Cardinal) - tick_start + tick_end; end; function CheckThreadIsAlive(const AThread: TThread): Boolean; var lvCode:Cardinal; begin Result := false; if (AThread <> nil) and (GetExitCodeThread(AThread.Handle, lvCode)) then begin if lvCode=STILL_ACTIVE then begin Result := true; end; end; end; constructor TDQueueTask.Create; begin inherited Create; FLocker := TCriticalSection.Create; FDataQueue := TSafeQueue.Create; FCommEvent := TEvent.Create(nil,false,false,''); FEnable := true; end; destructor TDQueueTask.Destroy; begin StopWorker(3000); FDataQueue.Free; FLocker.Free; FCommEvent.Free; inherited Destroy; end; procedure TDQueueTask.DoCancelTask; var lvData:Pointer; begin while FDataQueue.DeQueue(lvData) do begin if Assigned(FOnCancelTask) then begin FOnCancelTask(Self, lvData); end; end; end; procedure TDQueueTask.DoTask(pvData: Pointer); begin if Assigned(FOnExecute) then FOnExecute(Self, pvData); end; procedure TDQueueTask.CheckForWorker; begin FLocker.Enter; try if FWorker = nil then begin FWorker := TDTaskWorker.Create(Self); {$IF RTLVersion<25} FWorker.Resume; {$ELSE} FWorker.Start; {$IFEND} Sleep(10); end; if FWorker <> nil then begin FWorker.FNotify.SetEvent; end; finally FLocker.Leave; end; end; procedure TDQueueTask.NotifyDestroyWorker; begin FLocker.Enter; try FWorkerAlive := False; FWorker := nil; finally FLocker.Leave; end; end; procedure TDQueueTask.PostATask(pvData: Pointer); begin FDataQueue.EnQueue(pvData); CheckForWorker; end; function TDQueueTask.StopWorker(pvTimeOut: Cardinal): Boolean; var l:Cardinal; begin Result := true; FEnable := false; if FWorker <> nil then begin FWorker.Terminate; FWorker.FNotify.SetEvent; FCommEvent.SetEvent; l := GetTickCount; while CheckThreadIsAlive(FWorker) do begin {$IFDEF MSWINDOWS} SwitchToThread; {$ELSE} TThread.Yield; {$ENDIF} if tick_diff(l, GetTickCount) > pvTimeOut then begin Result := false; Break; end; end; FWorker := nil; end; DoCancelTask; end; constructor TDTaskWorker.Create(AOwner: TDQueueTask); begin inherited Create(True); FreeOnTerminate := true; FNotify := TEvent.Create(nil,false,false,''); FOwner := AOwner; end; destructor TDTaskWorker.Destroy; begin FNotify.Free; inherited Destroy; end; {$IFDEF MSWINDOWS} procedure TDTaskWorker.CheckCoInitializeEx(pvReserved: Pointer = nil; coInit: Longint = 0); begin if not FCoInitialized then begin CoInitializeEx(pvReserved, coInit); FCoInitialized := true; end; end; {$ENDIF} procedure TDTaskWorker.Execute; var lvWaitResult:TWaitResult; lvData: Pointer; begin try while not self.Terminated do begin FOwner.FDebugInfo := 'Thread.Execute::FNotify.WaitFor()'; lvWaitResult := FNotify.WaitFor(1000 * 30); if (lvWaitResult=wrSignaled) then begin FOwner.FDebugInfo := 'Thread.Execute::FNotify.WaitFor(), succ'; while not self.Terminated do begin if not FOwner.FDataQueue.DeQueue(lvData) then Break; try FOwner.FDebugInfo := 'Thread.Execute::DoTask'; {$IFDEF MSWINDOWS} if FOwner.NeedCoInitialize then begin CheckCoInitializeEx(); end; {$ENDIF} FOwner.DoTask(lvData); except on E:Exception do begin FOwner.FLastErrorMessage := E.Message; //FOwner.incErrorCounter; end; end; end; end else if lvWaitResult = wrTimeout then begin Break; end; end; finally FOwner.NotifyDestroyWorker; {$IFDEF MSWINDOWS} if FCoInitialized then CoUninitialize(); {$ENDIF} end; end; end.
unit Test.ObjectOnline; interface uses Windows, Classes, TestFrameWork, GMGlobals, Threads.ObjectOnline, GMSqlQuery, GMBlockValues; type TObjectOnlineThreadForTest = class(TObjectOnlineThread) protected utOnlineTime: LongWord; procedure SafeExecute; override; function OnlineTime: LongWord; override; end; TObjectOnlineThreadTest = class(TTestCase) private thread: TObjectOnlineThreadForTest; procedure InsertData(); protected procedure SetUp; override; procedure TearDown; override; published procedure ProcessObjects; procedure DB(); end; implementation uses DateUtils, SysUtils, GMConst; function TObjectOnlineThreadForTest.OnlineTime: LongWord; begin Result := utOnlineTime; end; procedure TObjectOnlineThreadForTest.SafeExecute; begin end; procedure TObjectOnlineThreadTest.DB; var cnt: string; res: ArrayOfString; begin thread.ProcessObjects(); cnt := QueryResult('select count(*) from ObjectStates'); Check(cnt = '3'); res := QueryResultArray_FirstColumn('select ID_Obj from ObjectStates order by 1'); Check(Length(res) = 3); Check((res[0] = '1') and (res[1] = '2') and (res[2] = '4')); res := QueryResultArray_FirstRow('select min(LastOnline), max(LastOnline) from ObjectStates'); Check(Length(res) = 3); Check((StrToInt(res[0]) = int64(thread.utOnlineTime)) and (res[0] = res[1])); end; procedure TObjectOnlineThreadTest.InsertData; var i: int; begin for i := 0 to 10 do begin thread.ObjectOnline(1, -1, 0); thread.ObjectOnline(0, OBJ_TYPE_GM, 200); thread.ObjectOnline(0, OBJ_TYPE_GM, 100); thread.ObjectOnline(4, -1, 0); thread.ObjectOnline(0, OBJ_TYPE_K105, 1); end; end; procedure TObjectOnlineThreadTest.SetUp; begin inherited; thread := TObjectOnlineThreadForTest.Create(); thread.utOnlineTime := NowGM(); InsertData(); ExecSQL('delete from ObjectStates; delete from ParamStates;'); end; procedure TObjectOnlineThreadTest.TearDown; begin inherited; thread.Free(); end; procedure TObjectOnlineThreadTest.ProcessObjects; var sl: TstringList; begin sl := TStringList.Create(); try sl.Text := thread.UpdateQuery(); Check(sl.Count = 5); // второй раз не засылаем sl.Text := thread.UpdateQuery(); Check(sl.Count = 0); // типа пришли обновления thread.utOnlineTime := thread.utOnlineTime + 1; InsertData(); sl.Text := thread.UpdateQuery(); Check(sl.Count = 5); finally sl.Free(); end; end; initialization RegisterTest('GMIOPSrv/Threads', TObjectOnlineThreadTest.Suite); end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit DesignIntf; interface {$IFDEF MSWINDOWS} uses System.SysUtils, System.Classes, System.Types, Winapi.ActiveX, System.TypInfo, DesignConst {$IFNDEF PARSER_TEST} , System.IniFiles, DesignerTypes, DesignMenus, Vcl.Controls, Winapi.Messages {$ENDIF} ; {$ENDIF} {$IFDEF LINUX} uses SysUtils, Classes, Types, TypInfo, IniFiles, DesignerTypes, DesignMenus; {$ENDIF} { Property Editor Types } type TPropKind = (pkProperties, pkEvents); { This interface abstracts the notion of a TTypeData record for an event } IEventInfo = interface ['{C3A5B0FD-37C6-486B-AD29-642C51928787}'] function GetMethodKind: TMethodKind; function GetParamCount: Integer; function GetParamName(Index: Integer): string; function GetParamType(Index: Integer): string; function GetParamFlags(Index: Integer): TParamFlags; function GetResultType: string; end; TEventInfo = class(TInterfacedObject, IEventInfo) private FMethodKind: TMethodKind; FParamNames: array of string; FParamTypes: array of string; FParamFlags: array of TParamFlags; FResultType: string; procedure Initialize(ATypeData: PTypeData); protected function GetMethodKind: TMethodKind; function GetParamCount: Integer; function GetParamName(Index: Integer): string; function GetParamType(Index: Integer): string; function GetParamFlags(Index: Integer): TParamFlags; function GetResultType: string; public constructor Create(APropInfo: PPropInfo); overload; constructor Create(ATypeData: PTypeData); overload; end; {$IFNDEF PARSER_TEST} IProperty = interface; TGetPropProc = procedure(const Prop: IProperty) of object; TPropertyAttribute = (paValueList, paSubProperties, paDialog, paMultiSelect, paAutoUpdate, paSortList, paReadOnly, paRevertable, paFullWidthName, paVolatileSubProperties, paVCL, paNotNestable, paDisplayReadOnly, paCustomDropDown, paValueEditable); TPropertyAttributes = set of TPropertyAttribute; { IProperty This is the interface used by the object inspector to edit properties. Activate Called whenever the property becomes selected in the object inspector. This is potentially useful to allow certain property attributes to to only be determined whenever the property is selected in the object inspector. Only paSubProperties and paMultiSelect, returned from GetAttributes, need to be accurate before this method is called. AllEqual Called whenever there is more than one component selected. If this method returns true, GetValue is called, otherwise blank is displayed in the Object Inspector. This is called only when GetAttributes returns paMultiSelect. AutoFill Called to determine whether the values returned by GetValues can be selected incrementally in the Object Inspector. This is called only when GetAttributes returns paValueList. Edit Called when the '...' button is pressed or the property is double-clicked. This can, for example, bring up a dialog to allow the editing the component in some more meaningful fashion than by text (e.g. the Font property). GetAttributes Returns the information for use in the Object Inspector to be able to show the appropriate tools. GetAttributes returns a set of type TPropertyAttributes: paValueList: The property editor can return an enumerated list of values for the property. If GetValues calls Proc with values then this attribute should be set. This will cause the drop-down button to appear to the right of the property in the Object Inspector. paSortList: Object Inspector to sort the list returned by GetValues. paSubProperties: The property editor has sub-properties that will be displayed indented and below the current property in standard outline format. If GetProperties will generate property objects then this attribute should be set. paDialog: Indicates that the Edit method will bring up a dialog. This will cause the '...' button to be displayed to the right of the property in the Object Inspector. paMultiSelect: Allows the property to be displayed when more than one component is selected. Some properties are not appropriate for multi-selection (e.g. the Name property). paAutoUpdate: Causes the SetValue method to be called on each change made to the editor instead of after the change has been approved (e.g. the Caption property). paReadOnly: Value is not allowed to change. paRevertable: Allows the property to be reverted to the original value. Things that shouldn't be reverted are nested properties (e.g. Fonts) and elements of a composite property such as set element values. paFullWidthName: Tells the object inspector that the value does not need to be rendered and as such the name should be rendered the full width of the inspector. paVolatileSubProperties: Any change of property value causes any shown subproperties to be recollected. paReference: Property contains a reference to something else. When used in conjunction with paSubProperties the referenced object should be displayed as sub properties to this property. paNotNestable: Indicates that the property is not safe to show when showing the properties of an expanded reference. paDisplayReadOnly: This differes from paReadOnly in that it tells the Object inspector to display this property as read-only and that there is no way to actually set this value. paReadOnly simply tells the OI to disable changes to the property direct changes to the property. It *may* still be changeable via another property or editor. paCustomDropDown: Tells the OI to display the drop-down button, but instead of requiring a value list to be returned from get values, it simply called the Edit method. This attribute is really only valuable if the the IProperty80 interface is implemented so the property editor can call DropDownControl on IPropertyHost to display a custom drop-down. paValueEditable: When this flag is combined with paReadOnly, it allows the value to be changed *only* via a dialog or the drop down list. This will keep the user from entering free- form text into the edit field, yet allow the value to be changed. GetComponent Returns the Index'th component being edited by this property editor. This is used to retrieve the components. A property editor can only refer to multiple components when paMultiSelect is returned from GetAttributes. GetEditLimit Returns the number of character the user is allowed to enter for the value. The inplace editor of the object inspector will be have its text limited set to the return value. By default this limit is 255. GetName Returns the name of the property. By default the value is retrieved from the type information with all underbars replaced by spaces. This should only be overridden if the name of the property is not the name that should appear in the Object Inspector. GetComponentValue Return the value as a TComponent if, and only if, it is a object that descends from TComponent in Classes, otherwise return nil. This is only implemented by the TComponentProperty editor. If you register a component property editor that obscures the default TComponentProperty, ensure it correctly implements this method. GetProperties Should be overridden to call PropertyProc for every sub-property (or nested property) of the property begin edited and passing a new TPropertyEdtior for each sub-property. By default, PropertyProc is not called and no sub-properties are assumed. TClassProperty will pass a new property editor for each published property in a class. TSetProperty passes a new editor for each element in the set. GetPropType Returns the type information pointer for the property(s) being edited. GetValue Returns the string value of the property. TPropertyEditor will return '(unknown)' by default. GetValues Called when paValueList is returned in GetAttributes. Should call Proc for every value that is acceptable for this property. TEnumProperty will pass every element in the enumeration. SetValue(Value) Called to set the value of the property. The property editor should be able to translate the string and call one of the SetXxxValue methods. If the string is not in the correct format or not an allowed value, the property editor should generate an exception describing the problem. Set value can ignore all changes and allow all editing of the property be accomplished through the Edit method (e.g. the Picture property). ValueAvailable Returns true if the value can be accessed without causing an exception. This is used to verify you can edit properties of some ActiveX controls that are poorly written. GetEditValue(out Value): Boolean Returns true if value can be edited. } IProperty = interface ['{7ED7BF29-E349-11D3-AB4A-00C04FB17A72}'] procedure Activate; function AllEqual: Boolean; function AutoFill: Boolean; procedure Edit; overload; function HasInstance(Instance: TPersistent): Boolean; function GetAttributes: TPropertyAttributes; function GetEditLimit: Integer; function GetEditValue(out Value: string): Boolean; function GetName: string; procedure GetProperties(Proc: TGetPropProc); function GetPropInfo: PPropInfo; function GetPropType: PTypeInfo; function GetValue: string; procedure GetValues(Proc: TGetStrProc); procedure Revert; procedure SetValue(const Value: string); function ValueAvailable: Boolean; end; IPropertyKind = interface ['{DC38E982-F69D-40BB-B99D-F14EE83CD448}'] function GetKind: TTypeKind; property Kind: TTypeKind read GetKind; end; IPropertyControl = interface ['{7FEC88A8-CC8D-43EF-AA14-AFCAD7E3418A}'] procedure ClearCache; end; IWideProperty = interface ['{ACBF6140-1378-4AAC-94D6-D4660DFE7053}'] function GetValue: WideString; function GetEditValue(out Value: widestring): Boolean; procedure SetValue(const Value: WideString); end; TGetWideStrProc = procedure(const S: WideString) of object; IWideProperty10 = interface ['{EB335848-4AD4-4423-8598-37FFDF5984D5}'] function GetName: WideString; procedure GetValues(Proc: TGetWideStrProc); end; { IProperty70 GetIsDefault Return True if the current value is the default value for this property. Non-default values will be in bold. If IProperty70 is not implemented by the object, items will not be bolded. In general, you should return true if a given property will NOT be stored in the dfm. } IProperty70 = interface(IProperty) ['{57B97F18-B47F-4635-94CB-3344783E7069}'] function GetIsDefault: Boolean; property IsDefault: Boolean read GetIsDefault; end; IPropertyHost = interface; { IProperty80 Edit If this interface is implemented, this Edit method is called instead of the IProperty.Edit method. Also, this method is called if GetAttribute returns the paCustomDropDown attribute. DblClick will be true if this method is called as a result of the user double-clicking on the property value. } IProperty80 = interface(IProperty) ['{A02577DB-D5E5-4374-A8AB-4B2F83177878}'] procedure Edit(const Host: IPropertyHost; DblClick: Boolean); end; { IProperty160 SetPropertyPath If this interface is implemented, the property path will be supplied to the property when a TPropItem representing the property is created.} IProperty160 = interface(IProperty) ['{265F5E34-8999-4B9B-AC30-A2AED60885DF}'] procedure SetPropertyPath(const Value: string); end; { IPropertyDescription GetDescription If this interface is implemented and the property inspector selection is set to show the description pane, then the results of GetDescription are displayed in the OI in a pane below the property list along with the property name } IPropertyDescription = interface ['{FEAA70CD-F6BC-44D7-8D1D-ED9CB9146075}'] function GetDescription: string; end; IWidePropertyDescription = interface ['{87A17602-67E2-46b3-B78B-D53E1E123053}'] function GetDescription: WideString; end; { IPropertyHost DropDownControl Call this method from within the Edit method on IProperty80 to display an arbitrary custom control. Control *must* be a Controls.TControl descendant in order to properly function. This control is parented to a host control which is sized to match the size of the Control. It is then displayed as a drop-down window below the currently selected property. CloseDropDown Call this to terminate the drop-down "modal" loop. This is typically in response to some user interaction with the previously dropped down control. } IPropertyHost = interface ['{093B302C-2AFC-4891-9B17-FAB69678C956}'] procedure DropDownControl(Control: TPersistent); procedure CloseDropDown; end; IPropertyHost20 = interface ['{46000055-6FD3-4C80-8E4C-8B28D0CD0593}'] function GetDropDownWidth: Integer; end; IMethodProperty = interface ['{392CBF4A-F078-47E9-B731-0E0B7F1F4998}'] end; IActivatable = interface ['{F00AA4BD-3459-43E9-ACB2-97DBD1663AFF}'] procedure Activate; end; IReferenceProperty = interface ['{C7EE2B1E-3F89-40AD-9250-D2667BA3D46B}'] function GetComponentReference: TComponent; end; IShowReferenceProperty = interface ['{ECD009DA-C711-4C7F-912B-3AB5A6A4B290}'] function ShowReferenceProperty: Boolean; end; var GReferenceExpandable: Boolean = True; GShowReadOnlyProps: Boolean = True; type IClass = interface ['{94CD802C-3E83-4C38-AB36-1CD9DB196519}'] function ClassNameIs(const AClassName: string): Boolean; function GetClassName: string; function GetUnitName: string; function GetClassParent: IClass; property ClassName: string read GetClassName; property ClassParent: IClass read GetClassParent; property UnitName: string read GetUnitName; end; IDesignObject = interface ['{B1648433-D671-4D5E-B49F-26740D4EB360}'] function Equals(Obj: TObject): Boolean; overload; function Equals(const ADesignObject: IDesignObject): Boolean; overload; function GetClassType: IClass; function GetClassName: string; function GetComponentIndex: Integer; function GetComponentName: string; function GetIsComponent: Boolean; function GetNamePath: string; property ClassType: IClass read GetClassType; property ClassName: string read GetClassName; property ComponentIndex: Integer read GetComponentIndex; property ComponentName: string read GetComponentName; property IsComponent: Boolean read GetIsComponent; property NamePath: string read GetNamePath; end; IDesignPersistent = interface(IDesignObject) ['{8858E03D-5B6A-427A-BFFC-4A9B8198FB13}'] function GetPersistent: TPersistent; property Persistent: TPersistent read GetPersistent; end; { IDesignerSelections Used to transport the selected objects list in and out of the form designer. Replaces TDesignerSelectionList in form designer interface. } IDesignerSelections = interface ['{7ED7BF30-E349-11D3-AB4A-00C04FB17A72}'] function Add(const Item: TPersistent): Integer; function Equals(const List: IDesignerSelections): Boolean; function Get(Index: Integer): TPersistent; function GetDesignObject(Index: Integer): IDesignObject; function GetCount: Integer; property Count: Integer read GetCount; property Items[Index: Integer]: TPersistent read Get; default; property DesignObjects[Index: Integer]: IDesignObject read GetDesignObject; end; IDesigner = interface; IDesigner70 = interface; IDesigner60 = interface ['{A29C6480-D4AF-11D3-BA96-0080C78ADCDB}'] procedure Activate; procedure Modified; function CreateMethod(const Name: string; TypeData: PTypeData): TMethod; overload; function GetMethodName(const Method: TMethod): string; procedure GetMethods(TypeData: PTypeData; Proc: TGetStrProc); overload; function GetPathAndBaseExeName: string; function GetPrivateDirectory: string; function GetBaseRegKey: string; function GetIDEOptions: TCustomIniFile; procedure GetSelections(const List: IDesignerSelections); function MethodExists(const Name: string): Boolean; procedure RenameMethod(const CurName, NewName: string); procedure SelectComponent(Instance: TPersistent); overload; procedure SetSelections(const List: IDesignerSelections); procedure ShowMethod(const Name: string); procedure GetComponentNames(TypeData: PTypeData; Proc: TGetStrProc); function GetComponent(const Name: string): TComponent; function GetComponentName(Component: TComponent): string; function GetObject(const Name: string): TPersistent; function GetObjectName(Instance: TPersistent): string; procedure GetObjectNames(TypeData: PTypeData; Proc: TGetStrProc); function MethodFromAncestor(const Method: TMethod): Boolean; function CreateComponent(ComponentClass: TComponentClass; Parent: TComponent; Left, Top, Width, Height: Integer): TComponent; function CreateCurrentComponent(Parent: TComponent; const Rect: TRect): TComponent; function IsComponentLinkable(Component: TComponent): Boolean; function IsComponentHidden(Component: TComponent): Boolean; procedure MakeComponentLinkable(Component: TComponent); procedure Revert(Instance: TPersistent; PropInfo: PPropInfo); function GetIsDormant: Boolean; procedure GetProjectModules(Proc: TGetModuleProc); function GetAncestorDesigner: IDesigner; function IsSourceReadOnly: Boolean; function GetScrollRanges(const ScrollPosition: TPoint): TPoint; procedure Edit(const Component: TComponent); procedure ChainCall(const MethodName, InstanceName, InstanceMethod: string; TypeData: PTypeData); overload; procedure ChainCall(const MethodName, InstanceName, InstanceMethod: string; const AEventInfo: IEventInfo); overload; procedure CopySelection; procedure CutSelection; function CanPaste: Boolean; procedure PasteSelection; procedure DeleteSelection(ADoAll: Boolean = False); procedure ClearSelection; procedure NoSelection; procedure ModuleFileNames(var ImplFileName, IntfFileName, FormFileName: string); function GetRootClassName: string; function UniqueName(const BaseName: string): string; function GetRoot: TComponent; function GetShiftState: TShiftState; procedure ModalEdit(EditKey: Char; const ReturnWindow: IActivatable); procedure SelectItemName(const PropertyName: string); procedure Resurrect; property Root: TComponent read GetRoot; property IsDormant: Boolean read GetIsDormant; property AncestorDesigner: IDesigner read GetAncestorDesigner; end; IDesigner70 = interface(IDesigner60) ['{2F704CE2-7614-4AAF-B177-357D00D9634B}'] function GetActiveClassGroup: TPersistentClass; function FindRootAncestor(const AClassName: string): TComponent; property ActiveClassGroup: TPersistentClass read GetActiveClassGroup; end; IDesigner80 = interface(IDesigner70) ['{BCE34322-B22A-4494-BEA5-5B2B9754DE36}'] function CreateMethod(const Name: string; const AEventInfo: IEventInfo): TMethod; overload; procedure GetMethods(const AEventInfo: IEventInfo; Proc: TGetStrProc); overload; procedure SelectComponent(const ADesignObject: IDesignObject); overload; end; IDesigner100 = interface(IDesigner80) ['{55501C77-FE8D-4844-A407-A7F90F7D5303}'] function GetDesignerExtension: string; property DesignerExtention: string read GetDesignerExtension; end; IDesigner170 = interface(IDesigner100) ['{17ACD4A3-ED00-483E-8480-B5FBD4589440}'] function GetAppDataDirectory(Local: Boolean = False): string; end; IDesigner200 = interface(IDesigner170) ['{4B854DD8-2C2C-455A-B1DC-08AAED7370A6}'] function GetCurrentParent: TComponent; property CurrentParent: TComponent read GetCurrentParent; end; IDesigner = interface(IDesigner200) ['{93F3FCBC-968E-45A9-9641-609E8FB3AC60}'] function CreateChild(ComponentClass: TComponentClass; Parent: TComponent): TComponent; end; TGetDesignerEvent = procedure(Sender: TObject; out ADesigner: IDesigner) of object; { IDesignNotification An implementation of this can be registered with RegisterDesignNotification and it will be called by the designer to allow notifications of various events. ItemDeleted - AItem has been deleted (triggered indirectly by the Notification method of the owner of the component). ItemInserted - AItem has been insterted (triggered indirectly by the Notification method of the owner of the component). ItemModified - The modified method of the given ADesigner was called indicating that one or more items may have been modified. DesignerOpened - ADesigner has been created. If you store a reference to ADesigner you *must* clear that reference when DesignerClosed is called with AGoingDormant = False. If AResurrecting is True, then this designer has previously gone dormant and its design root is now being recreated. DesignerClosed - ADesigner is in the process of being destroyed. Any reference to the designer must be release. You may also want to destroy any associated windows that are specific to ADesigner. If AGoingDormant is True then this indicates that the design root is being destroyed but the designer itself is not. This will happen when a design-time package is unloaded. In *most* cases, the reference to the designer must be released regardless of the AGoingDormant flag, however it is not mandatory. } IDesignNotification = interface ['{E8C9F739-5601-4ADD-9D95-594132D4CEFD}'] procedure ItemDeleted(const ADesigner: IDesigner; AItem: TPersistent); procedure ItemInserted(const ADesigner: IDesigner; AItem: TPersistent); procedure ItemsModified(const ADesigner: IDesigner); procedure SelectionChanged(const ADesigner: IDesigner; const ASelection: IDesignerSelections); procedure DesignerOpened(const ADesigner: IDesigner; AResurrecting: Boolean); procedure DesignerClosed(const ADesigner: IDesigner; AGoingDormant: Boolean); end; { IDesignNotificationEx An implementation of this can be registered with RegisterDesignNotification and it will be called by the designer to allow notifications DescedantUpdated - ADesigner has been updated because of changes in an ancestor. } IDesignNotificationEx = interface(IDesignNotification) ['{41DDF415-B9ED-48AE-8291-D49429E3CDF7}'] procedure DescendantUpdated(const ADesigner: IDesigner); end; { IDesignNotificationViews An implementation of this can be registered with RegisterDesignNotification and it will be called by the designer to allow notifications of various events. ViewAdded - ViewName view has been created for ADesigner ViewRemoved - ViewName view has been removed from ADesigner } IDesignNotificationViews = interface(IDesignNotification) ['{92B08B96-E8CF-4AE9-8D02-E1BEBF7DB662}'] procedure ViewAdded(const ADesigner: IDesigner; const ViewName: string); procedure ViewRemoved(const ADesigner: IDesigner; const ViewName: string); end; { IDesignWindow IDesignWindow should be used when the IDesignNotification handler is a top level window. It it is also registered with RegisterDesignNotifications. WindowHide - This is called when all design windows should be hidden such as when the IDE is debugging. WindowShow - This is called when all design windows can not be reshown such as when the IDE finishes debugging. } IDesignWindow = interface(IDesignNotification) ['{7ED7BF2E-E349-11D3-AB4A-00C04FB17A72}'] procedure WindowHide; procedure WindowShow; end; TRegisterDesignNotification = procedure (const DesignNotification: IDesignNotification); var RegisterDesignNotificationProc: TRegisterDesignNotification; UnregisterDesignNotificationProc: TRegisterDesignNotification; procedure RegisterDesignNotification(const DesignNotification: IDesignNotification); procedure UnregisterDesignNotification(const DesignNotification: IDesignNotification); type TBasePropertyEditor = class(TInterfacedObject) protected procedure Initialize; virtual; abstract; procedure SetPropEntry(Index: Integer; AInstance: TPersistent; APropInfo: PPropInfo); virtual; abstract; public constructor Create(const ADesigner: IDesigner; APropCount: Integer); virtual; end; TPropertyEditorClass = class of TBasePropertyEditor; { RegisterPropertyEditor Registers a new property editor for the given type. When a component is selected the Object Inspector will create a property editor for each of the component's properties. The property editor is created based on the type of the property. If, for example, the property type is an Integer, the property editor for Integer will be created (by default that would be TIntegerProperty). Most properties do not need specialized property editors. For example, if the property is an ordinal type the default property editor will restrict the range to the ordinal subtype range (e.g. a property of type TMyRange = 1..10 will only allow values between 1 and 10 to be entered into the property). Enumerated types will display a drop-down list of all the enumerated values (e.g. TShapes = (sCircle, sSquare, sTriangle) will be edited by a drop-down list containing only sCircle, sSquare and sTriangle). A property editor need only be created if default property editor or none of the existing property editors are sufficient to edit the property. This is typically because the property is an object. The properties are looked up newest to oldest. This allows and existing property editor replaced by a custom property editor. PropertyType The type information pointer returned by the TypeInfo built-in function (e.g. TypeInfo(TMyRange) or TypeInfo(TShapes)). ComponentClass Type of the component to which to restrict this type editor. This parameter can be left nil which will mean this type editor applies to all properties of PropertyType. PropertyName The name of the property to which to restrict this type editor. This parameter is ignored if ComponentClass is nil. This parameter can be an empty string ('') which will mean that this editor applies to all properties of PropertyType in ComponentClass. EditorClass The class of the editor to be created whenever a property of the type passed in PropertyTypeInfo is displayed in the Object Inspector. The class will be created by calling EditorClass.Create. } type TRegisterPropertyEditorProc = procedure (PropertyType: PTypeInfo; ComponentClass: TClass; const PropertyName: string; EditorClass: TPropertyEditorClass); TPropertyEditorFilterFunc = function(const ATestEditor: IProperty): Boolean of object; var RegisterPropertyEditorProc: TRegisterPropertyEditorProc; procedure RegisterPropertyEditor(PropertyType: PTypeInfo; ComponentClass: TClass; const PropertyName: string; EditorClass: TPropertyEditorClass); { SetPropertyEditorGroup Restricts the given editor class to be active for the classes associated to GroupClass by calls to GroupDescendentsWith. For example, this is used to ensure the proper version of TShortCutProperty is created depending on if it is a CLX component or a VCL component. Using this is very similar to using the ComponentClass parameter of RegisterPropertyEditor, but instead of limiting it to a particular class, it limits the editor to a group of classes created by StartClassGroup. EditorClass The class of the editor to restrict to a particular class group. GroupClass The class used to determine the group EditorClass is restricted to. } type TSetPropertyEditorGroupProc = procedure (EditorClass: TPropertyEditorClass; GroupClass: TPersistentClass); var SetPropertyEditorGroupProc: TSetPropertyEditorGroupProc; procedure SetPropertyEditorGroup(EditorClass: TPropertyEditorClass; GroupClass: TPersistentClass); { UnlistPublishedProperty From time to time there is a need to hide a property that has been published by an ancestor class. Whenever this occurs you should make sure that you are descending from the right class. We realize, though, that sometimes this is not feasible. The following procedure will therefore allow you to make a specific property on a specific class not appear in the Object inspector. ** Please note that this function does not stop the streaming system from streaming the published property nor does it make the published property from begin programmatically access at runtime. It simply tells the object inspector not to list (and in turn edit) it when components of the specified class are selected. } procedure UnlistPublishedProperty(ComponentClass: TClass; const PropertyName: string); { Standard Property Category Names } resourcestring sAppearanceCategoryName = 'Appearance'; sBehaviorCategoryName = 'Behavior'; sDesignCategoryName = 'Design'; sFocusCategoryName = 'Focus'; sWindowStyleName = 'Window Style'; sPropertyChangeCategoryName = 'Property Changed'; sMouseCategoryName = 'Mouse'; sKeyCategoryName = 'Key'; sActionCategoryName = 'Action'; sDataCategoryName = 'Data'; sDatabaseCategoryName = 'Database'; {$IFDEF MSWINDOWS} sDragNDropCategoryName = 'Drag Drop/Docking'; {$ENDIF} {$IFDEF LINUX} sDragNDropCategoryName = 'Drag Drop'; {$ENDIF} sHelpCategoryName = 'Help and Hints'; sLayoutCategoryName = 'Layout'; sLegacyCategoryName = 'Legacy'; sLinkageCategoryName = 'Linkage'; sLocaleCategoryName = 'Locale'; sLocalizableCategoryName = 'Localizable'; sMiscellaneousCategoryName = 'Miscellaneous'; sVisualCategoryName = 'Visual'; sInputCategoryName = 'Input'; { Property Category Types } type TRegisterPropertyInCategoryProc = procedure (const CategoryName: string; ComponentClass: TClass; PropertyType: PTypeInfo; const PropertyName: string); var RegisterPropertyInCategoryProc: TRegisterPropertyInCategoryProc; procedure RegisterPropertyInCategory(const CategoryName, PropertyName: string); overload; procedure RegisterPropertyInCategory(const CategoryName: string; ComponentClass: TClass; const PropertyName: string); overload; procedure RegisterPropertyInCategory(const CategoryName: string; PropertyType: PTypeInfo; const PropertyName: string); overload; procedure RegisterPropertyInCategory(const CategoryName: string; PropertyType: PTypeInfo); overload; procedure RegisterPropertiesInCategory(const CategoryName: string; const Filters: array of const); overload; procedure RegisterPropertiesInCategory(const CategoryName: string; ComponentClass: TClass; const Filters: array of string); overload; procedure RegisterPropertiesInCategory(const CategoryName: string; PropertyType: PTypeInfo; const Filters: array of string); overload; resourcestring sInvalidFilter = 'Property filters may only be name, class or type based (%d:%d)'; { Property Mapper } type TPropertyMapperFunc = function(Obj: TPersistent; PropInfo: PPropInfo): TPropertyEditorClass; TRegisterPropertyMapperProc = procedure (Mapper: TPropertyMapperFunc); var RegisterPropertyMapperProc: TRegisterPropertyMapperProc; procedure RegisterPropertyMapper(Mapper: TPropertyMapperFunc); { Component Editor Types } type { IComponentEditor A component editor is created for each component that is selected in the form designer based on the component's type (see GetComponentEditor and RegisterComponentEditor). When the component is double-clicked the Edit method is called. When the context menu for the component is invoked the GetVerbCount and GetVerb methods are called to build the menu. If one of the verbs are selected ExecuteVerb is called. Paste is called whenever the component is pasted to the clipboard. You only need to create a component editor if you wish to add verbs to the context menu, change the default double-click behavior, or paste an additional clipboard format. The default component editor (TDefaultEditor) implements Edit to searches the properties of the component and generates (or navigates to) the OnCreate, OnChanged, or OnClick event (whichever it finds first). Whenever the component modifies the component is *must* call Designer.Modified to inform the designer that the form has been modified. Edit Called when the user double-clicks the component. The component editor can bring up a dialog in response to this method, for example, or some kind of design expert. If GetVerbCount is greater than zero, edit will execute the first verb in the list (ExecuteVerb(0)). ExecuteVerb(Index) The Index'ed verb was selected by the use off the context menu. The meaning of this is determined by component editor. GetVerb The component editor should return a string that will be displayed in the context menu. It is the responsibility of the component editor to place the & character and the '...' characters as appropriate. GetVerbCount The number of valid indices to GetVerb and Execute verb. The index is assumed to be zero based (i.e. 0..GetVerbCount - 1). PrepareItem While constructing the context menu PrepareItem will be called for each verb. It will be passed the menu item that will be used to represent the verb. The component editor can customize the menu item as it sees fit, including adding subitems. If you don't want that particular menu item to be shown, don't free it, simply set its Visible property to False. Copy Called when the component is being copied to the clipboard. The component's filed image is already on the clipboard. This gives the component editor a chance to paste a different type of format which is ignored by the designer but might be recognized by another application. IsInInlined Determines whether Component is in the Designer which owns it. Essentially, Components should not be able to be added to a Frame instance (collections are fine though) so this function checks to determine whether the currently selected component is within a Frame instance or not. GetComponent TODO GetDesigner TODO } IComponentEditor = interface ['{ECACBA34-DCDF-4BE2-A645-E4404BC06106}'] procedure Edit; procedure ExecuteVerb(Index: Integer); function GetVerb(Index: Integer): string; function GetVerbCount: Integer; procedure PrepareItem(Index: Integer; const AItem: IMenuItem); procedure Copy; function IsInInlined: Boolean; function GetComponent: TComponent; function GetDesigner: IDesigner; end; { TBaseComponentEditor All component editors are assumed derived from TBaseComponentEditor and implements the IComponentEditor interface. Create(AComponent, ADesigner) Called to create the component editor. AComponent is the component to be edited by the editor. ADesigner is an interface to the designer to find controls and create methods (this is not use often). If a component editor modifies the component in any way it *must* call ADesigner.Modified. } TBaseComponentEditor = class(TInterfacedObject) public constructor Create(AComponent: TComponent; ADesigner: IDesigner); virtual; end; TComponentEditorClass = class of TBaseComponentEditor; IDefaultEditor = interface(IComponentEditor) ['{5484FAE1-5C60-11D1-9FB6-0020AF3D82DA}'] end; { Register a component editor to be created when a component derived from ComponentClass is the only selection in the designer } type TRegisterComponentEditorProc = procedure (ComponentClass: TComponentClass; ComponentEditor: TComponentEditorClass); var RegisterComponentEditorProc: TRegisterComponentEditorProc; procedure RegisterComponentEditor(ComponentClass: TComponentClass; ComponentEditor: TComponentEditorClass); { Selection Editor Types } type { ISelectionEditor This interface performs functions similar to IComponentEditor but is not limited to one participant at a time. When a editor menu is needed Delphi will look at all of the selected objects and allow all selection editors that can match them participate in the menu construction and selection. A selection editor is selected by finding the most derived common ancestor of all the components in the selection and then finding the selection editor that was registered for that class or its closes ancestor. For example, if you register a selection editor for TControl and TButton and a button and a label are selected, the TControl selection editor will be created (because TControl is their common ancestor) but if two TButton's are selected, the TButton selection editor will be created. In other words, all the components in the selection are guarenteed, by the designer, to be at least derived from the class the selection editor is registered for. ExecuteVerb(Index) The Index'ed verb was selected by the use off the context menu. The meaning of this is determined by component editor. GetVerb The component editor should return a string that will be displayed in the context menu. It is the responsibility of the component editor to place the & character and the '...' characters as appropriate. GetVerbCount The number of valid indices to GetVerb and Execute verb. The index is assumed to be zero based (i.e. 0..GetVerbCount - 1). PrepareItem While constructing the context menu PrepareItem will be called for each verb. It will be passed the menu item that will be used to represent the verb. The selection editor can customize the menu item as it sees fit, including adding subitems. If you don't want that particular menu item to be shown, don't free it, simply set its Visible property to False. RequiresUnits Should call Proc with all the units that are needed to be used when using this class. The form designer automatically ensures the unit the class was declared in and all its ancestor's units are used in the user's program when they use this component. Sometimes, however, an event will use a type in one of its parameters that is not in its unit nor any of its ancestor's units. If this is the case a selection editor should be registerd that implements RequiresUnits and it should call Proc for each unit that declare the types needed by its events } ISelectionEditor = interface ['{B91F7A78-BB2C-45D9-957A-8A45A2D30435}'] procedure ExecuteVerb(Index: Integer; const List: IDesignerSelections); function GetVerb(Index: Integer): string; function GetVerbCount: Integer; procedure PrepareItem(Index: Integer; const AItem: IMenuItem); procedure RequiresUnits(Proc: TGetStrProc); end; { ISelectionPropertyFilter This optional interface is implemented on the same class that implements ISelectionEditor. If this interface is implemented, when the property list is constructed for a given selection, it is also passed through all the various implementations of this interface on the selected selection editors. From here the list of properties can be modified to add or remove properties from the list. If properties are added, then it is the responsibility of the implementor to properly construct an appropriate implementation of the IProperty interface. Since an added "property" will typically *not* be available via the normal RTTI mechanisms, it is the implementor's responsibility to make sure that the property editor overrides those methods that would normally access the RTTI for the selected objects. FilterProperties Once the list of properties has been gathered and before they are sent to the Object Inspector, this method is called with the list of properties. You may manupulate this list in any way you see fit, however, remember that another selection editor *may* have already modified the list. You are not guaranteed to have the original list. } ISelectionPropertyFilter = interface ['{0B424EF6-2F2F-41AB-A082-831292FA91A5}'] procedure FilterProperties(const ASelection: IDesignerSelections; const ASelectionProperties: IInterfaceList); end; { TBaseSelectionEditor All selection editors are assumed to derive from this class. A default implemenation for the ISelectionEditor interface is provided in TSelectionEditor class. } TBaseSelectionEditor = class(TInterfacedObject) public constructor Create(const ADesigner: IDesigner); virtual; end; TSelectionEditorClass = class of TBaseSelectionEditor; ISelectionEditorList = interface ['{C1360368-0099-4A7C-A4A8-7650503BA0C6}'] function Get(Index: Integer): ISelectionEditor; function GetCount: Integer; property Count: Integer read GetCount; property Items[Index: Integer]: ISelectionEditor read Get; default; end; type TRegisterSelectionEditorProc = procedure (AClass: TClass; AEditor: TSelectionEditorClass); var RegisterSelectionEditorProc: TRegisterSelectionEditorProc; procedure RegisterSelectionEditor(AClass: TClass; AEditor: TSelectionEditorClass); { Custom Module Types } { A custom module allows containers that descend from classes other than TForm to be created and edited by the form designer. This is useful for other form like containers (e.g. a report designer) or for specialized forms (e.g. an ActiveForm) or for generic component containers (e.g. a TDataModule). It is assumed that the base class registered will call InitInheritedComponent in its constructor which will initialize the component from the associated DFM or XFM file stored in the programs resources. See the constructors of TDataModule and TForm for examples of how to write such a constructor. The following designer assumptions are made, depending on the base components ancestor, If ComponentBaseClass descends from TForm (in either VCL or Clx), it is designed by creating an instance of the component as the form. Allows designing TForm descendents and modifying their properties as well as the form properties If ComponentBaseClass descends from TWinControl or TWidgetControl (but not TForm), it is designed by creating an instance of the control, placing it into a design-time form. The form's client size is the default size of the control. If ComponentBaseClass descends from TDataModule, it is designed by creating an instance of the class and creating a special non-visual container designer to edit the components and display the icons of the contained components. The module will appear in the project file with a colon and the base class name appended after the component name (e.g. MyDataModule: TDataModule). Note it is undefined what will happen if you try register anything that does not descend from one of the above. } type TCustomModuleAttribute = (cmaVirtualSize, cmaMultiView); TCustomModuleAttributes = set of TCustomModuleAttribute; { ICustomModule Created when a module is selected and prior to the module being created to request information about the custom module. GetAttributes Return information about the verb. Currently the only defined information is whether the designer should be virtually sized. This is only meaningful for modules that design visual components but not the top level visual component. This causes scroll-bars to appear instead of the visual component being client aligned in the parent designer. ExecuteVerb Execute the verb associated with Index. The text of the verb should be returned by GetVerb. GetVerb Return the text, suitable for placement in a menu, that you want the use to operate on the module as a whole. GetVerbCount Return the number of verbs returned by GetVerb and executed by ExecuteVerb. PrepareItem While constructing the context menu PrepareItem will be called for each verb. It will be passed the menu item that will be used to represent the verb. The module editor can customize the menu item as it sees fit, including adding subitems. If you don't want that particular menu item to be shown, don't free it, simply set its Visible property to False. Saving This is called prior to the module being saved. This allows the custom module to make sure the state of the module is consistent prior to saving. This method can be left blank. ValidateComponent This allows the custom module to reject components that are not suitable for the module. If the component is not applicable for the module ValidateComponent should raise and exception. TCustomModule implements this by calling ValidateComponentClass on the class of the component so if the filtering is done strictly by class implement ValidateComponentClass instead. ValidateComponentClass ValidateComponentClass is called by the designer to filter the contents of the palette to only the classes that are suitable for the module. Nestable Return true if this module can be nested into other modules. This will only be called if the TBaseCustomModule is created with a nil Root and, when Root is nil, only Nestable will be called on this interface. } ICustomModule = interface ['{95DA4A2B-D800-4CBB-B0B8-85AB7D3CFADA}'] function GetAttributes: TCustomModuleAttributes; procedure ExecuteVerb(Index: Integer); function GetVerb(Index: Integer): string; function GetVerbCount: Integer; procedure PrepareItem(Index: Integer; const AItem: IMenuItem); procedure Saving; procedure ValidateComponent(Component: TComponent); function ValidateComponentClass(ComponentClass: TComponentClass): Boolean; function Nestable: Boolean; end; { TBaseCustomModule All custom modules are assumed to derive from TBaseCustomModule. The ARoot ARoot parameter might be nil which means that only Nestable will be called on the ICustomModule interfaced implementated by the instance } TBaseCustomModule = class(TInterfacedObject) public constructor Create(ARoot: TComponent; const Designer: IDesigner); virtual; class function DesignClass: TComponentClass; virtual; end; TCustomModuleClass = class of TBaseCustomModule; TRegisterCustomModuleProc = procedure (Group: Integer; ComponentBaseClass: TComponentClass; CustomModuleClass: TCustomModuleClass); var RegisterCustomModuleProc: TRegisterCustomModuleProc; procedure RegisterCustomModule(ComponentBaseClass: TComponentClass; CustomModuleClass: TCustomModuleClass); { IHostForm } type IHostForm = interface ['{24E50CA3-CD64-42B6-B639-600209E723D7}'] procedure BringToFront; procedure CheckPosChanged; procedure DeinitializeDesigner(ARoot: TComponent); function GetCanPrint: Boolean; function GetCaption: string; function GetDesignerState: TDesignerState; function GetFont: TPersistent; function GetForm: TComponent; function GetFormImage: TObject; function GetScrollPos(Horiz: Boolean): Integer; function GetVisible: Boolean; function GetWindowState: TShowState; procedure HideWindow; function IsMenuKey(var Message: TWMKey): Boolean; procedure SetCaption(const ACaption: string); procedure SetDesigner(const ADesigner: IInterface); procedure SetDesigning(DesignMode: Boolean); procedure Show; procedure ShowWindow(AShowState: TShowState); procedure SetFormDefaults(ARoot: TComponent; const ARootName: string; X, Y: Integer; Scale: Boolean); procedure Unmodify; property Caption: string read GetCaption write SetCaption; property Visible: Boolean read GetVisible; end; { Designer selection } type { This is the default implementation of IDesignerSelections } TDesignerSelections = class(TInterfacedObject, IDesignerSelections) private FList: TList; protected function Add(const Item: TPersistent): Integer; function Equals(const List: IDesignerSelections): Boolean; reintroduce; function Get(Index: Integer): TPersistent; function GetDesignObject(Index: Integer): IDesignObject; function GetCount: Integer; property Count: Integer read GetCount; property Items[Index: Integer]: TPersistent read Get; default; public constructor Create; virtual; constructor Copy(const Selections: IDesignerSelections); destructor Destroy; override; end; function CreateSelectionList: IDesignerSelections; const MaxIdentLength = 63; { Designer types } type { TEditAction previously had eaBringToFront, eaSendToBack, etc. This has been replaced by a new OTA mechanism. See TOTAAffect. } TEditAction = (eaUndo, eaRedo, eaCut, eaCopy, eaPaste, eaDelete, eaSelectAll, eaPrint, eaElide); TEditStates = (esCanUndo, esCanRedo, esCanCut, esCanCopy, esCanPaste, esCanDelete, esCanEditOle, esCanPrint, esCanSelectAll, esCanCreateTemplate, esCanElide); TEditState = set of TEditStates; {$ENDIF} IImplementation = interface ['{F9D448F2-50BC-11D1-9FB5-0020AF3D82DA}'] function GetInstance: TObject; end; {$IFNDEF PARSER_TEST} IEditHandler = interface ['{7ED7BF2D-E349-11D3-AB4A-00C04FB17A72}'] function EditAction(Action: TEditAction): Boolean; function GetEditState: TEditState; end; IDesignEditQuery = IEditHandler; // For compatiblity with v5.0 {$IFDEF LINUX} TThreadAffinity = (taQT, taWine); IDesignerThreadAffinity = interface ['{7ED7BF2D-E449-11D3-A84A-00C05FB1767A}'] function GetThreadAffinity: TThreadAffinity; end; {$ENDIF} { ForceDemandLoadState Call this function to override the automatic demand-load state detection logic in the IDE. This is useful in the rare occasions where the IDE may disqualify a package from being demand-loaded when in-fact it can be. Cases that cause a package to automatically be disqualified are: o Registering a component from outside the package group o Registering a property/component/selection editor that applies to components outside the package group. o Registering an old Open Tools API style Expert o Modifying the main IDE menus o Not registering any components or property/component/selection editors, as in cases where the package just contains IDE enhancements o Registering an IOTAMenuWizard since the IDE cannot determine the proper values of the GetState call when the package is not loaded A "package group" is defined as the package being loaded and all packages directly or indirectly required by that package except for IDE packages. For instance, vclxx.bpl is considered an IDE package in this case since it is loaded and required by the IDE. It should go without saying, that forcing a package to demand-load when it was disqualified by the IDE *may* cause unpredictable behaviour. IMPORTANT NOTE: Many packages contain multiple "Register" procedures from various units within the design-time package. Calling this function from *any* Register procedure applies to the entire package as a whole. Also, the *first* caller takes precedence and any subsequent callers *must* pass the same value for the DemandLoadState or an exception is raised and the package cannot be loaded. The default DemandLoadState is dlDefault which causes the IDE to automatically decide the demand-load fate of the package. EnableDemandLoadReport Call this function to tell the IDE to generate a report that describes all the reasons why a package was disqualified from being demand-loaded, if it was actually disqualified. Passing True to the Detailed flag will cause the IDE to include a complete report of what the package registered regardless if the package qualified for demand-loading or not. NOTE: As with ForceDemandLoadState, the first caller of EnableDemandLoadReport takes precedence and will set the Detailed flag accordingly. Any subsequent calls, unlike ForceDemandLoadState, are ignored. } type TDemandLoadState = (dlDefault, dlDisable, dlEnable); TForceDemandLoadStateProc = procedure (DemandLoadState: TDemandLoadState); TEnableDemandLoadReportProc = procedure (Detailed: Boolean); var ForceDemandLoadStateProc: TForceDemandLoadStateProc; EnableDemandLoadReportProc: TEnableDemandLoadReportProc; procedure ForceDemandLoadState(DemandLoadState: TDemandLoadState); procedure EnableDemandLoadReport(Detailed: Boolean); {$IFDEF MSWINDOWS} type { Drag drop interface } TDragTarget = class private FDesigner: IDesigner; public constructor Create(const ADesigner: IDesigner); virtual; function DragOver(Target, Source: TObject; X, Y: Integer; State: TDragState): Boolean; virtual; abstract; procedure DragDrop(Target, Source: TObject; X, Y: Integer); virtual; abstract; property Designer: IDesigner read FDesigner; end; TDragTargetClass = class of TDragTarget; TRegisterDragTargetProc = procedure(const SourceName: string; TargetClass: TDragTargetClass); var RegisterDragTargetProc: TRegisterDragTargetProc; procedure RegisterDragTarget(const SourceName: string; TargetClass: TDragTargetClass); type TRegisterDesignDragObject = procedure (DragObjectClass: TDragObjectClass); var RegisterDesignDragObjectProc: TRegisterDesignDragObject; procedure RegisterDesignDragObject(DragObjectClass: TDragObjectClass); type TRegisterIDropTarget = procedure (const ADropTarget: IDropTarget); var RegisterIDropTargetProc: TRegisterIDropTarget; procedure RegisterIDropTarget(const ADropTarget: IDropTarget); {$ENDIF} function PersistentToDesignObject(APersistent: TPersistent): IDesignObject; type // Base wrapper for IClass TClassWrapper = class(TInterfacedObject, IClass) private FClass: TClass; protected function ClassNameIs(const AClassName: string): Boolean; function GetClassName: string; function GetClassParent: IClass; function GetUnitName: string; public constructor Create(AClass: TClass); end; { TDesignerGuideType - Describes how to handle the a particular guide line type or style. For the gtAlignLeft, gtAlignTop, gtAlignRight, gtAlignBottom types, they must match another guideline of the same type. For the gtMarginLeft, gtMarginTop, gtMarginRight, gtMarginBottom types, they must match one of the opposite type (ie. gtMarginTop matches gtMarginBottom). Use the gtBaseline type to indicate some important internal feature of the control such as the text baseline on a button or edit control. } TDesignerGuideType = (gtAlignLeft, gtAlignTop, gtAlignRight, gtAlignBottom, gtMarginLeft, gtMarginTop, gtMarginRight, gtMarginBottom, gtPaddingLeft, gtPaddingTop, gtPaddingRight, gtPaddingBottom, gtBaseline); IComponentGuidelines = interface ['{237413D7-F6B8-4B8D-B581-3CDC320CE854}'] { Returns the number of guide lines described by this interface instance } function GetCount: Integer; { Returns the index'ed designer guide type } function GetDesignerGuideType(Index: Integer): TDesignerGuideType; { Returns the index'ed designer guide offset. This is the offset from the control origin. It can be negative to describe guidelines that exist to the top and left of a control. } function GetDesignerGuideOffset(Index: Integer): Integer; property Count: Integer read GetCount; property DesignerGuideTypes[Index: Integer]: TDesignerGuideType read GetDesignerGuideType; property DesignerGuideOffsets[Index: Integer]: Integer read GetDesignerGuideOffset; end; TBaseComponentGuidelines = class(TInterfacedObject) private FDesigner: IDesigner; public constructor Create(const ADesigner: IDesigner); virtual; procedure Initialize(AComponent: TComponent; AContainer: TComponent); virtual; abstract; property Designer: IDesigner read FDesigner; end; TComponentGuidelinesClass = class of TBaseComponentGuidelines; TRegisterComponentGuidelines = procedure (AComponentClass: TComponentClass; AComponentGuidelineClass: TComponentGuidelinesClass); var RegisterComponentGuidelinesProc: TRegisterComponentGuidelines; procedure RegisterComponentGuidelines(AComponentClass: TComponentClass; AComponentGuidelinesClass: TComponentGuidelinesClass); {$ENDIF} //IFNDEF PARSER_TEST implementation { TEventInfo } constructor TEventInfo.Create(APropInfo: PPropInfo); begin inherited Create; Initialize(GetTypeData(APropInfo.PropType^)); end; constructor TEventInfo.Create(ATypeData: PTypeData); begin inherited Create; Initialize(ATypeData); end; function TEventInfo.GetMethodKind: TMethodKind; begin Result := FMethodKind; end; function TEventInfo.GetParamCount: Integer; begin Result := Length(FParamNames); end; function TEventInfo.GetParamFlags(Index: Integer): TParamFlags; begin Result := FParamFlags[Index]; end; function TEventInfo.GetParamName(Index: Integer): string; begin Result := FParamNames[Index]; end; function TEventInfo.GetParamType(Index: Integer): string; begin Result := FParamTypes[Index]; end; function TEventInfo.GetResultType: string; begin Result := FResultType; end; procedure TEventInfo.Initialize(ATypeData: PTypeData); type PParamFlags = ^TParamFlags; var I: Integer; Data: PAnsiChar; begin FMethodKind := TMethodKind(Byte(ATypeData.MethodKind) and not $10); SetLength(FParamNames, ATypeData.ParamCount); SetLength(FParamTypes, ATypeData.ParamCount); SetLength(FParamFlags, ATypeData.ParamCount); Data := ATypeData.ParamList; for I := 0 to Length(FParamNames) - 1 do begin FParamFlags[I] := PParamFlags(Data)^; Inc(Data, SizeOf(TParamFlags)); FParamNames[I] := UTF8ToString(PShortString(Data)^); Inc(Data, Length(PShortString(Data)^) + 1); FParamTypes[I] := UTF8ToString(PShortString(Data)^); Inc(Data, Length(PShortString(Data)^) + 1); end; FResultType := UTF8ToString(PShortString(Data)^); end; {$IFNDEF PARSER_TEST} type TDesignObject = class(TInterfacedObject, IDesignObject, IDesignPersistent) private FPersistent: TPersistent; protected { IDesignObject } function Equals(Obj: TObject): Boolean; overload; override; function Equals(const ADesignObject: IDesignObject): Boolean; reintroduce; overload; function GetClassName: string; function GetClassType: IClass; function GetComponentIndex: Integer; function GetComponentName: string; function GetIsComponent: Boolean; function GetNamePath: string; { IDesignPersistent } function GetPersistent: TPersistent; public constructor Create(APersistent: TPersistent); end; procedure RegisterPropertyMapper(Mapper: TPropertyMapperFunc); begin if Assigned(RegisterPropertyMapperProc) then RegisterPropertyMapperProc(Mapper); end; procedure RegisterPropertyInCategory(const CategoryName, PropertyName: string); overload; begin if Assigned(RegisterPropertyInCategoryProc) then RegisterPropertyInCategoryProc(CategoryName, nil, nil, PropertyName); end; procedure RegisterPropertyInCategory(const CategoryName: string; ComponentClass: TClass; const PropertyName: string); overload; begin if Assigned(RegisterPropertyInCategoryProc) then RegisterPropertyInCategoryProc(CategoryName, ComponentClass, nil, PropertyName); end; procedure RegisterPropertyInCategory(const CategoryName: string; PropertyType: PTypeInfo; const PropertyName: string); overload; begin if Assigned(RegisterPropertyInCategoryProc) then RegisterPropertyInCategoryProc(CategoryName, nil, PropertyType, PropertyName); end; procedure RegisterPropertyInCategory(const CategoryName: string; PropertyType: PTypeInfo); overload; begin if Assigned(RegisterPropertyInCategoryProc) then RegisterPropertyInCategoryProc(CategoryName, nil, PropertyType, ''); end; procedure RegisterPropertiesInCategory(const CategoryName: string; const Filters: array of const); overload; var I: Integer; begin if Assigned(RegisterPropertyInCategoryProc) then for I := Low(Filters) to High(Filters) do with Filters[I] do case vType of vtPointer: RegisterPropertyInCategoryProc(CategoryName, nil, PTypeInfo(vPointer), ''); vtClass: RegisterPropertyInCategoryProc(CategoryName, vClass, nil, ''); vtAnsiString: RegisterPropertyInCategoryProc(CategoryName, nil, nil, string(vAnsiString)); vtUnicodeString: RegisterPropertyInCategoryProc(CategoryName, nil, nil, string(vUnicodeString)); else raise Exception.CreateResFmt(@sInvalidFilter, [I, vType]); end; end; procedure RegisterPropertiesInCategory(const CategoryName: string; ComponentClass: TClass; const Filters: array of string); overload; var I: Integer; begin if Assigned(RegisterPropertyInCategoryProc) then for I := Low(Filters) to High(Filters) do RegisterPropertyInCategoryProc(CategoryName, ComponentClass, nil, Filters[I]); end; procedure RegisterPropertiesInCategory(const CategoryName: string; PropertyType: PTypeInfo; const Filters: array of string); overload; var I: Integer; begin if Assigned(RegisterPropertyInCategoryProc) then for I := Low(Filters) to High(Filters) do RegisterPropertyInCategoryProc(CategoryName, nil, PropertyType, Filters[I]); end; { Design notification registration } procedure RegisterDesignNotification(const DesignNotification: IDesignNotification); begin if Assigned(RegisterDesignNotificationProc) then RegisterDesignNotificationProc(DesignNotification); end; procedure UnregisterDesignNotification(const DesignNotification: IDesignNotification); begin if Assigned(UnregisterDesignNotificationProc) then UnregisterDesignNotificationProc(DesignNotification); end; { TBasePropertyEditor } constructor TBasePropertyEditor.Create(const ADesigner: IDesigner; APropCount: Integer); begin inherited Create; end; { TBaseComponentEditor } constructor TBaseComponentEditor.Create(AComponent: TComponent; ADesigner: IDesigner); begin inherited Create; end; procedure RegisterComponentEditor(ComponentClass: TComponentClass; ComponentEditor: TComponentEditorClass); begin if Assigned(RegisterComponentEditorProc) then RegisterComponentEditorProc(ComponentClass, ComponentEditor); end; { TDesignerSelections } function TDesignerSelections.Add(const Item: TPersistent): Integer; begin Result := FList.Add(Item); end; constructor TDesignerSelections.Copy(const Selections: IDesignerSelections); var I: Integer; begin Create; for I := 0 to Selections.Count - 1 do Add(Selections[I]); end; constructor TDesignerSelections.Create; begin inherited; FList := TList.Create; end; destructor TDesignerSelections.Destroy; begin FList.Free; inherited; end; function TDesignerSelections.Equals(const List: IDesignerSelections): Boolean; var I: Integer; begin Result := False; if List.Count <> Count then Exit; for I := 0 to Count - 1 do if Items[I] <> List[I] then Exit; Result := True; end; function TDesignerSelections.Get(Index: Integer): TPersistent; begin Result := TPersistent(FList[Index]); end; function TDesignerSelections.GetDesignObject(Index: Integer): IDesignObject; begin Result := TDesignObject.Create(Get(Index)); end; function TDesignerSelections.GetCount: Integer; begin Result := FList.Count; end; function CreateSelectionList: IDesignerSelections; begin Result := TDesignerSelections.Create; end; procedure RegisterPropertyEditor(PropertyType: PTypeInfo; ComponentClass: TClass; const PropertyName: string; EditorClass: TPropertyEditorClass); begin if Assigned(RegisterPropertyEditorProc) then RegisterPropertyEditorProc(PropertyType, ComponentClass, PropertyName, EditorClass); end; procedure SetPropertyEditorGroup(EditorClass: TPropertyEditorClass; GroupClass: TPersistentClass); begin if Assigned(SetPropertyEditorGroupProc) then SetPropertyEditorGroupProc(EditorClass, GroupClass); end; procedure UnlistPublishedProperty(ComponentClass: TClass; const PropertyName: string); var LPropInfo: PPropInfo; begin LPropInfo := GetPropInfo(ComponentClass, PropertyName); if LPropInfo <> nil then RegisterPropertyEditor(LPropInfo^.PropType^, ComponentClass, PropertyName, nil); end; { TBaseSelectionEditor } constructor TBaseSelectionEditor.Create(const ADesigner: IDesigner); begin inherited Create; end; procedure RegisterSelectionEditor(AClass: TClass; AEditor: TSelectionEditorClass); begin if Assigned(RegisterSelectionEditorProc) then RegisterSelectionEditorProc(AClass, AEditor); end; { TBaseCustomModule } constructor TBaseCustomModule.Create(ARoot: TComponent; const Designer: IDesigner); begin inherited Create; end; class function TBaseCustomModule.DesignClass: TComponentClass; begin Result := nil; end; procedure RegisterCustomModule(ComponentBaseClass: TComponentClass; CustomModuleClass: TCustomModuleClass); begin if Assigned(RegisterCustomModuleProc) then RegisterCustomModuleProc(CurrentGroup, ComponentBaseClass, CustomModuleClass); end; procedure ForceDemandLoadState(DemandLoadState: TDemandLoadState); begin if Assigned(ForceDemandLoadStateProc) then ForceDemandLoadStateProc(DemandLoadState); end; procedure EnableDemandLoadReport(Detailed: Boolean); begin if Assigned(EnableDemandLoadReportProc) then EnableDemandLoadReportProc(Detailed); end; {$IFDEF MSWINDOWS} { TDragTarget } constructor TDragTarget.Create(const ADesigner: IDesigner); begin inherited Create; FDesigner := ADesigner; end; procedure RegisterDragTarget(const SourceName: string; TargetClass: TDragTargetClass); begin if Assigned(RegisterDragTargetProc) then RegisterDragTargetProc(SourceName, TargetClass); end; procedure RegisterDesignDragObject(DragObjectClass: TDragObjectClass); begin if Assigned(RegisterDesignDragObjectProc) then RegisterDesignDragObjectProc(DragObjectClass); end; procedure RegisterIDropTarget(const ADropTarget: IDropTarget); begin if Assigned(RegisterIDropTargetProc) then RegisterIDropTargetProc(ADropTarget); end; {$ENDIF} { TDesignObject } constructor TDesignObject.Create(APersistent: TPersistent); begin inherited Create; FPersistent := APersistent; end; function TDesignObject.Equals(Obj: TObject): Boolean; begin Result := Obj = FPersistent; end; function TDesignObject.Equals(const ADesignObject: IDesignObject): Boolean; var DesignPersistent: IDesignPersistent; begin Result := Supports(ADesignObject, IDesignPersistent, DesignPersistent) and (DesignPersistent.Persistent = FPersistent); end; function TDesignObject.GetClassName: string; begin Result := FPersistent.ClassName; end; function TDesignObject.GetClassType: IClass; begin Result := TClassWrapper.Create(FPersistent.ClassType) as IClass; end; function TDesignObject.GetComponentIndex: Integer; begin if GetIsComponent then Result := TComponent(FPersistent).ComponentIndex else Result := -1; end; function TDesignObject.GetComponentName: string; begin if GetIsComponent then Result := TComponent(FPersistent).Name else Result := GetClassName; end; function TDesignObject.GetIsComponent: Boolean; begin Result := FPersistent is TComponent; end; function TDesignObject.GetNamePath: string; begin Result := FPersistent.GetNamePath; end; function TDesignObject.GetPersistent: TPersistent; begin Result := FPersistent; end; function PersistentToDesignObject(APersistent: TPersistent): IDesignObject; begin Result := TDesignObject.Create(APersistent) as IDesignObject; end; { TClassWrapper } function TClassWrapper.ClassNameIs(const AClassName: string): Boolean; begin Result := FClass.ClassNameIs(AClassName); end; constructor TClassWrapper.Create(AClass: TClass); begin inherited Create; FClass := AClass; end; function TClassWrapper.GetClassName: string; begin Result := FClass.ClassName; end; function TClassWrapper.GetClassParent: IClass; begin if FClass.ClassParent <> nil then Result := TClassWrapper.Create(FClass.ClassParent) as IClass else Result := nil; end; function TClassWrapper.GetUnitName: string; begin Result := FClass.UnitName; end; { TBaseComponentGuidelines } constructor TBaseComponentGuidelines.Create(const ADesigner: IDesigner); begin inherited Create; FDesigner := ADesigner; end; procedure RegisterComponentGuidelines(AComponentClass: TComponentClass; AComponentGuidelinesClass: TComponentGuidelinesClass); begin if Assigned(RegisterComponentGuideLinesProc) then RegisterComponentGuidelinesProc(AComponentClass, AComponentGuidelinesClass); end; {$ENDIF} // IFNDEF PARSER_TEST end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC error handling support } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Stan.Error; interface uses System.Classes, Data.DB, System.SysUtils, FireDAC.Stan.Intf; type EFDException = class; TFDDBError = class; EFDDBEngineException = class; EFDDBArrayExecuteError = class; EFDExceptionClass = class of EFDException; TFDDBErrorClass = class of TFDDBError; EFDDBEngineExceptionClass = class of EFDDBEngineException; EFDException = class(EDatabaseError) private FFDCode: Integer; FFDObjName: String; protected procedure SetFDObjectName(const AValue: IFDStanObject); procedure LoadFromStorage(const AStorage: IFDStanStorage); virtual; procedure SaveToStorage(const AStorage: IFDStanStorage); virtual; public constructor Create; overload; virtual; constructor Create(AFDCode: Integer; const AMessage: String); overload; procedure Duplicate(var AValue: EFDException); virtual; property FDCode: Integer read FFDCode write FFDCode; property FDObjName: String read FFDObjName write FFDObjName; end; TFDCommandExceptionKind = (ekOther, ekNoDataFound, ekTooManyRows, ekRecordLocked, ekUKViolated, ekFKViolated, ekObjNotExists, ekUserPwdInvalid, ekUserPwdExpired, ekUserPwdWillExpire, ekCmdAborted, ekServerGone, ekServerOutput, ekArrExecMalfunc, ekInvalidParams); TFDDBError = class(TObject) private FMessage: string; FErrorCode: Integer; FLevel: Integer; FObjName: String; FKind: TFDCommandExceptionKind; FCommandTextOffset: Integer; FRowIndex: Integer; protected procedure Assign(ASrc: TFDDBError); virtual; procedure LoadFromStorage(const AStorage: IFDStanStorage); virtual; procedure SaveToStorage(const AStorage: IFDStanStorage); virtual; public constructor Create; overload; virtual; constructor Create(ALevel, AErrorCode: Integer; const AMessage, AObjName: String; AKind: TFDCommandExceptionKind; ACmdOffset, ARowIndex: Integer); overload; virtual; property ErrorCode: Integer read FErrorCode write FErrorCode; property Kind: TFDCommandExceptionKind read FKind write FKind; property Level: Integer read FLevel write FLevel; property Message: String read FMessage write FMessage; property ObjName: String read FObjName write FObjName; property CommandTextOffset: Integer read FCommandTextOffset write FCommandTextOffset; property RowIndex: Integer read FRowIndex write FRowIndex; end; EFDDBEngineException = class(EFDException) private FItems: TFDObjList; FParams: TStrings; FSQL: String; function GetErrors(AIndex: Integer): TFDDBError; function GetErrorCount: Integer; function GetKind: TFDCommandExceptionKind; function GetErrorCode: Integer; procedure SetParams(const AValue: TStrings); protected procedure SetSQLAndParams(const AValue: IFDMoniAdapter); procedure LoadFromStorage(const AStorage: IFDStanStorage); override; procedure SaveToStorage(const AStorage: IFDStanStorage); override; function GetErrorClass: TFDDBErrorClass; virtual; function AppendError: TFDDBError; overload; public constructor Create; overload; override; constructor Create(AADCode: Integer; const AMessage: String); overload; destructor Destroy; override; function AppendError(ALevel, AErrorCode: Integer; const AMessage, AObjName: String; AKind: TFDCommandExceptionKind; ACmdOffset, ARowIndex: Integer): TFDDBError; overload; procedure Duplicate(var AValue: EFDException); override; procedure Append(AItem: TFDDBError); procedure Remove(AItem: TFDDBError); procedure Clear; procedure Merge(AValue: EFDDBEngineException; AIndex: Integer); property ErrorCount: Integer read GetErrorCount; property Errors[Index: Integer]: TFDDBError read GetErrors; default; property ErrorCode: Integer read GetErrorCode; property Kind: TFDCommandExceptionKind read GetKind; property Params: TStrings read FParams write SetParams; property SQL: String read FSQL write FSQL; end; EFDDBArrayExecuteError = class(EFDException) private FTimes: Integer; FOffset: Integer; FAction: TFDErrorAction; FException: EFDDBEngineException; FRetryLevel: Integer; public constructor Create(ATimes, AOffset: Integer; AException: EFDDBEngineException; ARetryLevel: Integer); overload; property Times: Integer read FTimes; property Offset: Integer read FOffset; property Exception: EFDDBEngineException read FException; property RetryLevel: Integer read FRetryLevel; property Action: TFDErrorAction read FAction write FAction; end; TFDErrorEvent = procedure (ASender, AInitiator: TObject; var AException: Exception) of object; procedure FDException(AObj: TObject; AEx: EFDException {$IFDEF FireDAC_Monitor}; ATracing: Boolean {$ENDIF}); overload; function FDExceptionLayers(const ALayers: array of String): String; function FDGetErrorMessage(ACode: Integer; const AArgs: array of const): String; procedure FDException(AObj: TObject; const ALayers: array of String; ACode: Integer; const AArgs: array of const); overload; procedure FDCapabilityNotSupported(AObj: TObject; const ALayers: array of String); function FDDBEngineExceptionLoad(const AStorage: IFDStanStorage): TObject; function FDDBEngineExceptionCreate(AClass: EFDDBEngineExceptionClass; ACode: Integer; const AArgs: array of const): EFDDBEngineException; function FDExceptionLoad(const AStorage: IFDStanStorage): TObject; procedure FDExceptionSave(AObject: TObject; const AStorage: IFDStanStorage); implementation uses System.Generics.Collections, System.Types, FireDAC.Stan.Consts, FireDAC.Stan.ResStrs, FireDAC.Stan.Util; {-------------------------------------------------------------------------------} { Utilities } {-------------------------------------------------------------------------------} procedure FDException(AObj: TObject; AEx: EFDException {$IFDEF FireDAC_Monitor}; ATracing: Boolean {$ENDIF}); var oHndlr: IFDStanErrorHandler; oMAIntf: IFDMoniAdapter; oEx: Exception; oObj: IFDStanObject; begin if (AEx is EFDDBEngineException) and Supports(AObj, IFDMoniAdapter, oMAIntf) and (oMAIntf.SupportItems * [ikSQL, ikParam] = [ikSQL, ikParam]) then EFDDBEngineException(AEx).SetSQLAndParams(oMAIntf); if Supports(AObj, IFDStanObject, oObj) then AEx.SetFDObjectName(oObj); oEx := Exception(AEx); if Supports(AObj, IFDStanErrorHandler, oHndlr) then try oHndlr.HandleException(oObj, oEx); except on E: Exception do begin if (E <> oEx) and (oEx <> nil) then FDFree(oEx); raise; end; end; if oEx <> nil then begin {$IFDEF FireDAC_Monitor} // The monitor client messages queue may be not empty. When an exception // is raised and an IDE is stopped, the queue remains not empty and // FDMonitor does not show error message. So, give the CPU to other threads. if ATracing then Sleep(50); {$ENDIF} raise oEx at ReturnAddress; end; end; {-------------------------------------------------------------------------------} function FDExceptionLayers(const ALayers: array of String): String; var i: Integer; begin Result := '[FireDAC]'; for i := Low(ALayers) to High(ALayers) do Result := Result + '[' + ALayers[i] + ']'; end; {-------------------------------------------------------------------------------} function FDGetErrorMessage(ACode: Integer; const AArgs: array of const): String; function CheckCustomMessage(const AStdMessage: String): String; begin if TVarRec(AArgs[1]).VInteger = 1 then Result := AStdMessage else {$IFDEF NEXTGEN} Result := String(TVarRec(AArgs[0]).VUnicodeString); {$ELSE} Result := String(TVarRec(AArgs[0]).VAnsiString); {$ENDIF} end; begin case ACode of er_FD_DuplicatedName: Result := S_FD_DuplicatedName; er_FD_NameNotFound: Result := S_FD_NameNotFound; er_FD_ColTypeUndefined: Result := S_FD_ColTypeUndefined; er_FD_NoColsDefined: Result := S_FD_NoColsDefined; er_FD_CheckViolated: Result := CheckCustomMessage(S_FD_CheckViolated); er_FD_CantBeginEdit: Result := S_FD_CantBeginEdit; er_FD_CantCreateChildView: Result := S_FD_CantCreateChildView; er_FD_RowCantBeDeleted: Result := S_FD_RowCantBeDeleted; er_FD_ColMBBLob: Result := S_FD_ColMBBLob; er_FD_FixedLenDataMismatch: Result := S_FD_FixedLenDataMismatch; er_FD_RowNotInEditableState: Result := S_FD_RowNotInEditableState; er_FD_ColIsReadOnly: Result := S_FD_ColIsReadOnly; er_FD_RowCantBeInserted: Result := S_FD_RowCantBeInserted; er_FD_RowColMBNotNull: Result := S_FD_RowColMBNotNull; er_FD_DuplicateRows: Result := CheckCustomMessage(S_FD_DuplicateRows); er_FD_NoMasterRow: Result := CheckCustomMessage(S_FD_NoMasterRow); er_FD_HasChildRows: Result := CheckCustomMessage(S_FD_HasChildRows); er_FD_CantCompareRows: Result := S_FD_CantCompareRows; er_FD_ConvIsNotSupported: Result := S_FD_ConvIsNotSupported; er_FD_ColIsNotSearchable: Result := S_FD_ColIsNotSearchable; er_FD_RowMayHaveSingleParent: Result := S_FD_RowMayHaveSingleParent; er_FD_CantOperateInvObj: Result := S_FD_CantOperateInvObj; er_FD_CantSetParentRow: Result := S_FD_CantSetParentRow; er_FD_RowIsNotNested: Result := S_FD_RowIsNotNested; er_FD_ColumnIsNotRef: Result := S_FD_ColumnIsNotRef; er_FD_ColumnIsNotSetRef: Result := S_FD_ColumnIsNotSetRef; er_FD_OperCNBPerfInState: Result := S_FD_OperCNBPerfInState; er_FD_CantSetUpdReg: Result := S_FD_CantSetUpdReg; er_FD_TooManyAggs: Result := S_FD_TooManyAggs; er_FD_GrpLvlExceeds: Result := S_FD_GrpLvlExceeds; er_FD_VarLenDataMismatch: Result := S_FD_VarLenDataMismatch; er_FD_BadForeignKey: Result := S_FD_BadForeignKey; er_FD_BadUniqueKey: Result := S_FD_BadUniqueKey; er_FD_CantChngColType: Result := S_FD_CantChngColType; er_FD_BadRelation: Result := S_FD_BadRelation; er_FD_CantCreateParentView: Result := S_FD_CantCreateParentView; er_FD_CantChangeTableStruct: Result := S_FD_CantChangeTableStruct; er_FD_FoundCascadeLoop: Result := S_FD_FoundCascadeLoop; er_FD_RecLocked: Result := S_FD_RecLocked; er_FD_RecNotLocked: Result := S_FD_RecNotLocked; er_FD_TypeIncompat: Result := S_FD_TypeIncompat; er_FD_ValueOutOfRange: Result := S_FD_ValueOutOfRange; er_FD_CantMerge: Result := S_FD_CantMerge; er_FD_ColumnDoesnotFound: Result := S_FD_ColumnDoesnotFound; er_FD_ExprTermination: Result := S_FD_ExprTermination; er_FD_ExprMBAgg: Result := S_FD_ExprMBAgg; er_FD_ExprCantAgg: Result := S_FD_ExprCantAgg; er_FD_ExprTypeMis: Result := S_FD_ExprTypeMis; er_FD_ExprIncorrect: Result := S_FD_ExprIncorrect; er_FD_InvalidKeywordUse: Result := S_FD_InvalidKeywordUse; er_FD_ExprInvalidChar: Result := S_FD_ExprInvalidChar; er_FD_ExprNameError: Result := S_FD_ExprNameError; er_FD_ExprStringError: Result := S_FD_ExprStringError; er_FD_ExprNoLParen: Result := S_FD_ExprNoLParen; er_FD_ExprNoRParenOrComma: Result := S_FD_ExprNoRParenOrComma; er_FD_ExprNoRParen: Result := S_FD_ExprNoRParen; er_FD_ExprEmptyInList: Result := S_FD_ExprEmptyInList; er_FD_ExprExpected: Result := S_FD_ExprExpected; er_FD_ExprNoArith: Result := S_FD_ExprNoArith; er_FD_ExprBadScope: Result := S_FD_ExprBadScope; er_FD_ExprEmpty: Result := S_FD_ExprEmpty; er_FD_ExprEvalError: Result := S_FD_ExprEvalError; er_FD_DSNoBookmark: Result := S_FD_DSNoBookmark; er_FD_DSViewNotSorted: Result := S_FD_DSViewNotSorted; er_FD_DSNoAdapter: Result := S_FD_DSNoAdapter; er_FD_DSNoNestedMasterSource: Result := S_FD_DSNoNestedMasterSource; er_FD_DSCircularDataLink: Result := S_FD_DSCircularDataLink; er_FD_DSRefreshError: Result := S_FD_DSRefreshError; er_FD_DSNoDataTable: Result := S_FD_DSNoDataTable; er_FD_DSIndNotFound: Result := S_FD_DSIndNotFound; er_FD_DSAggNotFound: Result := S_FD_DSAggNotFound; er_FD_DSIndNotComplete: Result := S_FD_DSIndNotComplete; er_FD_DSAggNotComplete: Result := S_FD_DSAggNotComplete; er_FD_DSCantUnidir: Result := S_FD_DSCantUnidir; er_FD_DSIncompatBmkFields: Result := S_FD_DSIncompatBmkFields; er_FD_DSCantEdit: Result := S_FD_DSCantEdit; er_FD_DSCantInsert: Result := S_FD_DSCantInsert; er_FD_DSCantDelete: Result := S_FD_DSCantDelete; er_FD_DSFieldNotFound: Result := S_FD_DSFieldNotFound; er_FD_DSCantOffline: Result := S_FD_DSCantOffline; er_FD_DSCantOffCachedUpdates: Result := S_FD_DSCantOffCachedUpdates; er_FD_DefCircular: Result := S_FD_DefCircular; er_FD_DefRO: Result := S_FD_DefRO; er_FD_DefCantMakePers: Result := S_FD_DefCantMakePers; er_FD_DefAlreadyLoaded: Result := S_FD_DefAlreadyLoaded; er_FD_DefNotExists: Result := S_FD_DefNotExists; er_FD_DefDupName: Result := S_FD_DefDupName; er_FD_AccSrvNotFound: Result := S_FD_AccSrvNotFound; er_FD_AccCannotReleaseDrv: Result := S_FD_AccCannotReleaseDrv; er_FD_AccSrvNotDefined: Result := S_FD_AccSrvNotDefined; er_FD_AccSrvMBConnected: Result := S_FD_AccSrvMBConnected; er_FD_AccCapabilityNotSup: Result := S_FD_AccCapabilityNotSup; er_FD_AccTxMBActive: Result := S_FD_AccTxMBActive; er_FD_AccTxMBInActive: Result := S_FD_AccTxMBInActive; er_FD_AccCantChngCommandState: Result := S_FD_AccCantChngCommandState; er_FD_AccCommandMBFilled: Result := S_FD_AccCommandMBFilled; er_FD_AccEscapeEmptyName: Result := S_FD_AccEscapeEmptyName; er_FD_AccCmdMHRowSet: Result := S_FD_AccCmdMHRowSet; er_FD_AccCmdMBPrepared: Result := S_FD_AccCmdMBPrepared; er_FD_AccCantExecCmdWithRowSet: Result := S_FD_AccCantExecCmdWithRowSet; er_FD_AccCmdMBOpen4Fetch: Result := S_FD_AccCmdMBOpen4Fetch; er_FD_AccExactMismatch: Result := S_FD_AccExactMismatch; er_FD_AccMetaInfoMismatch: Result := S_FD_AccMetaInfoMismatch; {$IFDEF CPUX64} er_FD_AccCantLoadLibrary: Result := S_FD_AccCantLoadLibrary + Format(S_FD_AccCantLoadLibraryHint,['x64']); {$ELSE} er_FD_AccCantLoadLibrary: Result := S_FD_AccCantLoadLibrary + Format(S_FD_AccCantLoadLibraryHint,['x86']); {$ENDIF} er_FD_AccCantGetLibraryEntry: Result := S_FD_AccCantGetLibraryEntry; er_FD_AccSrvMBDisConnected: Result := S_FD_AccSrvMBDisConnected; er_FD_AccToManyLogins: Result := S_FD_AccToManyLogins; er_FD_AccDrvMngrMB: Result := S_FD_AccDrvMngrMB; er_FD_AccPrepMissed: Result := S_FD_AccPrepMissed; er_FD_AccPrepTooLongIdent: Result := S_FD_AccPrepTooLongIdent; er_FD_AccParamArrayMismatch: Result := S_FD_AccParamArrayMismatch; er_FD_AccAsyncOperInProgress: Result := S_FD_AccAsyncOperInProgress; er_FD_AccEscapeIsnotSupported: Result := S_FD_AccEscapeIsnotSupported; er_FD_AccMetaInfoReset: Result := S_FD_AccMetaInfoReset; er_FD_AccWhereIsEmpty: Result := S_FD_AccWhereIsEmpty; er_FD_AccUpdateTabUndefined: Result := S_FD_AccUpdateTabUndefined; er_FD_AccNameHasErrors: Result := S_FD_AccNameHasErrors; er_FD_AccEscapeBadSyntax: Result := S_FD_AccEscapeBadSyntax; er_FD_AccShutdownTO: Result := S_FD_AccShutdownTO; er_FD_AccParTypeUnknown: Result := S_FD_AccParTypeUnknown; er_FD_AccParDataMapNotSup: Result := S_FD_AccParDataMapNotSup; er_FD_AccParDefChanged: Result := S_FD_AccParDefChanged; er_FD_AccMetaInfoNotDefined: Result := S_FD_AccMetaInfoNotDefined; er_FD_AccCantAssignTxIntf: Result := S_FD_AccCantAssignTxIntf; er_FD_AccParSetChanged: Result := S_FD_AccParSetChanged; er_FD_AccDataToLarge: Result := S_FD_AccDataToLarge; er_FD_AccDbNotExists: Result := S_FD_AccDbNotExists; er_FD_AccClassNotRegistered: Result := S_FD_AccClassNotRegistered; er_FD_AccSysClassNotRegistered: Result := S_FD_AccSysClassNotRegistered; er_FD_AccUnrecognizedDbFormat: Result := S_FD_AccUnrecognizedDbFormat; er_FD_AccNotValidPassword: Result := S_FD_AccNotValidPassword; er_FD_AccUnknownOleError: Result := S_FD_AccUnknownOleError; er_FD_AccUnsupParamObjValue: Result := S_FD_AccUnsupParamObjValue; er_FD_AccUnsupColumnType: Result := S_FD_AccUnsupColumnType; er_FD_AccLongDataStream: Result := S_FD_AccLongDataStream; er_FD_AccArrayDMLWithIntStr: Result := S_FD_AccArrayDMLWithIntStr; er_FD_SvcLinkMBSet: Result := S_FD_SvcLinkMBSet; er_FD_SvcMBActive: Result := S_FD_SvcMBActive; er_FD_SvcCannotUninstall: Result := S_FD_SvcCannotUninstall; er_FD_DAptRecordIsDeleted: Result := S_FD_DAptRecordIsDeleted; er_FD_DAptNoSelectCmd: Result := S_FD_DAptNoSelectCmd; er_FD_DAptApplyUpdateFailed: Result := S_FD_DAptApplyUpdateFailed; er_FD_DAptCantEdit: Result := S_FD_DAptCantEdit; er_FD_DAptCantInsert: Result := S_FD_DAptCantInsert; er_FD_DAptCantDelete: Result := S_FD_DAptCantDelete; er_FD_ClntSessMBSingle: Result := S_FD_ClntSessMBSingle; er_FD_ClntSessMBInactive: Result := S_FD_ClntSessMBInactive; er_FD_ClntSessMBActive: Result := S_FD_ClntSessMBActive; er_FD_ClntDbDupName: Result := S_FD_ClntDbDupName; er_FD_ClntDbMBInactive: Result := S_FD_ClntDbMBInactive; er_FD_ClntDbMBActive: Result := S_FD_ClntDbMBActive; er_FD_ClntDbLoginAborted: Result := S_FD_ClntDbLoginAborted; er_FD_ClntDbCantConnPooled: Result := S_FD_ClntDbCantConnPooled; er_FD_ClntDBNotFound: Result := S_FD_ClntDBNotFound; er_FD_ClntAdaptMBActive: Result := S_FD_ClntAdaptMBActive; er_FD_ClntAdaptMBInactive: Result := S_FD_ClntAdaptMBInactive; er_FD_ClntNotCachedUpdates: Result := S_FD_ClntNotCachedUpdates; er_FD_ClntDbNotDefined: Result := S_FD_ClntDbNotDefined; er_FD_ClntDbMBOnline: Result := S_FD_ClntDbMBOnline; er_FD_ClntTxMBActive: Result := S_FD_AccTxMBActive; er_FD_ClntCantShareAdapt: Result := S_FD_ClntCantShareAdapt; er_FD_ClntConnNotMatch: Result := S_FD_ClntConnNotMatch; er_FD_ClntPKNotFound: Result := S_FD_ClntPKNotFound; er_FD_ClntLocalSQLMisuse: Result := S_FD_ClntLocalSQLMisuse; er_FD_ClntWrongIndex: Result := S_FD_ClntWrongIndex; er_FD_ClntDSNameEmpty: Result := S_FD_ClntDSNameEmpty; er_FD_ClntDSNameNotUnique: Result := S_FD_ClntDSNameNotUnique; er_FD_ClntDataSetParamIncompat: Result := S_FD_ClntDataSetParamIncompat; er_FD_DPNoTxtFld: Result := S_FD_DPNoTxtFld; er_FD_DPNoSrcDS: Result := S_FD_DPNoSrcDS; er_FD_DPNoDestDS: Result := S_FD_DPNoDestDS; er_FD_DPNoTxtDest: Result := S_FD_DPNoTxtDest; er_FD_DPNoTxtSrc: Result := S_FD_DPNoTxtSrc; er_FD_DPBadFixedSize: Result := S_FD_DPBadFixedSize; er_FD_DPTxtFldDup: Result := S_FD_DPTxtFldDup; er_FD_DPBadTextFmt: Result := S_FD_DPBadTextFmt; er_FD_DPSrcUndefined: Result := S_FD_DPSrcUndefined; er_FD_DPDestNoKeyFields: Result := S_FD_DPDestNoKeyFields; er_FD_DPNoSQLTab: Result := S_FD_DPNoSQLTab; er_FD_DPNoSQLBatch: Result := S_FD_DPNoSQLBatch; er_FD_DPNoTxtFlds: Result := S_FD_DPNoTxtFlds; er_FD_DPNoJsonDest: Result := S_FD_DPNoJsonDest; er_FD_DPNoJsonSrc: Result := S_FD_DPNoJsonSrc; er_FD_DPNoJsonFld: Result := S_FD_DPNoJsonFld; er_FD_DPJsonFldDup: Result := S_FD_DPJsonFldDup; er_FD_DPMapUndefined: Result := S_FD_DPMapUndefined; er_FD_StanTimeout: Result := S_FD_StanTimeout; er_FD_StanCantGetBlob: Result := S_FD_StanCantGetBlob; er_FD_StanCantNonblocking: Result := S_FD_StanCantNonblocking; er_FD_StanMacroNotFound: Result := S_FD_StanMacroNotFound; er_FD_StanBadParRowIndex: Result := S_FD_StanBadParRowIndex; er_FD_StanPoolTooManyItems: Result := S_FD_StanPoolTooManyItems; er_FD_StanStrgInvBinFmt: Result := S_FD_StanStrgInvBinFmt; er_FD_StanStrgCantReadProp: Result := S_FD_StanStrgCantReadProp; er_FD_StanStrgCantReadObj: Result := S_FD_StanStrgCantReadObj; er_FD_StanStrgCantReadCDATA: Result := S_FD_StanStrgCantReadCDATA; er_FD_StanStrgDictOverflow: Result := S_FD_StanStrgDictOverflow; er_FD_StanStrgClassUnknown: Result := S_FD_StanStrgClassUnknown; er_FD_StanStrgUnknownFmt: Result := S_FD_StanStrgUnknownFmt; er_FD_StanStrgFileError: Result := S_FD_StanStrgFileError; er_FD_StanStrgInvDIntFmt: Result := S_FD_StanStrgInvDIntFmt; er_FD_StanStrgInvJSONFmt: Result := S_FD_StanStrgInvJSONFmt; er_FD_ScrCantExecHostCmd: Result := S_FD_ScrCantExecHostCmd; er_FD_ScrStrSize1: Result := S_FD_ScrStrSize1; er_FD_ScrStrNotAlphaNum: Result := S_FD_ScrStrNotAlphaNum; er_FD_ScrSetArgInvalid: Result := S_FD_ScrSetArgInvalid; er_FD_ScrInvalidSyntax: Result := S_FD_ScrInvalidSyntax; er_FD_ScrAccMustSpecVar: Result := S_FD_ScrAccMustSpecVar; er_FD_ScrDefReqValue: Result := S_FD_ScrDefReqValue; er_FD_ScrVarMissedCloseBrace: Result := S_FD_ScrVarMissedCloseBrace; er_FD_ScrVarUnsupType: Result := S_FD_ScrVarUnsupType; er_FD_ScrNotLogged: Result := S_FD_ScrNotLogged; er_FD_ScrNoCmds: Result := S_FD_ScrNoCmds; er_FD_ScrNoScript: Result := S_FD_ScrNoScript; er_FD_DBXParMBNotEmpty: Result := S_FD_DBXParMBNotEmpty; er_FD_DBXNoDriverCfg: Result := S_FD_DBXNoDriverCfg; er_FD_MySQLBadVersion: Result := S_FD_MySQLBadVersion; er_FD_MySQLCantSetPort: Result := S_FD_MySQLCantSetPort; er_FD_MySQLBadParams: Result := S_FD_MySQLBadParams; er_FD_MySQLCantInitEmbeddedServer: Result := S_FD_MySQLCantInitEmbeddedServer; er_FD_MySQLFieldDataTypeUnsup: Result := S_FD_MySQLFieldDataTypeUnsup; er_FD_OdbcVarDataTypeUnsup: Result := S_FD_OdbcVarDataTypeUnsup; er_FD_OraNoCursor: Result := S_FD_OraNoCursor; er_FD_OraCantSetCharset: Result := S_FD_OraCantSetCharset; er_FD_OraCantAssFILE: Result := S_FD_OraCantAssFILE; er_FD_OraNoCursorParams: Result := S_FD_OraNoCursorParams; er_FD_OraNotInstalled: Result := S_FD_OraNotInstalled; er_FD_OraBadVersion: Result := S_FD_OraBadVersion; er_FD_OraBadVarType: Result := S_FD_OraBadVarType; er_FD_OraTooLongGTRID: Result := S_FD_OraTooLongGTRID; er_FD_OraTooLongBQUAL: Result := S_FD_OraTooLongBQUAL; er_FD_OraTooLongTXName: Result := S_FD_OraTooLongTXName; er_FD_OraDBTNManyClBraces: Result := S_FD_OraDBTNManyClBraces; er_FD_OraNotPLSQLObj: Result := S_FD_OraNotPLSQLObj; er_FD_OraNotPackageProc: Result := S_FD_OraNotPackageProc; er_FD_OraBadTableType: Result := S_FD_OraBadTableType; er_FD_OraUnNamedRecParam: Result := S_FD_OraUnNamedRecParam; er_FD_OraCantConvNum: Result := S_FD_OraCantConvNum; er_FD_OraPipeAlertToMany: Result := S_FD_OraPipeAlertToMany; er_FD_IBTraceIsActive: Result := S_FD_IBTraceIsActive; er_FD_PgProcNotFound: Result := S_FD_PgProcNotFound; er_FD_PgMultiDimArrNotSup: Result := S_FD_PgMultiDimArrNotSup; er_FD_PgUnsupArrValueTypeNotSup: Result := S_FD_PgUnsupArrValueTypeNotSup; er_FD_PgArrIndexOutOfBound: Result := S_FD_PgArrIndexOutOfBound; er_FD_PgCannotDescribeType: Result := S_FD_PgCannotDescribeType; er_FD_PgIsNotArray: Result := S_FD_PgIsNotArray; er_FD_PgUnsupTextType: Result := S_FD_PgUnsupTextType; er_FD_SQLiteInitFailed: Result := S_FD_SQLiteInitFailed; er_FD_SQLiteDBNotFound: Result := S_FD_SQLiteDBNotFound; er_FD_SQLitePwdInvalid: Result := S_FD_SQLitePwdInvalid; er_FD_SQLiteVTabInvalidArgs: Result := S_FD_SQLiteVTabInvalidArgs; er_FD_SQLiteVTabDSNotFoundOrEmpty: Result := S_FD_SQLiteVTabDSNotFoundOrEmpty; er_FD_SQLiteVTabDSNotSupported: Result := S_FD_SQLiteVTabDSNotSupported; er_FD_SQLiteVTabDSSPNotFound: Result := S_FD_SQLiteVTabDSSPNotFound; er_FD_SQLiteVTabDSDataModFailed: Result := S_FD_SQLiteVTabDSDataModFailed; er_FD_SQLiteVTabDSRowidInvalid: Result := S_FD_SQLiteVTabDSRowidInvalid; er_FD_SQLiteVTabDSChangedOrFreed: Result := S_FD_SQLiteVTabDSChangedOrFreed; er_FD_SQLiteVTabDSNoRowExists: Result := S_FD_SQLiteVTabDSNoRowExists; er_FD_SQLiteVTabDSCursorInvalid: Result := S_FD_SQLiteVTabDSCursorInvalid; er_FD_SQLiteVTabCannotAttach: Result := S_FD_SQLiteVTabCannotAttach; er_FD_SQLiteVTabDataSetBusy: Result := S_FD_SQLiteVTabDataSetBusy; er_FD_ASADBToolNotFound: Result := S_FD_ASADBToolNotFound; er_FD_MSSQLFSNoTx: Result := S_FD_MSSQLFSNoTx; er_FD_MSSQLFSNoPath: Result := S_FD_MSSQLFSNoPath; er_FD_MSSQLFSIOError: Result := S_FD_MSSQLFSIOError; er_FD_MSSQLQNSubError: Result := S_FD_MSSQLQNSubError; er_FD_MongoError: Result := S_FD_MongoError; er_FD_MongoBadURI: Result := S_FD_MongoBadURI; er_FD_MongoDocReadOnly: Result := S_FD_MongoDocReadOnly; er_FD_MongoFailedInitBSON: Result := S_FD_MongoFailedInitBSON; er_FD_MongoBulkError: Result := S_FD_MongoBulkError; er_FD_MongoCursorError: Result := S_FD_MongoCursorError; er_FD_MongoExecuteError: Result := S_FD_MongoExecuteError; er_FD_MongoDBRefInvalid: Result := S_FD_MongoDBRefInvalid; er_FD_MongoDBRefNotFound: Result := S_FD_MongoDBRefNotFound; er_FD_MongoCannotOpenDataSet: Result := S_FD_MongoCannotOpenDataSet; er_FD_MongoFieldTypeMismatch: Result := S_FD_MongoFieldTypeMismatch; er_FD_MongoFieldIsNotFound: Result := S_FD_MongoFieldIsNotFound; er_FD_MongoAlertToMany: Result := S_FD_MongoAlertToMany; end; end; {-------------------------------------------------------------------------------} procedure FDException(AObj: TObject; const ALayers: array of String; ACode: Integer; const AArgs: array of const); var s, sMsg: String; begin sMsg := FDGetErrorMessage(ACode, AArgs); s := FDExceptionLayers(ALayers) + '-' + IntToStr(ACode) + '. '; try s := s + Format(sMsg, AArgs); except s := s + sMsg; end; FDException(AObj, EFDException.Create(ACode, s) {$IFDEF FireDAC_Monitor}, False {$ENDIF}); end; {-------------------------------------------------------------------------------} procedure FDCapabilityNotSupported(AObj: TObject; const ALayers: array of String); begin FDException(AObj, ALayers, er_FD_AccCapabilityNotSup, []); end; {-------------------------------------------------------------------------------} function FDDBEngineExceptionCreate(AClass: EFDDBEngineExceptionClass; ACode: Integer; const AArgs: array of const): EFDDBEngineException; var sMsg: String; begin sMsg := FDGetErrorMessage(ACode, AArgs); try sMsg := Format(sMsg, AArgs); except // silent end; Result := AClass.Create(ACode, sMsg); end; {-------------------------------------------------------------------------------} { EFDException } {-------------------------------------------------------------------------------} constructor EFDException.Create; begin inherited Create(''); end; {-------------------------------------------------------------------------------} constructor EFDException.Create(AFDCode: Integer; const AMessage: String); begin inherited Create(AMessage); FFDCode := AFDCode; end; {-------------------------------------------------------------------------------} procedure EFDException.SetFDObjectName(const AValue: IFDStanObject); var oObj: IFDStanObject; begin oObj := AValue; FFDObjName := ''; repeat if FFDObjName <> '' then FFDObjName := '.' + FFDObjName; FFDObjName := oObj.Name + FFDObjName; oObj := oObj.Parent; until oObj = nil; end; {-------------------------------------------------------------------------------} procedure EFDException.Duplicate(var AValue: EFDException); begin if AValue = nil then AValue := EFDExceptionClass(ClassType).Create; AValue.Message := Message; AValue.FDCode := FDCode; AValue.FDObjName := FDObjName; end; {-------------------------------------------------------------------------------} procedure EFDException.LoadFromStorage(const AStorage: IFDStanStorage); begin FDCode := AStorage.ReadInteger('FDCode', 0); Message := AStorage.ReadString('Message', ''); if AStorage.StreamVersion >= 8 then FDObjName := AStorage.ReadString('FDObjName', ''); end; {-------------------------------------------------------------------------------} procedure EFDException.SaveToStorage(const AStorage: IFDStanStorage); begin AStorage.WriteInteger('FDCode', FDCode, 0); AStorage.WriteString('Message', Message, ''); if AStorage.StreamVersion >= 8 then AStorage.WriteString('FDObjName', FDObjName, ''); end; {-------------------------------------------------------------------------------} function FDExceptionLoad(const AStorage: IFDStanStorage): TObject; begin Result := EFDException.Create; EFDException(Result).LoadFromStorage(AStorage); end; {-------------------------------------------------------------------------------} procedure FDExceptionSave(AObject: TObject; const AStorage: IFDStanStorage); begin EFDException(AObject).SaveToStorage(AStorage); end; {-------------------------------------------------------------------------------} { TFDDBError } {-------------------------------------------------------------------------------} constructor TFDDBError.Create; begin inherited Create; FCommandTextOffset := -1; FRowIndex := -1; end; {-------------------------------------------------------------------------------} constructor TFDDBError.Create(ALevel, AErrorCode: Integer; const AMessage, AObjName: String; AKind: TFDCommandExceptionKind; ACmdOffset, ARowIndex: Integer); begin Create; FLevel := ALevel; FErrorCode := AErrorCode; FMessage := AMessage; FObjName := AObjName; FKind := AKind; FCommandTextOffset := ACmdOffset; FRowIndex := ARowIndex; end; {-------------------------------------------------------------------------------} procedure TFDDBError.Assign(ASrc: TFDDBError); begin FLevel := ASrc.Level; FErrorCode := ASrc.ErrorCode; FMessage := ASrc.Message; FObjName := ASrc.ObjName; FKind := ASrc.Kind; FCommandTextOffset := ASrc.CommandTextOffset; FRowIndex := ASrc.RowIndex; end; {-------------------------------------------------------------------------------} procedure TFDDBError.LoadFromStorage(const AStorage: IFDStanStorage); begin ErrorCode := AStorage.ReadInteger('ErrorCode', 0); Kind := TFDCommandExceptionKind(AStorage.ReadInteger('Kind', 0)); Level := AStorage.ReadInteger('Level', 0); Message := AStorage.ReadString('Message', ''); ObjName := AStorage.ReadString('ObjName', ''); CommandTextOffset := AStorage.ReadInteger('CommandTextOffset', 0); RowIndex := AStorage.ReadInteger('RowIndex', 0); end; {-------------------------------------------------------------------------------} procedure TFDDBError.SaveToStorage(const AStorage: IFDStanStorage); begin AStorage.WriteInteger('ErrorCode', ErrorCode, 0); AStorage.WriteInteger('Kind', Integer(Kind), 0); AStorage.WriteInteger('Level', Level, 0); AStorage.WriteString('Message', Message, ''); AStorage.WriteString('ObjName', ObjName, ''); AStorage.WriteInteger('CommandTextOffset', CommandTextOffset, 0); AStorage.WriteInteger('RowIndex', RowIndex, 0); end; {-------------------------------------------------------------------------------} { EFDDBEngineException } {-------------------------------------------------------------------------------} constructor EFDDBEngineException.Create; begin inherited Create(0, ''); FItems := TFDObjList.Create; FParams := TFDStringList.Create; end; {-------------------------------------------------------------------------------} constructor EFDDBEngineException.Create(AADCode: Integer; const AMessage: String); begin inherited Create(AADCode, AMessage); FItems := TFDObjList.Create; FParams := TFDStringList.Create; end; {-------------------------------------------------------------------------------} destructor EFDDBEngineException.Destroy; begin Clear; FDFreeAndNil(FItems); FDFreeAndNil(FParams); inherited Destroy; end; {-------------------------------------------------------------------------------} procedure EFDDBEngineException.SetSQLAndParams(const AValue: IFDMoniAdapter); var i: Integer; sName: String; vValue: Variant; eKind: TFDMoniAdapterItemKind; begin FParams.Clear; FSQL := ''; if AValue <> nil then for i := 0 to AValue.ItemCount - 1 do begin AValue.GetItem(i, sName, vValue, eKind); if eKind = ikParam then FParams.Add(FDValToStr(sName, False) + '=' + FDValToStr(vValue, False)) else if eKind = ikSQL then FSQL := AdjustLineBreaks(vValue, tlbsCRLF); end; end; {-------------------------------------------------------------------------------} procedure EFDDBEngineException.SetParams(const AValue: TStrings); begin FParams.SetStrings(AValue); end; {-------------------------------------------------------------------------------} function EFDDBEngineException.GetErrorClass: TFDDBErrorClass; begin Result := TFDDBError; end; {-------------------------------------------------------------------------------} procedure EFDDBEngineException.Duplicate(var AValue: EFDException); var oItem: TFDDBError; i: Integer; begin inherited Duplicate(AValue); EFDDBEngineException(AValue).FParams.SetStrings(FParams); EFDDBEngineException(AValue).FSQL := FSQL; for i := 0 to FItems.Count - 1 do begin oItem := EFDDBEngineException(AValue).AppendError; oItem.Assign(TFDDBError(FItems[i])); end; end; {-------------------------------------------------------------------------------} function EFDDBEngineException.GetErrorCount: Integer; begin Result := FItems.Count; end; {-------------------------------------------------------------------------------} function EFDDBEngineException.GetErrors(AIndex: Integer): TFDDBError; begin Result := TFDDBError(FItems[AIndex]); end; {-------------------------------------------------------------------------------} function EFDDBEngineException.GetKind: TFDCommandExceptionKind; var i: Integer; begin Result := ekOther; for i := 0 to FItems.Count - 1 do if Errors[i].Kind <> ekOther then begin Result := Errors[i].Kind; Break; end; end; {-------------------------------------------------------------------------------} function EFDDBEngineException.GetErrorCode: Integer; var i: Integer; begin Result := 0; for i := 0 to FItems.Count - 1 do if Errors[i].ErrorCode <> 0 then begin Result := Errors[i].ErrorCode; Break; end; end; {-------------------------------------------------------------------------------} function EFDDBEngineException.AppendError: TFDDBError; begin Result := GetErrorClass.Create; Append(Result); end; {-------------------------------------------------------------------------------} function EFDDBEngineException.AppendError(ALevel, AErrorCode: Integer; const AMessage, AObjName: String; AKind: TFDCommandExceptionKind; ACmdOffset, ARowIndex: Integer): TFDDBError; begin Result := GetErrorClass.Create(ALevel, AErrorCode, AMessage, AObjName, AKind, ACmdOffset, ARowIndex); Append(Result); end; {-------------------------------------------------------------------------------} procedure EFDDBEngineException.Append(AItem: TFDDBError); begin FItems.Add(AItem); end; {-------------------------------------------------------------------------------} procedure EFDDBEngineException.Remove(AItem: TFDDBError); begin FItems.Remove(AItem); end; {-------------------------------------------------------------------------------} procedure EFDDBEngineException.Merge(AValue: EFDDBEngineException; AIndex: Integer); var i: Integer; begin for i := AValue.ErrorCount - 1 downto 0 do begin FItems.Insert(AIndex, AValue[i]); AValue.FItems.Delete(i); end; end; {-------------------------------------------------------------------------------} procedure EFDDBEngineException.Clear; var i: Integer; begin for i := 0 to FItems.Count - 1 do FDFree(TFDDBError(FItems[i])); FItems.Clear; end; {-------------------------------------------------------------------------------} procedure EFDDBEngineException.LoadFromStorage(const AStorage: IFDStanStorage); var oErr: TFDDBError; begin inherited LoadFromStorage(AStorage); if AStorage.StreamVersion >= 11 then AStorage.ReadObjectBegin('DBErrors', osFlatArray); while not AStorage.IsObjectEnd('DBError') do begin AStorage.ReadObjectBegin('DBError', osObject); try oErr := AppendError; oErr.LoadFromStorage(AStorage); finally AStorage.ReadObjectEnd('DBError', osObject); end; end; if AStorage.StreamVersion >= 11 then AStorage.ReadObjectEnd('DBErrors', osFlatArray); end; {-------------------------------------------------------------------------------} procedure EFDDBEngineException.SaveToStorage(const AStorage: IFDStanStorage); var i: Integer; oErr: TFDDBError; begin inherited SaveToStorage(AStorage); if AStorage.StreamVersion >= 11 then AStorage.WriteObjectBegin('DBErrors', osFlatArray); for i := 0 to ErrorCount - 1 do begin AStorage.WriteObjectBegin('DBError', osObject); try oErr := Errors[i]; oErr.SaveToStorage(AStorage); finally AStorage.WriteObjectEnd('DBError', osObject); end; end; if AStorage.StreamVersion >= 11 then AStorage.WriteObjectEnd('DBErrors', osFlatArray); end; {-------------------------------------------------------------------------------} function FDDBEngineExceptionLoad(const AStorage: IFDStanStorage): TObject; begin Result := EFDDBEngineException.Create; EFDDBEngineException(Result).LoadFromStorage(AStorage); end; {-------------------------------------------------------------------------------} { EFDDBArrayExecuteError } {-------------------------------------------------------------------------------} constructor EFDDBArrayExecuteError.Create(ATimes, AOffset: Integer; AException: EFDDBEngineException; ARetryLevel: Integer); begin inherited Create(er_FD_AccArrayExecError, 'Array DML failed: ' + AException.Message); FTimes := ATimes; FOffset := AOffset; FException := AException; FAction := eaFail; FRetryLevel := ARetryLevel; end; {-------------------------------------------------------------------------------} initialization FDStorageManager().RegisterClass(EFDException, 'Exception', @FDExceptionLoad, @FDExceptionSave); FDStorageManager().RegisterClass(EFDDBEngineException, 'DBEngineException', @FDDBEngineExceptionLoad, @FDExceptionSave); end.
unit LatLon; interface type TLatLon = record private fLat : double; fLon : double; fRadius : double; public constructor Create(const lat: double; const lon: double; const rad : double = 6371.0); function DistanceTo (const point : TLatLon) : double; function BearingTo(const point : TLatLon) : double; function FinalBearingTo(const point : TLatLon) : double; function MidPointTo(const point : TLatLon) : TLatLon; function DestinationPoint(const brng : double; const dist : double) : TLatLon; function Intersection(const p1 : TLatLon; const brng1 : double; const p2 : TLatLon; const brng2: double) : TLatLon; function RhumbDistanceTo(const point : TLatLon) : double; function RhumbBearingTo(const point : TLatLon) : double; function RhumbDestinationPoint(const brng : double; const dist : double) : TLatLon; function RhumbMidpointTo (const point : TLatLon) : TLatLon; property Lat : double read fLat; property Lon : double read fLon; property Radius : double read fRadius; end; implementation uses Math, Geo; // Creates a point on the earth's surface at the supplied latitude / longitude // // @constructor // @param {Number} lat: latitude in numeric degrees // @param {Number} lon: longitude in numeric degrees // @param {Number} [rad=6371]: radius of earth if different value is required from standard 6,371km constructor TLatLon.Create(const lat: double; const lon: double; const rad : double = 6371.0); begin fLat := lat; fLon := lon; fRadius := rad; end; //Returns the distance from this point to the supplied point, in km //(using Haversine formula) // // from: Haversine formula - R. W. Sinnott, "Virtues of the Haversine", // Sky and Telescope, vol 68, no 2, 1984 // // @param {LatLon} point: Latitude/longitude of destination point // @param {Number} [precision=4]: no of significant digits to use for returned value // @returns {Number} Distance in km between this point and destination point function TLatLon.DistanceTo(const point : TLatLon) : double; var R, lat1, lon1, lat2, lon2, dLat, dLon, a, c : double; begin R := fRadius; lat1 := DegToRad(fLat); lon1 := DegToRad(fLon); lat2 := DegToRad(point.Lat); lon2 := DegToRad(point.Lon); dLat := lat2 - lat1; dLon := lon2 - lon1; a := Sin(dLat / 2) * Sin(dLat / 2) + Cos(lat1) * Cos(lat2) * Sin(dLon / 2) * Sin(dLon / 2); c := 2 * Math.ArcTan2(Sqrt(a), Sqrt(1 - a)); Result := R * c; end; // Returns the (initial) bearing from this point to the supplied point, in degrees // see http://williams.best.vwh.net/avform.htm#Crs // // @param {LatLon} point: Latitude/longitude of destination point // @returns {Number} Initial bearing in degrees from North function TLatLon.BearingTo(const point : TLatLon) : double; var lat1, lat2, dLon, y, x, brng : double; begin lat1 := DegToRad(Lat); lat2 := DegToRad(point.Lat); dLon := DegToRad(point.Lon - self.Lon); y := Sin(dLon) * Cos(lat2); x := Cos(lat1) * Sin(lat2) - Sin(lat1) * Cos(lat2) * Cos(dLon); brng := Math.arcTan2(y, x); Result := FloatingPointMod(RadToDeg(brng) + 360, 360); end; // Returns final bearing arriving at supplied destination point from this point; the final bearing // will differ from the initial bearing by varying degrees according to distance and latitude // // @param {LatLon} point: Latitude/longitude of destination point // @returns {Number} Final bearing in degrees from North function TLatLon.FinalBearingTo(const point : TLatLon) : double; var lat1, lat2, dLon, y, x, brng : double; begin // get initial bearing from supplied point back to this point... lat1 := DegToRad(point.Lat); lat2 := DegToRad(self.Lat); dLon := DegToRad(self.Lon - point.Lon); y := Sin(dLon) * Cos(lat2); x := Cos(lat1) * Sin(lat2) - Sin(lat1) * Cos(lat2) * Cos(dLon); brng := Math.ArcTan2(y, x); Result := FloatingPointMod( RadToDeg(brng) + 180, 360); end; // Returns the midpoint between this point and the supplied point. // see http://mathforum.org/library/drmath/view/51822.html for derivation // // @param {LatLon} point: Latitude/longitude of destination point // @returns {LatLon} Midpoint between this point and the supplied point function TLatLon.MidPointTo(const point : TLatLon) : TLatLon; var lat1, lon1, lat2, dLon, Bx, By, lat3, lon3 : double; begin lat1 := DegToRad(self.Lat); lon1 := DegToRad(self.Lon); lat2 := DegToRad(point.Lat); dLon := DegToRad(point.Lon - Self.Lon); Bx := Cos(lat2) * Cos(dLon); By := Cos(lat2) * Sin(dLon); lat3 := Math.ArcTan2(Sin(lat1) + Sin(lat2), Sqrt((Cos(lat1) + Bx) * (Cos(lat1) + Bx) + By * By)); lon3 := lon1 + Math.ArcTan2(By, Cos(lat1) + Bx); lon3 := FloatingPointMod((lon3 + 3 * PI), (2 * PI)) - PI; // normalise to -180..+180º Result := TLatLon.Create(RadToDeg(lat3), RadToDeg(lon3)); end; // Returns the destination point from this point having travelled the given distance (in km) on the // given initial bearing (bearing may vary before destination is reached) // // see http://williams.best.vwh.net/avform.htm#LL // // @param {Number} brng: Initial bearing in degrees // @param {Number} dist: Distance in km // @returns {LatLon} Destination point function TLatLon.DestinationPoint(const brng : double; const dist : double) : TLatLon; var dist1, brng1, lat1, lon1, lat2, lon2 : double; begin dist1 := dist / self.Radius; // convert dist to angular distance in radians brng1 := DegToRad(brng); // lat1 := DegToRad(self.Lat); lon1 := DegToRad(self.Lon); lat2 := Math.ArcSin(Sin(lat1) * Cos(dist) + Cos(lat1) * Sin(dist) * Cos(brng1)); lon2 := lon1 + Math.ArcTan2(Sin(brng1) * Sin(dist1) * Cos(lat1), Cos(dist1) - Sin(lat1) * Sin(lat2)); lon2 := FloatingPointMod((lon2 + 3 * PI), (2 * PI)) - PI; // normalise to -180..+180º Result := TLatLon.Create(RadToDeg(lat2), RadToDeg(lon2)); end; // Returns the point of intersection of two paths defined by point and bearing // // see http://williams.best.vwh.net/avform.htm#Intersection // // @param {LatLon} p1: First point // @param {Number} brng1: Initial bearing from first point // @param {LatLon} p2: Second point // @param {Number} brng2: Initial bearing from second point // @returns {LatLon} Destination point (null if no unique intersection defined) function TLatLon.Intersection(const p1 : TLatLon; const brng1 : double; const p2 : TLatLon; const brng2: double) : TLatLon; begin //brng1 = typeof brng1 == 'number' ? brng1 : typeof brng1 == 'string' && trim(brng1)!='' ? +brng1 : NaN; // brng2 = typeof brng2 == 'number' ? brng2 : typeof brng2 == 'string' && trim(brng2)!='' ? +brng2 : NaN; // lat1 = p1._lat.toRad(), lon1 = p1._lon.toRad(); // lat2 = p2._lat.toRad(), lon2 = p2._lon.toRad(); // brng13 = brng1.toRad(), brng23 = brng2.toRad(); // dLat = lat2-lat1, dLon = lon2-lon1; // // dist12 = 2*Math.asin( Math.sqrt( Math.sin(dLat/2)*Math.sin(dLat/2) + // Math.cos(lat1)*Math.cos(lat2)*Math.sin(dLon/2)*Math.sin(dLon/2) ) ); // if (dist12 == 0) return null; // // // initial/final bearings between points // brngA = Math.acos( ( Math.sin(lat2) - Math.sin(lat1)*Math.cos(dist12) ) / // ( Math.sin(dist12)*Math.cos(lat1) ) ); // if (isNaN(brngA)) brngA = 0; // protect against rounding // brngB = Math.acos( ( Math.sin(lat1) - Math.sin(lat2)*Math.cos(dist12) ) / // ( Math.sin(dist12)*Math.cos(lat2) ) ); // // if (Math.sin(lon2-lon1) > 0) { // brng12 = brngA; // brng21 = 2*Math.PI - brngB; // } else { // brng12 = 2*Math.PI - brngA; // brng21 = brngB; // } // // alpha1 = (brng13 - brng12 + Math.PI) % (2*Math.PI) - Math.PI; // angle 2-1-3 // alpha2 = (brng21 - brng23 + Math.PI) % (2*Math.PI) - Math.PI; // angle 1-2-3 // // if (Math.sin(alpha1)==0 && Math.sin(alpha2)==0) return null; // infinite intersections // if (Math.sin(alpha1)*Math.sin(alpha2) < 0) return null; // ambiguous intersection // // //alpha1 = Math.abs(alpha1); // //alpha2 = Math.abs(alpha2); // // ... Ed Williams takes abs of alpha1/alpha2, but seems to break calculation? // // alpha3 = Math.acos( -Math.cos(alpha1)*Math.cos(alpha2) + // Math.sin(alpha1)*Math.sin(alpha2)*Math.cos(dist12) ); // dist13 = Math.atan2( Math.sin(dist12)*Math.sin(alpha1)*Math.sin(alpha2), // Math.cos(alpha2)+Math.cos(alpha1)*Math.cos(alpha3) ) // lat3 = Math.asin( Math.sin(lat1)*Math.cos(dist13) + // Math.cos(lat1)*Math.sin(dist13)*Math.cos(brng13) ); // dLon13 = Math.atan2( Math.sin(brng13)*Math.sin(dist13)*Math.cos(lat1), // Math.cos(dist13)-Math.sin(lat1)*Math.sin(lat3) ); // lon3 = lon1+dLon13; // lon3 = (lon3+3*Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..+180º // // return new LatLon(lat3.toDeg(), lon3.toDeg()); end; // Returns the distance from this point to the supplied point, in km, travelling along a rhumb line // // see http://williams.best.vwh.net/avform.htm#Rhumb // // @param {LatLon} point: Latitude/longitude of destination point // @returns {Number} Distance in km between this point and destination point function TLatLon.RhumbDistanceTo(const point : TLatLon) : double; var R, lat1, lat2, dLat, dLon, dPhi, q : double; begin R := self.Radius; lat1 := DegToRad(self.Lat); lat2 := DegToRad(point.Lat); dLat := DegToRad(point.Lat - Self.Lat); dLon := DegToRad(Abs(point.Lon - self.Lon)); dPhi := Ln(Tan(lat2 / 2 + PI / 4) / Tan(lat1 / 2 + PI / 4)); if IsNan(dLat/dPhi)then begin q := Cos(lat1) end else begin q := dLat / dPhi; end; // if dLon over 180° take shorter rhumb across anti-meridian: if (Abs(dLon) > PI) then begin if dLon > 0 then dLon := -(2 * PI - dLon) else dlon := (2 * PI + dLon); end; Result := Sqrt(dLat * dLat + q * q * dLon * dLon) * R; end; // Returns the bearing from this point to the supplied point along a rhumb line, in degrees // // @param {LatLon} point: Latitude/longitude of destination point // @returns {Number} Bearing in degrees from North function TLatLon.RhumbBearingTo(const point : TLatLon) : double; var lat1 , lat2, dLon, dPhi, brng : double; begin lat1 := DegToRad(self.Lat); lat2 := DegToRad(point.Lat); dLon := DegToRad(point.Lon - self.Lon); dPhi := Ln(Tan(lat2 / 2 + PI / 4) / Tan( lat1 / 2 + PI / 4)); if (Abs(dLon) > PI) then begin if dLon > 0 then begin dLon := -(2 * PI - dLon); end else begin dLon := (2 * PI + dLon); end; end; brng := Math.ArcTan2(dLon, dPhi); Result := FloatingPointMod(RadToDeg(brng) + 360, 360); end; // Returns the destination point from this point having travelled the given distance (in km) on the // given bearing along a rhumb line // // @param {Number} brng: Bearing in degrees from North // @param {Number} dist: Distance in km // @returns {LatLon} Destination point function TLatLon.RhumbDestinationPoint(const brng : double; const dist : double) : TLatLon; var R, d, lat1, lon1, brng1, dLat, lat2, lon2, dPhi, q, dLon : double; begin R := self.Radius; d := dist / R; // d = angular distance covered on earth’s surface lat1 := DegToRad(self.Lat); lon1 := DegToRad(self.Lon); brng1 := DegToRad(brng); dLat := d * Cos(brng1); // nasty kludge to overcome ill-conditioned results around parallels of latitude: if (Abs(dLat) < 1e-10) then dLat := 0; // dLat < 1 mm lat2 := lat1 + dLat; dPhi := Ln(Tan(lat2 / 2 + PI / 4) / Tan(lat1 / 2 + PI / 4)); if IsNan(dLat / dPhi) then begin q := Cos(lat1); end else begin q := dLat / dPhi; end; dLon := d * Sin(brng1) / q; // check for some daft bugger going past the pole, normalise latitude if so if (Abs(lat2) > PI / 2) then begin if lat2 > 0 then begin lat2 := PI - lat2; end else begin lat2 := -PI - lat2; end; end; lon2 := FloatingPointMod(lon1 + dLon + 3 * PI, 2 * PI) - PI; Result := TLatLon.Create(RadToDeg(lat2), RadToDeg(lon2)); end; function TLatLon.RhumbMidpointTo (const point : TLatLon) : TLatLon; var lat1, lon1, lat2, lon2, lat3, f1, f2, f3, lon3 : double; begin lat1 := DegToRad(self.Lat); lon1 := DegToRad(self.Lon); lat2 := DegToRad(point.Lat); lon2 := DegToRad(point.Lon); if (Abs(lon2-lon1) > PI) then lon1 := lon1 + (2 * PI); // crossing anti-meridian lat3 := (lat1 + lat2) / 2; f1 := Tan(PI / 4 + lat1 / 2); f2 := Tan(PI / 4 + lat2 / 2); f3 := Tan(PI / 4 + lat3 / 2); lon3 := ((lon2 - lon1) * Ln(f3) + lon1 * Ln(f2) - lon2 * Ln(f1)) / ln(f2 / f1); if (Math.IsNan(lon3)) then lon3 := (lon1 + lon2) / 2; // parallel of latitude lon3 := FloatingPointMod(lon3 + 3 * PI, 2 * PI) - PI; // normalise to -180..+180º Result := TLatLon.Create(RadToDeg(lat3), RadToDeg(lon3)); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995,99 Inprise Corporation } { } {*******************************************************} unit CompProd; interface uses Classes, HTTPApp, WebComp; type TComponentsPageProducer = class(TPageProducer) protected function FindComponent(TagParams: TStrings): TComponent; virtual; function FindComponentName(TagParams: TStrings): string; function GetComponentContent(TagParams: TStrings): string; virtual; procedure DoTagEvent(Tag: TTag; const TagString: string; TagParams: TStrings; var ReplaceText: string); override; function GetContentOptions(var Owned: Boolean): TWebContentOptions; virtual; published property OnHTMLTag; end; implementation uses SysUtils; procedure TComponentsPageProducer.DoTagEvent(Tag: TTag; const TagString: string; TagParams: TStrings; var ReplaceText: string); begin if Tag = tgCustom then begin if CompareText(TagString, 'COMPONENT') = 0 then begin ReplaceText := GetComponentContent(TagParams); Exit; end; end; inherited DoTagEvent(Tag, TagString, TagParams, ReplaceText); end; function TComponentsPageProducer.FindComponentName(TagParams: TStrings): string; begin Result := TagParams.Values['Name']; end; function TComponentsPageProducer.FindComponent(TagParams: TStrings): TComponent; var ComponentName: string; begin ComponentName := FindComponentName(TagParams); if ComponentName <> '' then if Owner <> nil then begin Result := Owner.FindComponent(ComponentName); Exit; end; Result := nil; end; function TComponentsPageProducer.GetComponentContent(TagParams: TStrings): string; var Component: TComponent; ContentIntf: IWebContent; Options: TWebContentOptions; Owned: Boolean; begin Component := FindComponent(TagParams); if Assigned(Component) then if Component.GetInterface(IWebContent, ContentIntf) then begin Options := GetContentOptions(Owned); try Result := ContentIntf.Content(Options, nil); finally if Owned then Options.Free; end; end; end; function TComponentsPageProducer.GetContentOptions(var Owned: Boolean): TWebContentOptions; begin Owned := True; Result := TWebContentOptions.Create([]); end; end.
unit GroupSearch; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopup, Data.DB, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, RzDBGrid, Vcl.Mask, RzEdit, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, RzButton, Vcl.ComCtrls, RzTreeVw; type TfrmGroupSearch = class(TfrmBasePopup) pnlSearch: TRzPanel; pnlSelect: TRzPanel; btnSelect: TRzShapeButton; pnlCancel: TRzPanel; btnCancel: TRzShapeButton; tvGroup: TRzTreeView; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure btnSelectClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure tvGroupDblClick(Sender: TObject); private { Private declarations } FLocation: string; procedure PopulateTree; protected { Public declarations } public constructor Create(AOwner: TComponent); overload; override; constructor Create(AOwner: TComponent; const ALocation: string); reintroduce; overload; end; implementation {$R *.dfm} uses EntitiesData, Group, IFinanceGlobal, GroupUtils; procedure TfrmGroupSearch.PopulateTree; var i, cnt: integer; function GetParentNode: TTreeNode; var n: integer; begin Result := nil; for n := 0 to tvGroup.Items.Count - 1 do if TGroup(tvGroup.Items[n].Data).GroupId = groups[i].ParentGroupId then begin Result := tvGroup.Items[n]; Exit; end; end; begin with tvGroup do begin Items.Clear; cnt := Length(groups) - 1; // loop through the list and insert items with no parent first for i := 0 to cnt do if groups[i].Location = FLocation then if not groups[i].HasParent then Items.AddObject(nil,groups[i].GroupName,groups[i]); // loop through the list and insert child items (with parent) for i := 0 to cnt do if groups[i].Location = FLocation then if groups[i].HasParent then Items.AddChildObject(GetParentNode,groups[i].GroupName,groups[i]); FullExpand; end; end; procedure TfrmGroupSearch.tvGroupDblClick(Sender: TObject); begin inherited; if Assigned(tvGroup.Selected.Data) then ModalResult := mrOk; end; procedure TfrmGroupSearch.btnSelectClick(Sender: TObject); begin inherited; ModalResult := mrOk; end; constructor TfrmGroupSearch.Create(AOwner: TComponent); begin inherited Create(AOwner); FLocation := ifn.LocationCode; end; constructor TfrmGroupSearch.Create(AOwner: TComponent; const ALocation: string); begin inherited Create(AOwner); FLocation := Trim(ALocation); end; procedure TfrmGroupSearch.FormClose(Sender: TObject; var Action: TCloseAction); var selGroup: TGroup; begin if ModalResult = mrOK then begin selGroup := TGroup(tvGroup.Selected.Data); if Assigned(selGroup) then begin grp.GroupId := selGroup.GroupId; grp.GroupName := selGroup.GroupName; end; end; inherited; end; procedure TfrmGroupSearch.FormCreate(Sender: TObject); begin PopulateGroupList(dmEntities.dstGroups); PopulateTree; inherited; end; procedure TfrmGroupSearch.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then ModalResult := mrOK; inherited; end; procedure TfrmGroupSearch.btnCancelClick(Sender: TObject); begin inherited; ModalResult := mrCancel; end; end.
unit Soccer.Voting.RuleChooser; interface uses System.SysUtils, System.Generics.Collections, Soccer.Exceptions, Soccer.Voting.AbstractRule, Soccer.Voting.RulePreferenceList, Soccer.Voting.Preferences; type ISoccerVotingRuleChooser = interface function ChooseRuleFindWinners(AProfile: TSoccerVotingVotersPreferences; out ARules: TSoccerVotingRulePreferenceList): TList<string>; end; TSoccerRuleChooser = class(TInterfacedObject, ISoccerVotingRuleChooser) public function ChooseRuleFindWinners(AProfile: TSoccerVotingVotersPreferences; out ARules: TSoccerVotingRulePreferenceList) : System.Generics.Collections.TList<string>; end; function GetDefaultRuleChooser: ISoccerVotingRuleChooser; implementation function GetDefaultRuleChooser: ISoccerVotingRuleChooser; begin Result := TSoccerRuleChooser.Create; end; { TRuleChooser } function TSoccerRuleChooser.ChooseRuleFindWinners (AProfile: TSoccerVotingVotersPreferences; out ARules: TSoccerVotingRulePreferenceList) : System.Generics.Collections.TList<System.string>; var i: integer; LRule: ISoccerVotingRule; LResult: TList<string>; LRuleFound: Boolean; begin LRuleFound := false; LResult := nil; if not AProfile.Properties.Complete then raise ESoccerParserException.Create ('Incompete profiles are not supported for now'); if ARules.Count = 0 then raise ESoccerParserException.Create('No rule was imported'); for i := 0 to ARules.Count - 1 do begin LRule := ARules.Items[i]; if LRule.ExecuteOn(AProfile, LResult) then begin LRuleFound := true; break; end; if Assigned(LResult) then FreeAndNil(LResult); end; if not LRuleFound then raise ESoccerParserException.Create('No rule was found for your purposes'); Result := TList<string>.Create; Result.Add(LRule.GetName); Result.AddRange(LResult.ToArray); FreeAndNil(LResult); end; end.
unit dllinject; {$mode delphi} interface uses Classes, SysUtils, exereader, Windows, JwaWinType, InstDecode; type { This buffer will be injected into the spawned process. This will be used to load a dll (target) and execute a function inside it (procname) See "PayloadProc" proc for more } PInjectionBuffer = ^TInjectionBuffer; TInjectionBuffer = record LoadLibrary: function(lpLibFileName:LPCSTR):HINST; stdcall; // 00 GetProcAddr: function(hModule:HINST; lpProcName:LPCSTR):FARPROC; stdcall; // 4 CustomData: Pointer; // 8 target: array[0..511] of Char; // dll path + name // 12 procName: array[0..63] of Char; // dll proc name // 524 end; procedure injectLoader(target, params: string; dll, funcname: string; CustomData: Pointer; CustomDataSize: Integer; SimpleInject: Boolean = False); function InjectDLL(PID: Cardinal; sDll, CallProc: string;CustomData: Pointer; CustomDataSize: Integer): boolean; implementation type TCallFunc = procedure(Data: Pointer); stdcall; { the payload function - directly copied from here into the target process. } procedure PayloadProc(data: PInjectionBuffer); stdcall; begin TCallFunc(data^.GetProcAddr(data^.LoadLibrary(@data^.target[0]), @data^.procName[0]))(data^.CustomData); end; function GetEntryPoint(aFilename: string): Integer; var f: TExeFile; begin result:=0; f:=TExeFile.Create; try if f.LoadFile(aFilename) then begin case f.FileType of fkExe32: begin result:=f.NTHeader.OptionalHeader.ImageBase + f.NTHeader.OptionalHeader.AddressOfEntryPoint; end; fkExe64: begin result:=f.NTHeader64.OptionalHeader.ImageBase + f.NTHeader64.OptionalHeader.AddressOfEntryPoint; end; end; end; finally f.Free; end; end; function SizeOfProc(Proc: pointer): longword; var Length: longword; Inst: TInstruction; begin FillChar(Inst, SizeOf(Inst), 0); {$ifdef CPUX86} Inst.Archi:=CPUX32; {$ELSE} Inst.Archi:=CPUX64; {$ENDIF} Inst.Addr:=Proc; Result := 0; repeat Length := DecodeInst(@Inst); Inst.Addr := Inst.NextInst; Inc(Result, Length); if Inst.OpType = otRET then Break; until Length = 0; end; function InjectDLL(PID: Cardinal; sDll, CallProc: string; CustomData: Pointer; CustomDataSize: Integer): boolean; var hThread: THandle; pMod, pCode: Pointer; dWritten: NativeUInt; ThreadID: Cardinal; buffer: TInjectionBuffer; i: Integer; begin Result := False; Fillchar(buffer, SizeOF(TInjectionBuffer), #0); dWritten:=0; if PID <> INVALID_HANDLE_VALUE then begin // fill payload structure buffer.LoadLibrary:=GetProcAddress(GetModuleHandle(PChar('KERNEL32.dll')), 'LoadLibraryA'); buffer.GetProcAddr:=GetProcAddress(GetModuleHandle(PChar('KERNEL32.dll')), 'GetProcAddress'); for i:=1 to Length(sDll) do buffer.target[i-1]:=sDll[i]; for i:=1 to Length(CallProc) do buffer.procName[i-1]:=CallProc[i]; result:=True; // allocate memory for custom data & copy if required if Assigned(CustomData) then begin buffer.CustomData:=VirtualAllocEx(PID, nil, CustomDataSize, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE); if WriteProcessMemory(PID, buffer.CustomData, CustomData, CustomDataSize, dWritten) then Result := result and TRUE; end else buffer.CustomData:=nil; // allocate memory & copy payload proc pCode := VirtualAllocEx(PID, nil, SizeOfProc(@PayloadProc), MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE); if WriteProcessMemory(PID, pCode, @PayloadProc, SizeOfProc(@PayloadProc), dWritten) then Result := result and TRUE; // allocate memory & copy payload buffer pMod := VirtualAllocEx(PID, nil, SizeOf(TInjectionBuffer), MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE); if WriteProcessMemory(PID, pMod, @Buffer, SizeOf(TInjectionBuffer), dWritten) then Result := result and TRUE; if result then begin ThreadID:=0; hThread := CreateRemoteThread(PID, nil, 0, pCode, pMod, 0, ThreadID); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); end; end; end; procedure injectLoader(target, params: string; dll, funcname: string; CustomData: Pointer; CustomDataSize: Integer; SimpleInject: Boolean); var StartupInfo: TSTARTUPINFO; ProcessInformation: PROCESS_INFORMATION; hProcess: THANDLE; entry: PtrUInt; oldProtect: DWORD; bytesRead: PTRUINT; original, patch: array[0..1] of Byte; i: Integer; AContext: CONTEXT; f: TExeFile; IsRelocatable: Boolean; s: string; begin f:=TExeFile.Create; IsRelocatable:=False; bytesRead:=0; try if f.LoadFile(target) then begin IsRelocatable:=False; for i:=0 to f.SectionCount-1 do if (f.Sections[i].Name='.reloc')and(f.Sections[i].NumberOfRelocations>0) then IsRelocatable:=True; case f.FileType of fkExe32: begin entry:=f.NTHeader.OptionalHeader.ImageBase + f.NTHeader.OptionalHeader.AddressOfEntryPoint; {$ifndef CPUX86} raise Exception.Create('This is a 32 bit executable - please use the 32 bit flavour of this program!'); {$endif} end; fkExe64: begin entry:=f.NTHeader64.OptionalHeader.ImageBase + f.NTHeader64.OptionalHeader.AddressOfEntryPoint; {$ifdef CPUX86} raise Exception.Create('This is a 64 bit executable - please use the 64 bit flavour of this program!'); {$endif} end; fkExeArm: begin raise Exception.Create('LOL Windows ARM Binary!'); end; else raise Exception.Create('Executable required'); end; end else raise Exception.Create(f.Status); finally f.Free; end; Fillchar(StartupInfo, SizeOf(StartupInfo), #0); FIllchar(ProcessInformation, SizeOf(ProcessInformation), #0); StartupInfo.cb:=SizeOf(StartupInfo); // change to same directory as target chdir(ExtractFilePath(target)); // create new process with target s:= target + ' ' + params; if (CreateProcessA(nil, PChar(s), nil, nil, False, CREATE_SUSPENDED, nil, nil, StartupInfo, ProcessInformation)) then begin hProcess:=ProcessInformation.hProcess; try {$IFDEF CPUX86} if SimpleInject or IsRelocatable then {$ENDIF} begin { just inject while running without all that fancy patching... the more I test this, the more reasonable this approach seems - it just works, no problems with ASLR/relocatable images.. but tested with win10 only. I think the whole reason behind patching the entry point was to make sure the process was properly initialized so a dll can be injected without interfering with the rest of the process. } if not InjectDLL(hProcess, dll, funcname, CustomData, CustomDataSize) then begin //if not InjectLibrary2(hProcess, dll, funcname, CustomData, CustomDataSize) then raise Exception.Create('Could not inject dll'); end; ResumeThread(ProcessInformation.hThread); Exit; end; {$IFDEF CPUX86} if not VirtualProtectEx(hProcess, LPVOID(entry), 2, PAGE_EXECUTE_READWRITE, @oldProtect) then begin raise Exception.Create('Cannot unprotect entrypoint (relocatable? ALSR?)'); end; // save original entry point instructions if not ReadProcessMemory(hProcess, LPVOID(entry), @original[0], 2, bytesRead) then begin raise Exception.Create('Read from process memory failed: '+SysErrorMessage(GetLastError)); end; // patch entry point with jmp -2 => force process into an infinite loop once it's // reached it's entry point patch[0]:=$EB; patch[1]:=$FE; if not WriteProcessMemory(hProcess, Pointer(entry), @patch[0], 2, @bytesRead) then begin raise Exception.Create('Write to process memory failed: '+SysErrorMessage(GetLastError)); end; // resume process and wait a reasonable time until it has instruction pointer is at entry point ResumeThread(ProcessInformation.hThread); for i:=0 to 49 do begin Sleep(100); AContext.ContextFlags:=CONTEXT_CONTROL; GetThreadContext(ProcessInformation.hThread, AContext); if AContext.Eip = Entry then Break; end; if AContext.Eip <> Entry then begin // wait timeout, this happens with ASLR end; // finally, inject the payload if not InjectDLL(hProcess, dll, funcname, CustomData, CustomDataSize) then begin //if not InjectLibrary2(hProcess, dll, funcname, CustomData, CustomDataSize) then raise Exception.Create('Could not inject dll'); end; // suspend the thread again SuspendThread(ProcessInformation.hThread); // restore original entry point instructions if not WriteProcessMemory(hProcess, Pointer(entry), @original[0], 2, @bytesRead) then begin // if this fails, it usually means that the process has terminated in the meantime // (this e.g. happens when the injected dll throws an error and quits) // raise Exception.Create('Write to process memory (2) failed: '+SysErrorMessage(GetLastError)); end; // resume process ResumeThread(ProcessInformation.hThread); {$ENDIF} except // terminate process and throw again TerminateProcess(hProcess, UINT(-1)); raise; end; end else raise Exception.Create('Could not create process: '+SysErrorMessage(GetLastError)); end; end.
{**********************************************************************} { Unit archived using GP-Version } { GP-Version is Copyright 1997 by Quality Software Components Ltd } { } { For further information / comments, visit our WEB site at } { http://www.qsc.u-net.com } {**********************************************************************} { $Log: 10052: kpUnrdc.pas { { Rev 1.0 8/14/2005 1:10:08 PM KLB Version: VCLZip Pro 3.06 { Initial load of VCLZip Pro on this computer } { { Rev 1.0 10/15/2002 8:15:20 PM Supervisor } { { Rev 1.0 9/3/2002 8:16:52 PM Supervisor } { { Rev 1.1 7/9/98 6:47:19 PM Supervisor { Version 2.13 { { 1) New property ResetArchiveBitOnZip causes each file's { archive bit to be turned off after being zipped. { { 2) New Property SkipIfArchiveBitNotSet causes files { who's archive bit is not set to be skipped during zipping { operations. { { 3) A few modifications were made to allow more { compatibility with BCB 1. { { 4) Modified how directory information is used when { comparing filenames to be unzipped. Now it is always { used. } { ********************************************************************************** } { } { COPYRIGHT 1997 Kevin Boylan } { Source File: Unreduce.pas } { Description: VCLUnZip component - native Delphi unzip component. } { Date: March 1997 } { Author: Kevin Boylan, CIS: boylank } { Internet: boylank@compuserve.com } { } { ********************************************************************************** } procedure Unreduce; var followers: f_arrayPtr; { changed to Ptr type 5/18/98 2.13} Slen: array[0..255] of Byte; factor: WORD; procedure READBITS( nbits: WORD; var zdest: Byte ); begin if nbits > bits_left then FillBitBuffer; zdest := Byte(WORD(bitbuf) and mask_bits[nbits]); bitbuf := LongInt(bitbuf shr nbits); Dec(bits_left, nbits); end; procedure LoadFollowers; var x: short_int; i: short_int; begin for x := 255 downto 0 do begin READBITS(6,Slen[x]); i := 0; while (i < Slen[x]) do begin READBITS(8,followers^[x][i]); Inc(i); end; end; end; procedure xflush( w: WORD ); var n: WORD; p: BYTEPTR; begin p := @area^.slide[0]; while (w <> 0) do begin n := OUTBUFSIZ - outcnt; if (n >= w) then n := w; MoveMemory( outptr, p, n ); Inc(outptr,n); Inc(outcnt,n); if (outcnt = OUTBUFSIZ) then xFlushOutput; Inc(p,n); Dec(w,n); end; end; var { Unreduce } lchar: short_int; nchar: Byte; ExState: short_int; V: short_int; Len: short_int; s: LongInt; w: WORD; u: WORD; follower: Byte; bitsneeded: short_int; e: WORD; n: WORD; d: WORD; begin { Unreduce } lchar := 0; ExState := 0; V := 0; Len := 0; s := ucsize; w := 0; u := 1; followers := f_arrayPtr(@area^.slide[WSIZE div 2]); { added typecast 5/18/98 2.13 } factor := file_info.compression_method - 1; LoadFollowers; while (s > 0) do begin if (Slen[lchar] = 0) then READBITS(8,nchar) Else begin READBITS(1,nchar); if (nchar <> 0) then READBITS(8,nchar) Else begin bitsneeded := B_table[Slen[lchar]]; READBITS(bitsneeded, follower); nchar := followers^[lchar][follower]; end; end; Case ExState of 0: begin if (nchar <> DLE) then begin Dec(s); area^.slide[w] := Byte(nchar); Inc(w); if (w = (WSIZE div 2)) then begin xflush(w); w := 0; u := 0; end; end Else ExState := 1; end; { 0: } 1: begin if (nchar <> 0) then begin V := nchar; Len := V and L_table[factor]; if (WORD(Len) = L_table[factor]) then ExState := 2 Else ExState := 3; end Else begin Dec(s); area^.Slide[w] := DLE; Inc(w); if (w = (WSIZE div 2)) then begin xflush(w); w := 0; u := 0; end; ExState := 0; end; end; { 1: } 2: begin Inc(Len,nchar); ExState := 3; end; { 2: } 3: begin n := Len + 3; d := w - ((((V shr D_shift[factor]) and D_mask[factor]) shl 8) + nchar + 1); Dec(s,n); Repeat d := d and $3fff; if d > w then e := (WSIZE div 2) - d else e := (WSIZE div 2) - w; if e > n then e := n; Dec(n,e); if (u <> 0) and (w <= d) then begin ZeroMemory( @area^.Slide[w], e ); Inc(w,e); Inc(d,e); end Else begin if (w - d < e) then Repeat area^.Slide[w] := area^.Slide[d]; Inc(w); Inc(d); Dec(e); Until e = 0 Else begin MoveMemory( @area^.Slide[w], @area^.Slide[d], e ); Inc(w,e); Inc(d,e); end; end; if (w = (WSIZE div 2)) then begin xflush(w); w := 0; u := 0; end; Until (n = 0); Exstate := 0; end; { 3: } end; { Case ExState of} lchar := nchar; end; { while (s > 0) } xflush(w); xFlushOutput; end;
unit ClassLetterBoard; interface uses ClassBaseBoard, ClassLetters, ClassLetterStack, Classes, Controls, ExtCtrls, Graphics; const CStoneSize = 20; CBckgndColor = $00000000; CEmptyColor = $00B0FFFF; type TBoardStack = array[1..2] of TStack; TLetterBoard = class( TBaseBoard ) private FBrdStack : TBoardStack; FMarked : TLetter; FMarkX : integer; FMarkY : integer; procedure OnBtnDown( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer ); procedure PaintBoard; public constructor Create( Image : TImage ); destructor Destroy; override; procedure Clear; procedure SetStack( Stack : TLetterStack ); procedure RemoveMarked; procedure UnMark; procedure TakeBack( Letter : TLetter ); function GetBottomTiles : TNewLetters; property Marked : TLetter read FMarked; end; implementation uses SysUtils; //============================================================================== // Constructor / destructor //============================================================================== constructor TLetterBoard.Create( Image : TImage ); begin inherited Create( Image ); FMarked.C := #0; FMarkX := 0; FMarkY := 0; FImage.OnMouseDown := OnBtnDown; end; destructor TLetterBoard.Destroy; begin inherited; end; //============================================================================== // P R I V A T E //============================================================================== procedure TLetterBoard.OnBtnDown( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer ); var I, J : integer; L : TLetter; begin if (X = 0) or (X = FImage.Width-1) or (Y = 0) or (Y = FImage.Height-1) then exit; I := (X div (CStoneSize + 1))+1; J := (Y div (CStoneSize + 1))+1; if ((FMarkX = 0) and (FMarkY = 0)) then begin if (FBrdStack[J,I].C <> #0) then begin FMarkX := I; FMarkY := J; FMarked := FBrdStack[J,I]; PaintLetter( FBrdStack[J,I] , I , J , CMrkColor , CMrkBckColor ); end; end else begin if (FBrdStack[J,I].C = #0) then begin FBrdStack[J,I] := FBrdStack[FMarkY,FMarkX]; FBrdStack[FMarkY,FMarkX].C := #0; FBrdStack[FMarkY,FMarkX].Value := 0; PaintEmpty( (FMarkX-1)*CStoneSize+(FMarkX-1) , (FMarkY-1)*CStoneSize+(FMarkY-1) , CEmptyColor ); PaintLetter( FBrdStack[J,I] , I , J , CLtrColor , CLtrBckColor ); end else begin L := FBrdStack[J,I]; FBrdStack[J,I] := FBrdStack[FMarkY,FMarkX]; FBrdStack[FMarkY,FMarkX] := L; PaintLetter( FBrdStack[J,I] , I , J , CLtrColor , CLtrBckColor ); PaintLetter( FBrdStack[FMarkY,FMarkX] , FMarkX , FMarkY , CLtrColor , CLtrBckColor ); end; FMarked.C := #0; FMarkX := 0; FMarkY := 0; end; end; procedure TLetterBoard.PaintBoard; var I, J : integer; begin FImage.Canvas.Brush.Color := CBckgndColor; FImage.Canvas.FillRect( FImage.ClientRect ); for J := 1 to 2 do for I := 1 to 7 do if (FBrdStack[J,I].C = #0) then PaintEmpty( (I-1)*CStoneSize+(I-1) , (J-1)*CStoneSize+(J-1) , CEmptyColor ) else PaintLetter( FBrdStack[J,I] , I , 1 , CLtrColor , CLtrBckColor ); end; //============================================================================== // P U B L I C //============================================================================== procedure TLetterBoard.Clear; var I, J : integer; begin for I := 1 to 2 do for J := 1 to 7 do FBrdStack[I,J].C := #0; PaintBoard; end; procedure TLetterBoard.SetStack( Stack : TLetterStack ); var I : integer; begin for I := 1 to 7 do begin FBrdStack[1,I] := Stack.Stack[I]; FBrdStack[2,I].C := #0; end; PaintBoard; end; procedure TLetterBoard.RemoveMarked; begin PaintEmpty( (FMarkX-1)*CStoneSize+(FMarkX-1) , (FMarkY-1)*CStoneSize+(FMarkY-1) , CEmptyColor ); FBrdStack[FMarkY,FMarkX].C := #0; FMarked.C := #0; FMarkX := 0; FMarkY := 0; end; procedure TLetterBoard.UnMark; begin if ((FMarkX = 0) or (FMarkY = 0)) then exit; PaintLetter( FBrdStack[FMarkY,FMarkX] , FMarkX , FMarkY , CLtrColor , CLtrBckColor ); FMarked.C := #0; FMarkX := 0; FMarkY := 0; end; procedure TLetterBoard.TakeBack( Letter : TLetter ); var I, J : integer; begin for I := 1 to 2 do for J := 1 to 7 do if (FBrdStack[I,J].C = #0) then begin if (Letter.Value = 0) then Letter.C := '?'; FBrdStack[I,J] := Letter; PaintLetter( FBrdStack[I,J] , J , I , CLtrColor , CLtrBckColor ); exit; end; end; function TLetterBoard.GetBottomTiles : TNewLetters; var I, J : integer; begin J := 0; for I := 1 to 7 do if (FBrdStack[2,I].C <> #0) then Inc( J ); SetLength( Result , J ); J := 0; for I := 1 to 7 do if (FBrdStack[2,I].C <> #0) then begin Result[J] := FBrdStack[2,I]; Inc( J ); end; end; end.
unit Xml.Internal.AbnfUtils; // AbnfUtils 1.0.1 // Delphi 4 to 2009 and Kylix 3 Implementation // December 2007 // // // LICENSE // // The contents of this file are subject to the Mozilla Public License Version // 1.1 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // "http://www.mozilla.org/MPL/" // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for // the specific language governing rights and limitations under the License. // // The Original Code is "AbnfUtils.pas". // // The Initial Developer of the Original Code is Dieter Köhler (Heidelberg, // Germany, "http://www.philo.de/"). Portions created by the Initial Developer // are Copyright (C) 2003-2007 Dieter Köhler. All Rights Reserved. // // Alternatively, the contents of this file may be used under the terms of the // GNU General Public License Version 2 or later (the "GPL"), in which case the // provisions of the GPL are applicable instead of those above. If you wish to // allow use of your version of this file only under the terms of the GPL, and // not to allow others to use your version of this file under the terms of the // MPL, indicate your decision by deleting the provisions above and replace them // with the notice and other provisions required by the GPL. If you do not delete // the provisions above, a recipient may use your version of this file under the // terms of any one of the MPL or the GPL. // HISTORY // // 2007-12-03 1.0.1 Made .NET compatible. // 2003-08-03 1.0.0 interface {$IFNDEF NEXTGEN} // Augmented Backus-Naur Form (ABNF) Core Rules according to RFC 2234, sect. 6.1. function IsAbnfALPHAWideChar(C: WideChar): Boolean; function IsAbnfBITWideChar(C: WideChar): Boolean; function IsAbnfCHARWideChar(C: WideChar): Boolean; function IsAbnfCRWideChar(C: WideChar): Boolean; function IsAbnfCRLFWideStr(S: WideString): Boolean; function IsAbnfCTLWideChar(C: WideChar): Boolean; function IsAbnfDIGITWideChar(C: WideChar): Boolean; function IsAbnfDQUOTEWideChar(C: WideChar): Boolean; function IsAbnfHEXDIGWideChar(C: WideChar): Boolean; function IsAbnfHTABWideChar(C: WideChar): Boolean; function IsAbnfLFWideChar(C: WideChar): Boolean; function IsAbnfLWSPWideStr(S: WideString): Boolean; function IsAbnfOCTETWideChar(C: WideChar): Boolean; function IsAbnfSPWideChar(C: WideChar): Boolean; function IsAbnfVCHARWideChar(C: WideChar): Boolean; function IsAbnfWSPWideChar(C: WideChar): Boolean; {$ENDIF NEXTGEN} function IsAbnfALPHAChar(C: Char): Boolean; function IsAbnfBITChar(C: Char): Boolean; function IsAbnfCHARChar(C: Char): Boolean; function IsAbnfCRChar(C: Char): Boolean; function IsAbnfCRLFStr(S: string): Boolean; function IsAbnfCTLChar(C: Char): Boolean; function IsAbnfDIGITChar(C: Char): Boolean; function IsAbnfDQUOTEChar(C: Char): Boolean; function IsAbnfHEXDIGChar(C: Char): Boolean; function IsAbnfHTABChar(C: Char): Boolean; function IsAbnfLFChar(C: Char): Boolean; function IsAbnfLWSPStr(S: string): Boolean; function IsAbnfOCTETChar(C: Char): Boolean; function IsAbnfSPChar(C: Char): Boolean; function IsAbnfVCHARChar(C: Char): Boolean; function IsAbnfWSPChar(C: Char): Boolean; implementation uses System.SysUtils; const FirstIndex = Low(string); AdjustIndex= 1-Low(string); {$IFNDEF NEXTGEN} function IsAbnfALPHAWideChar(C: WideChar): Boolean; begin case Word(C) of $0041..$005A, $0061..$007A: Result := True; else Result := False; end; end; function IsAbnfBITWideChar(C: WideChar): Boolean; begin if (C = '0') or (C = '1') then Result := True else Result := False; end; function IsAbnfCHARWideChar(C: WideChar): Boolean; begin case Word(C) of $0001..$007F: Result := True; else Result := False; end; end; function IsAbnfCRWideChar(C: WideChar): Boolean; begin if C = #$0D then Result := True else Result := False; end; function IsAbnfCRLFWideStr(S: wideString): Boolean; begin if S = #$0D#$0A then Result := True else Result := False; end; function IsAbnfCTLWideChar(C: WideChar): Boolean; begin case Word(C) of $0000..$001F, $007F: Result := True; else Result := False; end; end; function IsAbnfDIGITWideChar(C: WideChar): Boolean; begin case Word(C) of $0030..$0039: Result := True; else Result := False; end; end; function IsAbnfDQUOTEWideChar(C: WideChar): Boolean; begin if C = #$22 then Result := True else Result := False; end; function IsAbnfHEXDIGWideChar(C: WideChar): Boolean; begin case Word(C) of $0030..$0039, $0041..$0046: Result := True; else Result := False; end; end; function IsAbnfHTABWideChar(C: WideChar): Boolean; begin if C = #$09 then Result := True else Result := False; end; function IsAbnfLFWideChar(C: WideChar): Boolean; begin if C = #$0A then Result := True else Result := False; end; function IsAbnfLWSPWideStr(S: WideString): Boolean; var I, L: integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end else Result := True; I := 0; while I < L do begin Inc(I); case Word(S[I-AdjustIndex]) of $0020, $0009: ; // SP or TAB --> Do nothing, because everthing is alright $000D: begin // CR --> Look for LF if I = L then begin Result := False; Exit; end; Inc(I); if S[I-AdjustIndex] <> #$0A then begin Result := False; Exit; end; end; else begin Result := False; Exit; end; end; end; end; function IsAbnfOCTETWideChar(C: WideChar): Boolean; begin case Word(C) of $0000..$00FF: Result := True; else Result := False; end; end; function IsAbnfSPWideChar(C: WideChar): Boolean; begin if C = #$20 then Result := True else Result := False; end; function IsAbnfVCHARWideChar(C: WideChar): Boolean; begin case Word(C) of $0021..$007E: Result := True; else Result := False; end; end; function IsAbnfWSPWideChar(C: WideChar): Boolean; begin case Word(C) of $0020, $0009: Result := True; else Result := False; end; end; {$ENDIF NEXTGEN} function IsAbnfALPHAChar(C: Char): Boolean; begin case Byte(C) of $41..$5A, $61..$7A: Result := True; else Result := False; end; end; function IsAbnfBITChar(C: Char): Boolean; begin if (C = '0') or (C = '1') then Result := True else Result := False; end; function IsAbnfCHARChar(C: Char): Boolean; begin case Byte(C) of $01..$7F: Result := True; else Result := False; end; end; function IsAbnfCRChar(C: Char): Boolean; begin if C = #$0D then Result := True else Result := False; end; function IsAbnfCRLFStr(S: string): Boolean; begin if S = #$0D#$0A then Result := True else Result := False; end; function IsAbnfCTLChar(C: Char): Boolean; begin case Byte(C) of $00..$1F, $7F: Result := True; else Result := False; end; end; function IsAbnfDIGITChar(C: Char): Boolean; begin case Byte(C) of $30..$39: Result := True; else Result := False; end; end; function IsAbnfDQUOTEChar(C: Char): Boolean; begin if C = #$22 then Result := True else Result := False; end; function IsAbnfHEXDIGChar(C: Char): Boolean; begin case Byte(C) of $30..$39, $41..$46: Result := True; else Result := False; end; end; function IsAbnfHTABChar(C: Char): Boolean; begin if C = #$09 then Result := True else Result := False; end; function IsAbnfLFChar(C: Char): Boolean; begin if C = #$0A then Result := True else Result := False; end; function IsAbnfLWSPStr(S: string): Boolean; var I, L: integer; begin L := S.Length; if L = 0 then begin Result := False; Exit; end else Result := True; I := 0; while I < L do begin Inc(I); case Byte(S[I-AdjustIndex]) of $20, $09: ; // SP or TAB --> Do nothing, because everthing is alright $0D: begin // CR --> Look for LF if I = L then begin Result := False; Exit; end; Inc(I); if S[I-AdjustIndex] <> #$0A then begin Result := False; Exit; end; end; else begin Result := False; Exit; end; end; end; end; function IsAbnfOCTETChar(C: Char): Boolean; begin case Byte(C) of $00..$FF: Result := True; else Result := False; end; end; function IsAbnfSPChar(C: Char): Boolean; begin if C = #$20 then Result := True else Result := False; end; function IsAbnfVCHARChar(C: Char): Boolean; begin case Byte(C) of $21..$7E: Result := True; else Result := False; end; end; function IsAbnfWSPChar(C: Char): Boolean; begin case Byte(C) of $20, $09: Result := True; else Result := False; end; end; end.
unit BrickCamp.Repositories.IEmployee; interface uses System.JSON, BrickCamp.Model.TEmployee; type IEmployeeRepository = interface(IInterface) ['{1E6661EB-80D8-4A04-A16C-E8EBE3E34660}'] function GetOne(const Id: Integer): TEmployee; function GetList: TJSONArray; procedure Insert(const Employee: TEmployee); procedure Update(const Employee: TEmployee); procedure Delete(const Id: Integer); end; implementation end.
unit uDMClient; interface uses System.SysUtils, System.Classes, Data.FMTBcd, Datasnap.DBClient, Datasnap.Provider, Data.DB, Data.SqlExpr, uDM; type TDMClient = class(TDataModule) SQLFuncionarios: TSQLDataSet; dspFuncionarios: TDataSetProvider; cdsFuncionario: TClientDataSet; dspDependentes: TDataSetProvider; cdsDependente: TClientDataSet; SQLDependentes: TSQLDataSet; procedure cdsFuncionarioAfterScroll(DataSet: TDataSet); procedure SQLDependentesAfterScroll(DataSet: TDataSet); private public function GerarIDTabela(const ATabela: String): Integer; end; var DMClient: TDMClient; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TDMClient.cdsFuncionarioAfterScroll(DataSet: TDataSet); begin SQLDependentes.Params.ParamByName('ID_FUNCIONARIO').Value := SQLFuncionarios.FieldByName('ID_FUNCIONARIO').Value end; function TDMClient.GerarIDTabela(const ATabela: String): Integer; var oSQLIncremento: TSQLDataSet; begin oSQLIncremento := TSQLDataSet.Create(nil); try oSQLIncremento.SQLConnection := DM.SQLConnection; oSQLIncremento.CommandText := 'Select coalesce(max(id_'+ATabela+') ,0) + 1 As SEQ from ' + ATabela; oSQLIncremento.Open; result := oSQLIncremento.FieldByName('SEQ').AsInteger; finally oSQLIncremento.Free; end; end; procedure TDMClient.SQLDependentesAfterScroll(DataSet: TDataSet); begin SQLDependentes.Params.ParamByName('ID_FUNCIONARIO').Value := SQLFuncionarios.FieldByName('ID_FUNCIONARIO').Value end; end.
object AzPage: TAzPage Left = 227 Top = 108 BorderStyle = bsDialog Caption = 'Blob Page' ClientHeight = 397 ClientWidth = 488 Color = clBtnFace ParentFont = True OldCreateOrder = True Position = poScreenCenter PixelsPerInch = 96 TextHeight = 13 object Bevel1: TBevel Left = 8 Top = 8 Width = 465 Height = 337 Shape = bsFrame end object lbStartByte: TLabel Left = 24 Top = 24 Width = 68 Height = 13 Caption = 'Page Number:' end object Label1: TLabel Left = 224 Top = 24 Width = 129 Height = 13 Caption = '(each page has 512 bytes)' end object Label2: TLabel Left = 24 Top = 56 Width = 60 Height = 13 Caption = 'Page Count:' end object OKBtn: TButton Left = 317 Top = 364 Width = 75 Height = 25 Caption = 'Apply' Default = True ModalResult = 1 TabOrder = 6 end object CancelBtn: TButton Left = 398 Top = 364 Width = 75 Height = 25 Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 7 end object edtStartByte: TEdit Left = 98 Top = 21 Width = 103 Height = 21 Alignment = taRightJustify NumbersOnly = True TabOrder = 0 Text = '0' end object edtPageCount: TEdit Left = 98 Top = 53 Width = 103 Height = 21 Alignment = taRightJustify TabOrder = 1 Text = '1' end object rgOperation: TRadioGroup Left = 16 Top = 80 Width = 449 Height = 73 Caption = 'Operation' ItemIndex = 0 Items.Strings = ( 'Write the byte content into the specified range' 'Clears the specified range and releases the space') TabOrder = 2 end object gbCriteria: TGroupBox Left = 16 Top = 159 Width = 449 Height = 138 Caption = 'Optional Criteria' TabOrder = 3 object lblSequence: TLabel Left = 236 Top = 19 Width = 51 Height = 13 Caption = 'Sequence:' end object Label3: TLabel Left = 28 Top = 72 Width = 29 Height = 13 Caption = 'Since:' end object lblIf: TLabel Left = 45 Top = 101 Width = 12 Height = 13 Caption = 'If:' end object lblMD5: TLabeledEdit Left = 62 Top = 19 Width = 161 Height = 21 EditLabel.Width = 25 EditLabel.Height = 13 EditLabel.Caption = 'MD5:' LabelPosition = lpLeft TabOrder = 0 end object lblLease: TLabeledEdit Left = 62 Top = 46 Width = 375 Height = 21 EditLabel.Width = 46 EditLabel.Height = 13 EditLabel.Caption = 'Lease ID:' LabelPosition = lpLeft TabOrder = 3 end object cbSequenceOp: TComboBox Left = 293 Top = 19 Width = 49 Height = 21 ItemIndex = 0 TabOrder = 1 Text = '<=' Items.Strings = ( '<=' ' < ' ' = ') end object edtSequence: TEdit Left = 348 Top = 19 Width = 89 Height = 21 Alignment = taRightJustify NumbersOnly = True TabOrder = 2 Text = '0' end object cbSince: TComboBox Left = 63 Top = 73 Width = 70 Height = 21 ItemIndex = 0 TabOrder = 4 Text = 'Modified' Items.Strings = ( 'Modified' 'Unmodified') end object edtSince: TEdit Left = 139 Top = 73 Width = 298 Height = 21 TabOrder = 5 end object edtMatch: TEdit Left = 139 Top = 100 Width = 298 Height = 21 TabOrder = 7 end object cbMatch: TComboBox Left = 63 Top = 100 Width = 70 Height = 21 TabOrder = 6 Text = 'Match' Items.Strings = ( 'Match' 'None Match') end end object lblContentLocation: TLabeledEdit Left = 110 Top = 303 Width = 304 Height = 21 EditLabel.Width = 86 EditLabel.Height = 13 EditLabel.Caption = 'Content Location:' LabelPosition = lpLeft TabOrder = 4 end object btnExplorer: TButton Left = 420 Top = 303 Width = 33 Height = 25 Caption = '...' TabOrder = 5 OnClick = btnExplorerClick end end
// ************************************************************************************************** // Delphi Aio Library. // Unit Greenlets // https://github.com/Purik/AIO // The contents of this file are subject to the Apache License 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 // // // The Original Code is Greenlets.pas. // // Contributor(s): // Pavel Minenkov // Purik // https://github.com/Purik // // The Initial Developer of the Original Code is Pavel Minenkov [Purik]. // All Rights Reserved. // // ************************************************************************************************** unit Greenlets; interface uses GInterfaces, SyncObjs, SysUtils, Classes, Gevent, GarbageCollector, Hub, PasMP; type TSmartPointer<T> = record strict private FObjRef: IGCObject; FRef: T; class function IsClass: Boolean; static; public class operator Implicit(A: TSmartPointer<T>): T; class operator Implicit(A: T): TSmartPointer<T>; function Get: T; end; /// <summary> /// Ensures that the coroutines addressed to the resource /// will be queued and in the same order will be /// access when Condition is reset. state /// Thanks to the participation of the mutex / critical section can save ABA problems /// </summary> { code example: ___ greenlet/thread no.1 Cond := TGCondVariable.Create; .... do somethings .... Cond.Broadcast; ___ greenlet/thread no.2 Cond.Wait; ... wait signal ___ greenlet/thread no.3 Cond.Wait; ... wait signal } TGCondVariable = record strict private Impl: IGCondVariable; function GetImpl: IGCondVariable; public class function Make(aExternalMutex: TCriticalSection = nil): TGCondVariable; static; /// <summary> /// Wait for the signal state /// </summary> /// <remarks> /// If the decision about Wait is received inside the Lock /// will safely escape this lock inside the call Wait /// because getting into the waiting queue must happen /// to unLock-a and not lose state /// </remarks> procedure Wait(aUnlocking: TCriticalSection = nil); overload; inline; procedure Wait(aSpinUnlocking: TPasMPSpinLock); overload; inline; /// <summary> /// Toss the first in the queue (if there is one) /// </summary> procedure Signal; inline; /// <summary> /// To pull all queue /// </summary> procedure Broadcast; inline; end; /// <summary> /// Semaphore /// </summary> TGSemaphore = record strict private Impl: IGSemaphore; public class function Make(Limit: LongWord): TGSemaphore; static; procedure Acquire; inline; procedure Release; inline; function Limit: LongWord; inline; function Value: LongWord; inline; end; TGMutex = record strict private Impl: IGMutex; function GetImpl: IGMutex; public procedure Acquire; inline; procedure Release; inline; end; /// <summary> /// A queue for synchronizing coroutines or coroutines with a thread /// </summary> TGQueue<T> = record strict private Impl: IGQueue<T>; public class function Make(MaxCount: LongWord = 0): TGQueue<T>; static; procedure Enqueue(A: T); inline; procedure Dequeue(out A: T); inline; procedure Clear; inline; function Count: Integer; inline; end; {* The environment allows grinlets created in the text. context inherit environment variables *} IGreenEnvironment = interface procedure SetValue(const Name: string; Value: TPersistent); function GetValue(const Name: string): TPersistent; procedure UnsetValue(const Name: string); procedure Clear; // simple values procedure SetIntValue(const Name: string; Value: Integer); procedure SetStrValue(const Name: string; Value: string); procedure SetFloatValue(const Name: string; Value: Single); procedure SetDoubleValue(const Name: string; const Value: Double); procedure SetInt64Value(const Name: string; const Value: Int64); function GetIntValue(const Name: string): Integer; function GetStrValue(const Name: string): string; function GetFloatValue(const Name: string): Single; function GetDoubleValue(const Name: string): Double; function GetInt64Value(const Name: string): Int64; end; {* Coroutine - starts the procedure on its stack with its CPU registers with its exception handler tree *} TGreenlet = record private Impl: IGreenlet; public constructor Create(const Routine: TSymmetricRoutine); overload; constructor Create(const Routine: TSymmetricArgsRoutine; const Args: array of const); overload; constructor Create(const Routine: TSymmetricArgsStatic; const Args: array of const); overload; procedure Run; class function Spawn(const Routine: TSymmetricRoutine): TGreenlet; overload; static; class function Spawn(const Routine: TSymmetricArgsRoutine; const Args: array of const): TGreenlet; overload; static; class function Spawn(const Routine: TSymmetricArgsStatic; const Args: array of const): TGreenlet; overload; static; procedure Kill; procedure Join; class operator Implicit(const A: TGreenlet): IGreenlet; overload; class operator Implicit(const A: TGreenlet): TGevent; overload; /// <summary> /// Give Processor /// </summary> function Switch: tTuple; overload; // You can transfer parameters on the move, which are Greenlet // get through ... var X: tTuple; X: = Yield; ... // (useful when tuning the generator on the fly) function Switch(const Args: array of const): tTuple; overload; // Вернуть управление вызвавшему class function Yield: tTuple; overload; static; // Вернуть управление вызвавшей микронитке и передать данные через очередь Thread-а // (удобно при маппинге данных) class function Yield(const A: array of const): tTuple; overload; static; end; // Generator { code example: var Gen := TGenerator<Integer> I: Integer; begin Gen := TGenerator<Integer>.Create(Increment, [4, 11, 3]) for I in Gen do begin // will produce 4, 7, 10 witout allocation data in memory -> do somethings end end; procedure Increment(const Args: array of const); var Value, Stop, IncValue: Integer; begin Value := Args[0].AsInteger; Stop := Args[1].AsInteger; IncValue := Args[2].AsInteger; repeat TGenerator<Integer>.Yield(Value); Value := Value + IncValue; until Value > Stop; end; } TGenerator<T> = record private Impl: IGenerator<T>; public constructor Create(const Routine: TSymmetricRoutine); overload; constructor Create(const Routine: TSymmetricArgsRoutine;const Args: array of const); overload; constructor Create(const Routine: TSymmetricArgsStatic; const Args: array of const); overload; procedure Setup(const Args: array of const); function GetEnumerator: GInterfaces.TEnumerator<T>; class procedure Yield(const Value: T); static; end; {* Allows you to combine machines into a group and simultaneously destroy / wait *} TGreenGroup<KEY> = record private Impl: IGreenGroup<KEY>; function GetImpl: IGreenGroup<KEY>; procedure SetValue(const Key: KEY; G: IRawGreenlet); function GetValue(const Key: KEY): IRawGreenlet; public property Item[const Index: KEY]: IRawGreenlet read GetValue write SetValue; default; function Join(Timeout: LongWord = INFINITE; const RaiseError: Boolean = False): Boolean; procedure Clear; procedure KillAll; function IsEmpty: Boolean; function Copy: TGreenGroup<KEY>; function Count: Integer; end; TSymmetric = record private Impl: IRawGreenlet; public constructor Create(const Routine: TSymmetricRoutine); overload; constructor Create(const Routine: TSymmetricRoutineStatic); overload; procedure Run; class function Spawn(const Routine: TSymmetricRoutine): TSymmetric; overload; static; class function Spawn(const Routine: TSymmetricRoutineStatic): TSymmetric; overload; static; procedure Kill; procedure Join(const RaiseErrors: Boolean = False); class operator Implicit(const A: TSymmetric): IRawGreenlet; overload; class operator Implicit(const A: TSymmetric): TGevent; overload; end; TSymmetric<T> = record private Impl: IRawGreenlet; public constructor Create(const Routine: TSymmetricRoutine<T>; const A: T); overload; constructor Create(const Routine: TSymmetricRoutineStatic<T>; const A: T); overload; procedure Run; class function Spawn(const Routine: TSymmetricRoutine<T>; const A: T): TSymmetric<T>; overload; static; class function Spawn(const Routine: TSymmetricRoutineStatic<T>; const A: T): TSymmetric<T>; overload; static; procedure Kill; procedure Join(const RaiseErrors: Boolean = False); class operator Implicit(const A: TSymmetric<T>): IRawGreenlet; overload; class operator Implicit(const A: TSymmetric<T>): TGevent; overload; end; TSymmetric<T1, T2> = record private Impl: IRawGreenlet; public constructor Create(const Routine: TSymmetricRoutine<T1, T2>; const A1: T1; const A2: T2); overload; constructor Create(const Routine: TSymmetricRoutineStatic<T1, T2>; const A1: T1; const A2: T2); overload; procedure Run; class function Spawn(const Routine: TSymmetricRoutine<T1, T2>; const A1: T1; const A2: T2): TSymmetric<T1, T2>; overload; static; class function Spawn(const Routine: TSymmetricRoutineStatic<T1, T2>; const A1: T1; const A2: T2): TSymmetric<T1, T2>; overload; static; procedure Kill; procedure Join(const RaiseErrors: Boolean = False); class operator Implicit(const A: TSymmetric<T1, T2>): IRawGreenlet; overload; class operator Implicit(const A: TSymmetric<T1, T2>): TGevent; overload; end; TSymmetric<T1, T2, T3> = record private Impl: IRawGreenlet; public constructor Create(const Routine: TSymmetricRoutine<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3); overload; constructor Create(const Routine: TSymmetricRoutineStatic<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3); overload; procedure Run; class function Spawn(const Routine: TSymmetricRoutine<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3): TSymmetric<T1, T2, T3>; overload; static; class function Spawn(const Routine: TSymmetricRoutineStatic<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3): TSymmetric<T1, T2, T3>; overload; static; procedure Kill; procedure Join(const RaiseErrors: Boolean = False); class operator Implicit(const A: TSymmetric<T1, T2, T3>): IRawGreenlet; overload; class operator Implicit(const A: TSymmetric<T1, T2, T3>): TGevent; overload; end; TSymmetric<T1, T2, T3, T4> = record private Impl: IRawGreenlet; public constructor Create(const Routine: TSymmetricRoutine<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4); overload; constructor Create(const Routine: TSymmetricRoutineStatic<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4); overload; procedure Run; class function Spawn(const Routine: TSymmetricRoutine<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TSymmetric<T1, T2, T3, T4>; overload; static; class function Spawn(const Routine: TSymmetricRoutineStatic<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TSymmetric<T1, T2, T3, T4>; overload; static; procedure Kill; procedure Join(const RaiseErrors: Boolean = False); class operator Implicit(const A: TSymmetric<T1, T2, T3, T4>): IRawGreenlet; overload; class operator Implicit(const A: TSymmetric<T1, T2, T3, T4>): TGevent; overload; end; TAsymmetric<Y> = record private Impl: IAsymmetric<Y>; public constructor Create(const Routine: TAsymmetricRoutine<Y>); overload; constructor Create(const Routine: TAsymmetricRoutineStatic<Y>); overload; procedure Run; class function Spawn(const Routine: TAsymmetricRoutine<Y>): TAsymmetric<Y>; overload; static; class function Spawn(const Routine: TAsymmetricRoutineStatic<Y>): TAsymmetric<Y>; overload; static; procedure Kill; procedure Join(const RaiseErrors: Boolean = False); class operator Implicit(const A: TAsymmetric<Y>): IRawGreenlet; overload; class operator Implicit(const A: TAsymmetric<Y>): IAsymmetric<Y>; overload; class operator Implicit(const A: TAsymmetric<Y>): TGevent; overload; function GetResult(const Block: Boolean = True): Y; {$IFDEF DCC} class function Spawn<T>(const Routine: TAsymmetricRoutine<T, Y>; const A: T): TAsymmetric<Y>; overload; static; class function Spawn<T>(const Routine: TAsymmetricRoutineStatic<T, Y>; const A: T): TAsymmetric<Y>; overload; static; class function Spawn<T1,T2>(const Routine: TAsymmetricRoutine<T1,T2,Y>; const A1: T1; const A2: T2): TAsymmetric<Y>; overload; static; class function Spawn<T1,T2>(const Routine: TAsymmetricRoutineStatic<T1,T2,Y>; const A1: T1; const A2: T2): TAsymmetric<Y>; overload; static; class function Spawn<T1,T2,T3>(const Routine: TAsymmetricRoutine<T1,T2,T3,Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<Y>; overload; static; class function Spawn<T1,T2,T3>(const Routine: TAsymmetricRoutineStatic<T1,T2,T3,Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<Y>; overload; static; class function Spawn<T1,T2,T3,T4>(const Routine: TAsymmetricRoutine<T1,T2,T3,T4,Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<Y>; overload; static; class function Spawn<T1,T2,T3,T4>(const Routine: TAsymmetricRoutineStatic<T1,T2,T3,T4,Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<Y>; overload; static; {$ENDIF} end; TAsymmetric<T, Y> = record private Impl: IAsymmetric<Y>; public constructor Create(const Routine: TAsymmetricRoutine<T, Y>; const A: T); overload; constructor Create(const Routine: TAsymmetricRoutineStatic<T, Y>; const A: T); overload; procedure Run; class function Spawn(const Routine: TAsymmetricRoutine<T, Y>; const A: T): TAsymmetric<T, Y>; overload; static; class function Spawn(const Routine: TAsymmetricRoutineStatic<T, Y>; const A: T): TAsymmetric<T, Y>; overload; static; procedure Kill; procedure Join(const RaiseErrors: Boolean = False); class operator Implicit(const A: TAsymmetric<T, Y>): IRawGreenlet; overload; class operator Implicit(const A: TAsymmetric<T, Y>): IAsymmetric<Y>; overload; class operator Implicit(const A: TAsymmetric<T, Y>): TGevent; overload; function GetResult(const Block: Boolean = True): Y; end; TAsymmetric<T1, T2, Y> = record private Impl: IAsymmetric<Y>; public constructor Create(const Routine: TAsymmetricRoutine<T1, T2, Y>; const A1: T1; const A2: T2); overload; constructor Create(const Routine: TAsymmetricRoutineStatic<T1, T2, Y>; const A1: T1; const A2: T2); overload; procedure Run; class function Spawn(const Routine: TAsymmetricRoutine<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<T1, T2, Y>; overload; static; class function Spawn(const Routine: TAsymmetricRoutineStatic<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<T1, T2, Y>; overload; static; procedure Kill; procedure Join(const RaiseErrors: Boolean = False); class operator Implicit(const A: TAsymmetric<T1, T2, Y>): IRawGreenlet; overload; class operator Implicit(const A: TAsymmetric<T1, T2, Y>): IAsymmetric<Y>; overload; class operator Implicit(const A: TAsymmetric<T1, T2, Y>): TGevent; overload; function GetResult(const Block: Boolean = True): Y; end; TAsymmetric<T1, T2, T3, Y> = record private Impl: IAsymmetric<Y>; public constructor Create(const Routine: TAsymmetricRoutine<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3); overload; constructor Create(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3); overload; procedure Run; class function Spawn(const Routine: TAsymmetricRoutine<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<T1, T2, T3, Y>; overload; static; class function Spawn(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<T1, T2, T3, Y>; overload; static; procedure Kill; procedure Join(const RaiseErrors: Boolean = False); class operator Implicit(const A: TAsymmetric<T1, T2, T3, Y>): IRawGreenlet; overload; class operator Implicit(const A: TAsymmetric<T1, T2, T3, Y>): IAsymmetric<Y>; overload; class operator Implicit(const A: TAsymmetric<T1, T2, T3, Y>): TGevent; overload; function GetResult(const Block: Boolean = True): Y; end; TAsymmetric<T1, T2, T3, T4, Y> = record private Impl: IAsymmetric<Y>; public constructor Create(const Routine: TAsymmetricRoutine<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4); overload; constructor Create(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4); overload; procedure Run; class function Spawn(const Routine: TAsymmetricRoutine<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<T1, T2, T3, T4, Y>; overload; static; class function Spawn(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<T1, T2, T3, T4, Y>; overload; static; procedure Kill; procedure Join(const RaiseErrors: Boolean = False); class operator Implicit(const A: TAsymmetric<T1, T2, T3, T4, Y>): IRawGreenlet; overload; class operator Implicit(const A: TAsymmetric<T1, T2, T3, T4, Y>): IAsymmetric<Y>; overload; class operator Implicit(const A: TAsymmetric<T1, T2, T3, T4, Y>): TGevent; overload; function GetResult(const Block: Boolean = True): Y; end; TSymmetricFactory = class strict private FHub: THub; public constructor Create(Hub: THub); function Spawn(const Routine: TSymmetricRoutine): TSymmetric; overload; function Spawn(const Routine: TSymmetricRoutineStatic): TSymmetric; overload; function Spawn<T>(const Routine: TSymmetricRoutine<T>; const A: T): TSymmetric<T>; overload; function Spawn<T>(const Routine: TSymmetricRoutineStatic<T>; const A: T): TSymmetric<T>; overload; function Spawn<T1, T2>(const Routine: TSymmetricRoutine<T1, T2>; const A1: T1; const A2: T2): TSymmetric<T1, T2>; overload; function Spawn<T1, T2>(const Routine: TSymmetricRoutineStatic<T1, T2>; const A1: T1; const A2: T2): TSymmetric<T1, T2>; overload; function Spawn<T1, T2, T3>(const Routine: TSymmetricRoutine<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3): TSymmetric<T1, T2, T3>; overload; function Spawn<T1, T2, T3>(const Routine: TSymmetricRoutineStatic<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3): TSymmetric<T1, T2, T3>; overload; function Spawn<T1, T2, T3, T4>(const Routine: TSymmetricRoutine<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TSymmetric<T1, T2, T3, T4>; overload; function Spawn<T1, T2, T3, T4>(const Routine: TSymmetricRoutineStatic<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TSymmetric<T1, T2, T3, T4>; overload; end; TAsymmetricFactory<Y> = class strict private FHub: THub; public constructor Create(Hub: THub); function Spawn(const Routine: TAsymmetricRoutine<Y>): TAsymmetric<Y>; overload; function Spawn(const Routine: TAsymmetricRoutineStatic<Y>): TAsymmetric<Y>; overload; function Spawn<T>(const Routine: TAsymmetricRoutine<T, Y>; const A: T): TAsymmetric<Y>; overload; function Spawn<T>(const Routine: TAsymmetricRoutineStatic<T, Y>; const A: T): TAsymmetric<Y>; overload; function Spawn<T1, T2>(const Routine: TAsymmetricRoutine<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<Y>; overload; function Spawn<T1, T2>(const Routine: TAsymmetricRoutineStatic<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<Y>; overload; function Spawn<T1, T2, T3>(const Routine: TAsymmetricRoutine<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<Y>; overload; function Spawn<T1, T2, T3>(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<Y>; overload; function Spawn<T1, T2, T3, T4>(const Routine: TAsymmetricRoutine<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<Y>; overload; function Spawn<T1, T2, T3, T4>(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<Y>; overload; end; TGreenThread = class(TThread) class var NumberOfInstances: Integer; strict private FOnTerminate: TGevent; FHub: TSingleThreadHub; FSymmetrics: TSymmetricFactory; FHash: TObject; function ExitCond: Boolean; procedure DoAbort; protected procedure Execute; override; public constructor Create; overload; destructor Destroy; override; procedure Kill(const GreenBlock: Boolean = True); function Symmetrics: TSymmetricFactory; function Asymmetrics<Y>: TAsymmetricFactory<Y>; end; /// <summary> /// Allows nonblocking write / read for channels through Select /// </summary> TCase<T> = record private Impl: ICase; FValueHolder: TSmartPointer<T>; FValueToWrite: IFuture<T, TPendingError>; FValueToRead: IFuture<T, TPendingError>; public class operator Implicit(var A: TCase<T>): ICase; class operator Implicit(const A: TCase<T>): T; class operator Implicit(const A: T): TCase<T>; class operator Equal(a: TCase<T>; b: T) : Boolean; overload; class operator Equal(a: T; b: TCase<T>) : Boolean; overload; function Get: T; end; /// <summary> /// transmission channel, allows data to be exchanged between actors /// 1) you can catch the closing of the channel /// 2) As in Erlang and Scala, you can build graphs of processing from actors (implemented on greenlets) /// linked channels /// 3) the solution to the problem of lost-update -> after the channel is closed, you can "add" the latest data /// 4) you can catch DeadLock-and or LeaveLock-and /// 5) synchronous. channel with ThreadSafe = False - minimum of overheads for data transmission /// </summary> { code example: ___ geenlet/thread no.1 (producer) ___ Ch := TChannel<Integer>.Make; repeat A := MakeData(...) unlil not Ch.Write(A); Ch.Close; ___ geenlet/thread no.2 (consumer) ___ while Ch.Read(Value) do begin ... // do somethings end; } TChannel<T> = record type // readonly side TReadOnly = record private Impl: IReadOnly<T>; function GetDeadlockException: TExceptionClass; procedure SetDeadlockEsxception(const Value: TExceptionClass); public class operator Implicit(const Ch: TReadOnly): IAbstractChannel; class operator LessThan(var a: TCase<T>; const b: TReadOnly): Boolean; function Read(out A: T): Boolean; function ReadPending: IFuture<T, TPendingError>; function GetEnumerator: TEnumerator<T>; function Get: T; procedure Close; function IsClosed: Boolean; property DeadlockEsxception: TExceptionClass read GetDeadlockException write SetDeadlockEsxception; function IsNull: Boolean; end; // writeonly side TWriteOnly = record private Impl: IWriteOnly<T>; function GetDeadlockException: TExceptionClass; procedure SetDeadlockEsxception(const Value: TExceptionClass); public class operator Implicit(const Ch: TWriteOnly): IAbstractChannel; class operator LessThan(const a: TWriteOnly; var b: TCase<T>): Boolean; function Write(const A: T): Boolean; function WritePending(const A: T): IFuture<T, TPendingError>; procedure Close; function IsClosed: Boolean; property DeadlockEsxception: TExceptionClass read GetDeadlockException write SetDeadlockEsxception; function IsNull: Boolean; end; private Impl: IChannel<T>; function GetDeadlockException: TExceptionClass; procedure SetDeadlockEsxception(const Value: TExceptionClass); public class function Make(Size: LongWord = 0; const ThreadSafe: Boolean = True): TChannel<T>; static; class operator Implicit(const Ch: TChannel<T>): IChannel<T>; class operator LessThan(var a: TCase<T>; const b: TChannel<T>): Boolean; class operator LessThan(const a: TChannel<T>; var b: TCase<T>): Boolean; function Read(out A: T): Boolean; function ReadPending: IFuture<T, TPendingError>; function Write(const A: T): Boolean; function WritePending(const A: T): IFuture<T, TPendingError>; function ReadOnly: TReadOnly; function WriteOnly: TWriteOnly; procedure Close; function IsClosed: Boolean; function GetEnumerator: TEnumerator<T>; function Get: T; property DeadlockEsxception: TExceptionClass read GetDeadlockException write SetDeadlockEsxception; function IsNull: Boolean; end; /// <summary> /// Fan - allows to duplicate copies on channels /// </summary> { code example: Ch := TChannel<Integer>.Make; FanOut := TFanOut<Integer>.Make(Ch.ReadOnly); Consumer1 := Spawn(Routine1, FanOut.Inflate); Consumer2 := Spawn(Routine2, FanOut.Inflate); .... ConsumerN := Spawn(RoutineN, FanOut.Inflate); ... Ch.Write(1); Ch.Write(2); ... Ch.Write(M); } TFanOut<T> = record strict private Impl: IFanOut<T>; public constructor Make(const Input: TChannel<T>.TReadOnly); function Inflate(const BufSize: Integer=-1): TChannel<T>.TReadOnly; end; TFuturePromise<RESULT, STATUS> = record strict private FFuture: IFuture<RESULT, STATUS>; FPromise: IPromise<RESULT, STATUS>; procedure Init; function GetFuture: IFuture<RESULT, STATUS>; function GetPromise: IPromise<RESULT, STATUS>; public property Future: IFuture<RESULT, STATUS> read GetFuture; property Promise: IPromise<RESULT, STATUS> read GetPromise; end; TSwitchResult = (srClosed, srDeadlock, srTimeout, srReadSuccess, srWriteSuccess, srException, srError); TCaseSet = record private Collection: ICollection<ICase>; function GetCollection: ICollection<ICase>; public class function Make(const Cases: array of ICase): TCaseSet; static; class operator Implicit(const A: ICase): TCaseSet; class operator Add(a: TCaseSet; b: ICase): TCaseSet; class operator Add(a: TCaseSet; b: TCaseSet): TCaseSet; class operator Subtract(a: TCaseSet; b: ICase) : TCaseSet; class operator Subtract(a: TCaseSet; b: TCaseSet) : TCaseSet; function IsEmpty: Boolean; procedure Clear; function Has(a: ICase): Boolean; class operator In(a: ICase; b: TCaseSet) : Boolean; end; // current context function GetCurrent: TObject; function GetEnvironment: IGreenEnvironment; // Greenlet context access function Context(const Key: string): TObject; overload; // достать значение по ключу procedure Context(const Key: string; Value: TObject); overload; // установить по ключу // Garbage collector function GC(A: TObject): IGCObject; overload; // Return control from current Greenlet context procedure Yield; // Put greenlets on service in the current context // RaiseErrors=True -> Exception in some of greenlet will be thrown out function Join(const Workers: array of IRawGreenlet; const Timeout: LongWord=INFINITE; const RaiseErrors: Boolean = False): Boolean; // Join all grinlets launched in on current HUB. hub by default function JoinAll(const Timeout: LongWord=INFINITE; const RaiseErrors: Boolean = False): Boolean; // demultiplexer for a set of events, Index - index of the first signaled function Select(const Events: array of TGevent; out Index: Integer; const Timeout: LongWord=INFINITE): TWaitResult; overload; function Select(const Events: array of THandle; out Index: Integer; const Timeout: LongWord=INFINITE): Boolean; overload; // Demultiplexer for channels, for nonblocking input-output function Switch(const Cases: array of ICase; out Index: Integer; const Timeout: LongWord=INFINITE): TSwitchResult; overload; function Switch(var ReadSet: TCaseSet; var WriteSet: TCaseSet; var ErrorSet: TCaseSet; const Timeout: LongWord=INFINITE): TSwitchResult; overload; // Put the coroutine / thread on aTimeOut msec // this does not block the work of other machines procedure GreenSleep(aTimeOut: LongWord = INFINITE); // jump over to another thread procedure MoveTo(Thread: TGreenThread); procedure BeginThread; procedure EndThread; // context handlers procedure RegisterKillHandler(Cb: TThreadMethod); procedure RegisterHubHandler(Cb: TThreadMethod); type TVarRecHelper = record helper for TVarRec function IsString: Boolean; function IsObject: Boolean; function IsInteger: Boolean; function IsInt64: Boolean; function IsSingle: Boolean; function IsDouble: Boolean; function IsBoolean: Boolean; function IsVariant: Boolean; function IsClass: Boolean; function IsPointer: Boolean; function IsInterface: Boolean; function AsString: string; function AsObject: TObject; function AsLongWord: LongWord; function AsInteger: Integer; function AsInt64: Int64; function AsSingle: Single; function AsDouble: Double; function AsBoolean: Boolean; function AsVariant: Variant; function AsDateTime: TDateTime; function AsClass: TClass; function AsPointer: Pointer; function AsInterface: IInterface; function AsAnsiString: AnsiString; procedure Finalize; end; implementation uses Math, ChannelImpl, GreenletsImpl, TypInfo, {$IFDEF FPC} contnrs, fgl {$ELSE}Generics.Collections, Generics.Defaults {$ENDIF}; const READ_SET_GUID = '{809964D9-7F70-42AE-AA37-366120DEE5A6}'; WRITE_SET_GUID = '{6FAB5314-C59A-473D-8871-E30F44CBF5C4}'; ERROR_SET_GUID = '{5768E2B8-BB72-4A87-BC06-9BCD282BE588}'; type TRawGreenletPimpl = class(TRawGreenletImpl); threadvar YieldsFlag: Boolean; function GetCurrent: TObject; begin Result := TRawGreenletPimpl.GetCurrent end; function GetEnvironment: IGreenEnvironment; begin Result := TRawGreenletPimpl.GetEnviron; end; function Context(const Key: string): TObject; begin if GetCurrent = nil then Result := GetCurrentHub.HLS(Key) else begin Result := TRawGreenletImpl(GetCurrent).Context.GetValue(Key) end; end; procedure Context(const Key: string; Value: TObject); var Current: TRawGreenletImpl; Obj: TObject; CurHub: TCustomHub; begin Current := TRawGreenletImpl(GetCurrent); if Current = nil then begin if Hub.HubInfrasctuctureEnable then begin CurHub := GetCurrentHub; if Assigned(CurHub) then CurHub.HLS(Key, Value) end; end else begin if Current.Context.IsExists(Key) then begin Obj := Current.Context.GetValue(Key); Obj.Free; Current.Context.UnsetValue(Key); end; if Assigned(Value) then Current.Context.SetValue(Key, Value) end; end; function GC(A: TObject): IGCObject; var Current: TRawGreenletImpl; begin Current := TRawGreenletImpl(GetCurrent); if Current = nil then begin if HubInfrasctuctureEnable then Result := GetCurrentHub.GC(A) else Result := nil end else begin if Current.GetState <> gsKilling then Result := Current.GC.SetValue(A) else Result := nil; end; end; function PendingError2SwitchStatus(const Input: TPendingError; const IO: TIOOperation): TSwitchResult; begin Result := srError; case Input of psClosed: Result := srClosed; psDeadlock: Result := srDeadlock; psTimeout: Result := srTimeout; psException: Result := srException; psSuccess: begin case IO of ioNotSet: Result := srError; ioRead: Result := srReadSuccess; ioWrite: Result := srWriteSuccess; end; end else Result := srError end; end; { TVarRecHelper } function TVarRecHelper.AsAnsiString: AnsiString; begin Result := GreenletsImpl.AsAnsiString(Self); end; function TVarRecHelper.AsBoolean: Boolean; begin Result := GreenletsImpl.AsBoolean(Self) end; function TVarRecHelper.AsClass: TClass; begin Result := GreenletsImpl.AsClass(Self) end; function TVarRecHelper.AsDateTime: TDateTime; begin Result := GreenletsImpl.AsDateTime(Self) end; function TVarRecHelper.AsDouble: Double; begin Result := GreenletsImpl.AsDouble(Self) end; function TVarRecHelper.AsInt64: Int64; begin Result := GreenletsImpl.AsInt64(Self) end; function TVarRecHelper.AsInteger: Integer; begin Result := GreenletsImpl.AsInteger(Self) end; function TVarRecHelper.AsInterface: IInterface; begin Result := GreenletsImpl.AsInterface(Self) end; function TVarRecHelper.AsLongWord: LongWord; begin Result := LongWord(Self.AsInteger) end; function TVarRecHelper.AsObject: TObject; begin Result := GreenletsImpl.AsObject(Self) end; function TVarRecHelper.AsPointer: Pointer; begin Result := GreenletsImpl.AsPointer(Self) end; function TVarRecHelper.AsSingle: Single; begin Result := GreenletsImpl.AsSingle(Self) end; function TVarRecHelper.AsString: string; begin Result := GreenletsImpl.AsString(Self) end; function TVarRecHelper.AsVariant: Variant; begin Result := GreenletsImpl.AsVariant(Self) end; procedure TVarRecHelper.Finalize; begin GreenletsImpl.Finalize(Self); end; function TVarRecHelper.IsBoolean: Boolean; begin Result := GreenletsImpl.IsBoolean(Self) end; function TVarRecHelper.IsClass: Boolean; begin Result := GreenletsImpl.IsClass(Self) end; function TVarRecHelper.IsDouble: Boolean; begin Result := GreenletsImpl.IsDouble(Self) end; function TVarRecHelper.IsInt64: Boolean; begin Result := GreenletsImpl.IsInt64(Self) end; function TVarRecHelper.IsInteger: Boolean; begin Result := GreenletsImpl.IsInteger(Self) end; function TVarRecHelper.IsInterface: Boolean; begin Result := GreenletsImpl.IsInterface(Self) end; function TVarRecHelper.IsObject: Boolean; begin Result := GreenletsImpl.IsObject(Self) end; function TVarRecHelper.IsPointer: Boolean; begin Result := GreenletsImpl.IsPointer(Self) end; function TVarRecHelper.IsSingle: Boolean; begin Result := GreenletsImpl.IsSingle(Self) end; function TVarRecHelper.IsString: Boolean; begin Result := GreenletsImpl.IsString(Self) end; function TVarRecHelper.IsVariant: Boolean; begin Result := GreenletsImpl.IsVariant(Self) end; { TGreenlet } constructor TGreenlet.Create(const Routine: TSymmetricRoutine); begin Impl := TGreenletImpl.Create(Routine); end; constructor TGreenlet.Create(const Routine: TSymmetricArgsRoutine; const Args: array of const); begin Impl := TGreenletImpl.Create(Routine, Args); end; constructor TGreenlet.Create(const Routine: TSymmetricArgsStatic; const Args: array of const); begin Impl := TGreenletImpl.Create(Routine, Args); end; class operator TGreenlet.Implicit(const A: TGreenlet): IGreenlet; begin Result := A.Impl end; class operator TGreenlet.Implicit(const A: TGreenlet): TGevent; begin Result := A.Impl.GetOnTerminate end; procedure TGreenlet.Join; begin Greenlets.Join([Self]) end; procedure TGreenlet.Kill; begin Impl.Kill end; procedure TGreenlet.Run; begin if Impl.GetState = gsReady then Impl.Switch end; class function TGreenlet.Spawn(const Routine: TSymmetricRoutine): TGreenlet; begin Result := TGreenlet.Create(Routine); Result.Switch; end; class function TGreenlet.Spawn(const Routine: TSymmetricArgsRoutine; const Args: array of const): TGreenlet; begin Result := TGreenlet.Create(Routine, Args); Result.Switch; end; class function TGreenlet.Spawn(const Routine: TSymmetricArgsStatic; const Args: array of const): TGreenlet; begin Result := TGreenlet.Create(Routine, Args); Result.Switch; end; function TGreenlet.Switch(const Args: array of const): tTuple; begin YieldsFlag := True; Result := Impl.Switch(Args); YieldsFlag := False; end; function TGreenlet.Switch: tTuple; begin YieldsFlag := True; Result := Impl.Switch; YieldsFlag := False; end; class function TGreenlet.Yield(const A: array of const): tTuple; begin if YieldsFlag then if GetCurrent.InheritsFrom(TGreenletImpl) then Result := TGreenletImpl(GetCurrent).Yield(A) else Greenlets.Yield else Greenlets.Yield end; class function TGreenlet.Yield: tTuple; begin if YieldsFlag then if GetCurrent.InheritsFrom(TGreenletImpl) then Result := TGreenletImpl(GetCurrent).Yield else Greenlets.Yield else Greenlets.Yield end; { TChannel<T> } procedure TChannel<T>.Close; begin if Assigned(Impl) then Impl.Close end; function TChannel<T>.Get: T; begin Result := Impl.Get end; function TChannel<T>.GetDeadlockException: TExceptionClass; begin Result := Impl.GetDeadlockExceptionClass; end; function TChannel<T>.GetEnumerator: GInterfaces.TEnumerator<T>; begin Result := Impl.GetEnumerator end; class operator TChannel<T>.Implicit(const Ch: TChannel<T>): IChannel<T>; begin Result := Ch.Impl end; function TChannel<T>.IsClosed: Boolean; begin if Assigned(Impl) then Result := Impl.IsClosed else Result := False end; function TChannel<T>.IsNull: Boolean; begin Result := not Assigned(Impl) end; class operator TChannel<T>.LessThan(const a: TChannel<T>; var b: TCase<T>): Boolean; begin Result := a.WriteOnly < b; end; class operator TChannel<T>.LessThan(var a: TCase<T>; const b: TChannel<T>): Boolean; begin Result := a < b.ReadOnly end; class function TChannel<T>.Make(Size: LongWord; const ThreadSafe: Boolean): TChannel<T>; begin if Size = 0 then Result.Impl := TSyncChannel<T>.Create(ThreadSafe) else Result.Impl := TAsyncChannel<T>.Create(Size) end; function TChannel<T>.Read(out A: T): Boolean; begin Result := Impl.Read(A) end; function TChannel<T>.ReadOnly: TReadOnly; begin Result.Impl := Self.Impl.ReadOnly end; function TChannel<T>.ReadPending: IFuture<T, TPendingError>; begin Result := Impl.ReadPending; end; procedure TChannel<T>.SetDeadlockEsxception(const Value: TExceptionClass); begin Impl.SetDeadlockExceptionClass(Value); end; function TChannel<T>.Write(const A: T): Boolean; begin Result := Impl.Write(A) end; function TChannel<T>.WriteOnly: TWriteOnly; begin Result.Impl := Self.Impl.WriteOnly end; function TChannel<T>.WritePending(const A: T): IFuture<T, TPendingError>; begin Result := Impl.WritePending(A); end; function Join(const Workers: array of IRawGreenlet; const Timeout: LongWord=INFINITE; const RaiseErrors: Boolean = False): Boolean; var I: Integer; List, TermList: TList<IRawGreenlet>; StateEv: TGevent; G: IRawGreenlet; StopTime: TTime; procedure ProcessActiveList; var I, ActiveCnt: Integer; StopTime, NowStamp: TTime; CurHub: TCustomHub; begin CurHub := GetCurrentHub; StopTime := TimeOut2Time(Timeout) + Now; ActiveCnt := List.Count - TermList.Count; NowStamp := Now; while (ActiveCnt > 0) and (NowStamp <= StopTime) do begin for I := 0 to List.Count-1 do begin G := List[I]; if G.GetProxy.GetHub = nil then begin if TermList.IndexOf(G) = -1 then begin TermList.Add(G); Dec(ActiveCnt); end; end else if G.GetProxy.GetHub = CurHub then begin // this hub if G.GetState in [gsReady, gsExecute] then G.Switch; if G.GetProxy.GetHub = CurHub then begin case G.GetState of gsException: begin if RaiseErrors then G.ReraiseException else if TermList.IndexOf(G) = -1 then begin TermList.Add(G); Dec(ActiveCnt); end; end; gsReady, gsExecute: begin // nothing to do end; gsSuspended: begin Dec(ActiveCnt); end else begin if TermList.IndexOf(G) = -1 then begin TermList.Add(G); Dec(ActiveCnt); end; end; end; end; G := nil; end else begin // other hub case G.GetState of gsException: begin if RaiseErrors then G.ReraiseException else if TermList.IndexOf(G) = -1 then begin TermList.Add(G); Dec(ActiveCnt); end; end; gsTerminated, gsKilled: begin if TermList.IndexOf(G) = -1 then begin TermList.Add(G); Dec(ActiveCnt); end; end else Dec(ActiveCnt); end; end; NowStamp := Now; end; if (ActiveCnt > 0) then begin if GetCurrent = nil then // we will give an opportunity to work out the demultiplexer CurHub.Serve(0) else // let's work out the neighboring contexts TRawGreenletImpl(GetCurrent).Yield; end end; end; begin if Length(Workers) = 0 then Exit(True); List := TList<IRawGreenlet>.Create; TermList := TList<IRawGreenlet>.Create; StateEv := TGevent.Create; try for I := 0 to High(Workers) do begin if Assigned(Workers[I]) and (Workers[I].GetInstance <> GetCurrent) then begin G := Workers[I]; List.Add(G); StateEv.Associate(G.GetOnStateChanged, I); end; end; if Timeout = INFINITE then begin while TermList.Count < List.Count do begin ProcessActiveList; if TermList.Count < List.Count then StateEv.WaitFor end; end else if Timeout = 0 then begin ProcessActiveList end else begin StopTime := Now + GreenletsImpl.TimeOut2Time(Timeout); while (StopTime > Now) and (TermList.Count < List.Count) do begin ProcessActiveList; if TermList.Count < List.Count then StateEv.WaitFor(GreenletsImpl.Time2TimeOut(StopTime-Now)); end; end; Result := TermList.Count = List.Count; finally List.Free; TermList.Free; StateEv.Free; end; end; function JoinAll(const Timeout: LongWord=INFINITE; const RaiseErrors: Boolean = False): Boolean; var StopTime: TTime; All: tArrayOfGreenlet; Joiner: TJoiner; Index: Integer; procedure ReraiseExceptions; var I: Integer; begin for I := 0 to High(All) do if All[I].GetState = gsException then TGreenletImpl(All[I].GetInstance).ReraiseException; end; begin Assert(GetCurrent = nil, 'You can not call JoinAll from Greenlet context'); Result := False; Joiner := GetJoiner(GetCurrentHub); StopTime := Now + TimeOut2Time(Timeout); repeat All := Joiner.GetAll; ReraiseExceptions; if Join(All, 0, RaiseErrors) then begin Exit(True); end; if (not Joiner.HasExecutions) and (Now < StopTime) then Select(Joiner.GetStateEvents, Index, Time2TimeOut(StopTime - Now)); ReraiseExceptions; until Now >= StopTime; end; function Select(const Events: array of TGevent; out Index: Integer; const Timeout: LongWord=INFINITE): TWaitResult; begin Result := TGevent.WaitMultiple(Events, Index, Timeout) end; function Switch(const Cases: array of ICase; out Index: Integer; const Timeout: LongWord=INFINITE): TSwitchResult; var Events: array of TGevent; InternalIndex, I: Integer; WaitRes: TWaitResult; begin if Length(Cases) = 0 then raise EArgumentException.Create('Cases sequence is empty'); SetLength(Events, 2*Length(Cases)); for I := 0 to High(Cases) do begin Events[2*I] := Cases[I].GetOnSuccess; Events[2*I+1] := Cases[I].GetOnError; end; Index := -1; WaitRes := Select(Events, InternalIndex, Timeout); case WaitRes of wrSignaled: begin Index := InternalIndex div 2; if (InternalIndex mod 2) = 0 then Result := PendingError2SwitchStatus(psSuccess, Cases[Index].Operation) else Result := PendingError2SwitchStatus(Cases[Index].GetErrorHolder.GetErrorCode, Cases[Index].Operation) end; wrTimeout: Result := srTimeout; else Result := srError end; end; function Switch(var ReadSet: TCaseSet; var WriteSet: TCaseSet; var ErrorSet: TCaseSet; const Timeout: LongWord=INFINITE): TSwitchResult; var Iter: ICase; I, WriteOffs, ErrOffs, InternalIndex, Index: Integer; ReadEvents, WriteEvents, ErrorEvents, AllEvents: array of TGevent; WaitRes: TWaitResult; begin for Iter in ReadSet.GetCollection do if Iter.Operation <> ioRead then raise EArgumentException.Create('ReadSet must contain initialized cases'); for Iter in WriteSet.GetCollection do if Iter.Operation <> ioWrite then raise EArgumentException.Create('WriteSet must contain initialized cases'); if ReadSet.IsEmpty and WriteSet.IsEmpty and ErrorSet.IsEmpty then raise EArgumentException.Create('ReadSet, WriteSet, ErrorSet are is empty'); SetLength(ReadEvents, ReadSet.GetCollection.Count); for I := 0 to High(ReadEvents) do ReadEvents[I] := ReadSet.GetCollection.Get(I).OnSuccess; WriteOffs := Length(ReadEvents); SetLength(WriteEvents, WriteSet.GetCollection.Count); for I := 0 to High(WriteEvents) do WriteEvents[I] := WriteSet.GetCollection.Get(I).OnSuccess; ErrOffs := Length(WriteEvents) + Length(ReadEvents); SetLength(ErrorEvents, ErrorSet.GetCollection.Count); for I := 0 to High(ErrorEvents) do ErrorEvents[I] := ErrorSet.GetCollection.Get(I).OnError; SetLength(AllEvents, Length(ReadEvents) + Length(WriteEvents) + Length(ErrorEvents)); Move(ReadEvents[0], AllEvents[0], Length(ReadEvents)*SizeOf(TGevent)); Move(WriteEvents[0], AllEvents[WriteOffs], Length(WriteEvents)*SizeOf(TGevent)); Move(ErrorEvents[0], AllEvents[ErrOffs], Length(ErrorEvents)*SizeOf(TGevent)); InternalIndex := -1; WaitRes := Select(AllEvents, InternalIndex, Timeout); case WaitRes of wrSignaled: begin if InRange(InternalIndex, 0, WriteOffs-1) then begin Index := InternalIndex; Iter := ReadSet.GetCollection.Get(Index); Result := srReadSuccess; WriteSet.Clear; ErrorSet.Clear; ReadSet := TCaseSet.Make([Iter]); end else if InRange(InternalIndex, WriteOffs, ErrOffs-1) then begin Index := InternalIndex - WriteOffs; Iter := WriteSet.GetCollection.Get(Index); Result := srWriteSuccess; ReadSet.Clear; ErrorSet.Clear; WriteSet := TCaseSet.Make([Iter]) end else begin Index := InternalIndex - ErrOffs; Iter := ErrorSet.GetCollection.Get(Index); Result := PendingError2SwitchStatus(Iter.ErrorHolder.GetErrorCode, Iter.Operation); ReadSet.Clear; WriteSet.Clear; ErrorSet := TCaseSet.Make([Iter]) end end; wrTimeout: Result := srTimeout; else Result := srError end; end; function Select(const Events: array of THandle; out Index: Integer; const Timeout: LongWord=INFINITE): Boolean; var Gevents: array of TGevent; I: Integer; begin SetLength(Gevents, Length(Events)); for I := 0 to High(Gevents) do begin Gevents[I] := TGevent.Create(Events[I]); end; try Result := Select(Gevents, Index) = wrSignaled finally for I := 0 to High(Gevents) do Gevents[I].Free end; end; procedure TimeoutCb(Id: THandle; Data: Pointer); begin TGevent(Data).SetEvent(True); end; procedure GreenSleep(aTimeOut: LongWord = INFINITE); var Ev: TGevent; Timeout: THandle; begin if GetCurrent = nil then begin Timeout := 0; Ev := TGEvent.Create; try if aTimeOut = 0 then begin Timeout := Hub.GetCurrentHub.CreateTimeout(TimeoutCb, Ev, aTimeOut); Ev.WaitFor end else Ev.WaitFor(aTimeOut) finally if Timeout <> 0 then Hub.GetCurrentHub.DestroyTimeout(Timeout); Ev.Free; end; end else begin TRawGreenletPimpl(GetCurrent).Sleep(aTimeOut); end; end; procedure MoveTo(Thread: TGreenThread); begin if GetCurrent <> nil then TRawGreenletPimpl(GetCurrent).MoveTo(Thread); end; procedure BeginThread; begin if GetCurrent <> nil then TRawGreenletPimpl(GetCurrent).BeginThread; end; procedure EndThread; begin if GetCurrent <> nil then TRawGreenletPimpl(GetCurrent).EndThread; end; procedure RegisterKillHandler(Cb: TThreadMethod); begin if GetCurrent = nil then begin end else begin TRawGreenletPimpl(GetCurrent).KillTriggers.OnCb(Cb); end; end; procedure RegisterHubHandler(Cb: TThreadMethod); begin if GetCurrent = nil then begin // nothing end else begin TRawGreenletPimpl(GetCurrent).HubTriggers.OnCb(Cb); end; end; procedure Yield; begin if GetCurrent <> nil then TRawGreenletImpl(GetCurrent).Yield else begin GetCurrentHub.Serve(INFINITE) end; end; { TSymmetric<T> } constructor TSymmetric<T>.Create(const Routine: TSymmetricRoutine<T>; const A: T); begin Impl := TSymmetricImpl<T>.Create(Routine, A); end; constructor TSymmetric<T>.Create(const Routine: TSymmetricRoutineStatic<T>; const A: T); begin Impl := TSymmetricImpl<T>.Create(Routine, A); end; class operator TSymmetric<T>.Implicit(const A: TSymmetric<T>): IRawGreenlet; begin Result := A.Impl end; class operator TSymmetric<T>.Implicit(const A: TSymmetric<T>): TGevent; begin Result := A.Impl.GetOnTerminate end; procedure TSymmetric<T>.Join(const RaiseErrors: Boolean); begin Impl.Join(RaiseErrors); end; procedure TSymmetric<T>.Kill; begin Impl.Kill end; procedure TSymmetric<T>.Run; begin if Impl.GetState = gsReady then Impl.GetProxy.Pulse end; class function TSymmetric<T>.Spawn(const Routine: TSymmetricRoutineStatic<T>; const A: T): TSymmetric<T>; begin Result := TSymmetric<T>.Create(Routine, A); Result.Impl.Switch; end; class function TSymmetric<T>.Spawn(const Routine: TSymmetricRoutine<T>; const A: T): TSymmetric<T>; begin Result := TSymmetric<T>.Create(Routine, A); Result.Impl.Switch; end; { TChannel<T>.TReadOnly } function TChannel<T>.TReadOnly.Get: T; begin Result := Impl.Get end; procedure TChannel<T>.TReadOnly.Close; begin Impl.Close end; function TChannel<T>.TReadOnly.GetDeadlockException: TExceptionClass; begin Result := Impl.GetDeadlockExceptionClass; end; function TChannel<T>.TReadOnly.GetEnumerator: GInterfaces.TEnumerator<T>; begin Result := Impl.GetEnumerator end; class operator TChannel<T>.TReadOnly.Implicit(const Ch: TReadOnly): IAbstractChannel; begin Result := Ch.Impl end; function TChannel<T>.TReadOnly.IsClosed: Boolean; begin Result := Impl.IsClosed end; function TChannel<T>.TReadOnly.IsNull: Boolean; begin Result := not Assigned(Impl) end; class operator TChannel<T>.TReadOnly.LessThan(var a: TCase<T>; const b: TReadOnly): Boolean; var Future: IFuture<T, TPendingError>; CaseImpl: ICase; Index: Integer; begin CaseImpl := a; if b.IsNull then Exit(False); if (CaseImpl.Operation <> ioNotSet) then begin if Select([CaseImpl.OnSuccess, CaseImpl.OnError], Index, 0) = wrTimeout then raise EReadError.Create('This case already reserved for pending IO operation'); end; Future := b.Impl.ReadPending; a.FValueToRead := Future; CaseImpl.Operation := ioRead; CaseImpl.OnSuccess := Future.OnFullFilled; CaseImpl.OnError := Future.OnRejected; CaseImpl.ErrorHolder := Future; Result := True; end; function TChannel<T>.TReadOnly.Read(out A: T): Boolean; begin Result := Impl.Read(A) end; function TChannel<T>.TReadOnly.ReadPending: IFuture<T, TPendingError>; begin Result := Impl.ReadPending; end; procedure TChannel<T>.TReadOnly.SetDeadlockEsxception( const Value: TExceptionClass); begin Impl.SetDeadlockExceptionClass(Value); end; { TChannel<T>.TWriteOnly } procedure TChannel<T>.TWriteOnly.Close; begin Impl.Close end; function TChannel<T>.TWriteOnly.GetDeadlockException: TExceptionClass; begin Result := Impl.GetDeadlockExceptionClass end; class operator TChannel<T>.TWriteOnly.Implicit( const Ch: TWriteOnly): IAbstractChannel; begin Result := Ch.Impl end; function TChannel<T>.TWriteOnly.IsClosed: Boolean; begin Result := Impl.IsClosed end; function TChannel<T>.TWriteOnly.IsNull: Boolean; begin Result := not Assigned(Impl) end; class operator TChannel<T>.TWriteOnly.LessThan(const a: TWriteOnly; var b: TCase<T>): Boolean; var Future: IFuture<T, TPendingError>; CaseImpl: ICase; Index: Integer; begin CaseImpl := b; if a.IsNull then Exit(False); if (CaseImpl.Operation <> ioNotSet) then begin if Select([CaseImpl.OnSuccess, CaseImpl.OnError], Index, 0) = wrTimeout then raise EWriteError.Create('This case already reserved for pending IO operation'); end; if not CaseImpl.WriteValueExists then raise EWriteError.Create('You must set value for pending write'); Future := a.Impl.WritePending(b.FValueHolder); b.FValueToRead := Future; CaseImpl.Operation := ioWrite; CaseImpl.OnSuccess := Future.OnFullFilled; CaseImpl.OnError := Future.OnRejected; CaseImpl.ErrorHolder := Future; Result := True; end; {var Future: IFuture<T, TPendingError>; begin Future := b.Impl.ReadPending; a.Impl := TCaseImpl.Create(Future, ioRead, Future.OnFullFilled, Future.OnRejected); a.FValueToRead := Future; Result := True; end; } procedure TChannel<T>.TWriteOnly.SetDeadlockEsxception( const Value: TExceptionClass); begin Impl.SetDeadlockExceptionClass(Value); end; function TChannel<T>.TWriteOnly.Write(const A: T): Boolean; begin Result := Impl.Write(A); end; function TChannel<T>.TWriteOnly.WritePending( const A: T): IFuture<T, TPendingError>; begin Result := Impl.WritePending(A) end; { TSymmetric<T1, T2> } constructor TSymmetric<T1, T2>.Create( const Routine: TSymmetricRoutine<T1, T2>; const A1: T1; const A2: T2); begin Impl := TSymmetricImpl<T1,T2>.Create(Routine, A1, A2) end; constructor TSymmetric<T1, T2>.Create( const Routine: TSymmetricRoutineStatic<T1, T2>; const A1: T1; const A2: T2); begin Impl := TSymmetricImpl<T1,T2>.Create(Routine, A1, A2) end; class operator TSymmetric<T1, T2>.Implicit( const A: TSymmetric<T1, T2>): TGevent; begin Result := A.Impl.GetOnTerminate end; class operator TSymmetric<T1, T2>.Implicit( const A: TSymmetric<T1, T2>): IRawGreenlet; begin Result := A.Impl end; procedure TSymmetric<T1, T2>.Join(const RaiseErrors: Boolean); begin Impl.Join(RaiseErrors); end; procedure TSymmetric<T1, T2>.Kill; begin Impl.Kill end; procedure TSymmetric<T1, T2>.Run; begin if Impl.GetState = gsReady then Impl.GetProxy.Pulse end; class function TSymmetric<T1, T2>.Spawn( const Routine: TSymmetricRoutine<T1, T2>; const A1: T1; const A2: T2): TSymmetric<T1, T2>; begin Result := TSymmetric<T1, T2>.Create(Routine, A1, A2); Result.Impl.Switch; end; class function TSymmetric<T1, T2>.Spawn( const Routine: TSymmetricRoutineStatic<T1, T2>; const A1: T1; const A2: T2): TSymmetric<T1, T2>; begin Result := TSymmetric<T1, T2>.Create(Routine, A1, A2); Result.Impl.Switch; end; { TSymmetric<T1, T2, T3> } constructor TSymmetric<T1, T2, T3>.Create( const Routine: TSymmetricRoutine<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3); begin Impl := TSymmetricImpl<T1,T2,T3>.Create(Routine, A1, A2, A3); end; constructor TSymmetric<T1, T2, T3>.Create( const Routine: TSymmetricRoutineStatic<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3); begin Impl := TSymmetricImpl<T1,T2,T3>.Create(Routine, A1, A2, A3); end; class operator TSymmetric<T1, T2, T3>.Implicit( const A: TSymmetric<T1, T2, T3>): TGevent; begin Result := A.Impl.GetOnTerminate end; class operator TSymmetric<T1, T2, T3>.Implicit( const A: TSymmetric<T1, T2, T3>): IRawGreenlet; begin Result := A.Impl end; procedure TSymmetric<T1, T2, T3>.Join(const RaiseErrors: Boolean); begin Impl.Join(RaiseErrors); end; procedure TSymmetric<T1, T2, T3>.Kill; begin Impl.Kill end; procedure TSymmetric<T1, T2, T3>.Run; begin if Impl.GetState = gsReady then Impl.GetProxy.Pulse end; class function TSymmetric<T1, T2, T3>.Spawn( const Routine: TSymmetricRoutine<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3): TSymmetric<T1, T2, T3>; begin Result := TSymmetric<T1, T2, T3>.Create(Routine, A1, A2, A3); Result.Impl.Switch; end; class function TSymmetric<T1, T2, T3>.Spawn( const Routine: TSymmetricRoutineStatic<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3): TSymmetric<T1, T2, T3>; begin Result := TSymmetric<T1, T2, T3>.Create(Routine, A1, A2, A3); Result.Impl.Switch; end; { TAsymmetric<Y> } constructor TAsymmetric<Y>.Create( const Routine: TAsymmetricRoutine<Y>); begin Impl := TAsymmetricImpl<Y>.Create(Routine); end; constructor TAsymmetric<Y>.Create( const Routine: TAsymmetricRoutineStatic<Y>); begin Impl := TAsymmetricImpl<Y>.Create(Routine); end; function TAsymmetric<Y>.GetResult(const Block: Boolean): Y; begin Result := Impl.GetResult(Block) end; class operator TAsymmetric<Y>.Implicit(const A: TAsymmetric<Y>): IAsymmetric<Y>; begin Result := A.Impl; end; procedure TAsymmetric<Y>.Join(const RaiseErrors: Boolean); begin Greenlets.Join([Self], INFINITE, RaiseErrors) end; procedure TAsymmetric<Y>.Kill; begin Impl.Kill end; procedure TAsymmetric<Y>.Run; begin if Impl.GetState = gsReady then Impl.GetProxy.Pulse end; class operator TAsymmetric<Y>.Implicit(const A: TAsymmetric<Y>): IRawGreenlet; begin Result := A.Impl; end; class function TAsymmetric<Y>.Spawn( const Routine: TAsymmetricRoutine<Y>): TAsymmetric<Y>; begin Result := TAsymmetric<Y>.Create(Routine); Result.Impl.Switch; end; class function TAsymmetric<Y>.Spawn( const Routine: TAsymmetricRoutineStatic<Y>): TAsymmetric<Y>; begin Result := TAsymmetric<Y>.Create(Routine); Result.Impl.Switch; end; {$IFDEF DCC} class function TAsymmetric<Y>.Spawn<T>(const Routine: TAsymmetricRoutine<T, Y>; const A: T): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T,Y>.Create(Routine, A); Result.Impl.Switch; end; class function TAsymmetric<Y>.Spawn<T>(const Routine: TAsymmetricRoutineStatic<T, Y>; const A: T): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T,Y>.Create(Routine, A); Result.Impl.Switch; end; class function TAsymmetric<Y>.Spawn<T1, T2>(const Routine: TAsymmetricRoutine<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T1,T2,Y>.Create(Routine, A1, A2); Result.Impl.Switch; end; class function TAsymmetric<Y>.Spawn<T1, T2>(const Routine: TAsymmetricRoutineStatic<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T1,T2,Y>.Create(Routine, A1, A2); Result.Impl.Switch; end; class function TAsymmetric<Y>.Spawn<T1, T2, T3>(const Routine: TAsymmetricRoutine<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T1,T2,T3,Y>.Create(Routine, A1, A2, A3); Result.Impl.Switch; end; class function TAsymmetric<Y>.Spawn<T1, T2, T3>(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T1,T2,T3,Y>.Create(Routine, A1, A2, A3); Result.Impl.Switch; end; class function TAsymmetric<Y>.Spawn<T1,T2,T3,T4>(const Routine: TAsymmetricRoutine<T1,T2,T3,T4,Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T1,T2,T3,T4,Y>.Create(Routine, A1, A2, A3, A4); Result.Impl.Switch; end; class function TAsymmetric<Y>.Spawn<T1,T2,T3,T4>(const Routine: TAsymmetricRoutineStatic<T1,T2,T3,T4,Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T1,T2,T3,T4,Y>.Create(Routine, A1, A2, A3, A4); Result.Impl.Switch; end; {$ENDIF} class operator TAsymmetric<Y>.Implicit(const A: TAsymmetric<Y>): TGevent; begin Result := A.Impl.GetOnTerminate end; { TAsymmetric<T, Y> } constructor TAsymmetric<T, Y>.Create(const Routine: TAsymmetricRoutine<T, Y>; const A: T); begin Impl := TAsymmetricImpl<T, Y>.Create(Routine, A) end; constructor TAsymmetric<T, Y>.Create( const Routine: TAsymmetricRoutineStatic<T, Y>; const A: T); begin Impl := TAsymmetricImpl<T, Y>.Create(Routine, A) end; function TAsymmetric<T, Y>.GetResult(const Block: Boolean): Y; begin Result := Impl.GetResult(Block) end; class operator TAsymmetric<T, Y>.Implicit( const A: TAsymmetric<T, Y>): IAsymmetric<Y>; begin Result := A.Impl end; procedure TAsymmetric<T, Y>.Join(const RaiseErrors: Boolean); begin Greenlets.Join([Self], INFINITE, RaiseErrors) end; procedure TAsymmetric<T, Y>.Kill; begin Impl.Kill end; procedure TAsymmetric<T, Y>.Run; begin if Impl.GetState = gsReady then Impl.GetProxy.Pulse end; class operator TAsymmetric<T, Y>.Implicit( const A: TAsymmetric<T, Y>): IRawGreenlet; begin Result := A.Impl; end; class function TAsymmetric<T, Y>.Spawn(const Routine: TAsymmetricRoutine<T, Y>; const A: T): TAsymmetric<T, Y>; begin Result := TAsymmetric<T, Y>.Create(Routine, A); Result.Impl.Switch; end; class function TAsymmetric<T, Y>.Spawn( const Routine: TAsymmetricRoutineStatic<T, Y>; const A: T): TAsymmetric<T, Y>; begin Result := TAsymmetric<T, Y>.Create(Routine, A); Result.Impl.Switch; end; class operator TAsymmetric<T, Y>.Implicit(const A: TAsymmetric<T, Y>): TGevent; begin Result := A.Impl.GetOnTerminate end; { TAsymmetric<T1, T2, Y> } constructor TAsymmetric<T1, T2, Y>.Create( const Routine: TAsymmetricRoutine<T1, T2, Y>; const A1: T1; const A2: T2); begin Impl := TAsymmetricImpl<T1, T2, Y>.Create(Routine, A1, A2) end; constructor TAsymmetric<T1, T2, Y>.Create( const Routine: TAsymmetricRoutineStatic<T1, T2, Y>; const A1: T1; const A2: T2); begin Impl := TAsymmetricImpl<T1, T2, Y>.Create(Routine, A1, A2) end; function TAsymmetric<T1, T2, Y>.GetResult(const Block: Boolean): Y; begin Result := Impl.GetResult(Block) end; class operator TAsymmetric<T1, T2, Y>.Implicit( const A: TAsymmetric<T1, T2, Y>): IRawGreenlet; begin Result := A.Impl end; class operator TAsymmetric<T1, T2, Y>.Implicit( const A: TAsymmetric<T1, T2, Y>): IAsymmetric<Y>; begin Result := A.Impl end; procedure TAsymmetric<T1, T2, Y>.Join(const RaiseErrors: Boolean); begin Greenlets.Join([Self], INFINITE, RaiseErrors) end; procedure TAsymmetric<T1, T2, Y>.Kill; begin Impl.Kill end; procedure TAsymmetric<T1, T2, Y>.Run; begin if Impl.GetState = gsReady then Impl.GetProxy.Pulse end; class function TAsymmetric<T1, T2, Y>.Spawn( const Routine: TAsymmetricRoutine<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<T1, T2, Y>; begin Result := TAsymmetric<T1, T2, Y>.Create(Routine, A1, A2); Result.Impl.Switch; end; class function TAsymmetric<T1, T2, Y>.Spawn( const Routine: TAsymmetricRoutineStatic<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<T1, T2, Y>; begin Result := TAsymmetric<T1, T2, Y>.Create(Routine, A1, A2); Result.Impl.Switch; end; class operator TAsymmetric<T1, T2, Y>.Implicit( const A: TAsymmetric<T1, T2, Y>): TGevent; begin Result := A.Impl.GetOnTerminate end; { TSymmetric } constructor TSymmetric.Create(const Routine: TSymmetricRoutine); begin Impl := TSymmetricImpl.Create(Routine); end; constructor TSymmetric.Create( const Routine: TSymmetricRoutineStatic); begin Impl := TSymmetricImpl.Create(Routine); end; class operator TSymmetric.Implicit(const A: TSymmetric): IRawGreenlet; begin Result := A.Impl end; class operator TSymmetric.Implicit(const A: TSymmetric): TGevent; begin Result := A.Impl.GetOnTerminate end; procedure TSymmetric.Join(const RaiseErrors: Boolean); begin Impl.Join(RaiseErrors) end; procedure TSymmetric.Kill; begin Impl.Kill end; procedure TSymmetric.Run; begin if Impl.GetState = gsReady then Impl.GetProxy.Pulse end; class function TSymmetric.Spawn(const Routine: TSymmetricRoutine): TSymmetric; begin Result := TSymmetric.Create(Routine); Result.Impl.Switch; end; class function TSymmetric.Spawn( const Routine: TSymmetricRoutineStatic): TSymmetric; begin Result := TSymmetric.Create(Routine); Result.Impl.Switch; end; { TAsymmetric<T1, T2, T3, Y> } constructor TAsymmetric<T1, T2, T3, Y>.Create( const Routine: TAsymmetricRoutine<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3); begin Impl := TAsymmetricImpl<T1, T2, T3, Y>.Create(Routine, A1, A2, A3) end; constructor TAsymmetric<T1, T2, T3, Y>.Create( const Routine: TAsymmetricRoutineStatic<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3); begin Impl := TAsymmetricImpl<T1, T2, T3, Y>.Create(Routine, A1, A2, A3) end; function TAsymmetric<T1, T2, T3, Y>.GetResult(const Block: Boolean): Y; begin Result := Impl.GetResult(Block) end; class operator TAsymmetric<T1, T2, T3, Y>.Implicit( const A: TAsymmetric<T1, T2, T3, Y>): IRawGreenlet; begin Result := A.Impl end; class operator TAsymmetric<T1, T2, T3, Y>.Implicit( const A: TAsymmetric<T1, T2, T3, Y>): IAsymmetric<Y>; begin Result := A.Impl end; procedure TAsymmetric<T1, T2, T3, Y>.Join(const RaiseErrors: Boolean); begin Greenlets.Join([Self], INFINITE, RaiseErrors) end; procedure TAsymmetric<T1, T2, T3, Y>.Kill; begin Impl.Kill end; procedure TAsymmetric<T1, T2, T3, Y>.Run; begin if Impl.GetState = gsReady then Impl.GetProxy.Pulse end; class function TAsymmetric<T1, T2, T3, Y>.Spawn( const Routine: TAsymmetricRoutine<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<T1, T2, T3, Y>; begin Result := TAsymmetric<T1, T2, T3, Y>.Create(Routine, A1, A2, A3); Result.Impl.Switch; end; class function TAsymmetric<T1, T2, T3, Y>.Spawn( const Routine: TAsymmetricRoutineStatic<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<T1, T2, T3, Y>; begin Result := TAsymmetric<T1, T2, T3, Y>.Create(Routine, A1, A2, A3); Result.Impl.Switch; end; class operator TAsymmetric<T1, T2, T3, Y>.Implicit( const A: TAsymmetric<T1, T2, T3, Y>): TGevent; begin Result := A.Impl.GetOnTerminate end; { TAsymmetric<T1, T2, T3, T4, Y> } constructor TAsymmetric<T1, T2, T3, T4, Y>.Create( const Routine: TAsymmetricRoutine<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4); begin Impl := TAsymmetricImpl<T1, T2, T3, T4, Y>.Create(Routine, A1, A2, A3, A4) end; constructor TAsymmetric<T1, T2, T3, T4, Y>.Create( const Routine: TAsymmetricRoutineStatic<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4); begin Impl := TAsymmetricImpl<T1, T2, T3, T4, Y>.Create(Routine, A1, A2, A3, A4) end; function TAsymmetric<T1, T2, T3, T4, Y>.GetResult(const Block: Boolean): Y; begin Result := Impl.GetResult(Block) end; class operator TAsymmetric<T1, T2, T3, T4, Y>.Implicit( const A: TAsymmetric<T1, T2, T3, T4, Y>): IRawGreenlet; begin Result := A.Impl end; class operator TAsymmetric<T1, T2, T3, T4, Y>.Implicit( const A: TAsymmetric<T1, T2, T3, T4, Y>): IAsymmetric<Y>; begin Result := A.Impl end; procedure TAsymmetric<T1, T2, T3, T4, Y>.Join(const RaiseErrors: Boolean); begin Greenlets.Join([Self], INFINITE, RaiseErrors) end; procedure TAsymmetric<T1, T2, T3, T4, Y>.Kill; begin Impl.Kill end; procedure TAsymmetric<T1, T2, T3, T4, Y>.Run; begin if Impl.GetState = gsReady then Impl.GetProxy.Pulse end; class function TAsymmetric<T1, T2, T3, T4, Y>.Spawn( const Routine: TAsymmetricRoutine<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<T1, T2, T3, T4, Y>; begin Result := TAsymmetric<T1, T2, T3, T4, Y>.Create(Routine, A1, A2, A3, A4); Result.Impl.Switch; end; class function TAsymmetric<T1, T2, T3, T4, Y>.Spawn( const Routine: TAsymmetricRoutineStatic<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<T1, T2, T3, T4, Y>; begin Result := TAsymmetric<T1, T2, T3, T4, Y>.Create(Routine, A1, A2, A3, A4); Result.Impl.Switch; end; class operator TAsymmetric<T1, T2, T3, T4, Y>.Implicit( const A: TAsymmetric<T1, T2, T3, T4, Y>): TGevent; begin Result := A.Impl.GetOnTerminate end; { TGenerator<T> } constructor TGenerator<T>.Create(const Routine: TSymmetricRoutine); begin Impl := TGeneratorImpl<T>.Create(Routine); end; constructor TGenerator<T>.Create(const Routine: TSymmetricArgsRoutine; const Args: array of const); begin Impl := TGeneratorImpl<T>.Create(Routine, Args); end; constructor TGenerator<T>.Create(const Routine: TSymmetricArgsStatic; const Args: array of const); begin Impl := TGeneratorImpl<T>.Create(Routine, Args); end; function TGenerator<T>.GetEnumerator: GInterfaces.TEnumerator<T>; begin Result := Impl.GetEnumerator end; procedure TGenerator<T>.Setup(const Args: array of const); begin Impl.Setup(Args); end; class procedure TGenerator<T>.Yield(const Value: T); begin TGeneratorImpl<T>.Yield(Value) end; { TGreenThread } function TGreenThread.Asymmetrics<Y>: TAsymmetricFactory<Y>; var Key: string; Hash: TObjectDictionary<string, TObject>; begin Key := TAsymmetricFactory<Y>.ClassName; Hash := TObjectDictionary<string, TObject>(FHash); if Hash.ContainsKey(Key) then begin Result := TAsymmetricFactory<Y>(Hash[Key]); end else begin Result := TAsymmetricFactory<Y>.Create(DefHub(Self)); Hash.Add(Key, Result) end; end; constructor TGreenThread.Create; begin FOnTerminate := TGevent.Create(True); inherited Create(False); FSymmetrics := TSymmetricFactory.Create(DefHub(Self)); FHash := TObjectDictionary<string, TObject>.Create([doOwnsValues]); AtomicIncrement(NumberOfInstances); end; destructor TGreenThread.Destroy; begin Kill(True); FOnTerminate.Free; if Assigned(FHub) then begin FHub.Free; end; FSymmetrics.Free; FHash.Free; AtomicDecrement(NumberOfInstances); inherited; end; procedure TGreenThread.DoAbort; begin Abort end; procedure TGreenThread.Execute; var Joiner: TJoiner; begin FHub := DefHub; Joiner := GetJoiner(FHub); try try FHub.Loop(Self.ExitCond); finally // who did not have time to reschedule - we kill // since otherwise, ambiguities appear in the logic Joiner.KillAll; TRawGreenletPimpl.ClearContexts; end; finally FOnTerminate.SetEvent; end; end; function TGreenThread.ExitCond: Boolean; begin Result := Terminated end; procedure TGreenThread.Kill(const GreenBlock: Boolean); begin if FOnTerminate.WaitFor(0) = wrSignaled then Exit; DefHub(Self).EnqueueTask(Self.DoAbort); if GreenBlock then FOnTerminate.WaitFor end; function TGreenThread.Symmetrics: TSymmetricFactory; begin Result := FSymmetrics end; { TGreenGroup<KEY> } procedure TGreenGroup<KEY>.Clear; begin GetImpl.Clear end; function TGreenGroup<KEY>.Copy: TGreenGroup<KEY>; begin Result.Impl := Self.GetImpl.Copy end; function TGreenGroup<KEY>.Count: Integer; begin Result := GetImpl.Count end; function TGreenGroup<KEY>.GetImpl: IGreenGroup<KEY>; begin if not Assigned(Impl) then Impl := TGreenGroupImpl<KEY>.Create; Result := Impl; end; function TGreenGroup<KEY>.GetValue(const Key: KEY): IRawGreenlet; begin Result := GetImpl.GetValue(Key) end; function TGreenGroup<KEY>.IsEmpty: Boolean; begin Result := GetImpl.IsEmpty end; function TGreenGroup<KEY>.Join(Timeout: LongWord; const RaiseError: Boolean): Boolean; begin Result := GetImpl.Join(Timeout, RaiseError); end; procedure TGreenGroup<KEY>.KillAll; begin GetImpl.KillAll end; procedure TGreenGroup<KEY>.SetValue(const Key: KEY; G: IRawGreenlet); begin GetImpl.SetValue(Key, G) end; { TFanOut<T> } constructor TFanOut<T>.Make(const Input: TChannel<T>.TReadOnly); begin Self.Impl := TFanOutImpl<T>.Create(Input.Impl); end; function TFanOut<T>.Inflate(const BufSize: Integer): TChannel<T>.TReadOnly; begin Result.Impl := Self.Impl.Inflate(BufSize) end; { TSmartPointer<T> } class operator TSmartPointer<T>.Implicit(A: TSmartPointer<T>): T; var Obj: TObject absolute Result; begin if IsClass then begin if Assigned(A.FObjRef) then Obj := A.FObjRef.GetValue else Obj := nil; end else begin Result := A.FRef end; end; function TSmartPointer<T>.Get: T; var Obj: TObject absolute Result; begin Result := FRef; if IsClass then if Assigned(FObjRef) then Obj := FObjRef.GetValue else Obj := nil end; class operator TSmartPointer<T>.Implicit(A: T): TSmartPointer<T>; var Obj: TObject absolute A; begin if IsClass then begin Result.FObjRef := GC(Obj) end else begin Result.FRef := A end; end; class function TSmartPointer<T>.IsClass: Boolean; var ti: PTypeInfo; begin ti := TypeInfo(T); Result := ti.Kind = tkClass; end; { TSymmetricFactory } constructor TSymmetricFactory.Create(Hub: THub); begin FHub := Hub; end; function TSymmetricFactory.Spawn( const Routine: TSymmetricRoutineStatic): TSymmetric; begin Result.Impl := TSymmetricImpl.Create(Routine, FHub); Result.Run; end; function TSymmetricFactory.Spawn(const Routine: TSymmetricRoutine): TSymmetric; begin Result.Impl := TSymmetricImpl.Create(Routine, FHub); Result.Run; end; function TSymmetricFactory.Spawn<T1, T2, T3, T4>( const Routine: TSymmetricRoutineStatic<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TSymmetric<T1, T2, T3, T4>; begin Result.Impl := TSymmetricImpl<T1, T2, T3, T4>.Create(Routine, A1, A2, A3, A4, FHub); Result.Run; end; function TSymmetricFactory.Spawn<T1, T2, T3>( const Routine: TSymmetricRoutine<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3): TSymmetric<T1, T2, T3>; begin Result.Impl := TSymmetricImpl<T1, T2, T3>.Create(Routine, A1, A2, A3, FHub); Result.Run; end; function TSymmetricFactory.Spawn<T1, T2, T3, T4>( const Routine: TSymmetricRoutine<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TSymmetric<T1, T2, T3, T4>; begin Result.Impl := TSymmetricImpl<T1, T2, T3, T4>.Create(Routine, A1, A2, A3, A4, FHub); Result.Run; end; function TSymmetricFactory.Spawn<T1, T2, T3>( const Routine: TSymmetricRoutineStatic<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3): TSymmetric<T1, T2, T3>; begin Result.Impl := TSymmetricImpl<T1, T2, T3>.Create(Routine, A1, A2, A3, FHub); Result.Run; end; function TSymmetricFactory.Spawn<T1, T2>( const Routine: TSymmetricRoutine<T1, T2>; const A1: T1; const A2: T2): TSymmetric<T1, T2>; begin Result.Impl := TSymmetricImpl<T1, T2>.Create(Routine, A1, A2, FHub); Result.Run; end; function TSymmetricFactory.Spawn<T1, T2>( const Routine: TSymmetricRoutineStatic<T1, T2>; const A1: T1; const A2: T2): TSymmetric<T1, T2>; begin Result.Impl := TSymmetricImpl<T1, T2>.Create(Routine, A1, A2, FHub); Result.Run; end; function TSymmetricFactory.Spawn<T>(const Routine: TSymmetricRoutine<T>; const A: T): TSymmetric<T>; begin Result.Impl := TSymmetricImpl<T>.Create(Routine, A, FHub); Result.Run; end; function TSymmetricFactory.Spawn<T>(const Routine: TSymmetricRoutineStatic<T>; const A: T): TSymmetric<T>; begin Result.Impl := TSymmetricImpl<T>.Create(Routine, A, FHub); Result.Run; end; { TSymmetric<T1, T2, T3, T4> } constructor TSymmetric<T1, T2, T3, T4>.Create( const Routine: TSymmetricRoutine<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4); begin Impl := TSymmetricImpl<T1,T2,T3,T4>.Create(Routine, A1, A2, A3, A4); end; constructor TSymmetric<T1, T2, T3, T4>.Create( const Routine: TSymmetricRoutineStatic<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4); begin Impl := TSymmetricImpl<T1,T2,T3,T4>.Create(Routine, A1, A2, A3, A4); end; class operator TSymmetric<T1, T2, T3, T4>.Implicit( const A: TSymmetric<T1, T2, T3, T4>): TGevent; begin Result := A.Impl.GetOnTerminate end; class operator TSymmetric<T1, T2, T3, T4>.Implicit( const A: TSymmetric<T1, T2, T3, T4>): IRawGreenlet; begin Result := A.Impl end; procedure TSymmetric<T1, T2, T3, T4>.Join(const RaiseErrors: Boolean); begin Impl.Join(RaiseErrors); end; procedure TSymmetric<T1, T2, T3, T4>.Kill; begin Impl.Kill end; procedure TSymmetric<T1, T2, T3, T4>.Run; begin if Impl.GetState = gsReady then Impl.GetProxy.Pulse end; class function TSymmetric<T1, T2, T3, T4>.Spawn( const Routine: TSymmetricRoutine<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TSymmetric<T1, T2, T3, T4>; begin Result := TSymmetric<T1, T2, T3, T4>.Create(Routine, A1, A2, A3, A4); Result.Impl.Switch; end; class function TSymmetric<T1, T2, T3, T4>.Spawn( const Routine: TSymmetricRoutineStatic<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TSymmetric<T1, T2, T3, T4>; begin Result := TSymmetric<T1, T2, T3, T4>.Create(Routine, A1, A2, A3, A4); Result.Impl.Switch; end; { TAsymmetricFactory<Y> } constructor TAsymmetricFactory<Y>.Create(Hub: THub); begin FHub := Hub end; function TAsymmetricFactory<Y>.Spawn( const Routine: TAsymmetricRoutineStatic<Y>): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<Y>.Create(Routine, FHub); Result.Run; end; function TAsymmetricFactory<Y>.Spawn( const Routine: TAsymmetricRoutine<Y>): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<Y>.Create(Routine, FHub); Result.Run; end; function TAsymmetricFactory<Y>.Spawn<T1, T2, T3, T4>( const Routine: TAsymmetricRoutineStatic<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T1, T2, T3, T4, Y>.Create(Routine, A1, A2, A3, A4, FHub); Result.Run; end; function TAsymmetricFactory<Y>.Spawn<T1, T2, T3>( const Routine: TAsymmetricRoutine<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T1, T2, T3, Y>.Create(Routine, A1, A2, A3, FHub); Result.Run; end; function TAsymmetricFactory<Y>.Spawn<T1, T2, T3, T4>( const Routine: TAsymmetricRoutine<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T1, T2, T3, T4, Y>.Create(Routine, A1, A2, A3, A4, FHub); Result.Run; end; function TAsymmetricFactory<Y>.Spawn<T1, T2, T3>( const Routine: TAsymmetricRoutineStatic<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T1, T2, T3, Y>.Create(Routine, A1, A2, A3, FHub); Result.Run; end; function TAsymmetricFactory<Y>.Spawn<T1, T2>( const Routine: TAsymmetricRoutine<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T1, T2, Y>.Create(Routine, A1, A2, FHub); Result.Run; end; function TAsymmetricFactory<Y>.Spawn<T1, T2>( const Routine: TAsymmetricRoutineStatic<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T1, T2, Y>.Create(Routine, A1, A2, FHub); Result.Run; end; function TAsymmetricFactory<Y>.Spawn<T>(const Routine: TAsymmetricRoutine<T, Y>; const A: T): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T, Y>.Create(Routine, A, FHub); Result.Run; end; function TAsymmetricFactory<Y>.Spawn<T>( const Routine: TAsymmetricRoutineStatic<T, Y>; const A: T): TAsymmetric<Y>; begin Result.Impl := TAsymmetricImpl<T, Y>.Create(Routine, A, FHub); Result.Run; end; { TGCondVariable } procedure TGCondVariable.Broadcast; begin GetImpl.Broadcast end; function TGCondVariable.GetImpl: IGCondVariable; begin if not Assigned(Impl) then Impl := TGCondVariableImpl.Create; Result := Impl; end; class function TGCondVariable.Make( aExternalMutex: TCriticalSection): TGCondVariable; begin Result.Impl := TGCondVariableImpl.Create(aExternalMutex); end; procedure TGCondVariable.Signal; begin GetImpl.Signal end; procedure TGCondVariable.Wait(aUnlocking: TCriticalSection); begin GetImpl.Wait(aUnlocking); end; procedure TGCondVariable.Wait(aSpinUnlocking: TPasMPSpinLock); begin GetImpl.Wait(aSpinUnlocking); end; { TGSemaphore } procedure TGSemaphore.Acquire; begin Impl.Acquire end; function TGSemaphore.Limit: LongWord; begin Result := Impl.Limit end; class function TGSemaphore.Make(Limit: LongWord): TGSemaphore; begin Result.Impl := TGSemaphoreImpl.Create(Limit) end; procedure TGSemaphore.Release; begin Impl.Release end; function TGSemaphore.Value: LongWord; begin Result := Impl.Value end; { TGMutex } procedure TGMutex.Acquire; begin GetImpl.Acquire; end; function TGMutex.GetImpl: IGMutex; begin if not Assigned(Impl) then Impl := TGMutexImpl.Create; Result := Impl end; procedure TGMutex.Release; begin GetImpl.Release end; { TGQueue<T> } procedure TGQueue<T>.Clear; begin Impl.Clear end; function TGQueue<T>.Count: Integer; begin Result := Impl.Count end; procedure TGQueue<T>.Dequeue(out A: T); begin Impl.Dequeue(A) end; procedure TGQueue<T>.Enqueue(A: T); begin Impl.Enqueue(A) end; class function TGQueue<T>.Make(MaxCount: LongWord): TGQueue<T>; begin Result.Impl := TGQueueImpl<T>.Create(MaxCount); end; { TFuturePromise<RESULT, STATUS> } function TFuturePromise<RESULT, STATUS>.GetFuture: IFuture<RESULT, STATUS>; begin if not Assigned(FFuture) then Init; Result := FFuture; end; function TFuturePromise<RESULT, STATUS>.GetPromise: IPromise<RESULT, STATUS>; begin if not Assigned(FPromise) then Init; Result := FPromise; end; procedure TFuturePromise<RESULT, STATUS>.Init; var F: TFutureImpl<RESULT, STATUS>; begin F := TFutureImpl<RESULT, STATUS>.Create; FFuture := F; FPromise := TPromiseImpl<RESULT, STATUS>.Create(F); end; { TCase<T> } class operator TCase<T>.Implicit(var A: TCase<T>): ICase; begin if not Assigned(A.Impl) then A.Impl := TCaseImpl.Create; Result := A.Impl end; class operator TCase<T>.Equal(a: TCase<T>; b: T): Boolean; var Comparer: IComparer<T>; begin Comparer := TComparer<T>.Default; Result := Comparer.Compare(a, b) = 0 end; class operator TCase<T>.Equal(a: T; b: TCase<T>): Boolean; var Comparer: IComparer<T>; val: T; begin Comparer := TComparer<T>.Default; Result := Comparer.Compare(a, b) = 0 end; function TCase<T>.Get: T; begin Result := Self; end; class operator TCase<T>.Implicit(const A: T): TCase<T>; begin Result.Impl := TCaseImpl.Create; Result.Impl.WriteValueExists := True; Result.FValueHolder := A; end; class operator TCase<T>.Implicit(const A: TCase<T>): T; begin if Assigned(A.Impl) then begin if A.Impl.GetOperation = ioRead then begin Result := A.FValueToRead.GetResult end else begin if A.FValueToWrite.OnFullFilled.WaitFor(0) = wrSignaled then Result := A.FValueToWrite.GetResult else raise EReadError.Create('You try access to value that is not completed in write operation'); end; end else raise EReadError.Create('Value is empty. Start read/write operation'); end; { TCaseSet } class operator TCaseSet.Add(a: TCaseSet; b: ICase): TCaseSet; begin Result.Collection := a.GetCollection.Copy; Result.Collection.Append(b, False); end; class operator TCaseSet.Add(a, b: TCaseSet): TCaseSet; begin Result.Collection := a.GetCollection.Copy; Result.Collection.Append(b.GetCollection, False); end; procedure TCaseSet.Clear; begin GetCollection.Clear; end; function TCaseSet.GetCollection: ICollection<ICase>; begin if not Assigned(Collection) then Collection := TCollectionImpl<ICase>.Create; Result := Collection; end; function TCaseSet.Has(a: ICase): Boolean; var I: ICase; begin Result := False; for I in GetCollection do if I = a then Exit(True); end; class operator TCaseSet.In(a: ICase; b: TCaseSet) : Boolean; begin Result := b.Has(a) end; class operator TCaseSet.Implicit(const A: ICase): TCaseSet; begin Result.GetCollection.Append(A, False) end; function TCaseSet.IsEmpty: Boolean; begin Result := GetCollection.Count = 0 end; class function TCaseSet.Make(const Cases: array of ICase): TCaseSet; var I: ICase; begin for I in Cases do begin Result.GetCollection.Append(I, False) end; end; class operator TCaseSet.Subtract(a, b: TCaseSet): TCaseSet; var I: ICase; begin Result.Collection := a.GetCollection.Copy; for I in b.GetCollection do Result.Collection.Remove(I); end; class operator TCaseSet.Subtract(a: TCaseSet; b: ICase): TCaseSet; begin Result.Collection := a.GetCollection.Copy; Result.GetCollection.Remove(b); end; initialization end.
unit uTabelaPreco; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFormPadrao, DB, DBClient, pFIBClientDataSet, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxClasses, cxCustomData, cxStyles, cxEdit, cxCustomPivotGrid, cxDBPivotGrid, cxFilter, cxData, cxDataStorage, cxDBData, cxGridBandedTableView, cxGridDBBandedTableView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxGridCustomView, cxGrid; type TfrmTabelaPreco = class(TfrmPadrao) DataPreco: TDataSource; CdsPreco: TpFIBClientDataSet; TvPreco: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxGrid1: TcxGrid; TvPrecoNOMETIPOSERVICO: TcxGridDBColumn; TvPrecoNOMECATEGORIAANIMAL: TcxGridDBColumn; TvPrecoPRECO: TcxGridDBColumn; vPrecoColumn1: TcxGridDBColumn; procedure CdsPrecoBeforePost(DataSet: TDataSet); procedure FormCreate(Sender: TObject); procedure CdsPrecoAfterOpen(DataSet: TDataSet); procedure CdsPrecoAfterPost(DataSet: TDataSet); private { Private declarations } Procedure AtuDados(Id: Integer = -1); public { Public declarations } end; var frmTabelaPreco: TfrmTabelaPreco; implementation uses UDmConexao, Comandos, MinhasClasses; {$R *.dfm} procedure TfrmTabelaPreco.AtuDados(Id: Integer = -1); begin inherited; Try CdsPreco.DisableControls; SetCds(CdsPreco,tpPetPrecoServico,''); Finally if ID <> -1 then CdsPreco.Locate('IDPRECOSERVICO',ID,[]); CdsPreco.EnableControls; TvPreco.ViewData.Expand(True); End; end; procedure TfrmTabelaPreco.CdsPrecoAfterOpen(DataSet: TDataSet); begin inherited; CdsPreco.FieldByName('CODIGO').ProviderFlags := []; CdsPreco.FieldByName('NOMETIPOSERVICO').ProviderFlags := []; CdsPreco.FieldByName('NOMECATEGORIAANIMAL').ProviderFlags := []; CdsPreco.FieldByName('IDTIPOANIMAL').ProviderFlags := []; CdsPreco.FieldByName('FLAGEDICAO').ProviderFlags := []; CdsPreco.FieldByName('NOMETIPOANIMAL').ProviderFlags := []; FormataMascara(CdsPreco.FieldByName('PRECO'),tcMoeda); end; procedure TfrmTabelaPreco.CdsPrecoAfterPost(DataSet: TDataSet); var I: Integer; begin inherited; try I := CdsPreco.FieldByName('IDPRECOSERVICO').AsInteger; StartTrans; SetRegistros(CdsPreco,tpPetPrecoServico); Commit; except on E: Exception do Begin RollBack; Raise; End; end; AtuDados(I); end; procedure TfrmTabelaPreco.CdsPrecoBeforePost(DataSet: TDataSet); begin inherited; if CdsPreco.FieldByName('IDPRECOSERVICO').IsNull then Begin CdsPreco.FieldByName('FLAGEDICAO').AsString :='I'; CdsPreco.FieldByName('IDPRECOSERVICO').AsInteger := GetValSeq('SEQ_IDPRECOSERVICO'); end else CdsPreco.FieldByName('FLAGEDICAO').AsString :='E'; end; procedure TfrmTabelaPreco.FormCreate(Sender: TObject); begin inherited; AtuDados; end; end.
unit btrerror; {text strings of BTrieve Errors } interface FUNCTION BtrStatus(StatusNum : INTEGER) : String; { Get string describing errors } FUNCTION BtrOp(OpNum : INTEGER) : String; { Get string describing operation. Account for extended ops } FUNCTION BtrErrReport(OpNum, ErrNum : INTEGER) : String; { both functions above in more verbose result } implementation CONST {array index corresponds to error number } BTRErrors : ARRAY[0..99] OF String[35] = ( { 0} ' 0: Success', { 1} ' 1: Invalid Operation', { 2} ' 2: I/O Error', { 3} ' 3: File Not Open', { 4} ' 4: Key Value Not Found', { 5} ' 5: Duplicate Key Value', { 6} ' 6: Invalid Key Number', { 7} ' 7: Different Key Number', { 8} ' 8: Invalid Positioning', { 9} ' 9: End Of File', {10} '10: Modifiable Key Value Error', {11} '11: Invalid File Name', {12} '12: File Not Found', {13} '13: Exetended File Error', {14} '14: Pre-Image Open Error', {15} '15: Pre-Image I/O Error', {16} '16: Expansion Error', {17} '17: Close Error', {18} '18: Disk Full', {19} '19: Unrecoverable Error', {20} '20: Record Manager Inactive', {21} '21: Key Buffer Too Short', {22} '22: Short Data Buffer Length', {23} '23: Wrong Position Block Length', {24} '24: Page Size Error', {25} '25: Create I/O Error', {26} '26: Wrong Number Of Keys', {27} '27: Invalid Key Position', {28} '28: Invalid Record Length', {29} '29: Invalid Key Length', {30} '30: Not A Btrieve File', {31} '31: File Already Extended', {32} '32: Extend I/O Error', {33} '33: Undefined Error', {34} '34: Invalid Extension Name', {35} '35: Directory Error', {36} '36: Transaction Error', {37} '37: Transaction Is Active', {38} '38: Trans. Control File I/O Error', {39} '39: End/Abort Transaction Error', {40} '40: Transaction Max Files', {41} '41: Operation Not Allowed', {42} '42: Incomplete Accelerated Access', {43} '43: Invalid Record Access', {44} '44: Null Key Path', {45} '45: Inconsistant Key Flags', {46} '46: Access To File Denied', {47} '47: Maximum Open Files', {48} '48: Invalid Alt. Sequence Def.', {49} '49: Key Type Error', {50} '50: Owner Already Set', {51} '51: Invalid Owner', {52} '52: Error Writing Cache', {53} '53: Invalid Interface', {54} '54: Variable Page Error', {55} '55: Autoincrement Error', {56} '56: Incomplete Index', {57} '57: Undefined Error', {58} '58: Compression Buffer Too Short', {59} '59: File Already Exists', {60} '60: Undefined Error', {61} '61: Undefined Error', {62} '62: Undefined Error', {63} '63: Undefined Error', {64} '64: Undefined Error', {65} '65: Undefined Error', {66} '66: Undefined Error', {67} '67: Undefined Error', {68} '68: Undefined Error', {69} '69: Undefined Error', {70} '70: Undefined Error', {71} '71: Undefined Error', {72} '72: Undefined Error', {73} '73: Undefined Error', {74} '74: Undefined Error', {75} '75: Undefined Error', {76} '76: Undefined Error', {77} '77: Undefined Error', {78} '78: Undefined Error', {79} '79: Undefined Error', {80} '80: Conflict On Update Or Delete', {81} '81: Lock Error', {82} '82: Lost Position', {83} '83: Read Outside Transaction', {84} '84: Record In Use', {85} '85: File In Use', {86} '86: File Table Full', {87} '87: Handle Table Full', {88} '88: Incompatible Mode Error', {89} '89: Undefined Error', {90} '90: Redirected Device Table Full', {91} '91: Server Error', {92} '92: Transaction Table Full', {93} '93: Incompatible File Lock Type', {94} '94: Permission Error', {95} '95: Session No Longer Valid', {96} '96: Communications Environment Err.', {97} '97: Data Message To Small', {98} '98: Internal Transaction Error', {99} '99: Undefined Error' ); { Btrieve Operation Codes } BtrOperation : ARRAY[0..40] of String[25] = ( '0: BTR Open', '1: BTR Close', '2: BTR Insert', '3: UpDate', '4: BTR Delete', '5: GetEqual', '6: GetNext', '7: GetPrevious', '8: GetGreater', '9: GetGreaterOrEqual', '10: GetLessThan', '11: GetLessThanOrEqual', '12: GetFirst', '13: GetLast', '14: Create', '15: Stat', '16: Extend', '17: SetDirectory', '18: GetDirectory', '19: BeginTrans', '20: EndTrans', '21: AbortTrans', '22: GetPos', '23: GetDirect', '24: StepNext', '25: Stop', '26: Version', '27: UnLock', '28: BTRReset', '29: SetOwner', '30: ClearOwner', '31: CreateIndex', '32: DropIndex', '33: StepFirst', '34: StepLast', '35: StepPrevious', '36: Undefined', '37: Undefined', '38: Undefined', '39: Undefined', '40: Undefined' ); {------------------------------------------------------------} FUNCTION BtrStatus(StatusNum : INTEGER) : String; { Get string describing errors } BEGIN BtrStatus := BtrErrors[StatusNum]; END {BtrStatus}; {------------------------------------------------------------} FUNCTION BtrOp(OpNum : INTEGER) : String; { Get string describing operation. Account for extended ops } VAR extend : WORD; extendedOp : String; BEGIN IF OpNum > 50 THEN BEGIN extend := OpNum div 50; CASE extend OF 1 : ExtendedOp := ' Extended: Get Key'; 2 : ExtendedOp := ' Extended: Lock Single Wait'; 4 : ExtendedOp := ' Extended: Lock Single No Wait'; 6 : ExtendedOp := ' Extended: Lock Multi Wait'; 8 : ExtendedOp := ' Extended: Lock Multi No Wait'; ELSE ExtendedOp := ' Extended: Invalid Extension'; END; BTROp := BtrOperation[OpNum mod 50] + ExtendedOp; END ELSE BTROp := BtrOperation[OpNum mod 50]; END {BtrOp}; FUNCTION BtrErrReport(OpNum, ErrNum : INTEGER) : String; BEGIN BtrErrReport := 'Error '+ BtrErrors[ErrNum] + ' during Op '+ BtrOp(OpNum); END; END.
unit Uforms; // SpyroTAS is licensed under WTFPL // overrides form class interface uses Utas, Forms, Windows, Messages, Controls, StdCtrls, ExtCtrls, Graphics, Grids, Classes, SysUtils {$IFDEF FPC} , LCLType {$ELSE} // fix for TCreateParams , Types {$ENDIF}; const CUSTOM_MESSAGE_DOWIPE = WM_USER + 1; type TFSpyroTAS = class(TForm) constructor Create(Owner: TComponent); override; constructor CreateUsual(); procedure SetZOrder(Topmost: Boolean); override; procedure CreateParams(var Params: TCreateParams); override; procedure Hide(StoreState: Boolean = False); procedure Show(RetoreState: Boolean = False); procedure WipeThisForm(); procedure DoWipe(var MSG: TMessage); message CUSTOM_MESSAGE_DOWIPE; procedure WMpos(var MSG: TMessage); message WM_WINDOWPOSCHANGING; procedure DefOnClose(Sender: TObject; var Action: TCloseAction); procedure SetPermanentHint(Control: TControl; Text: string); procedure SetPermanentGridHint(Grid: TStringGrid; Col, Row: Integer; Text: string); public procedure SetSizeClient(ALeft, Atop, AWidth, AHeight: Integer; OnlySize: Boolean); overload; procedure SetSizeSystem(ALeft, Atop, AWidth, AHeight: Integer); overload; procedure SetSizeSystem(Rect: TRect); overload; procedure SetSizeClient(Rect: TRect; OnlySize: Boolean); overload; function GetSizeClient(TargetWindow: Integer = 0): TRect; function GetSizeSystem(): TRect; procedure ForceSize(); procedure TemporaryDisable(Sender: TObject = nil); procedure Popup(); procedure TopMost(OnTop: Boolean); procedure Report(Caption, Text: string); overload; procedure Report(Caption, Text: string; Handle: HWND); overload; public StopVisibleChanging: Boolean; StopWipingHappen: Boolean; ThisIsOverlay: Boolean; private DoNotMessAround: Boolean; // to disable most of this class TemporaryDisabled: TControl; TemporaryDisableTime: Integer; WipeCounter: Integer; OldPos: TRect; // form position before move/resize OldVisible: Boolean; end; // customizing hints: type TSpyroTASHint = class(THintWindow) protected procedure CreateParams(var Params: TCreateParams); override; private OldPos: TRect; // for wiping WasWiped: Boolean; public procedure Paint; override; procedure DoWipe(); end; var TSpyroTASHintOkay: Boolean = False; type TAllFormsAction = (afaShow, afaHide, afaFocus, afaGhost, afaEnable, afaDisable, afaExit, afaPopup); procedure AllFormsAction(Action: TAllFormsAction); // called from GUI var HintsFont: string = 'Tahoma'; HintsCharset: TFontCharset = ANSI_CHARSET; HintsSize: Integer = 10; implementation uses UFgui, UFhide, UFbind, UFview, UFext, UFover, UFshot, UFedit, Umain, UFplug, Umisc; var InFocusedMode: Boolean; // for internal branching // to have one function instead of many: procedure AllFormsAction(Action: TAllFormsAction); procedure Process(OneForm: TFSpyroTAS); // (inner scope), called for each form begin if OneForm = nil then Exit; if Action = afaExit then begin OneForm.DoNotMessAround := True; OneForm.OnCloseQuery := nil; OneForm.OnClose := nil; OneForm.Close(); OneForm.Release(); Exit; end; if (Action <> afaEnable) and not OneForm.Enabled then Exit; // skipping disabled case Action of afaShow: // show all OneForm.Show(True); afaHide: // hide all if not OneForm.ThisIsOverlay then OneForm.Hide(True); // pad overlays are special cases afaFocus: // allow recieve focus begin SetWindowLong(OneForm.Handle, GWL_EXSTYLE, GetWindowLong(OneForm.Handle, GWL_EXSTYLE) and not WS_EX_NOACTIVATE); if OneForm.Visible then OneForm.Popup(); end; afaGhost: // deny recieving focus begin SetWindowLong(OneForm.Handle, GWL_EXSTYLE, GetWindowLong(OneForm.Handle, GWL_EXSTYLE) or WS_EX_NOACTIVATE); if OneForm.Visible then OneForm.Popup(); end; afaDisable: // disable and put to background begin OneForm.TopMost(False); OneForm.Enabled := False; end; afaEnable: // enable and restore topmost begin OneForm.Enabled := True; OneForm.TopMost(True); end; afaPopup: // begin OneForm.Popup(); OneForm.TopMost(True); end; end; end; begin // (body of AllFormsAction) if Action = afaFocus then begin if InFocusedMode then Exit; InFocusedMode := True; // store action end; if Action = afaGhost then begin if not InFocusedMode then Exit; InFocusedMode := False; end; // here must be all forms (except Fhide) Process(Fbind); Process(Fext); Process(Fover1); Process(Fover2); Process(FoverF); Process(FoverR); Process(Fview); Process(Fedit); Process(Fshot); Process(Fplug); Process(Fgui); end; constructor TFSpyroTAS.Create(Owner: TComponent); begin inherited Create(Owner); HandleNeeded(); Left := -9999; Top := -9999; ForceSize(); end; constructor TFSpyroTAS.CreateUsual(); begin DoNotMessAround := True; inherited Create(nil); end; // schedule black painting: procedure TFSpyroTAS.WipeThisForm(); begin if not IsGuiInvoked then // not initialized yet Exit; if Handle = Fhide.Handle then // don't wipe the brush Exit; // rect to fill OldPos := GetSizeSystem(); // post wiping Inc(WipeCounter); PostMessage(Handle, CUSTOM_MESSAGE_DOWIPE, 0, WipeCounter); end; // paint black in old posion: procedure TFSpyroTAS.DoWipe(var MSG: TMessage); begin if (Fhide = nil) or (Self.Handle = Fhide.Handle) then // don't do for brush itself Exit; if WipeCounter <> MSG.LPARAM then // react only on last call Exit; if StopWipingHappen then // denied by form itself Exit; Fhide.OldPos := Fhide.GetSizeSystem(); // store old position Fhide.SetSizeSystem(Self.OldPos); // move brush to old position of current window Fhide.Repaint(); Fhide.SetSizeSystem(Fhide.OldPos); // restore end; // hide form with black painting: procedure TFSpyroTAS.Hide(StoreState: Boolean = False); begin if DoNotMessAround then begin inherited Hide(); Exit; end; if StoreState then // to show only already visible forms later OldVisible := Visible; if not Visible then Exit; WipeThisForm(); // draw black inherited Hide(); ShowWindow(Handle, SW_HIDE); // hide always! end; // show form, maybe if needed to: procedure TFSpyroTAS.Show(RetoreState: Boolean = False); begin if DoNotMessAround then begin inherited Show(); Exit; end; if RetoreState and not OldVisible then Exit; // it wasn't visible during special Hide(); if Visible then Exit; SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_TOOLWINDOW or WS_EX_CONTEXTHELP); // explicit for Lazarus ShowWindow(Handle, SW_SHOWNOACTIVATE); // without stealing focus anyway Popup(); inherited Show; end; procedure TFSpyroTAS.SetZOrder(Topmost: Boolean); begin if (not StopVisibleChanging) or DoNotMessAround then inherited SetZOrder(Topmost); end; // set base window styles at first: procedure TFSpyroTAS.CreateParams(var Params: TCreateParams); begin if DoNotMessAround then begin inherited CreateParams(Params); Exit; end; Visible := False; Position := poDesigned; // stop the system to screw window creation inherited CreateParams(Params); Params.ExStyle := (Params.ExStyle or WS_EX_NOACTIVATE or WS_EX_TOPMOST or WS_EX_TOOLWINDOW or WS_EX_CONTEXTHELP) and not WS_EX_APPWINDOW; OnClose := DefOnClose; // see below end; // to make additional windows wipe when closed: procedure TFSpyroTAS.DefOnClose(Sender: TObject; var Action: TCloseAction); begin Ignores(Action); Hide(); end; // early resizing and moving: procedure TFSpyroTAS.WMpos(var MSG: TMessage); begin if DoNotMessAround then Exit; Ignores(MSG); if (not Enabled) or InFocusedMode then // skip when not in ghost mode Exit; if Visible then WipeThisForm(); // draw black in old position end; // assign a hint to a control that will be shown even when it is disabled: procedure TFSpyroTAS.SetPermanentHint(Control: TControl; Text: string); var Lab: TLabel; Name: string; begin Name := Control.Name + '_hint'; Lab := TLabel(FindComponent(Name)); if Lab = nil then Lab := TLabel.Create(Self); Lab.Name := Name; Lab.Parent := Control.Parent; Lab.ParentShowHint := True; Lab.AutoSize := False; // will be invisible Lab.SetBounds(Control.Left, Control.Top, Control.Width, Control.Height); Lab.Caption := ''; Lab.TRANSPARENT := True; Lab.Hint := StringReplace(Text, '|', 'l', [rfReplaceAll]); Control.Hint := Lab.Hint; // hint when enabled, also could be different, but we don't need it end; // same as above, but for grid cells: procedure TFSpyroTAS.SetPermanentGridHint(Grid: TStringGrid; Col, Row: Integer; Text: string); var Lab: TLabel; Rect: TRect; Name: string; begin Name := StringReplace(Grid.Name + IntToStr(Col) + '_' + IntToStr(Row) + '_hint', '-', '_', [rfReplaceAll]); Lab := TLabel(FindComponent(Name)); if Lab = nil then Lab := TLabel.Create(Self); Lab.Name := Name; Lab.Parent := Grid; Lab.ParentShowHint := True; Lab.AutoSize := False; if Col < 0 then begin Rect := Grid.CellRect(0, Row); Rect.Right := Grid.ClientWidth; end else if Row < 0 then begin Rect := Grid.CellRect(Col, 0); Rect.Bottom := Grid.ClientHeight; end else Rect := Grid.CellRect(Col, Row); // target area Lab.SetBounds(Rect.Left, Rect.Top, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top); Lab.Caption := ''; Lab.TRANSPARENT := True; Lab.Hint := StringReplace(StringReplace(Text, '|', 'l', [rfReplaceAll]), '#', #13, [rfReplaceAll]); end; procedure TFSpyroTAS.SetSizeClient(ALeft, Atop, AWidth, AHeight: Integer; OnlySize: Boolean); var Temp: TRect; begin Temp := Rect(ALeft, Atop, ALeft + AWidth, Atop + AHeight); AdjustWindowRectEx(Temp, GetWindowLong(Handle, GWL_STYLE), False, GetWindowLong(Handle, GWL_EXSTYLE)); {$IFDEF FPC} if OnlySize then SetBounds(ALeft, Atop, AWidth, AHeight) else SetBounds(Temp.Left, Temp.Top, AWidth, AHeight); {$ELSE} if OnlySize then SetBounds(ALeft, Atop, Temp.Right - Temp.Left, Temp.Bottom - Temp.Top) else SetBounds(Temp.Left, Temp.Top, Temp.Right - Temp.Left, Temp.Bottom - Temp.Top); {$ENDIF} end; procedure TFSpyroTAS.SetSizeSystem(ALeft, Atop, AWidth, AHeight: Integer); var Temp: TRect; begin Temp := Rect(ALeft, Atop, ALeft + AWidth, Atop + AHeight); AdjustWindowRectEx(Temp, GetWindowLong(Handle, GWL_STYLE), False, GetWindowLong(Handle, GWL_EXSTYLE)); {$IFDEF FPC} SetBounds(ALeft, Atop, AWidth * 2 - (Temp.Right - Temp.Left), AHeight * 2 - (Temp.Bottom - Temp.Top)); {$ELSE} SetBounds(ALeft, Atop, AWidth, AHeight); {$ENDIF} end; procedure TFSpyroTAS.SetSizeSystem(Rect: TRect); begin SetSizeSystem(Rect.Left, Rect.Top, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top); end; procedure TFSpyroTAS.SetSizeClient(Rect: TRect; OnlySize: Boolean); begin SetSizeClient(Rect.Left, Rect.Top, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top, OnlySize); end; function TFSpyroTAS.GetSizeClient(TargetWindow: Integer = 0): TRect; var Temp: TRect; begin Result.Left := 0; if TargetWindow = 0 then TargetWindow := Handle; GetWindowRect(TargetWindow, Result); Temp := Result; AdjustWindowRectEx(Temp, GetWindowLong(TargetWindow, GWL_STYLE), False, GetWindowLong(TargetWindow, GWL_EXSTYLE)); Result.Top := Result.Top * 2 - Temp.Top; Result.Left := Result.Left * 2 - Temp.Left; Result.Right := Result.Right * 2 - Temp.Right; Result.Bottom := Result.Bottom * 2 - Temp.Bottom; end; function TFSpyroTAS.GetSizeSystem(): TRect; begin Result.Left := 0; GetWindowRect(Handle, Result); end; procedure TFSpyroTAS.ForceSize(); var Rect: TRect; begin Rect.Left := Left; Rect.Top := Top; Rect.Right := Left + Width; Rect.Bottom := Top + Height; {$IFDEF FPC} AdjustWindowRectEx(Rect, GetWindowLong(Handle, GWL_STYLE), False, GetWindowLong(Handle, GWL_EXSTYLE)); {$ENDIF} MoveWindow(Handle, Left, Top, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top, False); end; procedure TFSpyroTAS.TemporaryDisable(Sender: TObject = nil); begin if TemporaryDisabled <> nil then begin TemporaryDisableTime := DefaultActionSleep - (Integer({%H-}GetTickCount()) - TemporaryDisableTime); if TemporaryDisableTime > 0 then Sleep(TemporaryDisableTime); TemporaryDisabled.Enabled := True; TemporaryDisabled := nil; end; if Sender <> nil then begin TemporaryDisabled := TControl(Sender); TemporaryDisabled.Enabled := False; TemporaryDisableTime := Integer({%H-}GetTickCount()); end; end; procedure TFSpyroTAS.Popup(); begin SetWindowPos(Handle, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE); end; procedure TFSpyroTAS.TopMost(OnTop: Boolean); begin if OnTop then SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE) else SetWindowPos(Handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE) end; procedure TFSpyroTAS.Report(Caption, Text: string); begin Umisc.Report(Caption, Text, Self); end; procedure TFSpyroTAS.Report(Caption, Text: string; Handle: HWND); begin Umisc.Report(Caption, Text, Handle); end; // remove shadow from hints: procedure TSpyroTASHint.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); // since shadow could glitch and stick detached forever Params.WindowClass.Style := Params.WindowClass.style and not CS_DROPSHADOW; LastHint := Self; Canvas.Font.Name := HintsFont; Canvas.Font.Charset := HintsCharset; Canvas.Font.Size := HintsSize; end; // wipe a hint, just like forms' DoWipe(); also called from gui timer: procedure TSpyroTASHint.DoWipe(); begin if (Fhide = nil) or (not IsGuiInvoked) or WasWiped or not TSpyroTASHintOkay then Exit; Fhide.OldPos := Fhide.GetSizeSystem(); Fhide.SetSizeSystem(Self.OldPos); Fhide.Repaint(); Fhide.SetSizeSystem(Fhide.OldPos); WasWiped := True; // don't wipe twice end; // paint event on a hint: procedure TSpyroTASHint.Paint(); begin if not TSpyroTASHintOkay then begin inherited Paint(); Exit; end; DoWipe(); // wipe in old position inherited Paint(); GetWindowRect(Handle, OldPos); // store new position LastHint := Self; // activete monitoring by timer WasWiped := False; end; end. // EOF
unit DelphiGenerator; interface uses TechnoGenerator, classes , PropertyObj ; type TDelphiClassGenerator = class(TTechnoClassGenerator) private class function getUpperFirstLetterAndPropertyStyleString(const aProp: TProperty; out aUfl: string; out aPss: string): boolean; class function getConstPropertyArgument(const aUfl: string; const aPss: string): string; procedure startCreate(const aSl: TStringList); function getCreateArguments: string; procedure addPrivate(const aSl: TStringList); procedure addPublished(const aSl: TStringList); procedure addPublic(const aSl: TStringList); procedure addCreator(const aSl: TStringList); procedure addCreatorParams(const aSl: TStringList); procedure addDestructor(const aSl: TStringList); procedure addGetters(const aSl: TStringList); procedure addSetters(const aSl: TStringList); public function generate: TStringList; override; end; implementation { TDelphiClassGenerator } uses sysUtils , Controller ; //////////////////////////////////////////////////////////////////////////////// class function TDelphiClassGenerator.getConstPropertyArgument(const aUfl, aPss: string): string; begin result := format('const a%s: %s', [aUfl, aPss]); end; class function TDelphiClassGenerator.getUpperFirstLetterAndPropertyStyleString( const aProp: TProperty; out aUfl, aPss: string): boolean; begin result := false; aUfl := ''; aPss := ''; if assigned(aProp) then begin aUfl := TTechnoClassGenerator.UpperFirstLetter(aProp.name); aPss := TController.getPropertyStyleString(aProp.style); result := true; end; end; //////////////////////////////////////////////////////////////////////////////// procedure TDelphiClassGenerator.startCreate(const aSl: TStringList); begin aSl.Add('begin'); aSl.Add(' inherited Create;'); end; function TDelphiClassGenerator.getCreateArguments: string; var i: integer; vProp: TProperty; vUfl: string; vPss: string; begin result := ''; for i := 0 to FGenerator.properties.Count - 1 do begin getUpperFirstLetterAndPropertyStyleString(FGenerator.properties.Items[i], vUfl, vPss); result := result + getConstPropertyArgument(vUfl, vPss); if i < FGenerator.properties.Count - 1 then result := result + '; '; end; end; procedure TDelphiClassGenerator.addCreator(const aSl: TStringList); var vProp: TProperty; begin aSl.Add(format('constructor T%s.Create;', [TTechnoClassGenerator.UpperFirstLetter(FGenerator.name)])); startCreate(aSl); for vProp in FGenerator.properties do begin aSL.Add(format(' %s := ;',[vProp.name])); end; aSl.Add('end'); end; procedure TDelphiClassGenerator.addCreatorParams(const aSl: TStringList); var vProp: TProperty; begin aSl.Add(format('constructor T%s.Create(%s);', [TTechnoClassGenerator.UpperFirstLetter(FGenerator.name), getCreateArguments])); startCreate(aSl); for vProp in FGenerator.properties do begin aSL.Add(format(' %s := a%s;',[vProp.name, TTechnoClassGenerator.UpperFirstLetter(vProp.name)])); end; aSl.Add('end'); end; procedure TDelphiClassGenerator.addDestructor(const aSl: TStringList); begin aSl.Add(format('destructor T%s.Destroy;', [TTechnoClassGenerator.UpperFirstLetter(FGenerator.name)])); aSl.Add('begin'); aSl.Add(' inherited Destroy;'); aSl.Add('end'); end; procedure TDelphiClassGenerator.addGetters(const aSl: TStringList); var vProp: TProperty; vUfl: string; vPss: string; begin for vProp in FGenerator.properties do begin aSl.Add(''); getUpperFirstLetterAndPropertyStyleString(vProp, vUfl, vPss); aSl.Add(format('function T%s.get%s: %s;', [TTechnoClassGenerator.UpperFirstLetter(FGenerator.name), vUfl, vPss])); aSl.Add('begin'); aSl.Add(format(' result := F%s;', [vUfl])); aSl.Add('end'); end; end; procedure TDelphiClassGenerator.addSetters(const aSl: TStringList); var vProp: TProperty; vUfl: string; vPss: string; begin for vProp in FGenerator.properties do begin aSl.Add(''); getUpperFirstLetterAndPropertyStyleString(vProp, vUfl, vPss); aSl.Add(format('procedure T%s.set%s(%s);', [TTechnoClassGenerator.UpperFirstLetter(FGenerator.name), vUfl, getConstPropertyArgument(vUfl, vPss)])); aSl.Add('begin'); aSl.Add(format(' F%s := a%s;', [vUfl, vUfl])); aSl.Add('end'); end; end; procedure TDelphiClassGenerator.addPrivate(const aSl: TStringList); var vProp: TProperty; vUfl: string; vPss: string; begin aSl.Add(' private'); for vProp in FGenerator.properties do begin getUpperFirstLetterAndPropertyStyleString(vProp, vUfl, vPss); aSl.Add(format(' F%s: %s;', [vUfl, vPss])); end; for vProp in FGenerator.properties do begin getUpperFirstLetterAndPropertyStyleString(vProp, vUfl, vPss); aSl.Add(format(' function get%s: %s;', [vUfl, vPss])); aSl.Add(format(' procedure set%s(%s);', [vUfl, getConstPropertyArgument(vUfl, vPss)])); end; end; procedure TDelphiClassGenerator.addPublic(const aSl: TStringList); begin aSl.Add(' public'); aSl.Add(' constructor Create; overload;'); aSl.add(format(' constructor Create(%s); overload;', [getCreateArguments])); aSl.Add(' destructor Destroy; override;'); end; procedure TDelphiClassGenerator.addPublished(const aSl: TStringList); var vProp: TProperty; vUfl: string; vPss: string; begin aSl.Add(' published'); for vProp in FGenerator.properties do begin getUpperFirstLetterAndPropertyStyleString(vProp, vUfl, vPss); aSl.Add(format(' property %s: %s read get%s write set%s;', [vProp.name, vPss, vUfl, vUfl])); end; end; function TDelphiClassGenerator.generate: TStringList; var vGenName: string; begin result := nil; if assigned(FGenerator) then begin result := TStringList.Create; vGenName := TTechnoClassGenerator.UpperFirstLetter(FGenerator.name); result.Add(format('type T%s = class', [vGenName])); addPrivate(result); addPublished(result); addPublic(result); result.Add('end;'); result.Add(''); result.Add('implementation'); result.Add(''); result.Add(format('{ T%s }', [vGenName])); result.Add(''); addCreator(result); result.Add(''); addCreatorParams(result); result.Add(''); addDestructor(result); addGetters(result); addSetters(result); end; end; end.
unit TestDotNetForm1; interface uses System.Drawing, System.Collections, System.ComponentModel, System.Windows.Forms, System.Data; type TWinForm = class(System.Windows.Forms.Form) {$REGION 'Designer Managed Code'} strict private /// <summary> /// Required designer variable. /// </summary> Components: System.ComponentModel.Container; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> procedure InitializeComponent; {$ENDREGION} strict protected /// <summary> /// Clean up any resources being used. /// </summary> procedure Dispose(Disposing: Boolean); override; private { Private Declarations } public constructor Create; end; [assembly: RuntimeRequiredAttribute(TypeOf(TWinForm))] implementation {$AUTOBOX ON} {$REGION 'Windows Form Designer generated code'} /// <summary> /// Required method for Designer support -- do not modify /// the contents of this method with the code editor. /// </summary> procedure TWinForm.InitializeComponent; begin Self.Components := System.ComponentModel.Container.Create; Self.Size := System.Drawing.Size.Create(300, 300); Self.Text := 'WinForm'; end; {$ENDREGION} procedure TWinForm.Dispose(Disposing: Boolean); begin if Disposing then begin if Components <> nil then Components.Dispose(); end; inherited Dispose(Disposing); end; constructor TWinForm.Create; begin inherited Create; // // Required for Windows Form Designer support // InitializeComponent; // // TODO: Add any constructor code after InitializeComponent call // end; end.
unit MyDialogs; interface uses System.SysUtils, System.Classes, System.Types, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.StdCtrls; type TDialogs = class public class function YesNo(Msg: string; BtnDefault: TMsgDlgBtn = mbNo): integer; class function YesNoCancel(Msg: string; BtnDefault: TMsgDlgBtn = mbCancel): integer; class function OkCancel(Msg: string; BtnDefault: TMsgDlgBtn = mbCancel): integer; end; implementation { TMyDialogs } class function TDialogs.YesNo(Msg: string; BtnDefault: TMsgDlgBtn): integer; begin Result := MessageDlg(Msg, mtWarning, mbYesNo, 0, BtnDefault); end; class function TDialogs.YesNoCancel(Msg: string; BtnDefault: TMsgDlgBtn): integer; begin Result := MessageDlg(Msg, mtWarning, mbYesNoCancel, 0, BtnDefault); end; class function TDialogs.OkCancel(Msg: string; BtnDefault: TMsgDlgBtn): integer; begin Result := MessageDlg(Msg, mtWarning, mbOkCancel, 0, BtnDefault); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1997,98 Inprise Corporation } { } {*******************************************************} unit WebConst; interface resourcestring sInvalidActionRegistration = 'Invalid Action registration'; sOnlyOneDataModuleAllowed = 'Only one data module per application'; sNoDataModulesRegistered = 'No data modules registered'; sNoDispatcherComponent = 'No dispatcher component found on data module'; sOnlyOneDispatcher = 'Only one WebDispatcher per form/data module'; sDuplicateActionName = 'Duplicate action name'; sTooManyActiveConnections = 'Maximum number of concurrent connections exceeded. ' + 'Please try again later'; sHTTPItemName = 'Name'; sHTTPItemURI = 'PathInfo'; sHTTPItemEnabled = 'Enabled'; sHTTPItemDefault = 'Default'; sInternalServerError = '<html><title>Internal Server Error 500</title>'#13#10 + '<h1>Internal Server Error 500</h1><hr>'#13#10 + 'Exception: %s<br>'#13#10 + 'Message: %s<br></html>'#13#10; sDocumentMoved = '<html><title>Document Moved 302</title>'#13#10 + '<body><h1>Object Moved</h1><hr>'#13#10 + 'This Object may be found <a HREF="%s">here.</a><br>'#13#10 + '<br></body></html>'#13#10; sResNotFound = 'Resource %s not found'; sTooManyColumns = 'Too many table columns'; sFieldNameColumn = 'Field Name'; sFieldTypeColumn = 'Field Type'; sInvalidMask = '''%s'' is an invalid mask at (%d)'; implementation end.
{$R-} {Range checking off} {$B+} {Boolean complete evaluation on} {$S+} {Stack checking on} {$I+} {I/O checking on} {$N-} {No numeric coprocessor} {$M 65500,16384,655360} {Turbo 3 default stack and heap} program Anagram; {Copyright 1985 by Bob Keefer} {Anagram.Pas takes a word of up to 10 letters from the keyboard and rearranges the letters into every possible permutation, or anagram, of the word.} {It then evaluates the likelihood that each anagram is an English word by looking up every trigram in the word in a probability table, which is stored in a separate file PROB.DAT and is read into the array Probability[X,Y,Z]. Finally, it records the top scoring anagrams in Scoreboard and prints them to the screen.} {The program must be compiled with the Turbo "c" compiler option to a *.COM file.} (* { $A-} {compiler directive for recursion} !{!^ 1. Directives A,B,C,D,F,G,P,U,W,X are obsolete or changed in meaning} { $C-} {.... ignore ^C and ^S breaks} !{!^ 2. Directives A,B,C,D,F,G,P,U,W,X are obsolete or changed in meaning} *) {$I-} {.... no i/o checking} {$V-} {.... no string checking} Uses Crt; const MaxLength = 13; {biggest word + 3} MaxScores = 200 ; {how many winners to store} LinesPerPage = 20; type ScoreLine = record {One line of the Scoreboard} Winner : string[MaxLength] ; Points : WORD ; end; var AWord : array [1..Maxlength] of char; {Word to permute} Wordlength : WORD; {Length of Word} Probability : array [0..26,0..26,0..26] of WORD; ScoreBoard : array [1..MaxScores] of ScoreLine; WordToScore : string[Maxlength]; {anagram} DataFile : file of WORD; {probability table} TheWord : String[Maxlength]; {Word as string} I : WORD; {counter} OutFile : text; procedure Score; var X,Y,Z : INTEGER; I,J : WORD ; Total : WORD ; Unlikelihood : WORD; procedure KeepScore; var N : WORD; procedure ChalkItUp; var TempScore, I : WORD; TempName : String[MaxLength]; begin {ChalkItUp} for I := N to MaxScores do begin with ScoreBoard[I] do {If an anagram} if Total>Points then {scores better,} begin {then record it...} begin TempScore := Points; TempName := Winner; Points := Total; Winner := WordToScore end; if I<>MaxScores then begin {..bump the rest down} with ScoreBoard[I+1] do begin WordToScore := TempName; Total := TempScore; end; end; end; end; end; {ChalkItUp} begin {KeepScore} for N := 1 to MaxScores do begin if WordToScore = ScoreBoard[N].Winner then Total := 0; {eliminate duplicates} if (Total > ScoreBoard[N].Points) then ChalkItUp; {record good-scoring words} end; end; {KeepScore} begin {procedure Score} WordToScore := ' ' + WordToScore + ' '; Total := 0; Unlikelihood := 0; for I := 1 to length(WordToScore) -2 do begin X := ord(WordToScore[I])-64; Y := ord(WordToScore[I+1])-64; Z := ord(WordToScore[I+3])-64; if X<0 then X:=0; if Y<0 then Y:=0; if Z<0 then Z:=0; Total := Total + Probability[X,Y,Z]; if Probability[X,Y,Z]=0 then Unlikelihood := succ(Unlikelihood); end; for J := 1 to Unlikelihood do Total := Total div 2; KeepScore; end; {procedure Score} procedure Permute (CurrentLength : WORD); var i : WORD; procedure Switch; var Temp : char; begin Temp := AWord[CurrentLength]; AWord[CurrentLength] := AWord[I]; AWord[I] := Temp; end; {Switch} procedure Outword; VAR j : WORD; begin WordToScore:=''; FOR j := 1 to Wordlength do WordToScore := WordToScore + AWord[j]; end; {Outword} begin {Permute body} if CurrentLength = 1 then begin Outword; Score; end else for i := 1 to CurrentLength do begin Switch; Permute(CurrentLength - 1); Switch; end; end; {Permute} procedure GetInput; var I : WORD; begin write('Enter word: '); readln(TheWord); WordLength := length(TheWord); for I := 1 to WordLength do begin AWord[I] := upcase(TheWord[I]); end; TheWord := ''; for I := 1 to WordLength do TheWord := TheWord + AWord[I]; end; {procedure GetInput} procedure ZeroScore; var I : WORD; begin for I:= 1 to MaxScores do begin with ScoreBoard[I] do begin Points := 0; Winner := ''; end; end; {with} end; {ZeroScore} procedure PostScore; var I,j : WORD; GotIt : boolean; begin GotIt:=false; j := 0; for I := 1 to MaxScores do begin with ScoreBoard[I] do begin if Points>0 then begin j := j + 1; writeln(I:2, ' ',Winner, ' ', Points); writeln(OutFile,I:2, ' ',Winner, ' ', Points); end; {if Points} end; {with} end; {for loop} end; {procedure PostScore} procedure ReadProb; var X,Y,Z : WORD; begin assign(Datafile,'PROB.DAT'); reset(DataFile); for X := 0 to 26 do begin write('*'); for Y := 0 to 26 do begin for Z := 0 to 26 do begin read(Datafile,Probability[X,Y,Z]); end; end; end; close(Datafile); writeln; end; {procedure ReadProb} procedure SignOn; begin clrscr; writeln('Anagram.Pas'); writeln('By Bob Keefer'); writeln('Copyright 1985'); writeln; writeln; writeln('To halt program, enter "*"'); writeln; writeln; writeln; writeln('Reading Probability Table...'); end; {procedure Signon} begin {Anagram program} SignOn; {Display signon message} ReadProb; {Read probability table} clrscr; assign(OutFile,'ANAGRAM.TXT'); rewrite(OutFile); repeat GetInput; {Get word} ZeroScore; {clear Scoreboard} Permute (Wordlength); {Evaluate words} writeln; PostScore; {Print results} writeln; writeln; until AWord[1]='*'; close(outfile); end. 
unit macro_3; interface implementation var G: Int32; S: string; F: float64; #macro ADD(V1, V2); begin V1 := V1 + V2; end; procedure Test; begin S := 'AB'; ADD(S, 'XX'); G := 2; ADD(G, 8); F := 1.5; ADD(F, 2.5); end; initialization Test(); finalization Assert(S = 'ABXX'); Assert(G = 10); Assert(F = 4); end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Vcl.Touch.GestureCtrls; interface uses Winapi.Windows, System.Classes, System.SysUtils, Winapi.Messages, Vcl.Controls, Vcl.ComCtrls, Vcl.ImgList, Vcl.Graphics, Vcl.GraphUtil, Vcl.Touch.GestureMgr, Vcl.Touch.Gestures, Vcl.ExtCtrls, System.Generics.Collections; type TCustomGesturePreview = class; TGestureProviderChangeEvent = reference to procedure(Sender: TObject; AGesture: TCustomGestureCollectionItem); IGestureProvider = interface ['{2BBA64C5-CD16-4DF7-A89A-10903F6649BC}'] procedure ChangeNotification(AComponent: TComponent; ASelectionChangeEvent: TGestureProviderChangeEvent); procedure RemoveChangeNotification(AComponent: TComponent); end; TGetGestureGroupEvent = procedure(Sender: TObject; Gesture: TCustomGestureCollectionItem; var GroupID: Integer) of object; TCreateSubItemsEvent = procedure(Sender: TObject; ListItem: TListItem; Gesture: TCustomGestureCollectionItem) of object; TCustomGestureListView = class(TCustomListView, IGestureProvider) protected type TGestureItemData = record Gesture: TCustomGestureCollectionItem; GroupID: Integer; end; TGestureItemDataArray = array of TGestureItemData; private FGestureData: TGestureItemDataArray; FGestureManager: TGestureManager; FGroupView: Boolean; FImages: TImageList; FImageSize: Integer; FNotifyList: TDictionary<TComponent, TGestureProviderChangeEvent>; FUpdateCount: Integer; FOnCreateSubItems: TCreateSubItemsEvent; FOnGetGestureGroup: TGetGestureGroupEvent; procedure AddGestureImage(const Points: array of TPoint); procedure RebuildListItem(ItemData: TGestureItemData); overload; procedure RebuildListItem(ItemData: TGestureItemData; ListItem: TListItem); overload; procedure SetGestureManager(const Value: TGestureManager); procedure SetGroupView(const Value: Boolean); procedure SetImageSize(const Value: Integer); procedure CMCustomGesturesChanged(var Message: TMessage); message CM_CUSTOMGESTURESCHANGED; protected procedure Change(Item: TListItem; Change: Integer); override; procedure CreateColumns; virtual; procedure CreateSubItems(ListItem: TListItem; Gesture: TCustomGestureCollectionItem); virtual; procedure CreateWnd; override; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure UpdateGesture(GestureID: TGestureID); virtual; procedure WndProc(var Message: TMessage); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddGesture(Gesture: TCustomGestureCollectionItem; GroupID: Integer = -1); overload; virtual; procedure AddGesture(GestureID: TGestureID; GroupID: Integer = -1); overload; virtual; procedure AddGestures(Control: TControl; GroupID: Integer = -1); overload; virtual; procedure AddGestures(Gestures: TGestureArray; GroupID: Integer = -1); overload; virtual; procedure AddGestures(Gestures: TCustomGestureCollection; GroupID: Integer = -1); overload; virtual; procedure BeginUpdate; procedure ChangeNotification(AComponent: TComponent; ASelectionChangeEvent: TGestureProviderChangeEvent); procedure ClearGestureList; procedure EndUpdate; function GestureIDFromItem(Item: TListItem): TGestureID; inline; function ItemFromGestureID(GestureID: TGestureID): TListItem; procedure RefreshList; procedure RemoveChangeNotification(AComponent: TComponent); procedure RemoveGesture(GestureID: TGestureID); virtual; property GestureManager: TGestureManager read FGestureManager write SetGestureManager; property GroupView: Boolean read FGroupView write SetGroupView; property ImageSize: Integer read FImageSize write SetImageSize default 20; property OnCreateSubItems: TCreateSubItemsEvent read FOnCreateSubItems write FOnCreateSubItems; property OnGetGestureGroup: TGetGestureGroupEvent read FOnGetGestureGroup write FOnGetGestureGroup; end; TGestureListView = class(TCustomGestureListView) published property Align; property AllocBy; property Anchors; property BevelEdges; property BevelInner; property BevelOuter; property BevelKind default bkNone; property BevelWidth; property BiDiMode; property BorderStyle; property BorderWidth; property Checkboxes; property Color; property Columns; property ColumnClick; property Constraints; property Ctl3D; property DoubleBuffered default True; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property FlatScrollBars; property FullDrag; property GestureManager; property GridLines; property Groups; property HideSelection; property HotTrack; property HotTrackStyles; property HoverTime; property IconOptions; property MultiSelect; property OwnerDraw; property GroupHeaderImages; property GroupView default False; property ReadOnly default True; property RowSelect default True; property ParentBiDiMode; property ParentColor default False; property ParentDoubleBuffered default False; property ParentFont; property ParentShowHint; property PopupMenu; property ImageSize; property ShowColumnHeaders; property ShowWorkAreas; property ShowHint; property SortType; property TabOrder; property TabStop default True; property Touch; property ViewStyle default vsReport; property Visible; property OnAdvancedCustomDraw; property OnAdvancedCustomDrawItem; property OnAdvancedCustomDrawSubItem; property OnChange; property OnChanging; property OnClick; property OnColumnClick; property OnColumnDragged; property OnColumnRightClick; property OnCompare; property OnContextPopup; property OnCreateSubItems; property OnCustomDraw; property OnCustomDrawItem; property OnCustomDrawSubItem; property OnCreateItemClass; property OnData; property OnDataFind; property OnDataHint; property OnDataStateChange; property OnDblClick; property OnDeletion; property OnDrawItem; property OnEdited; property OnEditing; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGesture; property OnGetGestureGroup; property OnGetImageIndex; property OnGetSubItemImage; property OnDragDrop; property OnDragOver; property OnInfoTip; property OnInsert; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseActivate; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnResize; property OnSelectItem; property OnItemChecked; property OnStartDock; property OnStartDrag; end; TCustomGesturePreview = class(TCustomControl) private type TAnimateDirection = (adForward, adBackward); TAnimateState = (asAnimating, asCompleted, asPaused, asRestarting); public type {$SCOPEDENUMS ON} TDrawingStyle = (dsNormal, dsGradient); {$SCOPEDENUMS OFF} TFrameStyle = psSolid..psDot; TLegendPosition = (lpNone, lpTop, lpBottom); public const DefGradientEndColor = $F0E5E6; DefGradientStartColor = $FDFDFD; private FAnimate: Boolean; FAnimateIndex: Integer; FAnimateDirection: TAnimateDirection; FAnimatedPointColor: TColor; FAnimateLastIndex: Integer; FAnimateLongDelay: Integer; FAnimatePoints: TGesturePointArray; FAnimateShortDelay: Integer; FAnimateState: TAnimateState; FAnimateStep: Integer; FDrawingStyle: TDrawingStyle; FDrawPoints: TGesturePointArray; FFrameColor: TColor; FFrameGesture: Boolean; FFrameStyle: TFrameStyle; FGesture: TCustomGestureCollectionItem; FGestureProvider: IGestureProvider; FGradientDirection: TGradientDirection; FGradientEndColor: TColor; FGradientStartColor: TColor; FLegendRect: TRect; FLegendPosition: TLegendPosition; FMaxPreviewSize: Integer; FPreviewEndPointColor: TColor; FPreviewLineColor: TColor; FTimer: TTimer; function AdjustGesturePoint(Point: TPoint): TPoint; procedure AnimateGesture(Sender: TObject); function InterpolatePoints(const Points: TGesturePointArray): TGesturePointArray; procedure SetAnimate(const Value: Boolean); procedure SetAnimatedPointColor(const Value: TColor); procedure SetAnimateLongDelay(const Value: Integer); procedure SetAnimateShortDelay(const Value: Integer); procedure SetDrawingStyle(const Value: TDrawingStyle); procedure SetFrameColor(const Value: TColor); procedure SetFrameGesture(const Value: Boolean); procedure SetFrameStyle(const Value: TFrameStyle); procedure SetGestureProvider(const Value: IGestureProvider); procedure SetGradientDirection(const Value: TGradientDirection); procedure SetGradientEndColor(const Value: TColor); procedure SetGradientStartColor(const Value: TColor); procedure SetGesture(const Value: TCustomGestureCollectionItem); procedure SetLegendPosition(const Value: TLegendPosition); procedure SetMaxPreviewSize(const Value: Integer); procedure SetPreviewEndPointColor(const Value: TColor); procedure SetPreviewLineColor(const Value: TColor); protected FInternalPreviewSize: Integer; FLegendText: string; FOffsetX: Integer; FOffsetY: Integer; procedure CreateWnd; override; procedure DrawBackground; virtual; procedure DrawGesturePoints; virtual; procedure DrawLegend; virtual; procedure DrawPoint(const P: TPoint; AColor: TColor); virtual; procedure EraseAnimatePoint(Index: Integer); virtual; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Paint; override; procedure Resize; override; procedure UpdatePosition; virtual; procedure WndProc(var Message: TMessage); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure StartAnimation; procedure SuspendAnimation; property Animate: Boolean read FAnimate write SetAnimate default True; property AnimatedPointColor: TColor read FAnimatedPointColor write SetAnimatedPointColor default clBlue; property AnimateLongDelay: Integer read FAnimateLongDelay write SetAnimateLongDelay default 500; property AnimateShortDelay: Integer read FAnimateShortDelay write SetAnimateShortDelay default 75; property DrawingStyle: TDrawingStyle read FDrawingStyle write SetDrawingStyle default TDrawingStyle.dsNormal; property FrameColor: TColor read FFrameColor write SetFrameColor default clLtGray; property FrameGesture: Boolean read FFrameGesture write SetFrameGesture default True; property FrameStyle: TFrameStyle read FFrameStyle write SetFrameStyle default psDot; property Gesture: TCustomGestureCollectionItem read FGesture write SetGesture; property GestureProvider: IGestureProvider read FGestureProvider write SetGestureProvider; property GradientDirection: TGradientDirection read FGradientDirection write SetGradientDirection default gdVertical; property GradientEndColor: TColor read FGradientEndColor write SetGradientEndColor default DefGradientEndColor; property GradientStartColor: TColor read FGradientStartColor write SetGradientStartColor default DefGradientStartColor; property LegendPosition: TLegendPosition read FLegendPosition write SetLegendPosition default lpBottom; property MaxPreviewSize: Integer read FMaxPreviewSize write SetMaxPreviewSize default 0; property PreviewEndPointColor: TColor read FPreviewEndPointColor write SetPreviewEndPointColor default clGray; property PreviewLineColor: TColor read FPreviewLineColor write SetPreviewLineColor default clGray; end; TGesturePreview = class(TCustomGesturePreview) published property Align; property Anchors; property Animate; property AnimatedPointColor; property AnimateLongDelay; property AnimateShortDelay; property BevelEdges; property BevelInner; property BevelOuter; property BevelKind default bkNone; property BevelWidth; property BiDiMode; property Color; property Constraints; property Ctl3D; property DoubleBuffered default True; property DragCursor; property DragKind; property DragMode; property DrawingStyle; property Enabled; property Font; property FrameColor; property FrameGesture; property FrameStyle; property GestureProvider; property GradientDirection; property GradientEndColor; property GradientStartColor; property Height default 200; property LegendPosition; property MaxPreviewSize; property ParentBiDiMode; property ParentColor; property ParentDoubleBuffered default False; property ParentFont; property ParentShowHint; property PopupMenu; property PreviewEndPointColor; property PreviewLineColor; property ShowHint; property Touch; property Visible; property Width default 200; property OnClick; property OnContextPopup; property OnEndDock; property OnEndDrag; property OnGesture; property OnDragDrop; property OnDragOver; property OnMouseActivate; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDock; property OnStartDrag; end; TGestureRecordedEvent = procedure(Sender: TObject; RecordedGesture: TGestureCollectionItem) of object; TCustomGestureRecorder = class(TCustomControl) public const DefGradientEndColor = $F0E5E6; DefGradientStartColor = $FDFDFD; public type {$SCOPEDENUMS ON} TDrawingStyle = (dsNormal, dsGradient); {$SCOPEDENUMS OFF} private FDrawingStyle: TDrawingStyle; FGesture: TGestureCollectionItem; FGestureLineColor: TColor; FGestureManager: TGestureManager; FGesturePointColor: TColor; FGradientDirection: TGradientDirection; FGradientEndColor: TColor; FGradientStartColor: TColor; FLastDrawnPoint: Integer; FPoints: TGesturePointArray; FRecordedPoints: TGesturePoints; FRecording: Boolean; FCaption: string; FOnGestureRecorded: TGestureRecordedEvent; procedure AddGesturePoint(const LastPoint, NextPoint: TPoint); function PointsToArray(Source: TGesturePoints): TGesturePointArray; procedure SetCaption(const Value: string); procedure SetDrawingStyle(const Value: TDrawingStyle); procedure SetGestureLineColor(const Value: TColor); procedure SetGesturePointColor(const Value: TColor); procedure SetGradientDirection(const Value: TGradientDirection); procedure SetGradientEndColor(const Value: TColor); procedure SetGradientStartColor(const Value: TColor); procedure SetGestureManager(const Value: TGestureManager); protected procedure DrawPoint(const Point: TPoint); virtual; function IsTouchPropertyStored(AProperty: TTouchProperty): Boolean; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Paint; override; procedure WndProc(var Message: TMessage); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Caption: string read FCaption write SetCaption; property DrawingStyle: TDrawingStyle read FDrawingStyle write SetDrawingStyle default TDrawingStyle.dsNormal; property Gesture: TGestureCollectionItem read FGesture write FGesture; property GestureManager: TGestureManager read FGestureManager write SetGestureManager; property GestureLineColor: TColor read FGestureLineColor write SetGestureLineColor default clBlue; property GesturePointColor: TColor read FGesturePointColor write SetGesturePointColor default clBlue; property GradientDirection: TGradientDirection read FGradientDirection write SetGradientDirection default gdVertical; property GradientEndColor: TColor read FGradientEndColor write SetGradientEndColor default DefGradientEndColor; property GradientStartColor: TColor read FGradientStartColor write SetGradientStartColor default DefGradientStartColor; property OnGestureRecorded: TGestureRecordedEvent read FOnGestureRecorded write FOnGestureRecorded; end; TGestureRecorder = class(TCustomGestureRecorder) published property Align; property Anchors; property BevelEdges; property BevelInner; property BevelOuter; property BevelKind default bkNone; property BevelWidth; property BiDiMode; property Caption; property Color; property Constraints; property Ctl3D; property DoubleBuffered default True; property DragCursor; property DragKind; property DragMode; property DrawingStyle; property Enabled; property Font; property GestureManager; property GestureLineColor; property GesturePointColor; property GradientDirection; property GradientEndColor; property GradientStartColor; property Height default 200; property ParentBiDiMode; property ParentColor; property ParentDoubleBuffered default False; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property Width default 200; property OnClick; property OnContextPopup; property OnEndDock; property OnEndDrag; property OnGesture; property OnGestureRecorded; property OnDragDrop; property OnDragOver; property OnMouseActivate; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDock; property OnStartDrag; end; procedure DrawGesture(ACanvas: TCanvas; const APoints: array of TPoint; AColor: TColor); overload; procedure DrawGesture(ACanvas: TCanvas; const APoints: array of TPoint; AColor: TColor; const AOffset: TPoint); overload; procedure DrawGesture(ACanvas: TCanvas; AGesture: TCustomGestureCollectionItem; AColor: TColor); overload; inline; procedure DrawGesture(ACanvas: TCanvas; AGesture: TCustomGestureCollectionItem; AColor: TColor; const AOffset: TPoint); overload; inline; function ScaleGesturePoints(const Points: array of TPoint; Size: Integer): TGesturePointArray; implementation uses Vcl.Touch.GestureConsts, Winapi.CommCtrl, Vcl.Forms, System.Math; procedure DrawGesture(ACanvas: TCanvas; const APoints: array of TPoint; AColor: TColor); begin DrawGesture(ACanvas, APoints, AColor, Point(0, 0)); end; procedure DrawGesture(ACanvas: TCanvas; const APoints: array of TPoint; AColor: TColor; const AOffset: TPoint); var I: Integer; LPoint: TPoint; begin if Length(APoints) > 0 then begin // Prepare first point LPoint := APoints[0]; ACanvas.Pen.Color := AColor; ACanvas.MoveTo(LPoint.X + AOffset.X, LPoint.Y + AOffset.Y); // Draw line between remaining points for I := 1 to Length(APoints) - 1 do begin LPoint := APoints[I]; ACanvas.LineTo(LPoint.X + AOffset.X, LPoint.Y + AOffset.Y); end; // Fill in final point ACanvas.Pixels[APoints[Length(APoints) - 1].X + AOffset.X, APoints[Length(APoints) - 1].Y + AOffset.Y] := AColor; end; end; procedure DrawGesture(ACanvas: TCanvas; AGesture: TCustomGestureCollectionItem; AColor: TColor); begin DrawGesture(ACanvas, AGesture.Points, AColor, Point(0, 0)); end; procedure DrawGesture(ACanvas: TCanvas; AGesture: TCustomGestureCollectionItem; AColor: TColor; const AOffset: TPoint); begin DrawGesture(ACanvas, AGesture.Points, AColor, AOffset); end; function ScaleGesturePoints(const Points: array of TPoint; Size: Integer): TGesturePointArray; var LPoint: TPoint; LScale: Double; I, MaxX, MaxY: Integer; OffsetX, OffsetY: Integer; begin MaxX := 0; MaxY := 0; for I := 0 to Length(Points) - 1 do begin if Points[I].X > MaxX then MaxX := Points[I].X; if Points[I].Y > MaxY then MaxY := Points[I].Y; end; if (MaxX = 0) and (MaxY = 0) then begin LScale := 1; OffsetX := 0; OffsetY := 0; end else begin if MaxX > MaxY then LScale := (Size / MaxX) else LScale := (Size / MaxY); OffsetX := (Size - Round(MaxX * LScale)) div 2; OffsetY := (Size - Round(MaxY * LScale)) div 2; end; SetLength(Result, Length(Points)); for I := 0 to Length(Result) - 1 do begin LPoint := Points[I]; Result[I] := Point(Round(LPoint.X * LScale) + OffsetX, Round(LPoint.Y * LScale) + OffsetY); end; end; { TCustomGestureListView } constructor TCustomGestureListView.Create(AOwner: TComponent); begin inherited; FImages := TImageList.Create(nil); FNotifyList := TDictionary<TComponent, TGestureProviderChangeEvent>.Create; SetLength(FGestureData, 0); FUpdateCount := 0; ImageSize := 24; // call setter to set size of imagelist ParentDoubleBuffered := False; DoubleBuffered := True; ReadOnly := True; RowSelect := True; LargeImages := FImages; SmallImages := FImages; ViewStyle := vsReport; CreateColumns; end; destructor TCustomGestureListView.Destroy; begin ClearGestureList; FreeAndNil(FNotifyList); FreeAndNil(FImages); inherited; end; procedure TCustomGestureListView.EndUpdate; begin Dec(FUpdateCount); if FUpdateCount = 0 then RefreshList; end; procedure TCustomGestureListView.AddGesture(Gesture: TCustomGestureCollectionItem; GroupID: Integer = -1); var LGesture: TGestureCollectionItem; begin if Gesture <> nil then begin SetLength(FGestureData, Length(FGestureData) + 1); LGesture := TGestureCollectionItem.Create(nil); LGesture.Assign(Gesture); FGestureData[Length(FGestureData) - 1].Gesture := LGesture; FGestureData[Length(FGestureData) - 1].GroupID := GroupID; if FUpdateCount = 0 then RefreshList; end; end; procedure TCustomGestureListView.AddGesture(GestureID: TGestureID; GroupID: Integer = -1); var LItem: TGestureCollectionItem; LGesture: TCustomGestureCollectionItem; begin case GestureID of sgiFirst..sgiLast: begin LItem := TGestureCollectionItem.Create(nil); try LItem.GestureID := GestureID; AddGesture(LItem, GroupID); finally LItem.Free; end; end; cgiFirst..cgiLast, rgiFirst..rgiLast: begin LGesture := nil; if FGestureManager <> nil then begin LGesture := FGestureManager.FindCustomGesture(GestureID); if LGesture <> nil then AddGesture(LGesture, GroupID); end; if LGesture = nil then raise EGestureException.CreateResFmt(@SInvalidGestureID, [GestureID]); end; else raise EGestureException.CreateResFmt(@SInvalidGestureID, [GestureID]); end; end; procedure TCustomGestureListView.AddGestureImage(const Points: array of TPoint); var I: Integer; LPoints: TGesturePointArray; LBitmap, LMask: TBitmap; begin LBitmap := TBitmap.Create; try LBitmap.SetSize(FImages.Width, FImages.Height); LBitmap.Canvas.Brush.Color := Color; LBitmap.Canvas.FillRect(Rect(0, 0, LBitmap.Width, LBitmap.Height)); LMask := TBitmap.Create; try LMask.Assign(LBitmap); LPoints := ScaleGesturePoints(Points, FImageSize - 4); LBitmap.Canvas.Pen.Color := clGray; LBitmap.Canvas.Pen.Style := psSolid; LBitmap.Canvas.MoveTo(LPoints[0].X + 2, LPoints[0].Y + 2); LMask.Canvas.Pen.Color := clBlack; LMask.Canvas.Pen.Style := psSolid; LMask.Canvas.MoveTo(LPoints[0].X + 2, LPoints[0].Y + 2); for I := 0 to Length(LPoints) - 1 do begin LBitmap.Canvas.LineTo(LPoints[I].X + 2, LPoints[I].Y + 2); LMask.Canvas.LineTo(LPoints[I].X + 2, LPoints[I].Y + 2); end; FImages.Add(LBitmap, LMask); finally LMask.Free; end; finally LBitmap.Free; end; end; procedure TCustomGestureListView.AddGestures(Control: TControl; GroupID: Integer); begin AddGestures(Control.Touch.GestureList); end; procedure TCustomGestureListView.AddGestures(Gestures: TCustomGestureCollection; GroupID: Integer); var LItem: TCollectionItem; begin if Gestures <> nil then begin BeginUpdate; try for LItem in Gestures do AddGesture(TCustomGestureCollectionItem(LItem), GroupID); finally EndUpdate; end; end; end; procedure TCustomGestureListView.AddGestures(Gestures: TGestureArray; GroupID: Integer = -1); var LItem: TCustomGestureCollectionItem; begin BeginUpdate; try for LItem in Gestures do AddGesture(LItem, GroupID); finally EndUpdate; end; end; procedure TCustomGestureListView.BeginUpdate; begin Inc(FUpdateCount); end; procedure TCustomGestureListView.Change(Item: TListItem; Change: Integer); var P: TPair<TComponent, TGestureProviderChangeEvent>; begin inherited; if (Change = LVIF_STATE) and (Selected <> nil) then for P in FNotifyList do P.Value(Self, TCustomGestureCollectionItem(Selected.Data)); end; procedure TCustomGestureListView.ChangeNotification(AComponent: TComponent; ASelectionChangeEvent: TGestureProviderChangeEvent); begin if AComponent <> nil then begin FNotifyList.Add(AComponent, ASelectionChangeEvent); AComponent.FreeNotification(Self); if HandleAllocated and (Selected <> nil) then ASelectionChangeEvent(Self, TCustomGestureCollectionItem(Selected.Data)); end end; procedure TCustomGestureListView.ClearGestureList; var LItem: TGestureItemData; begin for LItem in FGestureData do LItem.Gesture.Free; SetLength(FGestureData, 0); end; procedure TCustomGestureListView.CMCustomGesturesChanged(var Message: TMessage); begin case Message.WParam of gcnAdded: // Add new gesture AddGesture(FGestureManager.FindCustomGesture(Message.LParam)); gcnRemoved: // Remove gesture RemoveGesture(Message.LParam); gcnModified: // Update modified gesture UpdateGesture(Message.LParam); gcnRefreshAll: begin // Add all gestures from GestureManager SetLength(FGestureData, 0); AddGestures(FGestureManager.CustomGestures); end; end; end; procedure TCustomGestureListView.CreateColumns; begin // Create default columns with Columns.Add do begin Caption := SNameColumn; AutoSize := True; end; end; procedure TCustomGestureListView.CreateSubItems(ListItem: TListItem; Gesture: TCustomGestureCollectionItem); begin // Overrride or use OnCreateSubItems event to provide subitems end; procedure TCustomGestureListView.CreateWnd; begin inherited; if not (csLoading in ComponentState) and (Length(FGestureData) > 0) then RefreshList; end; function TCustomGestureListView.GestureIDFromItem(Item: TListItem): TGestureID; begin Result := TCustomGestureCollectionItem(Item.Data).GestureID; end; function TCustomGestureListView.ItemFromGestureID(GestureID: TGestureID): TListItem; var Item: TListItem; begin Result := nil; for Item in Items do if TCustomGestureCollectionItem(Item.Data).GestureID = GestureID then begin Result := Item; Break; end; end; procedure TCustomGestureListView.Loaded; begin inherited; if HandleAllocated and (Length(FGestureData) > 0) then RefreshList; end; procedure TCustomGestureListView.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) then begin if (AComponent = FGestureManager) then begin FGestureManager := nil; if not (csDestroying in ComponentState) then begin ClearGestureList; SetLength(FGestureData, 0); RefreshList; end; end else if not (csDestroying in ComponentState) and FNotifyList.ContainsKey(AComponent) then FNotifyList.Remove(AComponent); end; end; procedure TCustomGestureListView.RebuildListItem(ItemData: TGestureItemData); begin RebuildListItem(ItemData, Items.Add); end; procedure TCustomGestureListView.RebuildListItem(ItemData: TGestureItemData; ListItem: TListItem); var LGroupID: Integer; GestureData: TStandardGestureData; begin ListItem.Caption := ItemData.Gesture.DisplayName; ListItem.Data := ItemData.Gesture; // Create subitems if Assigned(FOnCreateSubItems) then FOnCreateSubItems(Self, ListItem, ItemData.Gesture) else CreateSubItems(ListItem, ItemData.Gesture); // Create image from points if ItemData.Gesture.GestureType <> gtStandard then AddGestureImage(ItemData.Gesture.Points) else begin FindStandardGesture(ItemData.Gesture.GestureID, GestureData); AddGestureImage(GestureData.Points); end; ListItem.ImageIndex := FImages.Count - 1; // Set group (if applicable) if GroupView then begin LGroupID := ItemData.GroupID; if Assigned(FOnGetGestureGroup) then FOnGetGestureGroup(Self, ItemData.Gesture, LGroupID); ListItem.GroupID := LGroupID; end; end; procedure TCustomGestureListView.RefreshList; var ItemData: TGestureItemData; begin if HandleAllocated and (FUpdateCount = 0) then begin FImages.Clear; Items.BeginUpdate; try Items.Clear; for ItemData in FGestureData do RebuildListItem(ItemData); finally Items.EndUpdate; end; end; end; procedure TCustomGestureListView.RemoveChangeNotification(AComponent: TComponent); begin if FNotifyList.ContainsKey(AComponent) then begin FNotifyList.Remove(AComponent); AComponent.RemoveFreeNotification(Self); end; end; procedure TCustomGestureListView.RemoveGesture(GestureID: TGestureID); var I: Integer; LItem: TGestureItemData; LGesture: TCustomGestureCollectionItem; begin for I := 0 to Items.Count - 1 do begin LGesture := TCustomGestureCollectionItem(Items[I].Data); if (LGesture <> nil) and (LGesture.GestureID = GestureID) then begin for LItem in FGestureData do if LItem.Gesture = LGesture then begin LItem.Gesture.Free; Break; end; Items[I].Delete; Break; end; end; end; procedure TCustomGestureListView.SetGestureManager(const Value: TGestureManager); begin if Value <> FGestureManager then begin if FGestureManager <> nil then begin FGestureManager.RemoveChangeNotification(Self); FGestureManager.RemoveFreeNotification(Self); end; FGestureManager := Value; SetLength(FGestureData, 0); if FGestureManager <> nil then begin FGestureManager.ChangeNotification(Self); FGestureManager.FreeNotification(Self); // Add gestures from GestureManager AddGestures(FGestureManager.CustomGestures); end else RefreshList; end; end; procedure TCustomGestureListView.SetGroupView(const Value: Boolean); begin if Value <> FGroupView then begin FGroupView := Value; if not (csDesigning in ComponentState) then begin inherited GroupView := Value; RefreshList; end; end; end; procedure TCustomGestureListView.SetImageSize(const Value: Integer); begin if Value <> FImageSize then begin FImageSize := Value; FImages.Height := FImageSize; FImages.Width := FImageSize; if HandleAllocated and not (csLoading in ComponentState) then begin // Force update of imagelists SmallImages := nil; SmallImages := FImages; LargeImages := nil; LargeImages := FImages; // Regenerate preview images and list items RefreshList; end; end; end; procedure TCustomGestureListView.UpdateGesture(GestureID: TGestureID); var I: Integer; LItem: TGestureItemData; LGesture: TCustomGestureCollectionItem; begin LGesture := FGestureManager.FindCustomGesture(GestureID); if LGesture <> nil then for LItem in FGestureData do if LItem.Gesture.GestureID = LGesture.GestureID then begin LItem.Gesture.Assign(LGesture); for I := 0 to Items.Count - 1 do if TCustomGestureCollectionItem(Items[I].Data).GestureID = LGesture.GestureID then begin RebuildListItem(LItem, Items[I]); Break; end; Break; end; end; procedure TCustomGestureListView.WndProc(var Message: TMessage); begin inherited WndProc(Message); end; { TCustomGesturePreview } constructor TCustomGesturePreview.Create; begin inherited; ControlStyle := ControlStyle + [csAcceptsControls]; DoubleBuffered := True; ParentDoubleBuffered := False; Height := 200; Width := 200; FAnimateState := asCompleted; FAnimatedPointColor := clBlue; FAnimateLongDelay := 500; FAnimateShortDelay := 75; FDrawingStyle := TDrawingStyle.dsNormal; FFrameColor := clLtGray; FFrameGesture := True; FFrameStyle := psDot; FGesture := TGestureCollectionItem.Create(nil); FGradientDirection := gdVertical; FGradientEndColor := DefGradientEndColor; FGradientStartColor := DefGradientStartColor; FLegendPosition := lpBottom; FMaxPreviewSize := 0; FPreviewEndPointColor := clGray; FPreviewLineColor := clGray; FAnimate := True; FTimer := TTimer.Create(nil); FTimer.Enabled := False; FTimer.OnTimer := AnimateGesture; FTimer.Interval := FAnimateLongDelay; end; procedure TCustomGesturePreview.CreateWnd; begin inherited; if not (csLoading in ComponentState) then begin UpdatePosition; if FAnimate then StartAnimation; end; end; destructor TCustomGesturePreview.Destroy; begin FreeAndNil(FGesture); FreeAndNil(FTimer); inherited; end; function TCustomGesturePreview.AdjustGesturePoint(Point: TPoint): TPoint; begin Result := Point; Inc(Result.X, FOffsetX + 5); Inc(Result.Y, FOffsetY + 5); end; procedure TCustomGesturePreview.AnimateGesture(Sender: TObject); var LPoint: TPoint; begin case FAnimateState of asAnimating: begin // Erase current animation point EraseAnimatePoint(FAnimateIndex); // Advance to next animation point Inc(FAnimateIndex, FAnimateStep); if ((FAnimateDirection = adForward) and (FAnimateIndex > FAnimateLastIndex)) or ((FAnimateDirection = adBackward) and (FAnimateIndex < FAnimateLastIndex)) then FAnimateIndex := FAnimateLastIndex; if FAnimateIndex = FAnimateLastIndex then begin if not (goUniDirectional in FGesture.Options) then begin FAnimateStep := -FAnimateStep; case FAnimateDirection of adForward: begin FAnimateDirection := adBackward; FAnimateLastIndex := 0; end; adBackward: begin FAnimateDirection := adForward; FAnimateLastIndex := Length(FAnimatePoints) - 1; end; end; end; FTimer.Interval := FAnimateLongDelay; FAnimateState := asCompleted; end; LPoint := AdjustGesturePoint(FAnimatePoints[FAnimateIndex]); DrawPoint(LPoint, FAnimatedPointColor); end; asCompleted: begin EraseAnimatePoint(FAnimateIndex); if FAnimateDirection = adForward then FAnimateIndex := 0 else FAnimateIndex := Length(FAnimatePoints) - 1; FAnimateState := asPaused; end; asPaused: begin DrawPoint(AdjustGesturePoint(FAnimatePoints[FAnimateIndex]), FAnimatedPointColor); FAnimateState := asRestarting; end; asRestarting: begin EraseAnimatePoint(FAnimateIndex); FAnimateState := asAnimating; FTimer.Interval := FAnimateShortDelay; end; end; end; procedure TCustomGesturePreview.DrawBackground; var LRect: TRect; begin // Fill background if FDrawingStyle = TDrawingStyle.dsGradient then GradientFillCanvas(Canvas, FGradientStartColor, FGradientEndColor, ClientRect, FGradientDirection) else begin Canvas.Brush.Color := Color; Canvas.FillRect(ClientRect); end; // Draw bounding box for gesture preview if FFrameGesture then begin LRect := Rect(FOffsetX, FOffsetY, FInternalPreviewSize + FOffsetX, FInternalPreviewSize + FOffsetY); Canvas.Pen.Color := FFrameColor; Canvas.Pen.Style := FFrameStyle; Canvas.Brush.Style := bsClear; Canvas.Rectangle(LRect); end; end; procedure TCustomGesturePreview.DrawGesturePoints; var LPoint: TPoint; begin // Draw line of gesture's points Canvas.Brush.Style := bsClear; Canvas.Pen.Style := psSolid; DrawGesture(Canvas, FDrawPoints, FPreviewLineColor, Point(FOffsetX + 5, FOffsetY + 5)); // Highlight first point LPoint := AdjustGesturePoint(FDrawPoints[0]); DrawPoint(LPoint, FPreviewEndPointColor); // Highlight last point if not (goUniDirectional in FGesture.Options) then begin LPoint := AdjustGesturePoint(FDrawPoints[Length(FDrawPoints) - 1]); DrawPoint(LPoint, FPreviewEndPointColor); end; end; procedure TCustomGesturePreview.DrawLegend; var LPoint: TPoint; begin // Determine label and dimensions if FLegendPosition <> lpNone then begin LPoint.X := FLegendRect.Left; LPoint.Y := FLegendRect.Top + ((FLegendRect.Bottom - FLegendRect.Top) div 2); // Draw point and label DrawPoint(LPoint, FPreviewEndPointColor); Canvas.Brush.Style := bsClear; Canvas.Font := Font; Canvas.TextOut(FLegendRect.Left + 10, FLegendRect.Top, FLegendText); end; end; procedure TCustomGesturePreview.DrawPoint(const P: TPoint; AColor: TColor); var LRect: TRect; begin LRect := Rect(P.X - 3, P.Y - 3, P.X + 4, P.Y + 4); Canvas.Pen.Color := AColor; Canvas.Brush.Color := AColor; Canvas.Ellipse(LRect); end; procedure TCustomGesturePreview.EraseAnimatePoint(Index: Integer); var P: TPoint; LRect: TRect; begin if (Index >= 0) and (Index < Length(FAnimatePoints)) then begin P := AdjustGesturePoint(FAnimatePoints[Index]); LRect := Rect(P.X - 3, P.Y - 3, P.X + 4, P.Y + 4); InvalidateRect(Handle, LRect, True); Application.ProcessMessages; end; end; function TCustomGesturePreview.InterpolatePoints( const Points: TGesturePointArray): TGesturePointArray; var PointList: TGesturePoints; StepX, StepY: Single; I, J, DeltaX, DeltaY: Integer; CountX, CountY, Count: Integer; begin PointList := TGesturePoints.Create; try for I := 1 to Length(Points) - 1 do begin // Add previous recorded point PointList.Add(Points[I - 1]); // Determine distance between current and last points DeltaX := Abs(Points[I].X - Points[I - 1].X); DeltaY := Abs(Points[I].Y - Points[I - 1].Y); // If points are too far apart insert intermediate points if (DeltaX > 8) or (DeltaY > 8) then begin // Determine how many points to insert CountX := DeltaX div 5; if (DeltaX mod 5) = 0 then Dec(CountX); CountY := DeltaY div 5; if (DeltaY mod 5) = 0 then Dec(CountY); Count := Max(CountX, CountY); // Determine spacing between inserted points StepX := (Points[I].X - Points[I - 1].X) / Count; StepY := (Points[I].Y - Points[I - 1].Y) / Count; // Insert points for J := 1 to Count - 1 do PointList.Add(Point(Points[I - 1].X + Round(StepX * J), Points[I - 1].Y + Round(StepY * J))); end; end; // Add last recorded point if Length(Points) > 0 then PointList.Add(Points[Length(Points) - 1]); // Copy list to result array SetLength(Result, PointList.Count); for I := 0 to PointList.Count - 1 do Result[I] := PointList[I]; finally PointList.Free; end; end; procedure TCustomGesturePreview.Loaded; begin inherited; if HandleAllocated then begin UpdatePosition; if FAnimate then StartAnimation; end; end; procedure TCustomGesturePreview.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = TComponent(FGestureProvider)) then begin FGestureProvider := nil; if not (csDestroying in ComponentState) then Gesture := nil; end end; procedure TCustomGesturePreview.Paint; begin DrawBackground; if Length(FDrawPoints) > 0 then DrawGesturePoints; DrawLegend; end; procedure TCustomGesturePreview.Resize; begin inherited; if not (csLoading in ComponentState) then UpdatePosition; end; procedure TCustomGesturePreview.SetAnimatedPointColor(const Value: TColor); begin if Value <> FAnimatedPointColor then begin FAnimatedPointColor := Value; Invalidate; end; end; procedure TCustomGesturePreview.SetAnimateLongDelay(const Value: Integer); begin if Value <> FAnimateLongDelay then FAnimateLongDelay := Value; end; procedure TCustomGesturePreview.SetAnimateShortDelay(const Value: Integer); begin if Value <> FAnimateShortDelay then FAnimateShortDelay := Value; end; procedure TCustomGesturePreview.SetDrawingStyle(const Value: TDrawingStyle); begin if Value <> FDrawingStyle then begin FDrawingStyle := Value; Invalidate; end; end; procedure TCustomGesturePreview.SetFrameColor(const Value: TColor); begin if Value <> FFrameColor then begin FFrameColor := Value; Invalidate; end; end; procedure TCustomGesturePreview.SetFrameGesture(const Value: Boolean); begin if Value <> FFrameGesture then begin FFrameGesture := Value; UpdatePosition; end; end; procedure TCustomGesturePreview.SetFrameStyle(const Value: TFrameStyle); begin if Value <> FFrameStyle then begin FFrameStyle := Value; Invalidate; end; end; procedure TCustomGesturePreview.SetGesture(const Value: TCustomGestureCollectionItem); var LData: TStandardGestureData; begin FTimer.Enabled := False; if Value <> nil then begin // Assign gesture FGesture.Assign(Value); if (Value.GestureType = gtStandard) and (Length(FGesture.Points) = 0) then if FindStandardGesture(Value.GestureID, LData) then FGesture.Points := LData.Points else FGesture.Points := TGesturePointArray.Create(); end else // Assign empty points FGesture.Points := TGesturePointArray.Create(); // Update position of gesture preview and rescale points if HandleAllocated and not (csLoading in ComponentState) then begin UpdatePosition; if FAnimate then StartAnimation; end; end; procedure TCustomGesturePreview.SetGestureProvider(const Value: IGestureProvider); begin if Value <> FGestureProvider then begin if FGestureProvider <> nil then begin FGestureProvider.RemoveChangeNotification(Self); TComponent(FGestureProvider).RemoveFreeNotification(Self); end; if Value is TComponent then FGestureProvider := Value; if FGestureProvider <> nil then begin FGestureProvider.ChangeNotification(Self, procedure(Sender: TObject; AGesture: TCustomGestureCollectionItem) begin SetGesture(AGesture); end); TComponent(FGestureProvider).FreeNotification(Self); end; end; end; procedure TCustomGesturePreview.SetGradientDirection(const Value: TGradientDirection); begin if Value <> FGradientDirection then begin FGradientDirection := Value; Invalidate; end; end; procedure TCustomGesturePreview.SetGradientEndColor(const Value: TColor); begin if Value <> FGradientEndColor then begin FGradientEndColor := Value; Invalidate; end; end; procedure TCustomGesturePreview.SetGradientStartColor(const Value: TColor); begin if Value <> FGradientStartColor then begin FGradientStartColor := Value; Invalidate; end; end; procedure TCustomGesturePreview.SetLegendPosition(const Value: TLegendPosition); begin if Value <> FLegendPosition then begin FLegendPosition := Value; UpdatePosition; end; end; procedure TCustomGesturePreview.SetMaxPreviewSize(const Value: Integer); begin if Value <> FInternalPreviewSize then begin FMaxPreviewSize := Value; UpdatePosition; end; end; procedure TCustomGesturePreview.SetPreviewEndPointColor(const Value: TColor); begin if Value <> FPreviewEndPointColor then begin FPreviewEndPointColor := Value; Invalidate; end; end; procedure TCustomGesturePreview.SetPreviewLineColor(const Value: TColor); begin if Value <> FPreviewLineColor then begin FPreviewLineColor := Value; Invalidate; end; end; procedure TCustomGesturePreview.SetAnimate(const Value: Boolean); begin if Value <> FAnimate then begin FAnimate := Value; if FAnimate then StartAnimation else SuspendAnimation; end; end; procedure TCustomGesturePreview.StartAnimation; begin // Initialize animation if (FGesture <> nil) and (Length(FAnimatePoints) > 0) then begin FAnimateDirection := adForward; FAnimateLastIndex := Length(FAnimatePoints) - 1; FAnimateIndex := 0; FAnimateState := asPaused; FAnimateStep := (Length(FAnimatePoints) div 15) + 1; FTimer.Interval := FAnimateLongDelay; FTimer.Enabled := True; end; end; procedure TCustomGesturePreview.SuspendAnimation; begin FTimer.Enabled := False; Invalidate; end; procedure TCustomGesturePreview.UpdatePosition; const CMargin = 8; CPointWidth = 10; CBoundingBoxMargin = 10; var LSize: TSize; LWidth: Integer; LHeight: Integer; LPreviewSize: Integer; begin if HandleAllocated then begin // Determine legend text, dimensions and position FOffsetX := 0; FOffsetY := 0; if FLegendPosition <> lpNone then begin Canvas.Font := Font; if (goUniDirectional in FGesture.Options) then FLegendText := SStartPoint else FLegendText := SStartPoints; LSize := Canvas.TextExtent(FLegendText); FLegendRect := Rect(0, 0, LSize.cx + 10, LSize.cy); case FLegendPosition of lpTop: begin OffsetRect(FLegendRect, (Width - (LSize.cx + CPointWidth)) div 2, CMargin); Inc(FOffsetY, LSize.cy + CMargin * 2); end; lpBottom: OffsetRect(FLegendRect, (Width - (LSize.cx + CPointWidth)) div 2, Height - LSize.cy - CMargin); end; end else begin FLegendRect := Rect(0, 0, 0 ,0); LSize.cx := 0; LSize.cy := 0; end; // Determine size of gesture preview LHeight := Height - LSize.cy - (CMargin * 2); LWidth := Width - (CMargin * 2); if (FLegendPosition <> lpNone) then Dec(LHeight, CMargin); if LWidth < LHeight then FInternalPreviewSize := LWidth else FInternalPreviewSize := LHeight; // Use the MaxPreviewSize property if it's non zero if (FMaxPreviewSize <> 0) and (FInternalPreviewSize > FMaxPreviewSize) then begin FInternalPreviewSize := FMaxPreviewSize; if FLegendPosition <> lpNone then Inc(FOffsetY, LSize.cy + CMargin); end; // Position gesture preview Inc(FOffsetX, (Width - FInternalPreviewSize) div 2); Inc(FOffsetY, (LHeight - FInternalPreviewSize) div 2); if FOffsetY < CMargin then FOffsetY := CMargin; // Account for bounding box if needed LPreviewSize := FInternalPreviewSize; Dec(LPreviewSize, CBoundingBoxMargin); // Scale gesture points to new size FDrawPoints := ScaleGesturePoints(FGesture.Points, LPreviewSize); FAnimatePoints := InterpolatePoints(FDrawPoints); // Repaint Invalidate; end; end; procedure TCustomGesturePreview.WndProc(var Message: TMessage); begin inherited WndProc(Message); end; { TCustomGestureRecorder } constructor TCustomGestureRecorder.Create(AOwner: TComponent); begin inherited; FDrawingStyle := TDrawingStyle.dsNormal; FGesture := nil; FGestureLineColor := clBlue; FGesturePointColor := clBlue; FGradientDirection := gdVertical; FGradientEndColor := DefGradientEndColor; FGradientStartColor := DefGradientStartColor; FRecordedPoints := TGesturePoints.Create; FRecording := False; Height := 200; Width := 200; ControlStyle := ControlStyle - [csGestures]; DoubleBuffered := True; ParentDoubleBuffered := False; Touch.InteractiveGestureOptions := []; Touch.InteractiveGestures := []; Touch.ParentTabletOptions := False; Touch.TabletOptions := []; end; destructor TCustomGestureRecorder.Destroy; begin FreeAndNil(FGesture); FreeAndNil(FRecordedPoints); inherited; end; procedure TCustomGestureRecorder.AddGesturePoint(const LastPoint, NextPoint: TPoint); var StepX, StepY: Single; I, DeltaX, DeltaY: Integer; CountX, CountY, Count: Integer; begin // Determine distance between points DeltaX := Abs(NextPoint.X - LastPoint.X); DeltaY := Abs(NextPoint.Y - LastPoint.Y); // If points are too close together discard the new point if (DeltaX < 4) and (DeltaY < 4) then Exit; // If points are too far apart insert intermediate points if (DeltaX > 8) or (DeltaY > 8) then begin // Determine how many points to insert CountX := DeltaX div 5; if (DeltaX mod 5) = 0 then Dec(CountX); CountY := DeltaY div 5; if (DeltaY mod 5) = 0 then Dec(CountY); Count := Max(CountX, CountY); // Determine spacing between inserted points StepX := (NextPoint.X - LastPoint.X) / Count; StepY := (NextPoint.Y - LastPoint.Y) / Count; // Insert points for I := 1 to Count - 1 do FRecordedPoints.Add(Point(LastPoint.X + Round(StepX * I), LastPoint.Y + Round(StepY * I))); end; // Add captured point FRecordedPoints.Add(NextPoint); end; procedure TCustomGestureRecorder.DrawPoint(const Point: TPoint); begin Canvas.Brush.Style := bsClear; Canvas.Pen.Color := FGesturePointColor; Canvas.Ellipse(Point.X - 2, Point.Y - 2, Point.X + 3, Point.Y + 3); Canvas.Pen.Color := FGestureLineColor; if FRecordedPoints.Count = 1 then Canvas.MoveTo(Point.X, Point.Y) else Canvas.LineTo(Point.X, Point.Y); end; function TCustomGestureRecorder.IsTouchPropertyStored( AProperty: TTouchProperty): Boolean; begin Result := inherited IsTouchPropertyStored(AProperty); case AProperty of tpInteractiveGestureOptions: Result := Touch.InteractiveGestureOptions <> []; tpInteractiveGestures: Result := Touch.InteractiveGestures <> []; tpParentTabletOptions: Result := Touch.ParentTabletOptions; end; end; procedure TCustomGestureRecorder.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin // Set recording mode FRecording := True; Invalidate; // Clear list of points FRecordedPoints.Clear; FRecordedPoints.Add(Point(X, Y)); DrawPoint(FRecordedPoints[0]); FLastDrawnPoint := 0; end; procedure TCustomGestureRecorder.MouseMove(Shift: TShiftState; X, Y: Integer); var I: Integer; begin if FRecording then begin // Add new gesture point AddGesturePoint(FRecordedPoints[FRecordedPoints.Count - 1], Point(X, Y)); for I := FLastDrawnPoint to FRecordedPoints.Count - 1 do DrawPoint(FRecordedPoints[I]); FLastDrawnPoint := FRecordedPoints.Count - 1; end else // Multi-touch drivers won't send mouse down in the expected // order but the fiirst mouse down from a touch source will // be our signal to start recording if ssTouch in Shift then begin // Set recording mode FRecording := True; Invalidate; // Clear list of points FRecordedPoints.Clear; FRecordedPoints.Add(Point(X, Y)); DrawPoint(FRecordedPoints[0]); FLastDrawnPoint := 0; end; end; procedure TCustomGestureRecorder.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var LGesture: TGestureCollectionItem; begin if FRecording then begin FRecording := False; // Add new gesture point AddGesturePoint(FRecordedPoints[FRecordedPoints.Count - 1], Point(X, Y)); // Normalize list of points FPoints := TGestureEngine.Recognizer.NormalizePoints(PointsToArray(FRecordedPoints)); // Create gesture from points if FGesture <> nil then FGesture.Free; FGesture := TGestureCollectionItem.Create(nil); FGesture.Points := FPoints; // Trigger OnRecorded event if more than 1 point was recorded if (Length(FPoints) > 1) then begin if FGestureManager <> nil then begin FGesture.GestureID := FGestureManager.AddRecordedGesture(FGesture); LGesture := TGestureCollectionItem(FGestureManager.FindCustomGesture(FGesture.GestureID)); end else LGesture := FGesture; if Assigned(FOnGestureRecorded) then FOnGestureRecorded(Self, LGesture); end; // Force repaint Invalidate; end; end; procedure TCustomGestureRecorder.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FGestureManager) then FGestureManager := nil; end; procedure TCustomGestureRecorder.Paint; var LRect: TRect; LText: string; I, LTextHeight: Integer; begin LRect := ClientRect; if FDrawingStyle = TDrawingStyle.dsNormal then begin Canvas.Brush.Color := Color; Canvas.FillRect(LRect); end else GradientFillCanvas(Canvas, FGradientStartColor, FGradientEndColor, LRect, FGradientDirection); if not FRecording then begin // Draw instructions Canvas.Font := Self.Font; Canvas.Brush.Style := bsClear; LText := FCaption; if (csDesigning in ComponentState) and (LText = '') then LText := Name; InflateRect(LRect, -25, 0); LRect.Top := 0; LRect.Bottom := 0; Canvas.TextRect(LRect, LText, [tfCalcRect, tfWordBreak]); LRect.Right := Width - 25; LTextHeight := LRect.Bottom - LRect.Top; LRect.Top := (Height - LTextHeight) div 2; Inc(LRect.Bottom, LRect.Top); Canvas.TextRect(LRect, LText, [tfCenter, tfWordBreak]); end else begin // Draw points for I := 0 to FRecordedPoints.Count - 1 do DrawPoint(FRecordedPoints[I]) end; end; function TCustomGestureRecorder.PointsToArray(Source: TGesturePoints): TGesturePointArray; var I: Integer; begin SetLength(Result, Source.Count); for I := 0 to Source.Count - 1 do Result[I] := Source[I]; end; procedure TCustomGestureRecorder.SetCaption(const Value: string); begin if Value <> FCaption then begin FCaption := Value; Invalidate; end; end; procedure TCustomGestureRecorder.SetDrawingStyle(const Value: TDrawingStyle); begin if Value <> FDrawingStyle then begin FDrawingStyle := Value; Invalidate; end; end; procedure TCustomGestureRecorder.SetGestureLineColor(const Value: TColor); begin if Value <> FGestureLineColor then begin FGestureLineColor := Value; Invalidate; end; end; procedure TCustomGestureRecorder.SetGestureManager(const Value: TGestureManager); begin if Value <> FGestureManager then begin if FGestureManager <> nil then FGestureManager.RemoveFreeNotification(Self); FGestureManager := Value; if FGestureManager <> nil then FGestureManager.FreeNotification(Self); end; end; procedure TCustomGestureRecorder.SetGesturePointColor(const Value: TColor); begin if Value <> FGesturePointColor then begin FGesturePointColor := Value; Invalidate; end; end; procedure TCustomGestureRecorder.SetGradientDirection(const Value: TGradientDirection); begin if Value <> FGradientDirection then begin FGradientDirection := Value; Invalidate; end; end; procedure TCustomGestureRecorder.SetGradientEndColor(const Value: TColor); begin if Value <> FGradientEndColor then begin FGradientEndColor := Value; Invalidate; end; end; procedure TCustomGestureRecorder.SetGradientStartColor(const Value: TColor); begin if Value <> FGradientStartColor then begin FGradientStartColor := Value; Invalidate; end; end; procedure TCustomGestureRecorder.WndProc(var Message: TMessage); begin inherited WndProc(Message); end; end.
unit UnHi; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.Button1Click(Sender: TObject); begin ShowMessage('Hi!'); ShowMessage('How are you?'); ShowMessage('Nice :)'); ShowMessage('Am I bothering you?'); ShowMessage('Are you sure?'); ShowMessage('Can not exit?'); ShowMessage('Or press the X button?'); ShowMessage('What can I say to you...'); ShowMessage('Hang on.'); ShowMessage('There is not much left..'); ShowMessage('You can be sure of that'); ShowMessage('Hang on a little bit more'); ShowMessage('Have faith that this is almost finishing'); ShowMessage('Joke!!!!'); ShowMessage('kkkkk'); ShowMessage('I think you this will be a little bit longer than you expected.'); ShowMessage('But have faith.'); ShowMessage('I know that you hate this'); ShowMessage('But it is not my fault '); ShowMessage('Because you have pressed the button'); ShowMessage('Not me'); ShowMessage('lol'); ShowMessage('But, you know what?'); ShowMessage('A few more seconds have passed'); ShowMessage('So... keep pressing the button'); ShowMessage('Because you are almost at the end'); ShowMessage('Continue to believe'); ShowMessage('Because only then you go forward'); ShowMessage('And who knows, even today it will reach the end'); ShowMessage('Keep believing in yourself'); ShowMessage('And don't try to use an auto-clicker'); ShowMessage('Now it's time to say goodbye.'); ShowMessage('Bye =*'); end; end.
// **************************************************************************** // * mxWebUpdate Component for Delphi // **************************************************************************** // * Copyright 2002-2005, Bitvadász Kft. All Rights Reserved. // **************************************************************************** // * This component can be freely used and distributed in commercial and // * private environments, provied this notice is not modified in any way. // **************************************************************************** // * Feel free to contact me if you have any questions, comments or suggestions // * at support@maxcomponents.net // **************************************************************************** // * Web page: www.maxcomponents.net // **************************************************************************** // * Description: // * // * TmxWebUpdate helps you to add automatic update support to your application. // * It retrieves information from the web, if a newer version available, it // * can download a file via HTTP and run the update. // * // **************************************************************************** Unit mxWebUpdate; Interface Uses Windows, Messages, SysUtils, Forms, Classes, Controls, WinInet, mxWebUpdateInfo; {$I MAX.INC} Const mxWebUpdateVersion = $0115; Type TDownloadEvent = Procedure( Sender: TObject; Total, Downloaded: Integer; UpdataStatus: Boolean ) Of Object; TShowInfoEvent = Procedure( Sender: TObject; Var ShowInfo: Boolean; Var CheckForUpdate: Boolean ) Of Object; TAfterShowInfoEvent = Procedure( Sender: TObject; CheckForUpdate: Boolean ) Of Object; TGetClientFileNameEvent = Procedure( Sender: TObject; Var FileName: String ) Of Object; TDownloadFileEvent = Procedure( Sender: TObject; FileName: String ) Of Object; TGetInfoEvent = Procedure( Sender: TObject; ActualVersion, NewVersion: String) Of Object; TClientFileExistsEvent = Procedure( Sender: TObject; Var FileName: String; Var Overwrite: Boolean ) Of Object; TUpdateAvailableEvent = Procedure( Sender: TObject; ActualVersion, NewVersion: String; Var CanUpdate: Boolean ) Of Object; TmxUpdateOption = ( uoRunUpdate, uoTerminate, uoOverwrite ); TmxUpdateOptions = Set Of TmxUpdateOption; TmxVersionFormat = ( vfStandard, vfString, vfNumber ); // ****************************************************************************** // ****************************************************************************** // ****************************************************************************** TmxProductInfo = Class( TPersistent ) Private FURL: String; FVersion: String; FVersionFormat: TmxVersionFormat; Procedure SetURL( AValue: String ); Public Constructor Create; Virtual; Destructor Destroy; Override; Published Property URL: String Read FURL Write SetURL; Property Version: String Read FVersion Write FVersion; Property VersionFormat: TmxVersionFormat Read FVersionFormat Write FVersionFormat Default vfStandard; End; // ****************************************************************************** // ****************************************************************************** // ****************************************************************************** TmxTagInfo = Class( TPersistent ) Private FAuthor: String; FEmail: String; FClientFileName: String; FDownload: String; FProductName: String; FRedirection: String; FRunParameters: String; FVersion: String; Public Constructor Create; Virtual; Destructor Destroy; Override; Published Property Author: String Read FAuthor Write FAuthor Stored True; Property Email: String Read FEmail Write FEmail Stored True; Property ClientFileName: String Read FClientFileName Write FClientFileName; Property Download: String Read FDownload Write FDownload Stored True; Property ProductName: String Read FProductName Write FProductName Stored True; Property Redirection: String Read FRedirection Write FRedirection Stored True; Property RunParameters: String Read FRunParameters Write FRunParameters Stored True; Property Version: String Read FVersion Write FVersion Stored True; End; // ****************************************************************************** // ****************************************************************************** // ****************************************************************************** TmxInfoCaption = Class( TPersistent ) Private FOk: String; FCancel: String; FCheckforUpdate: String; Public Constructor Create; Virtual; Published Property OkButton: String Read FOk Write FOk Stored True; Property CancelButton: String Read FCancel Write FCancel Stored True; Property CheckForUpdate: String Read FCheckforUpdate Write FCheckforUpdate; End; // ****************************************************************************** // ****************************************************************************** // ****************************************************************************** TmxWebUpdate = Class( TComponent ) Private FVersion: Integer; FProductInfo: TmxProductInfo; FTagInfo: TmxTagInfo; FOptions: TmxUpdateOptions; FInfoCaption: TmxInfoCaption; FActive: Boolean; FUpdataStatus: Boolean; FFileName: String; FUserName: String; FPassword: String; FInfo: TStringList; FOnDownload: TDownloadEvent; FOnDownloadError: TNotifyEvent; FOnNoUpdateFound: TNotifyEvent; FOnBeforeGetInfo: TNotifyEvent; FOnAfterGetInfo: TNotifyEvent; FOnCannotExecute: TNotifyEvent; FOnGetInfo: TGetInfoEvent; FOnBeforeShowInfo: TShowInfoEvent; FOnAfterShowInfo: TAfterShowInfoEvent; FOnBeforeDownload: TDownloadFileEvent; FOnAfterDownload: TDownloadFileEvent; FOnClientFileExists: TClientFileExistsEvent; FOnGetClientFileName: TGetClientFileNameEvent; FOnUpdateAvailable: TUpdateAvailableEvent; FAborting: Boolean; // *** Info Window *** frm_ShowInfoUpdate: Tfrm_ShowInfoUpdate; // *** Downloaded information *** FProductVersion: String; FUpdateURL: String; FClientFileName: String; FRedirectionURL: String; FAuthor: String; FEMail: String; FProductName: String; FRunParameters: String; // *** Parameters for Download *** FDownloadResult: Boolean; FFileSize: Integer; FDownloadSize: DWord; FDownloadedSize: DWord; //mitec begin FTargetFolder: string; FHTTPPort: Cardinal; //mitec end // ******************************* Procedure SetVersion( AValue: String ); Function GetVersion: String; Protected Procedure DoDownload; Virtual; Procedure DoDownloadError; Virtual; Procedure DoBeginDownload( Const FileName: String ); Virtual; Procedure DoDownloadComplete( Const FileName: String ); Virtual; Procedure DoNoUpdateFound; Virtual; Procedure DoAfterGetInfo; Virtual; Procedure DoBeforeGetInfo; Virtual; Procedure DoCannotExecute; Virtual; Procedure GetInfoFile; Procedure GetUpdateFile; procedure DoGetInfo; Procedure ParseInfoFile; Function IsValidUpdate: Boolean; Function ShowInformation: Boolean; Virtual; Function CreateTempFileName: String; Virtual; Procedure ParseURL( AURL: String; Var HostName, FileName: String ); Virtual; Procedure DownloadFile( FURL: String; FUserName: String; FPassword: String; FBinary: Boolean; FSaveToFile: Boolean; FFileName: String; Download: Boolean = true ); Public Property ProductVersion: String Read FProductVersion; Property UpdateURL: String Read FUpdateURL; Property ClientFileName: String Read FClientFileName; Property RedirectionURL: String Read FRedirectionURL; Property Author: String Read FAuthor; Property EMail: String Read FEMail; Property ProductName: String Read FProductName; Property RunParameters: String Read FRunParameters; Property Active: Boolean Read FActive; Constructor Create( AOwner: TComponent ); Override; Destructor Destroy; Override; Function CheckForAnUpdate: Boolean; function GetInfo: Boolean; Procedure Abort; Published Property TagInfo: TmxTagInfo Read FTagInfo Write FTagInfo; Property ProductInfo: TmxProductInfo Read FProductInfo Write FProductInfo; Property InfoCaption: TmxInfoCaption Read FInfoCaption Write FInfoCaption; Property UserName: String Read FUserName Write FUserName; Property Password: String Read FPassword Write FPassword; Property Options: TmxUpdateOptions Read FOptions Write FOptions; Property Version: String Read GetVersion Write SetVersion; //mitec begin property TargetFolder: string read FTargetFolder write FTargetFolder; property HTTPPort: Cardinal read FHTTPPort write FHTTPPort; //mitec end Property OnBeforeDownload: TDownloadFileEvent Read FOnBeforeDownload Write FOnBeforeDownload; Property OnAfterDownload: TDownloadFileEvent Read FOnAfterDownload Write FOnAfterDownload; Property OnGetInfo: TGetInfoEvent Read FOnGetInfo Write FOnGetInfo; Property OnUpdateAvailable: TUpdateAvailableEvent Read FOnUpdateAvailable Write FOnUpdateAvailable; Property OnGetClientFileName: TGetClientFileNameEvent Read FOnGetClientFileName Write FOnGetClientFileName; Property OnClientFileExists: TClientFileExistsEvent Read FOnClientFileExists Write FOnClientFileExists; Property OnBeforeShowInfo: TShowInfoEvent Read FOnBeforeShowInfo Write FOnBeforeShowInfo; Property OnAfterShowInfo: TAfterShowInfoEvent Read FOnAfterShowInfo Write FOnAfterShowInfo; Property OnBeforeGetInfo: TNotifyEvent Read FOnBeforeGetInfo Write FOnBeforeGetInfo; Property OnCannotExecute: TNotifyEvent Read FOnCannotExecute Write FOnCannotExecute; Property OnAfterGetInfo: TNotifyEvent Read FOnAfterGetInfo Write FOnAfterGetInfo; Property OnNoUpdateFound: TNotifyEvent Read FOnNoUpdateFound Write FOnNoUpdateFound; Property OnDownload: TDownloadEvent Read FOnDownload Write FOnDownload; Property OnDownloadError: TNotifyEvent Read FOnDownloadError Write FOnDownloadError; End; // ****************************************************************************** // ****************************************************************************** // ****************************************************************************** Implementation Uses ShellApi; // ************************************************************************************* // ************************************************************************************* // ************************************************************************************* // * TmxProductInfo // ************************************************************************************* // ************************************************************************************* // ************************************************************************************* Constructor TmxProductInfo.Create; Begin Inherited Create; SetURL( '' ); FVersion := '1.0'; FVersionFormat := vfStandard; End; Destructor TmxProductInfo.Destroy; Begin Inherited Destroy; End; Procedure TmxProductInfo.SetURL( AValue: String ); Begin If AnsiCompareText( Copy( AValue, 1, 7 ), 'http://' ) <> 0 Then AValue := 'http://' + AValue; FURL := AValue; End; // ************************************************************************************* // ************************************************************************************* // ************************************************************************************* // * TmxInfoCaption // ************************************************************************************* // ************************************************************************************* // ************************************************************************************* Constructor TmxInfoCaption.Create; Begin Inherited Create; FOk := '&OK'; FCancel := '&Cancel'; FCheckforUpdate := 'C&heck for updates in the future'; End; // ************************************************************************************* // ************************************************************************************* // ************************************************************************************* // * TmxTagInfo // ************************************************************************************* // ************************************************************************************* // ************************************************************************************* Constructor TmxTagInfo.Create; Begin Inherited Create; FAuthor := 'mxAuthor'; FEmail := 'mxEmail'; FDownload := 'mxDownload'; FClientFileName := 'mxClientSideName'; FProductName := 'mxProduct'; FRedirection := 'mxRedirection'; FRunParameters := 'mxRunParameters'; FVersion := 'mxVersion'; End; Destructor TmxTagInfo.Destroy; Begin Inherited Destroy; End; // ************************************************************************************* // ************************************************************************************* // ************************************************************************************* // * TmxWebUpdate // ************************************************************************************* // ************************************************************************************* // ************************************************************************************* Constructor TmxWebUpdate.Create( AOwner: TComponent ); Begin Inherited Create( AOwner ); FVersion := mxWebUpdateVersion; FOptions := [ uoRunUpdate, uoTerminate ]; FProductInfo := TmxProductInfo.Create; FTagInfo := TmxTagInfo.Create; FInfoCaption := TmxInfoCaption.Create; FRedirectionURL := ''; FInfo := TStringList.Create; //mitec begin FHTTPPort:=INTERNET_DEFAULT_HTTP_PORT; //mitec end End; Destructor TmxWebUpdate.Destroy; Begin Abort; FInfo.Free; FTagInfo.Free; FInfoCaption.Free; FProductInfo.Free; If Assigned( frm_ShowInfoUpdate ) Then frm_ShowInfoUpdate.Free; Inherited Destroy; End; Procedure TmxWebUpdate.SetVersion( AValue: String ); Begin // *** Does nothing *** End; Function TmxWebUpdate.GetVersion: String; Begin {$WARNINGS OFF} Result := Format( '%d.%d', [ Hi( FVersion ), Lo( FVersion ) ] ); {$WARNINGS ON} End; Procedure TmxWebUpdate.Abort; Begin FAborting := True; End; Procedure TmxWebUpdate.DoDownloadError; Begin If Assigned( FOnDownloadError ) Then FOnDownloadError( Self ); End; Procedure TmxWebUpdate.DoBeginDownload( Const FileName: String ); Begin If Assigned( FOnBeforeDownload ) Then FOnBeforeDownload( Self, FileName ); End; Procedure TmxWebUpdate.DoDownloadComplete( Const FileName: String ); Begin If Assigned( FOnAfterDownload ) Then FOnAfterDownload( Self, FileName ); End; Procedure TmxWebUpdate.DoDownload; Begin If Assigned( FOnDownload ) Then FOnDownload( Self, FFileSize, FDownloadedSize, FUpdataStatus); End; Procedure TmxWebUpdate.DoNoUpdateFound; Begin If Assigned( FOnNoUpdateFound ) Then FOnNoUpdateFound( Self ); End; Procedure TmxWebUpdate.DoCannotExecute; Begin If Assigned( FOnCannotExecute ) Then FOnCannotExecute( Self ); End; Procedure TmxWebUpdate.DoAfterGetInfo; Begin If Assigned( FOnAfterGetInfo ) Then FOnAfterGetInfo( Self ); End; Procedure TmxWebUpdate.DoBeforeGetInfo; Begin If Assigned( FOnBeforeGetInfo ) Then FOnBeforeGetInfo( Self ); End; Function TmxWebUpdate.CreateTempFileName: String; Var TempPath: String; R: Cardinal; Begin //mitec begin if DirectoryExists(FTargetFolder) then begin Result:=IncludeTrailingPathDelimiter(FTargetFolder)+FClientFileName; Exit; end; //mitec end Result := ''; R := GetTempPath( 0, Nil ); SetLength( TempPath, R ); {$WARNINGS OFF} R := GetTempPath( R, PChar( TempPath ) ); {$WARNINGS ON} If R <> 0 Then Begin {$WARNINGS OFF} SetLength( TempPath, StrLen( PChar( TempPath ) ) ); {$WARNINGS ON} Result := TempPath + FClientFileName; End; End; Procedure TmxWebUpdate.GetUpdateFile; Var Overwrite: Boolean; Begin FFileName := CreateTempFileName; If Assigned( FOnGetClientFileName ) Then FOnGetClientFileName( Self, FFileName ); FDownloadResult := False; If FileExists( FFileName ) Then Begin Overwrite := uoOverwrite In FOptions; If Assigned( FOnClientFileExists ) Then FOnClientFileExists( Self, FFileName, Overwrite ); If Not Overwrite Then Begin DoDownloadError; Exit; End; End; DoBeginDownload( FFileName ); DownloadFile( FUpdateURL, FUserName, FPassword, True, True, FFileName ); DoDownloadComplete( FFileName ); End; Procedure TmxWebUpdate.ParseInfoFile; Var I: Integer; Offset: Integer; TagName: String; TagLength: Integer; Function GetData( ALine: String ): String; Var Offset: Integer; DataLength: Integer; Begin Offset := Pos( 'CONTENT=', UpperCase( ALine ) ) + 9; DataLength := Pos( '"', Copy( ALine, Offset, 255 ) ) - 1; Result := Copy( ALine, Offset, DataLength ); End; Begin FRedirectionURL := ''; FProductVersion := ''; FUpdateURL := ''; FClientFileName := ''; FAuthor := ''; FEMail := ''; FProductName := ''; FRunParameters := ''; For I := 0 To FInfo.Count - 1 Do Begin Offset := Pos( 'META NAME', FInfo.Strings[ I ] ); If Offset = 0 Then Continue; Inc( Offset, 11 ); TagLength := Pos( '"', Copy( FInfo.Strings[ I ], Offset, 255 ) ) - 1; TagName := Copy( FInfo.Strings[ I ], Offset, TagLength ); If tagName = TagInfo.ProductName Then FProductName := GetData( FInfo.Strings[ I ] ); If tagName = TagInfo.ClientFileName Then FClientFileName := GetData( FInfo.Strings[ I ] ); If tagName = TagInfo.Version Then FProductVersion := GetData( FInfo.Strings[ I ] ); If tagName = TagInfo.Author Then FAuthor := GetData( FInfo.Strings[ I ] ); If tagName = TagInfo.EMail Then FEMail := GetData( FInfo.Strings[ I ] ); If tagName = TagInfo.Download Then FUpdateURL := GetData( FInfo.Strings[ I ] ); If tagName = TagInfo.Redirection Then FRedirectionURL := GetData( FInfo.Strings[ I ] ); If tagName = TagInfo.RunParameters Then FRunParameters := GetData( FInfo.Strings[ I ] ); End; End; Procedure TmxWebUpdate.GetInfoFile; Var URL: String; Begin FProductVersion := ''; FUpdateURL := ''; FAuthor := ''; FEMail := ''; FProductName := ''; FRunParameters := ''; If FRedirectionURL = '' Then URL := FProductInfo.URL Else URL := FRedirectionURL; DownloadFile( URL, FUserName, FPassword, False, False, '' ); If FDownloadResult Then Begin ParseInfoFile; If FRedirectionURL <> '' Then GetInfoFile; End; End; Function TmxWebUpdate.IsValidUpdate: Boolean; Var Version_Actual: String; Version_Update: String; V_A, V_U: Real; Code: Integer; Actual_Version: Integer; Update_Version: Integer; Position_Actual: Integer; Position_Update: Integer; Begin Result := False; Version_Actual := FProductInfo.Version; Version_Update := FProductVersion; Case FProductInfo.VersionFormat Of vfStandard: Begin Repeat Position_Actual := Pos( '.', Version_Actual ); Position_Update := Pos( '.', Version_Update ); If Position_Actual > 0 Then Actual_Version := StrToIntDef( Copy( Version_Actual, 1, Position_Actual - 1 ), 0 ) Else Actual_Version := StrToIntDef( Version_Actual, 0 ); If Position_Update > 0 Then Update_Version := StrToIntDef( Copy( Version_Update, 1, Position_Update - 1 ), 0 ) Else Update_Version := StrToIntDef( Version_Update, 0 ); If Update_Version > Actual_Version Then Begin Result := True; Exit; End; If Update_Version < Actual_Version Then Begin Result := False; DoNoUpdateFound; Exit; End; System.Delete( Version_Actual, 1, Position_Actual ); System.Delete( Version_Update, 1, Position_Update ); Until Position_Actual = 0; End; vfString: Result := Version_Update > Version_Actual; vfNumber: Begin Val( Version_Actual, V_A, Code ); Result := Code = 0; If Not Result Then Begin DoNoUpdateFound; Exit; End; Val( Version_Update, V_U, Code ); Result := Code = 0; If Not Result Then Begin DoNoUpdateFound; Exit; End; Result := V_U > V_A; End; End; If Not Result Then DoNoUpdateFound; End; Function TmxWebUpdate.ShowInformation: Boolean; Var ShowInfo: Boolean; Check: Boolean; Begin Result := True; ShowInfo := True; Check := True; If Assigned( FOnBeforeShowInfo ) Then FOnBeforeShowInfo( Self, ShowInfo, Check ); If Not ShowInfo Then Exit; If Not Assigned( frm_ShowInfoUpdate ) Then frm_ShowInfoUpdate := Tfrm_ShowInfoUpdate.Create( Nil ); frm_ShowInfoUpdate.chk_FutureUpdate.Checked := Check; frm_ShowInfoUpdate.btn_OK.Caption := FInfoCaption.OkButton; frm_ShowInfoUpdate.btn_Cancel.Caption := FInfoCaption.CancelButton; frm_ShowInfoUpdate.chk_FutureUpdate.Caption := FInfoCaption.CheckForUpdate; If FRedirectionURL = '' Then frm_ShowInfoUpdate.WebBrowser.Navigate( FProductInfo.URL ) Else frm_ShowInfoUpdate.WebBrowser.Navigate( FRedirectionURL ); Result := frm_ShowInfoUpdate.ShowModal = mrOK; If Assigned( FOnAfterShowInfo ) Then FOnAfterShowInfo( Self, frm_ShowInfoUpdate.chk_FutureUpdate.Checked ); End; Procedure TmxWebUpdate.ParseURL( AURL: String; Var HostName, FileName: String ); Var I: Integer; Begin If Pos( 'http://', LowerCase( AURL ) ) <> 0 Then System.Delete( AURL, 1, 7 ); I := Pos( '/', AURL ); HostName := Copy( AURL, 1, I ); FileName := Copy( AURL, I, Length( AURL ) - I + 1 ); If ( Length( HostName ) > 0 ) And ( HostName[ Length( HostName ) ] = '/' ) Then SetLength( HostName, Length( HostName ) - 1 ); End; Procedure TmxWebUpdate.DownloadFile( FURL: String; FUserName: String; FPassword: String; FBinary: Boolean; FSaveToFile: Boolean; FFileName: String; Download: Boolean = true ); Var {$WARNINGS OFF} hSession, hConnect, hRequest: hInternet; HostName, FileName: String; //mitec begin AcceptType: {$IFDEF UNICODE}LPWSTR{$ELSE}LPStr{$ENDIF}; //mitec end Buffer: Pointer; BufferLength, Index: DWord; //mitec begin Data: Array[ 0..1024 ] Of AnsiChar; //mitec end Agent: String; InternetFlag: DWord; RequestMethod: PChar; FReferer: String; TempStr: String; FStringResult: String; F: File; Procedure CloseHandles; Begin InternetCloseHandle( hRequest ); InternetCloseHandle( hConnect ); InternetCloseHandle( hSession ); End; {$WARNINGS ON} Begin Try FAborting := False; ParseURL( FURL, HostName, FileName ); //mitec begin if HostName='' then ParseURL(FProductInfo.URL,HostName,TempStr); //mitec end Agent := 'TmxWebUpdate'; {$WARNINGS OFF} hSession := InternetOpen( PChar( Agent ), INTERNET_OPEN_TYPE_PRECONFIG, Nil, Nil, 0 ); //mitec begin hConnect := InternetConnect( hSession, PChar( HostName ), FHTTPPort, PChar( FUserName ), PChar( FPassword ), INTERNET_SERVICE_HTTP, 0, 0 ); //mitec end RequestMethod := 'GET'; InternetFlag := INTERNET_FLAG_RELOAD; AcceptType := PChar( 'Accept: ' + '*/*' ); hRequest := HttpOpenRequest( hConnect, RequestMethod, PChar( FileName ), 'HTTP/1.0', PChar( FReferer ), @AcceptType, InternetFlag, 0 ); HttpSendRequest( hRequest, Nil, 0, Nil, 0 ); {$WARNINGS ON} If FAborting Then Begin CloseHandles; FDownloadResult := False; Exit; End; Index := 0; BufferLength := 1024; {$WARNINGS OFF} GetMem( Buffer, BufferLength ); FDownloadResult := HttpQueryInfo( hRequest, HTTP_QUERY_CONTENT_LENGTH, Buffer, BufferLength, Index ); {$WARNINGS ON} If FAborting Then Begin {$WARNINGS OFF} FreeMem( Buffer ); {$WARNINGS ON} CloseHandles; FDownloadResult := False; Exit; End; if Download then begin If FDownloadResult Or Not FBinary Then Begin {$WARNINGS OFF} //mitec begin If FDownloadResult Then FFileSize := StrToInt( String( Buffer ) ); //mitec end {$WARNINGS ON} FDownloadedSize := 0; If FSaveToFile Then Begin AssignFile( F, FFileName ); ReWrite( F, 1 ); End Else FStringResult := ''; While True Do Begin If FAborting Then Begin If FSaveToFile Then CloseFile( F ); {$WARNINGS OFF} FreeMem( Buffer ); {$WARNINGS ON} CloseHandles; FDownloadResult := False; Exit; End; {$WARNINGS OFF} If Not InternetReadFile( hRequest, @Data, SizeOf( Data ), FDownloadSize ) Then Break {$WARNINGS ON} Else Begin If FDownloadSize = 0 Then Break Else Begin {$WARNINGS OFF} If FSaveToFile Then BlockWrite( f, Data, FDownloadSize ) Else {$WARNINGS ON} Begin TempStr := Data; SetLength( TempStr, FDownloadSize ); FStringResult := FStringResult + TempStr; End; Inc( FDownloadedSize, FDownloadSize ); DoDownload; Application.ProcessMessages; End; End; End; If FSaveToFile Then Begin FDownloadResult := FFileSize = Integer( FDownloadedSize ) End Else Begin SetLength( FStringResult, FDownloadedSize ); FDownloadResult := FDownloadedSize <> 0; End; If FSaveToFile Then CloseFile( f ); End; {$WARNINGS OFF} FreeMem( Buffer ); {$WARNINGS ON} CloseHandles; If FDownloadResult Then Begin If Not FSaveToFile Then Begin FInfo.Clear; FInfo.Text := FStringResult; End; End Else DoDownloadError; end; Except FDownloadResult := False; End; End; procedure TmxWebUpdate.DoGetInfo; Var URL: String; Begin FProductVersion := ''; FUpdateURL := ''; FAuthor := ''; FEMail := ''; FProductName := ''; FRunParameters := ''; If FRedirectionURL = '' Then URL := FProductInfo.URL Else URL := FRedirectionURL; DownloadFile( URL, FUserName, FPassword, False, False, '', False ); If FDownloadResult Then Begin ParseInfoFile; If FRedirectionURL <> '' Then DoGetInfo; End; end; function TmxWebUpdate.GetInfo: Boolean; Begin Result := False; FUpdataStatus:= False; FRedirectionURL := ''; //DoBeforeGetInfo; GetInfoFile; FOnGetInfo( Self, FProductInfo.Version, FProductVersion ); //DoAfterGetInfo; Result:= True; end; Function TmxWebUpdate.CheckForAnUpdate: Boolean; Var CanUpdate: Boolean; Begin Result := False; FUpdataStatus:= False; If FActive Then Exit; FActive := True; FRedirectionURL := ''; DoBeforeGetInfo; GetInfoFile; DoAfterGetInfo; If ( FProductName = '' ) Or ( FProductVersion = '' ) Then Begin DoDownloadError; FDownloadResult := False; End; If Not FDownloadResult Then Begin FActive := False; Exit; End; If Not IsValidUpdate Then Begin FActive := False; Exit; End; CanUpdate := True; If Assigned( FOnUpdateAvailable ) Then FOnUpdateAvailable( Self, FProductInfo.Version, FProductVersion, CanUpdate ); If Not CanUpdate Then Begin FActive := False; Exit; End; If Not ShowInformation Then Begin FActive := False; Exit; End; FUpdataStatus:= True; GetUpdateFile; If Not FDownloadResult Then Begin FActive := False; Exit; End; If uoRunUpdate In FOptions Then Begin {$WARNINGS OFF} If ShellExecute( Application.MainForm.Handle, PChar( 'open' ), PChar( FFileName ), PChar( FRunParameters ), PChar( '' ), SW_SHOWNORMAL ) <= 32 Then DoCannotExecute; {$WARNINGS ON} If uoTerminate In FOptions Then Application.Terminate; End; FActive := False; Result := True; End; End.
(******************************************************************************* Author: -> Jean-Pierre LESUEUR (@DarkCoderSc) https://github.com/DarkCoderSc https://gist.github.com/DarkCoderSc https://www.phrozen.io/ License: -> MIT *******************************************************************************) unit UntMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, System.ImageList, Vcl.ImgList, Vcl.Menus, commctrl, Vcl.ExtCtrls; type TFrmMain = class(TForm) lstview: TListView; Img16: TImageList; status: TStatusBar; MainMenu1: TMainMenu; File1: TMenuItem; LoadFile1: TMenuItem; LoadProcess1: TMenuItem; N1: TMenuItem; Exit1: TMenuItem; About1: TMenuItem; OD: TOpenDialog; SD: TSaveDialog; Export1: TMenuItem; Clear1: TMenuItem; Export2: TMenuItem; Timer: TTimer; procedure FormCreate(Sender: TObject); procedure lstviewCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); procedure Exit1Click(Sender: TObject); procedure About1Click(Sender: TObject); procedure LoadFile1Click(Sender: TObject); procedure Clear1Click(Sender: TObject); procedure Export2Click(Sender: TObject); procedure LoadProcess1Click(Sender: TObject); private procedure Reset(); public procedure OpenDDL(ADLLFileName : String); procedure ExportListToFile(); end; var FrmMain: TFrmMain; implementation {$R *.dfm} uses UntEnumDLLExport, UntAbout, UntProcess; procedure TFrmMain.Reset(); begin self.lstview.Clear; status.Panels.Items[0].Text := 'Exported Count : N/A'; status.Panels.Items[1].Text := 'Status : N/A'; caption := 'DLL Export Enum'; end; procedure TFrmMain.Export2Click(Sender: TObject); begin self.ExportListToFile(); end; procedure TFrmMain.ExportListToFile(); var i, n : integer; AItem : TListItem; AList : TStringList; ARecord : String; begin if NOT SD.Execute() then Exit(); AList := TStringList.Create(); try for I := 0 to self.lstview.items.Count -1 do begin AItem := self.lstview.Items.Item[i]; ARecord := 'Name : ' + AItem.Caption + #13#10; for n := 0 to AItem.SubItems.Count -1 do begin ARecord := ARecord + self.lstview.Columns.Items[n].Caption + ' : ' + AItem.SubItems[n] + #13#10; end; ARecord := ARecord + '-----------------------------------------' + #13#10; AList.Add(ARecord); end; AList.SaveToFile(SD.FileName); finally if Assigned(AList) then FreeAndNil(AList); end; end; procedure TFrmMain.OpenDDL(ADLLFileName : String); var AEnumDLLExport : TEnumDLLExport; i : integer; AEntry : TExportEntry; AListItem : TListItem; AForwarded : Boolean; ARet : Integer; AStatus : String; begin self.lstview.Clear; AEnumDLLExport := TEnumDLLExport.Create(ADLLFileName); self.Caption := 'DLL Export Enum [' + AEnumDLLExport.FileName + ']'; ARet := AEnumDLLExport.Enum(); for i := 0 to AEnumDLLExport.Items.Count -1 do begin AEntry := AEnumDLLExport.Items.Items[i]; AListItem := self.lstview.Items.Add; AListItem.Caption := AEntry.Name; if AEntry.Forwarded then AListItem.SubItems.Add(AEntry.ForwardName) else AListItem.SubItems.Add(AEntry.FormatedAddress); AListItem.SubItems.Add(AEntry.FormatedRelativeAddress); AListItem.SubItems.Add(Format('%d (0x%s)', [AEntry.Ordinal, IntToHex(AEntry.Ordinal, 1)])); AListItem.ImageIndex := 0; end; status.Panels.Items[0].Text := Format('Exported Count : %d', [AEnumDLLExport.Items.Count]); case ARet of -99 : AStatus := 'Unknown'; -1 : AStatus := 'Could not open file.'; -2 : AStatus := 'Could not read image dos header.'; -3 : AStatus := 'Invalid or corrupted PE File.'; -4 : AStatus := 'Could not read nt header signature.'; -5 : AStatus := 'Could not read image file header.'; -6 : AStatus := 'Could not read optional header.'; -7 : AStatus := 'Could not retrieve entry export address.'; -8 : AStatus := 'Could not read export directory.'; -9 : AStatus := 'No exported functions'; else AStatus := 'Success'; end; status.Panels.Items[1].Text := AStatus; end; procedure TFrmMain.About1Click(Sender: TObject); begin FrmAbout.Show(); end; procedure TFrmMain.Clear1Click(Sender: TObject); begin Reset(); end; procedure TFrmMain.Exit1Click(Sender: TObject); begin FrmMain.Close(); end; procedure TFrmMain.FormCreate(Sender: TObject); begin Reset(); end; procedure TFrmMain.LoadFile1Click(Sender: TObject); begin if NOT OD.Execute() then Exit(); self.OpenDDL(OD.FileName); end; procedure TFrmMain.LoadProcess1Click(Sender: TObject); begin FrmProcess.ShowModal(); end; procedure TFrmMain.lstviewCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); begin if Odd(Item.Index) then Sender.Canvas.Brush.Color := RGB(245, 245, 245); end; end.
program hanoi2; procedure hanoi(num, src, dst: integer); { num is a number of a disc } begin if num = 0 then exit; hanoi(num-1, src, 6-src-dst); writeln('N', num, ': ', src, ' -> ', dst); hanoi(num-1, 6-src-dst, dst); end; begin hanoi(3, 1 ,3); end.
// ------------------------------------------------------------------------------- // Descrição: Um programa em Pascal que determina se um determinado número, // lido do teclado, é par // ------------------------------------------------------------------------------- // Autor : Fernando Gomes // Data : 19/08/2021 // ------------------------------------------------------------------------------- Program num_par ; //Seção de Declarações das variáveis var num: integer; Begin //Pede ao usuario que insira um numero Write('Digite um número: '); Readln(num); //Faz a verificacao com a operacao MOD (resto inteiro da divisao) if (num mod 2 = 0) then write('O número ',num, ' é par') else write('O número ',num, ' não é par') End.
unit BrowserTab; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cefvcl, ceflib, ComCtrls, StdCtrls, ToolWin, MainForm; type TBrowserTab = class(TForm) Chromium1: TChromium; ToolBar2: TToolBar; btnBack: TButton; btnForward: TButton; btnRefresh: TButton; addressBar: TEdit; btnGo: TButton; btnNewTab: TButton; btncloseTab: TButton; procedure Chromium1BeforePopup(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const targetUrl, targetFrameName: ustring; var popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings; var noJavascriptAccess: Boolean; out Result: Boolean); procedure FormCreate(Sender: TObject); procedure Chromium1BeforeBrowse(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean; out Result: Boolean); procedure Chromium1LoadingStateChange(Sender: TObject; const browser: ICefBrowser; isLoading, canGoBack, canGoForward: Boolean); procedure Chromium1TitleChange(Sender: TObject; const browser: ICefBrowser; const title: ustring); procedure Chromium1DownloadUpdated(Sender: TObject; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback); procedure Chromium1BeforeDownload(Sender: TObject; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback); procedure Chromium1LoadStart(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame); procedure addressBarKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } a: boolean; s: string; end; var BT: TBrowserTab; implementation uses URLMon; {$R *.dfm} procedure TBrowserTab.Chromium1BeforePopup(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const targetUrl, targetFrameName: ustring; var popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings; var noJavascriptAccess: Boolean; out Result: Boolean); begin s := targeturl; a := true; chromium1.Load(s); result := true; end; procedure TBrowserTab.FormCreate(Sender: TObject); begin a := false; addressBar.SetFocus; btnGo.Caption := '>'; btnBack.Caption := '<'; btnForward.Caption := '>'; btnRefresh.Caption := 'R'; btnNewTab.Caption := '+'; btnCloseTab.Caption := '-'; end; procedure TBrowserTab.Chromium1BeforeBrowse(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean; out Result: Boolean); begin if a then begin MF.openUrlInNewTab(s); result := true; a := false; end else begin result := false; end; end; procedure TBrowserTab.Chromium1LoadingStateChange(Sender: TObject; const browser: ICefBrowser; isLoading, canGoBack, canGoForward: Boolean); begin btnBack.Enabled := Chromium1.Browser.CanGoBack; btnForward.Enabled := Chromium1.Browser.CanGoForward; end; procedure TBrowserTab.Chromium1TitleChange(Sender: TObject; const browser: ICefBrowser; const title: ustring); var t: string; begin t := title; if Length(title) > 15 then begin t := Copy(title, 0, 12); t := t + '...'; end; (Parent as TTabSheet).Caption := t; if title <> '' then begin MF.Caption := title + ' - ' + 'MiraBrowser'; end; end; procedure TBrowserTab.Chromium1DownloadUpdated(Sender: TObject; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback); begin if downloaditem.TotalBytes = downloaditem.ReceivedBytes then begin // end; end; procedure TBrowserTab.Chromium1BeforeDownload(Sender: TObject; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback); begin callback.Cont('c:\', true); end; procedure TBrowserTab.Chromium1LoadStart(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame); begin addressBar.Text := browser.MainFrame.GetUrl; end; procedure TBrowserTab.addressBarKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin MF.actGo.Execute; exit; end; end; end.
unit UntLanguage_en_US; interface const // Login Screen sTituloLogin = 'Login'; lbIdioma = 'Language:'; lbUsername = 'Username:'; lbSenha = 'Password:'; btEntrar = 'Send'; btCancelar = 'Cancel'; // ComboBox CBoxLinguagem sItemPt = 'Portuguese (Brazil)'; sItemEn = 'English (US)'; sMsgErroLogin = 'Invalid username and/or password'; // Main Screen sTituloTelaPrincipal = 'Main Screen'; menuItemPesquisa = 'Search'; menuItemFuncionario = 'Employee'; menuItemCargo = 'Office'; menuItemFornecedor = 'Supplier'; menuItemProduto = 'Product'; menuItemSistema = 'System'; menuItemUsuario = 'User'; menuItemSair = 'Exit'; // Employee Search sTituloTelaPesqFunci = 'Employee Search'; sLblTituloTabSheet = 'Employees'; sTabShtInc = 'Add'; sTabShtEdt = 'Edit'; sMsgCargoObrigatorio = 'The Cargo field is required !'; slblIdFunci = 'Id:'; slblNomeFunci = 'Name:'; slblRGFunci = 'RG:'; slblCPFFunci = 'CPF:'; slblCargoFunci = 'Office:'; slblDBGIdFunci = 'Id'; slblDBGNomeFunci = 'Name'; slblDBGRGFunci = 'RG'; slblDBGCPFFunci = 'CPF'; sbtnPesquFunciSalvar = 'Salve'; sbtnPesquFunciCancelar = 'Cancel'; // Consts.pas SMsgDlgWarning = 'Warning'; SMsgDlgConfirm = 'Confirm'; SMsgDlgCancel = 'Cancel'; SDeleteRecordQuestion = 'Delete record?'; // Office Search sTituloTelaPesqCargo = 'Office Search'; sLblTituloTabSheetCargo = 'Offices'; slblIdCargo = 'Id:'; slblDescricaoCargo = 'Description:'; slblSalarioCargo = 'Salary:'; slblDBGIdCargo = 'Id'; slblDBGDescricaoCargo = 'Description'; slblDBGSalarioCargo = 'Salary'; sbtnPesquCargoSalvar = 'Salve'; sbtnPesquCargoCancelar = 'Cancel'; // Supplier Search sTituloTelaPesqFornecedor = 'Supplier Search'; sLblTituloTabSheetFornecedor = 'Suppliers'; slblCNPJFornecedor = 'CNPJ:'; slblNomeFantasiaFornecedor = 'Commercial name:'; slblDBGCNPJFornecedor = 'CNPJ'; slblDBGNomeFantasiaFornecedor = 'Trade/commercial name'; sbtnPesquFornecedorSalvar = 'Salve'; sbtnPesquFornecedorCancelar = 'Cancel'; // Product Search sTituloTelaPesqProduto = 'Product Search'; sLblTituloTabSheetProduto = 'Products'; sMsgFornecedorObrigatorio = 'The Fornecedor field is required !'; slblIdProduto = 'Id:'; slblDescricaoProduto = 'Description:'; slblDetalheProduto = 'Detail:'; slblPrecoCompraProduto = 'Purchase Price:'; slblPrecoVendaProduto = 'Sale Price:'; slblFornecedorProduto = 'Supplier:'; slblDBGIdProduto = 'Id'; slblDBGDescricaoProduto = 'Description'; slblDBGDetalheProduto = 'Detail'; slblDBGPrecoCompraProduto = 'Purchase Price'; slblDBGPrecoVendaProduto = 'Sale Price'; sbtnPesquProdutoSalvar = 'Salve'; sbtnPesquProdutoCancelar = 'Cancel'; // User Search sTituloTelaPesqUsuario = 'User Search'; sLblTituloTabSheetUsuario = 'Users'; sMsgFuncionarioObrigatorio = 'The Funcionário field is required !'; slblIdUsuario = 'Id:'; slblUsuarioUsuario = 'Username:'; slblSenhaUsuario = 'Password:'; slblFuncionarioUsuario = 'Employee:'; slblDBGIdUsuario = 'Id'; slblDBGUsuarioUsuario = 'Username'; slblDBGSenhaUsuario = 'Password'; sbtnPesquUsuarioSalvar = 'Salve'; sbtnPesquUsuarioCancelar = 'Cancel'; implementation end.
unit chfrConversa; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OleCtrls, cxPC, chBase, ExtCtrls; type TchFrameConversa = class(TFrame) Panel1: TPanel; private { Private declarations } FNodeID : String; FTabSheet : TcxTabSheet; FNodeInfo : TchNodeInfo; FVazia : Boolean; procedure SetNodeID(const Value: String); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AjustaCaption; procedure Fechar; function Chat: TClienteChat; procedure AtualizaNodeInfo; virtual; procedure AddMsg(ARecebeu: Boolean; AHora: TDateTime; ATexto: String); virtual; property Vazia: Boolean read FVazia; published property NodeID: String read FNodeID write SetNodeID; property TabSheet: TcxTabSheet read FTabSheet write FTabSheet; property NodeInfo: TchNodeInfo read FNodeInfo write FNodeInfo; { Public declarations } end; TchClasseFrameConversa = class of TchFrameConversa; implementation uses chpcConversas; {$R *.dfm} { TFrameConversa } procedure TchFrameConversa.AddMsg(ARecebeu: Boolean; AHora: TDateTime; ATexto: String); begin FVazia := False; end; procedure TchFrameConversa.AjustaCaption; var S: String; begin with FNodeInfo do begin S := niNome; if S = '' then S := 'Desconhecido'; if niStatus <> '' then S := S + ' (' + niStatus + ')'; end; TabSheet.Caption := S; end; procedure TchFrameConversa.AtualizaNodeInfo; begin LimpaNodeInfo(FNodeInfo); if Chat <> nil then Chat.GetNodeInfo(FNodeID, FNodeInfo); AjustaCaption; end; function TchFrameConversa.Chat: TClienteChat; begin if (FTabSheet<>nil) and (FTabSheet.PageControl<>nil) then Result := TchpcConversas(FTabSheet.PageControl).Chat else Result := nil; end; constructor TchFrameConversa.Create(AOwner: TComponent); begin inherited; FVazia := True; FNodeID := ''; FTabSheet := nil; LimpaNodeInfo(FNodeInfo); end; destructor TchFrameConversa.Destroy; begin if FTabSheet<>nil then FTabSheet.Free; inherited; end; procedure TchFrameConversa.Fechar; var T: TcxTabSheet; begin if FTabSheet=nil then Exit; T := FTabSheet; FTabSheet := nil; T.PageControl := nil; T.Free; end; procedure TchFrameConversa.SetNodeID(const Value: String); begin if Value = FNodeID then Exit; FNodeID := Value; AtualizaNodeInfo; end; end.
unit uSingleton; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TSingleton } TSingleton = class private constructor Create; public class function InstanceActive(var aPointer: TSingleton): Boolean; class function GetInstance: TSingleton; class function NewInstance: TObject; override; end; implementation var Instance: TSingleton; class function TSingleton.NewInstance: TObject; begin if not Assigned(Instance) then Instance := TSingleton(inherited NewInstance); Result := Instance; end; class function TSingleton.GetInstance: TSingleton; begin Result := TSingleton.Create; end; constructor TSingleton.Create; begin inherited; end; class function TSingleton.InstanceActive(var aPointer: TSingleton): Boolean; begin Result := Assigned(aPointer); end; initialization finalization FreeAndNil(Instance); end.
//////////////////////////////////////////////////////////////////////////////// // // **************************************************************************** // * Project : FWZip // * Unit Name : FWZipConsts // * Purpose : Типы и константы используемые для работы с ZIP архивами // * Author : Александр (Rouse_) Багель // * Copyright : © Fangorn Wizards Lab 1998 - 2023. // * Version : 2.0.0 // * Home Page : http://rouse.drkb.ru // * Home Blog : http://alexander-bagel.blogspot.ru // **************************************************************************** // * Stable Release : http://rouse.drkb.ru/components.php#fwzip // * Latest Source : https://github.com/AlexanderBagel/FWZip // **************************************************************************** // // Используемые источники: // ftp://ftp.info-zip.org/pub/infozip/doc/appnote-iz-latest.zip // https://zlib.net/zlib-1.2.13.tar.gz // http://www.base2ti.com/ // unit FWZipConsts; {$IFDEF FPC} {$MODE Delphi} {$H+} {$ENDIF} interface uses {$IFDEF MSWINDOWS} Windows, {$ELSE} Types, {$ENDIF} SysUtils, Classes; const MAXBYTE = 255; MAXWORD = 65535; MAXDWORD = DWORD(-1); MAX_PATH = 260; type DWORD = Cardinal; LOBYTE = Byte; LOWORD = Word; // зависит от платформы, под Windows будет праться из Windows.pas // под остальными из Types.pas TFileTime = FILETIME; PFileTime = ^TFileTime; TFileAttributeData = record dwFileAttributes: DWORD; ftCreationTime: TFileTime; ftLastAccessTime: TFileTime; ftLastWriteTime: TFileTime; nFileSizeHigh: DWORD; nFileSizeLow: DWORD; end; { IV. General Format of a .ZIP file --------------------------------- Files stored in arbitrary order. Large .ZIP files can span multiple diskette media or be split into user-defined segment sizes. [The minimum user-defined segment size for a split .ZIP file is 64K. (removed by PKWare 2003-06-01)] Overall .ZIP file format: [local file header 1] [file data 1] [data descriptor 1] . . . [local file header n] [file data n] [data descriptor n] [archive decryption header] (EFS) [archive extra data record] (EFS) [central directory] [zip64 end of central directory record] [zip64 end of central directory locator] [end of central directory record] } PLocalFileHeader = ^TLocalFileHeader; TLocalFileHeader = packed record LocalFileHeaderSignature: Cardinal; // (0x04034b50) VersionNeededToExtract, GeneralPurposeBitFlag, CompressionMethod, LastModFileTimeTime, LastModFileTimeDate: Word; Crc32, CompressedSize, UncompressedSize: Cardinal; FilenameLength, ExtraFieldLength: Word; // file name (variable size) // extra field (variable size) end; { If bit 3 of the general purpose bit flag is set, these fields are set to zero in the local header and the correct values are put in the data descriptor and in the central directory. } TDataDescriptor = packed record DescriptorSignature, // (0x08074b50) Crc32, CompressedSize, UncompressedSize: Cardinal; {For Zip64 format archives, the compressed and uncompressed sizes are 8 bytes each. ??!!} end; TEFS = packed record ArchiveExtraDataSignature, // (0x08064b50) ExtraFieldLength: Cardinal; // extra field data (variable size) end; { F. Central directory structure: [file header 1] . . . [file header n] [digital signature] } TCentralDirectoryFileHeader = packed record CentralFileHeaderSignature: Cardinal; // (0x02014b50) VersionMadeBy, VersionNeededToExtract, GeneralPurposeBitFlag, CompressionMethod, LastModFileTimeTime, LastModFileTimeDate: Word; Crc32, CompressedSize, UncompressedSize: Cardinal; FilenameLength, ExtraFieldLength, FileCommentLength, DiskNumberStart, InternalFileAttributes: Word; ExternalFileAttributes, RelativeOffsetOfLocalHeader: Cardinal; // file name (variable size) // extra field (variable size) // file comment (variable size) end; TCentralDirectoryFileHeaderEx = packed record Header: TCentralDirectoryFileHeader; UncompressedSize, CompressedSize, RelativeOffsetOfLocalHeader, DataOffset: Int64; DiskNumberStart: Integer; FileName, FileComment: string; Attributes: TFileAttributeData; ExceptOnWrite: Boolean; end; TNTFSFileTime = packed record Mtime: TFileTime; Atime: TFileTime; Ctime: TFileTime; end; TExDataHeaderAndSize = packed record Header: Word; Size: Word; end; TExDataNTFS = packed record HS: TExDataHeaderAndSize; Reserved: Cardinal; Tag: Word; RecordSize: Word; Data: TNTFSFileTime; end; TExDataInfo64 = packed record HS: TExDataHeaderAndSize; UncompressedSize, CompressedSize: Int64; end; TCentralDirectoryDigitalSignature = packed record HeaderSignature: Cardinal; // (0x05054b50) SizeOfData: Word; // signature data (variable size) end; TZip64EOFCentralDirectoryRecord = packed record Zip64EndOfCentralDirSignature: Cardinal; // (0x06064b50) SizeOfZip64EOFCentralDirectoryRecord: int64; VersionMadeBy, VersionNeededToExtract: Word; NumberOfThisDisk, // number of this disk DiskNumberStart: Cardinal; // number of the disk with the start of the central directory TotalNumberOfEntriesOnThisDisk, // total number of entries in the central directory on this disk TotalNumberOfEntries, // total number of entries in the central directory SizeOfTheCentralDirectory, // size of the central directory RelativeOffsetOfCentralDirectory: Int64; // offset of start of central directory with respect to the starting disk number // zip64 extensible data sector (variable size) end; TZip64EOFCentralDirectoryLocator = packed record Signature, // zip64 end of central dir locator signature (0x07064b50) DiskNumberStart: Cardinal; // number of the disk with the start of the zip64 end of central directory RelativeOffset: Int64; // relative offset of the zip64 end of central directory record TotalNumberOfDisks: Cardinal; end; TEndOfCentralDir = packed record EndOfCentralDirSignature: Cardinal; // (0x06054b50) NumberOfThisDisk, DiskNumberStart, TotalNumberOfEntriesOnThisDisk, TotalNumberOfEntries: Word; SizeOfTheCentralDirectory, RelativeOffsetOfCentralDirectory: Cardinal; ZipfileCommentLength: Word; // .ZIP file comment (variable size) end; const LOCAL_FILE_HEADER_SIGNATURE = $04034B50; DATA_DESCRIPTOR_SIGNATURE = $08074B50; // Маркер для разбитых на части архивов // см. zip_format.txt 8.5.4 - 8.5.5 SPAN_DESCRIPTOR_SIGNATURE = DATA_DESCRIPTOR_SIGNATURE; TEMPORARY_SPANING_DESCRIPTOR_SIGNATURE = $30304B50; EXTRA_DATA_SIGNATURE = $08064B50; CENTRAL_FILE_HEADER_SIGNATURE = $02014B50; CENTRAL_DIRECTORY_DIGITAL_SIGNATURE = $05054B50; ZIP64_END_OF_CENTRAL_DIR_SIGNATURE = $06064B50; ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE = $07064B50; END_OF_CENTRAL_DIR_SIGNATURE = $06054B50; ZIP_SLASH = '/'; // Флаги для GeneralPurposeBitFlag PBF_CRYPTED = 1; // (For Methods 8 and 9 - Deflating) PBF_COMPRESS_NORMAL = 0; PBF_COMPRESS_MAXIMUM = 2; PBF_COMPRESS_FAST = 4; PBF_COMPRESS_SUPERFAST = 6; PBF_DESCRIPTOR = 8; PBF_STRONG_CRYPT = 64; PBF_UTF8 = $800; // константы поддерживаемых полей ExData SUPPORTED_EXDATA_ZIP64 = 1; SUPPORTED_EXDATA_NTFSTIME = 10; defaultWindowBits = -15; type TProgressState = ( psStart, // начало распаковки элемента, результирующий файл еще не создан psInitialization, // результирующий файл создан и залочен, производится подготовка к распаковке psInProgress, // идет распаковка psFinalization, // распаковка завершена, сейчас будут разрушены все служебные объекты, результирующий файл все еще залочен psEnd, // операция распаковки полностью завершена, результирующий файл доступен на чтение/запись psException // ошибка ); TZipProgressEvent = procedure(Sender: TObject; const FileName: string; Percent, TotalPercent: Byte; var Cancel: Boolean; ProgressState: TProgressState) of object; TZipExtractItemEvent = procedure(Sender: TObject; const FileName: string; Extracted, TotalSize: Int64; ProgressState: TProgressState) of object; TZipNeedPasswordEvent = procedure(Sender: TObject; const FileName: string; var Password: string; var CancelExtract: Boolean) of object; TZipSaveExDataEvent = procedure(Sender: TObject; ItemIndex: Integer; UserExDataBlockCount: Integer; var Tag: Word; Data: TStream) of object; TZipLoadExDataEvent = procedure(Sender: TObject; ItemIndex: Integer; Tag: Word; Data: TStream) of object; // Типы поведения TFWZipWriter при ошибке в процессе создания архива TExceptionAction = ( eaRetry, // повторить попытку eaSkip, // пропустить текущий элемент eaAbort, // остановить создание архива eaUseNewFilePath, // использовать новый путь к файлу (пар. NewFilePath) eaUseNewFilePathAndDel, // то-же что и acUseNewFilePath, только файл удаляется после использования eaUseNewFileData // использовать содержимое файла из стрима (пар. NewFileData) ); TZipBuildExceptionEvent = procedure(Sender: TObject; E: Exception; const ItemIndex: Integer; var Action: TExceptionAction; var NewFilePath: string; NewFileData: TMemoryStream) of object; TZipExtractExceptionEvent = procedure(Sender: TObject; E: Exception; const ItemIndex: Integer; var Handled: Boolean) of object; // Типы поведения TFWZipReader при конфликте имен файлов TDuplicateAction = ( daSkip, // пропустить файл daOverwrite, // перезаписать daUseNewFilePath, // сохранить с новым именем daAbort // отменить распаковку ); TZipDuplicateEvent = procedure(Sender: TObject; var Path: string; var Action: TDuplicateAction) of object; const CRC32Table: array[Byte] of Cardinal = ( $00000000, $77073096, $EE0E612C, $990951BA, $076DC419, $706AF48F, $E963A535, $9E6495A3, $0EDB8832, $79DCB8A4, $E0D5E91E, $97D2D988, $09B64C2B, $7EB17CBD, $E7B82D07, $90BF1D91, $1DB71064, $6AB020F2, $F3B97148, $84BE41DE, $1ADAD47D, $6DDDE4EB, $F4D4B551, $83D385C7, $136C9856, $646BA8C0, $FD62F97A, $8A65C9EC, $14015C4F, $63066CD9, $FA0F3D63, $8D080DF5, $3B6E20C8, $4C69105E, $D56041E4, $A2677172, $3C03E4D1, $4B04D447, $D20D85FD, $A50AB56B, $35B5A8FA, $42B2986C, $DBBBC9D6, $ACBCF940, $32D86CE3, $45DF5C75, $DCD60DCF, $ABD13D59, $26D930AC, $51DE003A, $C8D75180, $BFD06116, $21B4F4B5, $56B3C423, $CFBA9599, $B8BDA50F, $2802B89E, $5F058808, $C60CD9B2, $B10BE924, $2F6F7C87, $58684C11, $C1611DAB, $B6662D3D, $76DC4190, $01DB7106, $98D220BC, $EFD5102A, $71B18589, $06B6B51F, $9FBFE4A5, $E8B8D433, $7807C9A2, $0F00F934, $9609A88E, $E10E9818, $7F6A0DBB, $086D3D2D, $91646C97, $E6635C01, $6B6B51F4, $1C6C6162, $856530D8, $F262004E, $6C0695ED, $1B01A57B, $8208F4C1, $F50FC457, $65B0D9C6, $12B7E950, $8BBEB8EA, $FCB9887C, $62DD1DDF, $15DA2D49, $8CD37CF3, $FBD44C65, $4DB26158, $3AB551CE, $A3BC0074, $D4BB30E2, $4ADFA541, $3DD895D7, $A4D1C46D, $D3D6F4FB, $4369E96A, $346ED9FC, $AD678846, $DA60B8D0, $44042D73, $33031DE5, $AA0A4C5F, $DD0D7CC9, $5005713C, $270241AA, $BE0B1010, $C90C2086, $5768B525, $206F85B3, $B966D409, $CE61E49F, $5EDEF90E, $29D9C998, $B0D09822, $C7D7A8B4, $59B33D17, $2EB40D81, $B7BD5C3B, $C0BA6CAD, $EDB88320, $9ABFB3B6, $03B6E20C, $74B1D29A, $EAD54739, $9DD277AF, $04DB2615, $73DC1683, $E3630B12, $94643B84, $0D6D6A3E, $7A6A5AA8, $E40ECF0B, $9309FF9D, $0A00AE27, $7D079EB1, $F00F9344, $8708A3D2, $1E01F268, $6906C2FE, $F762575D, $806567CB, $196C3671, $6E6B06E7, $FED41B76, $89D32BE0, $10DA7A5A, $67DD4ACC, $F9B9DF6F, $8EBEEFF9, $17B7BE43, $60B08ED5, $D6D6A3E8, $A1D1937E, $38D8C2C4, $4FDFF252, $D1BB67F1, $A6BC5767, $3FB506DD, $48B2364B, $D80D2BDA, $AF0A1B4C, $36034AF6, $41047A60, $DF60EFC3, $A867DF55, $316E8EEF, $4669BE79, $CB61B38C, $BC66831A, $256FD2A0, $5268E236, $CC0C7795, $BB0B4703, $220216B9, $5505262F, $C5BA3BBE, $B2BD0B28, $2BB45A92, $5CB36A04, $C2D7FFA7, $B5D0CF31, $2CD99E8B, $5BDEAE1D, $9B64C2B0, $EC63F226, $756AA39C, $026D930A, $9C0906A9, $EB0E363F, $72076785, $05005713, $95BF4A82, $E2B87A14, $7BB12BAE, $0CB61B38, $92D28E9B, $E5D5BE0D, $7CDCEFB7, $0BDBDF21, $86D3D2D4, $F1D4E242, $68DDB3F8, $1FDA836E, $81BE16CD, $F6B9265B, $6FB077E1, $18B74777, $88085AE6, $FF0F6A70, $66063BCA, $11010B5C, $8F659EFF, $F862AE69, $616BFFD3, $166CCF45, $A00AE278, $D70DD2EE, $4E048354, $3903B3C2, $A7672661, $D06016F7, $4969474D, $3E6E77DB, $AED16A4A, $D9D65ADC, $40DF0B66, $37D83BF0, $A9BCAE53, $DEBB9EC5, $47B2CF7F, $30B5FFE9, $BDBDF21C, $CABAC28A, $53B39330, $24B4A3A6, $BAD03605, $CDD70693, $54DE5729, $23D967BF,$B3667A2E, $C4614AB8, $5D681B02, $2A6F2B94, $B40BBE37, $C30C8EA1, $5A05DF1B, $2D02EF8D ); CurrentVersionMadeBy = 63; LongNamePrefix = '\\?\'; var /// <summary> /// Глобальная переменная управляющая включением/отключением поддержки длинных путей /// </summary> UseLongNamePrefix: Boolean = True; implementation end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLODESkeletonColliders<p> Skeleton colliders for defining and controlling ODE geoms.<p> <b>History :</b><font size=-1><ul> <li>10/11/12 - PW - Added CPP compatibility: restored records with arrays instead of vector arrays <li>17/11/09 - DaStr - Improved Unix compatibility (thanks Predator) (BugtrackerID = 2893580) <li>12/04/08 - DaStr - Cleaned up uses section (thanks Sandor Domokos) (BugtrackerID = 1808373) <li>06/02/08 - Mrqzzz - Upgrade to ODE 0.9 (replaced references, and CCilinder (ode 0.8) with Capsule(ode 0.9)) <li>02/08/04 - LR, YHC - BCB corrections: use record instead array <li>04/12/03 - SG - Creation. </ul></font> } unit GLODESkeletonColliders; interface uses Classes, GLPersistentClasses, GLVectorGeometry, GLVectorFileObjects, ODEImport; type // TSCODEBase // {: Base ODE skeleton collider class. } TSCODEBase = class(TSkeletonCollider) private FGeom : PdxGeom; public procedure WriteToFiler(writer : TVirtualWriter); override; procedure ReadFromFiler(reader : TVirtualReader); override; procedure AddToSpace(Space : PdxSpace); virtual; procedure AlignCollider; override; {: The geoms are created through the AddToSpace procedure. } property Geom : PdxGeom read FGeom; end; // TSCODESphere // {: Sphere shaped ODE geom in a skeleton collider. } TSCODESphere = class(TSCODEBase) private FRadius : TdReal; protected procedure SetRadius(const val : TdReal); public constructor Create; override; procedure WriteToFiler(writer : TVirtualWriter); override; procedure ReadFromFiler(reader : TVirtualReader); override; procedure AddToSpace(Space : PdxSpace); override; property Radius : TdReal read FRadius write SetRadius; end; // TSCODECCylinder // {: Capsule (sphere capped cylinder) shaped ODE geom in a skeleton collider. } TSCODECCylinder = class(TSCODEBase) private FRadius, FLength : Single; protected procedure SetRadius(const val : Single); procedure SetLength(const val : Single); public constructor Create; override; procedure WriteToFiler(writer : TVirtualWriter); override; procedure ReadFromFiler(reader : TVirtualReader); override; procedure AddToSpace(Space : PdxSpace); override; property Radius : Single read FRadius write SetRadius; property Length : Single read FLength write SetLength; end; // TSCODEBox // {: Box shaped ODE geom in a skeleton collider. } TSCODEBox = class(TSCODEBase) private FBoxWidth, FBoxHeight, FBoxDepth : TdReal; protected procedure SetBoxWidth(const val : TdReal); procedure SetBoxHeight(const val : TdReal); procedure SetBoxDepth(const val : TdReal); public constructor Create; override; procedure WriteToFiler(writer : TVirtualWriter); override; procedure ReadFromFiler(reader : TVirtualReader); override; procedure AddToSpace(Space : PdxSpace); override; property BoxWidth : TdReal read FBoxWidth write SetBoxWidth; property BoxHeight : TdReal read FBoxHeight write SetBoxHeight; property BoxDepth : TdReal read FBoxDepth write SetBoxDepth; end; {: After loading call this function to add all the geoms in a skeleton collider list to a given ODE space. } procedure AddSCODEGeomsToODESpace( colliders : TSkeletonColliderList; space : PdxSpace); // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------ // ------------------ Global methods ------------------ // ------------------ // AddSCODEGeomsToODESpace // procedure AddSCODEGeomsToODESpace( colliders : TSkeletonColliderList; space : PdxSpace); var i : Integer; begin for i:=0 to colliders.Count-1 do if colliders[i] is TSCODEBase then TSCODEBase(Colliders[i]).AddToSpace(space); end; // ------------------ // ------------------ TSCODEBase ------------------ // ------------------ // WriteToFiler // procedure TSCODEBase.WriteToFiler(writer : TVirtualWriter); begin inherited WriteToFiler(writer); with writer do begin WriteInteger(0); // Archive Version 0 end; end; // ReadFromFiler // procedure TSCODEBase.ReadFromFiler(reader : TVirtualReader); var archiveVersion : integer; begin inherited ReadFromFiler(reader); archiveVersion:=reader.ReadInteger; if archiveVersion=0 then with reader do // Nothing yet else RaiseFilerException(archiveVersion); end; // AddToSpace // procedure TSCODEBase.AddToSpace(Space : PdxSpace); begin AlignCollider; end; // AlignCollider // procedure TSCODEBase.AlignCollider; var R : TdMatrix3; Mat : TMatrix; begin inherited; if Assigned(FGeom) then begin Mat:=GlobalMatrix; dGeomSetPosition(FGeom,Mat.V[3].V[0],Mat.V[3].V[1],Mat.V[3].V[2]); R[0]:=Mat.V[0].V[0]; R[1]:=Mat.V[1].V[0]; R[2]:= Mat.V[2].V[0]; R[3]:= 0; R[4]:=Mat.V[0].V[1]; R[5]:=Mat.V[1].V[1]; R[6]:= Mat.V[2].V[1]; R[7]:= 0; R[8]:=Mat.V[0].V[2]; R[9]:=Mat.V[1].V[2]; R[10]:=Mat.V[2].V[2]; R[11]:=0; dGeomSetRotation(FGeom,R); end; end; // ------------------ // ------------------ TSCODESphere ------------------ // ------------------ // Create // constructor TSCODESphere.Create; begin inherited; FRadius:=0.5; AlignCollider; end; // WriteToFiler // procedure TSCODESphere.WriteToFiler(writer : TVirtualWriter); begin inherited WriteToFiler(writer); with writer do begin WriteInteger(0); // Archive Version 0 WriteFloat(FRadius); end; end; // ReadFromFiler // procedure TSCODESphere.ReadFromFiler(reader : TVirtualReader); var archiveVersion : integer; begin inherited ReadFromFiler(reader); archiveVersion:=reader.ReadInteger; if archiveVersion=0 then with reader do Radius:=ReadFloat else RaiseFilerException(archiveVersion); end; // AddToSpace // procedure TSCODESphere.AddToSpace(Space : PdxSpace); begin FGeom:=dCreateSphere(Space, FRadius); inherited; end; // SetRadius // procedure TSCODESphere.SetRadius(const val : TdReal); begin if val<>FRadius then begin FRadius:=val; if Assigned(FGeom) then dGeomSphereSetRadius(Geom, TdReal(FRadius)); end; end; // ------------------ // ------------------ TSCODECCylinder ------------------ // ------------------ // Create // constructor TSCODECCylinder.Create; begin inherited; FRadius:=0.5; FLength:=1; AlignCollider; end; // WriteToFiler // procedure TSCODECCylinder.WriteToFiler(writer : TVirtualWriter); begin inherited WriteToFiler(writer); with writer do begin WriteInteger(0); // Archive Version 0 WriteFloat(FRadius); WriteFloat(FLength); end; end; // ReadFromFiler // procedure TSCODECCylinder.ReadFromFiler(reader : TVirtualReader); var archiveVersion : integer; begin inherited ReadFromFiler(reader); archiveVersion:=reader.ReadInteger; if archiveVersion=0 then with reader do begin Radius:=ReadFloat; Length:=ReadFloat; end else RaiseFilerException(archiveVersion); end; // AddToSpace // procedure TSCODECCylinder.AddToSpace(Space : PdxSpace); begin FGeom:=dCreateCapsule(Space,FRadius,FLength); inherited; end; // SetRadius // procedure TSCODECCylinder.SetRadius(const val : Single); begin if val<>FRadius then begin FRadius:=val; if Assigned(FGeom) then dGeomCapsuleSetParams(FGeom,FRadius,FLength); end; end; // SetLength // procedure TSCODECCylinder.SetLength(const val : Single); begin if val<>FLength then begin FLength:=val; if Assigned(FGeom) then dGeomCapsuleSetParams(FGeom,FRadius,FLength); end; end; // ------------------ // ------------------ TSCODEBox ------------------ // ------------------ // Create // constructor TSCODEBox.Create; begin inherited; FBoxWidth:=1; FBoxHeight:=1; FBoxDepth:=1; AlignCollider; end; // WriteToFiler // procedure TSCODEBox.WriteToFiler(writer : TVirtualWriter); begin inherited WriteToFiler(writer); with writer do begin WriteInteger(0); // Archive Version 0 WriteFloat(FBoxWidth); WriteFloat(FBoxHeight); WriteFloat(FBoxDepth); end; end; // ReadFromFiler // procedure TSCODEBox.ReadFromFiler(reader : TVirtualReader); var archiveVersion : integer; begin inherited ReadFromFiler(reader); archiveVersion:=reader.ReadInteger; if archiveVersion=0 then with reader do begin BoxWidth:=ReadFloat; BoxHeight:=ReadFloat; BoxDepth:=ReadFloat; end else RaiseFilerException(archiveVersion); end; // AddToSpace // procedure TSCODEBox.AddToSpace(Space : PdxSpace); begin FGeom:=dCreateBox(Space, FBoxWidth, FBoxHeight, FBoxDepth); inherited; end; // SetBoxWidth // procedure TSCODEBox.SetBoxWidth(const val : TdReal); begin if val<>FBoxWidth then begin FBoxWidth:=val; if Assigned(FGeom) then dGeomBoxSetLengths(Geom, TdReal(FBoxWidth), TdReal(FBoxHeight), TdReal(FBoxDepth)); end; end; // SetBoxHeight // procedure TSCODEBox.SetBoxHeight(const val : TdReal); begin if val<>FBoxHeight then begin FBoxHeight:=val; if Assigned(FGeom) then dGeomBoxSetLengths(Geom, TdReal(FBoxWidth), TdReal(FBoxHeight), TdReal(FBoxDepth)); end; end; // SetBoxDepth // procedure TSCODEBox.SetBoxDepth(const val : TdReal); begin if val<>FBoxDepth then begin FBoxDepth:=val; if Assigned(FGeom) then dGeomBoxSetLengths(Geom, TdReal(FBoxWidth), TdReal(FBoxHeight), TdReal(FBoxDepth)); end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterClasses([TSCODEBase,TSCODESphere,TSCODECCylinder,TSCODEBox]); end.
{*******************************************************} { } { Delphi Runtime Library } { SOAP Support } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit WSDLCppWriter; interface uses TypInfo, xmldom, WSDLImpWriter, WSDLItems, WSDLModelIntf; type TWSDLCppWriter = class(TWSDLWriter) private FNamespace: DOMString; function GetPartFlagList(const Part: IWSDLPart; SkipFlags: TPartFlag = []): string; protected function IsDynArrayType(ArrayType: string): Boolean; { Overriden for C++ Codegeneration } function IsReservedWord(const Name: DOMString; var NewName: DOMString): Boolean; override; function TypeNameFromTypeInfo(TypeInfo: pTypeInfo): DOMString; override; procedure WriteInterfaceBegin(const WSDLPortType: IWSDLPortType; PassType: TPassWriterType); override; procedure WriteInterfaceEnd(const WSDLPortType: IWSDLPortType; PassType: TPassWriterType); override; procedure WriteMethod(const WSDLOperation: IWSDLOperation; const Parent: IWSDLPortType; PassType: TPassWriterType); override; procedure WriteEnum(const WSDLType: IWSDLType); override; procedure WriteAliasDef(const WSDLType: IWSDLType); override; procedure WriteArray(const WSDLType: IWSDLType); override; procedure WriteComplexTypeClass(const WSDLType: IWSDLType; PassType: TPassWriterType); override; function GetTypeInfo(const WSDLType: IWSDLType): DOMString; override; function RemapMembersOfTypeName: boolean; override; procedure WriteTypeNamespace(const TypeNamespace: DOMString; Using: Boolean = False); function Escape(const W: DOMString): DOMString; override; public constructor Create(const WSDLImporter: IWSDLImporter); override; constructor CreateFilename(const WSDLImporter: IWSDLImporter; OutFileName: string); override; destructor Destroy; override; procedure WriteIntfHeader; override; procedure WriteIntfFooter; override; function WriteSettingsFile: Boolean; override; procedure SetOutFile(const outFile: string; CheckProject: Boolean); override; function IntfExt: DOMString; override; function HasSource: Boolean; override; function SourceExt: DOMString; override; procedure WriteSource; override; procedure WriteRegCalls; override; procedure WriteSourceHeader; procedure WriteSourceFooter; property Namespace: DOMString read FNamespace write FNamespace; end; TWSDLCppWriterClass = class of TWSDLCppWriter; implementation uses IntfInfo, SysUtils, WSDLImpConst, XMLSchemaHelper, {$IFNDEF STANDALONE} GenWizard, {$ENDIF} SOAPConst, WSDLIntf, InvokeRegistry; const { Unknown, in, out, inOut, ret } PreParamMod: array[PartType] of string = ('', 'const ', '', '', '', '', ''); { Do not localize } PosParamMod: array[PartType] of string = ('', '', '&', '&', '', '', ''); { Do not localize } RefOp: array[Boolean] of string = ('', '*'); { Do not localize } PadStr: array[Boolean] of string = ('', ' '); { Do not localize } VirtualStr: array[Boolean] of string = ('', 'virtual '); { Do not localize } PureVirtStr: array[Boolean] of string = ('', ' = 0'); { Do not localize } CppReservedWords: array[0..105] of string =( '__asm', '_asm', 'asm', 'auto', '__automated', 'break', 'case', 'catch', '__cdecl', '_cdecl', 'cdecl', 'char', 'class', '__classid', '__closure', 'const', 'const_cast', 'continue', '__cs', '_cs', '__declspec', 'default', 'delete', 'dispid', '__dispid', 'do', 'double', '__ds', '_ds', 'dynamic_cast', 'else', 'enum', '__es', '_es', '__except', 'far', '__far', '_far', '__fastcall', '_fastcall', '__finally', 'float', 'for', 'friend', 'goto', 'huge', '__huge', '_huge', 'if', '__import', '_import', 'inline', 'int', '__int8', '__int16', '__int32', '__int64', 'interrupt', '__interrupt', '_interrupt', '__loadds', '_loadds', 'long', 'near', '_near', '__near', 'new', 'operator', 'pascal', 'private', '__property', 'protected', 'public', '__published', 'register', 'reinterpret_cast', 'return', '__rtti', '__saveregs', '_saveregs', '__seg', '_seg', 'short', 'signed', 'sizeof', '__ss', '_ss', 'static', 'static_cast', '__stdcall', '_stdcall', 'struct', 'switch', 'template', 'this', '__thread', 'throw', '__try', 'try', 'typeid', 'unsigned', 'virtual', 'void', 'volatile', 'wchar_t', 'while' ); { TWSDLCppWriter } constructor TWSDLCppWriter.Create(const WSDLImporter: IWSDLImporter); begin inherited Create(WSDLImporter); end; constructor TWSDLCppWriter.CreateFilename(const WSDLImporter: IWSDLImporter; OutFileName: string); begin inherited CreateFilename(WSDLImporter, OutFileName); end; destructor TWSDLCppWriter.Destroy; begin inherited Destroy; end; function TWSDLCppWriter.IsReservedWord(const Name: DOMString; var NewName: DOMString): Boolean; var I: Integer; begin Result := False; for I := Low(CppReservedWords) to High(CppReservedWords) do begin if Name = CppReservedWords[I] then begin Result := True; Exit; end; end; if not Result then begin Result := WSDLImpWriter.IsReservedNameInSymFile(Name, True, NewName); end; end; function TWSDLCppWriter.IsDynArrayType(ArrayType: string): Boolean; begin Result := False; end; function TWSDLCppWriter.TypeNameFromTypeInfo(TypeInfo: pTypeInfo): DOMString; begin Result := OtherTypeName(string(TypeInfo.Name)); if (Result = '') then Result := DOMString(TypeInfo.Name); end; procedure TWSDLCppWriter.WriteIntfHeader; const sMacros: array[WSDLImporterOpts] of string = ( '', // woHasSOAPDM, // SOAP Data module in the WSDL '', // woHasDocStyle, // Document style services '', // woHasLiteralUse, // Literal service sCppIsOptn, // woHasOptionalElem, // Types with optional elements sCppIsUnbd, // woHasUnboundedElem, // Types with unbounded elements sCppIsNlbl, // woHasNillableElem, // Types with nillable elements sCppIsUnql, // woHasUnqualifiedElem, // Types with unqualified elements sCppIsAttr, // woHasAttribute, // Complex types with attributes sCppIsText, // woHasText, // Properties that map to 'text' nodes - not ntElement sCppIsAny, // woHasAny sCppIsRef, // woHasRef sCppIsQual, // woHasQualifiedAttr sCppIsOut // woHasOut ); var Opt: WSDLImporterOpts; ImpOpts: TWSDLImporterOpts; begin WriteWSDLInfo; WriteFmt(sHdrGuardBegin, [OutFile]); { Some headers are specific to clients } if not (wfServer in Global_WSDLGenFlags) then WriteStr(sClientHeaders) else WriteLn(''); { Macros used in declaration } WriteStr(sCppRemoteClass); if EmitIndexMacros(ImpOpts, True) then begin for Opt := Low(WSDLImporterOpts) to High(WSDLImporterOpts) do if (Opt in ImpOpts) and (sMacros[Opt] <> '') then WriteStr(sMacros[Opt]); WriteLn(''); end; if (wfTypesInNamespace in Global_WSDLGenFlags) then WriteTypeNamespace(OutFile); end; procedure TWSDLCppWriter.WriteIntfFooter; begin if (wfTypesInNamespace in Global_WSDLGenFlags) then WriteTypeNamespace('', True); WriteFmt(sLineBreak + sHdrGuardEnd, [OutFile]); end; { NOTE: This routine must be overriden by a TWSDLWriter-derived class - The default implementation is strictly for testing purposes } function TWSDLCppWriter.HasSource: Boolean; begin Result := True; end; function TWSDLCppWriter.IntfExt: DOMString; begin Result := '.h'; { Do not localize } end; function TWSDLCppWriter.SourceExt: DOMString; begin Result := '.cpp'; { Do not localize } end; procedure TWSDLCppWriter.SetOutFile(const outFile: string; CheckProject: Boolean); {$IFNDEF STANDALONE} var I: integer; {$ENDIF} begin FOutFile := outFile; {$IFNDEF STANDALONE} I := 0; { Unit name can't conflict with existing file name } if CheckProject then begin while FileExistInActiveProject(FOutFile+SourceExt) do begin Inc(I); FOutFile := outFile + IntToStr(I); end; end; {$ENDIF} end; function TWSDLCppWriter.RemapMembersOfTypeName: boolean; begin Result := True; end; procedure TWSDLCppWriter.WriteTypeNamespace(const TypeNamespace: DOMString; Using: Boolean); begin { We're already in that namespace: shortcircuit! } if (Namespace = TypeNamespace) then Exit; if (Namespace <> '') then begin WriteFmt(sNamespaceHdrEnd, [Namespace]); if Using then WriteFmt(sNamespaceUsing, [Namespace]); end; Namespace := TypeNamespace; if (Namespace <> '') then WriteFmt(sNamespaceHdrBegin, [Namespace]); end; function TWSDLCppWriter.GetPartFlagList(const Part: IWSDLPart; SkipFlags: TPartFlag): string; const PartStr: array[PartFlag] of string = (sIS_OPTN, sIS_UNBD, sIS_NLBL, sIS_UNQL, sIS_TEXT, sIS_ANY, sIS_REF, sIS_QUAL); Delimiter = ' | '; var pf: PartFlag; Flags: TPartFlag; IsAttr: Boolean; begin Result := ''; if Assigned(Part) then begin if HasIndexDecl(Part, Flags, IsAttr, True) then begin if IsAttr then Result := sIS_ATTR; if Part.PartKind = pOut then begin if Length(Result) > 0 then Result := Result + Delimiter; Result := Result + sIS_OUT; end; for pf := Low(PartFlag) to High(PartFlag) do begin if (pf in Flags) and (not (pf in SkipFlags)) then begin if Length(Result) > 0 then Result := Result + Delimiter; Result := Result + PartStr[pf]; end; end; end; end; end; function TWSDLCppWriter.GetTypeInfo(const WSDLType: IWSDLType): DOMString; begin if Verbose then Result := Format(sCppComment, [inherited GetTypeInfo(WSDLType)]) else Result := ''; end; procedure TWSDLCppWriter.WriteEnum(const WSDLType: IWSDLType); const sClass: array[boolean] of string = ('', 'class '); { Do not localize } var Len, Count: Integer; begin { We can email either scoped or non-scoped enumeration } WriteLn('enum %s%s %s' + sLineBreak + '{', [sClass[wfUseScopedEnumeration in Global_WSDLGenFlags], { Do not localize } WSDLType.LangName, GetTypeInfo(WSDLType)]); { Do not localize } Len := Length(WSDLType.EnumValues); if Len > 0 then begin for Count:= 0 to (Len-1) do begin WriteFmt(' %s%s' + sLineBreak, [WSDLType.EnumValues[Count].LangName, Commas[Count < (Len-1)]]); end; end; WriteLn('};' + sLineBreak); { Write a TypeInfo container for the enum } WriteLn(sTypeInfoHolder, [WSDLType.LangName]); end; procedure TWSDLCppWriter.WriteAliasDef(const WSDLType: IWSDLType); begin WriteLn('typedef %s %s; %s', [WSDLType.BaseType.LangName, WSDLType.LangName, GetTypeInfo(WSDLType)]); { Do not localize } { Here the typedef could be that of an enum } { So we create a TypeInfo container } end; procedure TWSDLCppWriter.WriteArray(const WSDLType: IWSDLType); const ComplexOp: array[Boolean] of string = ('', '*'); var TypeDef: DOMString; TypeName: DOMString; ArrayDef: DOMString; I: Integer; begin ArrayDef := '%s'; if WSDLType.Dimensions > 1 then begin for I := 0 to (WSDLType.Dimensions-2) do ArrayDef := Format('DynamicArray< %s >', [ArrayDef]); end; TypeDef := Format('DynamicArray<%s%s>', [WSDLType.BaseType.LangName, { Do not localize } ComplexOp[IsComplex(WSDLType.BaseType)]]); Typedef := Format(ArrayDef, [TypeDef]); TypeName:= WSDLType.LangName+';'; WriteLn('typedef %-25s %-15s %s', [TypeDef, TypeName, GetTypeInfo(WSDLType)]); { Do not localize } end; procedure TWSDLCppWriter.WriteComplexTypeClass(const WSDLType: IWSDLType; PassType: TPassWriterType); function GetIndexDecl(const Member: IWSDLPart): string; begin Result := GetPartFlagList(Member); if Length(Result) > 0 then Result := Format('index=(%s), ', [Result]); end; function GetStoredDecl(const Member: IWSDLPart): string; begin Result := ''; if GenSpecifiedSupport(Member) then begin if HasIndexDecl(Member, True) then Result := Format(sSpecifiedStoredProcI, [Member.LangName]) else Result := Format(sSpecifiedStoredProcF, [Member.LangName]); end; end; const ReadPrefix: array[Boolean] of string = ('F', 'Get'); WritePrefix: array[Boolean] of string = ('F', 'Set'); GetterDecl: array[Boolean] of string = (sRemoteClassGetter, sRemoteClassGetterIdx); SetterDecl1: array[Boolean] of string = (sRemoteClassSetter, sRemoteClassSetterIdx); SetterDecl2: array[Boolean] of string = (sRemoteClassSetter2, sRemoteClassSetterIdx2); DefArrayLen: array[Boolean] of string = (sDefaultArrayImpl, sDefaultArrayImplIdx); DefArrayOp : array[Boolean] of string = (sDefaultArrayImplOp, sDefaultArrayImplOpIdx); var I: Integer; Members: IWSDLPartArray; ComplexNames: TDOMStrings; ComplexTypes: TDOMStrings; ArrayNames: TDOMStrings; ComplexMember, ComplexArray: Boolean; Reader, Writer, StoredDecl, IndexDecl: string; HasWriter: Boolean; HasCtr, HasDtr, SetGet, UseSetGets, GenSpcCode: Boolean; DefMember, Member: IWSDLPart; DefMemberType: IWSDLType; DtrImpl: Widestring; BaseName: DOMString; ArrayAsClass: Boolean; DataTypeName: string; begin Members := nil; { To shut up compiler warning ?? } { Just forward ref?? } if (PassType >= [ptForwardDecl]) then begin WriteLn('class SOAP_REMOTABLE_CLASS %s;', [WSDLType.LangName]); { Do not localize } Exit; end; ArrayAsClass := (xoInlineArrays in WSDLType.SerializationOpt) or (IsPureCollection(WSDLType) and (WSDLType.Members[0].PartKind = pDefaultArray)); ComplexNames := TDOMStrings.Create; ComplexTypes := TDOMStrings.Create; ArrayNames := TDOMStrings.Create; try Members := WSDLType.Members; { Name of base class } if (WSDLType.BaseType <> nil) and (WSDLType.BaseType.DataKind = wtClass) then BaseName := WSDLType.BaseType.LangName else BaseName := GetBaseClassName(WSDLType); { Collect Member Information } for Member in Members do begin if Member.PartKind = pDefaultArray then begin DefMember := Member; DefMemberType := DefMember.DataType; DefMemberType := UnwindType(DefMemberType); if (DefMemberType.DataKind = wtArray) then begin DefMemberType := DefMemberType.BaseType; DefMemberType := UnwindType(DefMemberType, True); end; end; { Collect complex members } ComplexMember := IsComplex(Member.DataType); if ComplexMember then begin ComplexNames.Add('F'+Member.LangName); ComplexTypes.Add(Member.DataType.LangName); end; { Collect complex arrays } ComplexArray := IsComplexArray(Member.DataType); if ComplexArray then begin ArrayNames.Add('F'+Member.LangName); end; end; HasCtr := (wfAutoInitMembers in Global_WSDLGenFlags) or WriteOutSerialOpts(WSDLType); HasDtr := (wfAutoDestroyMembers in Global_WSDLGenFlags) and ((wfServer in Global_WSDLGenFlags) = False) and ((ComplexNames.Count > 0) or (ArrayNames.Count > 0)); UseSetGets:= wfUseSettersAndGetters in Global_WSDLGenFlags; GenSpcCode:= wfProcessOptionalNillable in Global_WSDLGenFlags; HasWriter := True; { We're declaring the class } if (PassType >= [ptTypeDecl]) then begin if Verbose then WriteComplexClassInfo(WSDLType) else WriteLn(''); WriteFmt(sRemoteClassDecl, [WSDLType.LangName, BaseName]); { Member properties } for Member in Members do begin { Is this member itself represented as a class } ComplexMember := IsComplex(Member.DataType); WriteLn(sMemberField, [Member.DataType.LangName + RefOp[ComplexMember], Member.LangName]); if GenSpecifiedSupport(Member) then begin WriteLn(sSpecifiedField, ['bool', Member.LangName]); end; end; { Emit setter/getter methods } if UseSetGets or GenSpcCode then begin for Member in Members do begin if UseSetGets or GenSpecifiedSupport(Member) then begin DataTypeName := Member.DataType.LangName + RefOp[IsComplex(Member.DataType)]; if UseSetGets then WriteFmt(GetterDecl[HasIndexDecl(Member, True)], [Member.LangName, DataTypeName]); if UseSetGets or GenSpecifiedSupport(Member) then begin if GenSpecifiedSupport(Member) then WriteFmt(SetterDecl2[HasIndexDecl(Member, True)], [Member.LangName, DataTypeName]) else WriteFmt(SetterDecl1[HasIndexDecl(Member, True)], [Member.LangName, DataTypeName]); end; if GenIndexedSpecifiedSupport(Member) then WriteFmt(sSpecifiedStoredProcIdx, [Member.LangName]); end; end; end; { Array as class } if ArrayAsClass then begin WriteLn(''); WriteFmt(DefArrayLen[GenSpecifiedSupport(DefMember)], [DefMember.LangName]); end; { Public section } if HasCtr or HasDtr or ArrayAsClass then begin WriteLn(''); WriteStr(sRemoteClassPublic); end; { Public Constructor & Destructor } if (HasCtr or HasDtr) then begin if HasCtr then WriteFmt(sRemoteClassCtr, [WSDLType.LangName]); if HasDtr then WriteFmt(sRemoteClassDtr, [WSDLType.LangName]); end; if ArrayAsClass then begin if (HasCtr or HasDtr) then WriteLn(''); DataTypeName := DefMemberType.LangName + RefOp[IsComplex(DefMemberType)]; WriteLn(DefArrayOp[GenSpecifiedSupport(DefMember)], [DefMember.LangName, DataTypeName]); end; { Published section } WriteStr(sRemoteClassPublish); for Member in Members do begin DataTypeName := Member.DataType.LangName + RefOp[IsComplex(Member.DataType)]; SetGet := UseSetGets or GenSpecifiedSupport(Member); { Reader } Reader := Format('read=F%0:s', [Member.LangName]); Writer := ''; if HasWriter then Writer := Format(', write=%s%s', [WritePrefix[SetGet], Member.LangName]); { Index } IndexDecl := GetIndexDecl(Member); { Stored } StoredDecl := GetStoredDecl(Member); WriteLn(' __property %-10s %10s = { %s%s%s%s };', [DataTypeName, { Do not localize } Member.LangName, IndexDecl, Reader, Writer, StoredDecl]); end; WriteLn(sRemoteClassDeclEnd + sLineBreak); end; { We're implementing the type } if (PassType >= [ptTypeImpl]) then begin if (HasCtr) then begin WriteLn(sRemoteClsCtrImpl, [WSDLType.LangName, '']); end; if (HasDtr) then begin { Collect cleanup code } for I := 0 to ComplexNames.Count-1 do begin DtrImpl := Format(sDtrClsLine, [DtrImpl, ComplexNames[I]]); end; for I := 0 to ArrayNames.Count-1 do begin DtrImpl := Format(sDtrArrayLine, [DtrImpl, ArrayNames[I]]); end; WriteLn(sRemoteClsDtrImpl, [WSDLType.LangName, DtrImpl]); end; end; finally ComplexNames.Free; ComplexTypes.Free; ArrayNames.Free; end; end; {$IFNDEF UNICODE} function TWSDLCppWriter.Escape(const W: DOMString): DOMString; const cBackslash = '\'; var I: Integer; UniStr: string; begin Result := W; for I := Length(Result) downto 1 do begin if Result[I] = cBackslash then Insert(cBackslash, Result, I); if Result[I] > WideChar(255) then begin UniStr := Format('\u%s', [IntToHex(Word(Result[I]), 4)]); Delete(Result, I, 1); Insert(UniStr, Result, I); end; end; end; {$ELSE} function TWSDLCppWriter.Escape(const W: DOMString): DOMString; const cBackslash = '\'; var I: Integer; begin Result := W; for I := Length(Result) downto 1 do begin if Result[I] = cBackslash then Insert(cBackslash, Result, I); end; end; {$ENDIF} procedure TWSDLCppWriter.WriteInterfaceBegin(const WSDLPortType: IWSDLPortType; PassType: TPassWriterType); begin if (ptTypeDecl in PassType) then WriteFmt(sInterfaceDecl, [GUIDToString(WSDLPortType.GUID), WSDLPortType.LangName, WSDLPortType.BaseInterfaceName]) else if (ptTypeImpl in PassType) then WriteFmt(sImplDecl, [WsdlPortType.LangName]) else if (ptTypeFactoryImpl in PassType) then begin case WriteFactory(WSDLPortType) of ftWSDLURL: begin WriteLn(sFactoryImpl, [WSDLPortType.LangName, Escape(Self.FileName), Escape(WSDLPortType.URL), Escape(WSDLPortType.Service), Escape(WSDLPortType.Port)]); end; end; end; end; procedure TWSDLCppWriter.WriteMethod(const WSDLOperation: IWSDLOperation; const Parent: IWSDLPortType; PassType: TPassWriterType); function UseRef(const WSDLPart: IWSDLPart): Boolean; begin Result := IsComplex(WSDLPart.DataType); end; { Try to fabricate some dummy data - could use a lot of improvement } function DummyReturn(const WSDLType: IWSDLType): DOMString; begin if not Assigned(WSDLType) then Result := '' else begin case WSDLType.DataKind of wtClass: Result := Format(sReturnNewTempl, [WSDLType.LangName]); wtEnumeration: { Should check that we do have values?? } Result := Format(sReturnTempl, [WSDLType.EnumValues[0].LangName]); wtArray: Result := Format(sReturnDecl, [WSDLType.LangName, '_out']) + { Do not localize } Format(sReturnTempl, ['_out']); { Do not localize } else begin if WSDLType.TypeInfo <> nil then begin case WSDLType.TypeInfo.Kind of tkClass: Result := Format(sReturnNewTempl, [WSDLType.LangName]); tkInteger: Result := Format(sReturnTempl, ['123456789']); tkFloat: Result := Format(sReturnTempl, ['9.87654321']); tkInt64: Result := Format(sReturnTempl, ['918273645']); tkString, tkLString : Result := Format(sReturnTempl, ['"abcdefghij"']); tkWString: Result := Format(sReturnTempl, ['"xyz"']); tkDynArray: Result := Format(sReturnDecl, [WSDLType.LangName, '_out']) + Format(sReturnTempl, ['_out']); tkEnumeration: if SameTypeInfo(TypeInfo(System.boolean), WSDLType.TypeInfo) then Result := Format(sReturnTempl, ['true']); end; end else begin Result := Format(sReturnTempl, ['0']); end; end; end; end; end; var RetIndex, I, Params: Integer; RetDataType: IWSDLType; RetType: DOMString; WSDLPart: IWSDLPart; PostOp: DOMString; ClassName: DOMString; FormatStr: DOMString; begin if (ptTypeFactoryDecl in PassType) or (ptTypeFactoryImpl in PassType) then Exit; { Map return type to a string } RetIndex := WSDLOperation.ReturnIndex; if (RetIndex <> -1) then begin WSDLPart := WSDLOperation.Parts[RetIndex]; RetDataType := WSDLPart.DataType; RetType := WSDLPart.DataType.LangName + RefOp[UseRef(WSDLPart)]; end else begin RetType := 'void'; RetDataType := nil; end; { Include classname in method implementation } if ptMethImpl in PassType then ClassName := Format('T%sImpl::', [Parent.LangName]) else ClassName :=''; if ptMethImpl in PassType then FormatStr := '%s%s%s %s%s(' { ' ', 'virtual', 'ret', 'className::' 'funcName' ('} else FormatStr := '%s%s%-15s %s%s('; // Here we can emit information about the method if Verbose and (not (ptMethImpl in PassType)) and HasInfoAboutMethod(WSDLOperation) then WriteStr(GetMethodInfo(WSDLOperation)); { NOTE: Only put virtual on interface - not required in implementation } WriteFmt(FormatStr, [PadStr[(ptTypeDecl in PassType) or (ptTypeImpl in PassType)], VirtualStr[ptTypeDecl in PassType], RetType, ClassName, WSDLOperation.LangName]); { How many parameters ?? } Params := Length(WSDLOperation.Parts); if (RetIndex <> -1) then Dec(Params); if (Params > 0) then begin for I := 0 to Length(WSDLOperation.Parts)-1 do begin WSDLPart := WSDLOperation.Parts[I]; if (I <> RetIndex) then begin Dec(Params); { Get modifier } PostOp := ''; if UseRef(WSDLPart) then PostOp := RefOp[True]; PostOp := PostOp + PosParamMod[WSDLPart.PartKind]; WriteFmt('%s%s%s %s%s', [PreParamMod[WSDLPart.PartKind], WSDLPart.DataType.LangName, PostOp, WSDLPart.LangName, Commas[Params > 0]]); end; end; end; WriteLn(')%s%s', [PureVirtStr[ptTypeDecl in PassType], SemiStr[(ptTypeDecl in PassType) or (ptTypeImpl in PassType)]]); { Provide a dummy implementation - if we're implementing } if ptMethImpl in PassType then begin WriteFmt(sMethImpl, [WSDLOperation.LangName, DummyReturn(RetDataType)]); end; end; procedure TWSDLCppWriter.WriteInterfaceEnd(const WSDLPortType: IWSDLPortType; PassType: TPassWriterType); begin if (ptTypeDecl in PassType) then begin WriteFmt(sInterfaceDeclEnd, [WSDLPortType.LangName]); end else if (ptTypeImpl in PassType) then begin WriteStr(sImplOther); WriteFmt(sImplEnd, [WSDLPortType.LangName]); end else if (ptTypeFactoryDecl in PassType) then begin case WriteFactory(WSDLPortType) of ftWSDLURL: begin WriteFmt(sIntfFactoryDecl, [WSDLPortType.LangName]); end; end; end; end; function TWSDLCppWriter.WriteSettingsFile: Boolean; begin Result := False; end; procedure TWSDLCppWriter.WriteSource; begin WriteSourceHeader; WriteImplementations; WriteRegCalls; WriteSourceFooter; end; procedure TWSDLCppWriter.WriteSourceHeader; begin WriteWSDLInfo; WriteLn(sStandardSourceIncludeSystem, [FRelHeaderDir+OutFile]); if (wfTypesInNamespace in Global_WSDLGenFlags) then WriteTypeNamespace(OutFile); end; { Registration Calls } procedure TWSDLCppWriter.WriteRegCalls; procedure WriteTypeRegistration(const WSDLType: IWSDLType); var EnumMember: IWSDLItem; WSDLPart: IWSDLPart; SerialOpts: TSerializationOptions; ARegInfo: TRegInfoAttribute; begin case WSDLType.DataKind of { Classes } wtClass: begin if Verbose then WriteLn(sCppCommentIdent, [WSDLType.Name]); if WSDLType.Name <> WSDLType.LangName then WriteFmt(sRegClass2, [WSDLType.LangName, Escape(WSDLType.Namespace), WSDLType.LangName, Escape(WSDLType.Name)]) else WriteFmt(sRegClass1, [WSDLType.LangName, Escape(WSDLType.Namespace), Escape(WSDLType.LangName)]); for WSDLPart in WSDLType.Members do begin ARegInfo.Reset; //Assert((WSDLPart.RegInfo = '') or (WSDLPart.DataType.RegInfo = '')); if WSDLPart.DataType.RegInfo <> '' then ARegInfo.Load(WSDLPart.DataType.RegInfo); if WSDLPart.RegInfo <> '' then ARegInfo.Load(WSDLPart.RegInfo); if WSDLPart.Name <> WSDLPart.LangName then ARegInfo.SetAttr(InfoAttribute.iaExternalName, WSDLPart.Name); if ARegInfo.HasAttr then WriteFmt(sRegMemberRenamed, [WSDLType.LangName, WSDLPart.LangName, ARegInfo.AsString(True)]); end; { Class Serialization options } if (WSDLType.SerializationOpt <> []) then begin SerialOpts := WSDLType.SerializationOpt; WriteFmt(sRegClassSerOptsCpp, [WSDLType.LangName, SetToStr(TypeInfo(SerializationOptions), Integer(SerialOpts), [stsInsertion])]); end; end; { Enumerations } wtEnumeration: begin if Verbose then WriteLn(sCppCommentIdent, [WSDLType.Name]); if WSDLType.Name <> WSDLType.LangName then WriteFmt(sRegHolderTypeInfo2, [WSDLType.LangName, Escape(WSDLType.Namespace), Escape(WSDLType.Name)]) else WriteFmt(sRegHolderTypeInfo1, [WSDLType.LangName, Escape(WSDLType.Namespace)]); for EnumMember in WSDLType.EnumValues do if EnumMember.Name <> EnumMember.LangName then WriteFmt(sRegMemberRenamedE, [WSDLType.LangName, EnumMember.LangName, Escape(EnumMember.Name)]); end; { Arrays } wtArray: begin if Verbose then WriteLn(sCppCommentIdent, [WSDLType.Name]); if WSDLType.Name <> WSDLType.LangName then WriteFmt(sRegArrayTypeInfo2, [WSDLType.LangName, Escape(WSDLType.Namespace), Escape(WSDLType.LangName), Escape(WSDLType.Name)]) else WriteFmt(sRegArrayTypeInfo1, [WSDLType.LangName, Escape(WSDLType.Namespace), Escape(WSDLType.LangName)]); { Array serialization options } if (WSDLType.SerializationOpt <> []) then begin SerialOpts := WSDLType.SerializationOpt; WriteFmt(sRegInfoSerOptsCpp, [WSDLType.LangName, SetToStr(TypeInfo(SerializationOptions), Integer(SerialOpts), [stsInsertion])]); end; end; end; end; {$IFDEF _DEBUG} function GetSafeLiteral(const S: string; Indent: Integer; Delim: WideChar): string; var StrArray: TStringDynArray; I: Integer; IndentStr: string; begin if Length(S) < 255 then Result := '''' + S + '''' else begin { Create indent string } SetLength(IndentStr, Indent); for I := 1 to Length(IndentStr) do IndentStr[I] := ' '; { Break string up } SetLength(StrArray, 0); StrArray := StringToStringArray(S, Delim); for I := 0 to Length(StrArray)-1 do begin if I <> 0 then Result := Result + '+'; Result := Result + '''' + Delim + StrArray[I] + ''''; Result := Result + sLineBreak + IndentStr; end; end; end; {$ENDIF} var WSDLPortTypeArray: IWSDLPortTypeArray; I, J, K: Integer; WSDLTypeArray: IWSDLTypeArray; WSDLType: IWSDLType; WSDLPortType: IWSDLPortTYpe; WSDLOperations: IWSDLOperationArray; WSDLOperation: IWSDLOperation; WSDLParts: IWSDLPartArray; WSDLPart, ReturnPart: IWSDLPart; MethodHeading: Boolean; PartFlagList, ParamNamespace, InternalName, ExternalName, ReturnName: string; InputNamespace, OutputNamespace: string; ARegInfo: TRegInfoAttribute; RegInfoStr: string; begin SetLength(WSDLParts, 0); SetLength(WSDLOperations, 0); WriteStr(sRegProcInfo); WriteStr(sInfoEnd); WriteStr(sInitRoutineBeg); { Register PortTypes } WSDLPortTypeArray := FWSDLImporter.GetPortTypes; for I := 0 to Length(WSDLPortTypeArray)-1 do begin WSDLPortType := WSDLPortTypeArray[I]; if Verbose then WriteLn(sCppCommentIdent, [WSDLPortType.Name]); { Pick the optimal output } if (WSDLPortType.LangName <> WSDLPortType.Name) then WriteFmt(sRegInterface2, [WSDLPortType.LangName, Escape(WSDLPortType.Namespace), Escape(FWSDLImporter.Encoding), Escape(WSDLPortType.Name)]) else WriteFmt(sRegInterface1, [WSDLPortType.LangName, Escape(WSDLPortType.Namespace), Escape(FWSDLImporter.Encoding)]); { Register PortTypes - for server implementation } if wfServer in Global_WSDLGenFlags then begin if Verbose then WriteLn(sCppCommentIdent, [Format(sServerImpl, [WSDLPortType.LangName])]); WriteFmt(sRegImpl, [WSDLPortType.LangName]); end; { SOAPAction[s] } if (WSDLPortType.HasDefaultSOAPAction) then begin { If we're in server mode, avoid tricky SOAPActions that will make dispatching fail; Of course, this means that upfront we're not able to roundrip a WSDL } if (not (wfServer in Global_WSDLGenFlags)) or (Pos(DOMString(SOperationNameSpecifier), WSDLPortType.SOAPAction)=0) then WriteFmt(sRegSOAPAction, [WSDLPortType.LangName, Escape(WSDLPortType.SOAPAction)]); end else if WSDLPortType.HasAllSOAPActions then begin { Here we write out the SOAP action for each operation } if (not (wfServer in Global_WSDLGenFlags)) then begin WriteFmt(sRegAllSOAPAction, [WSDLPortType.LangName, Escape(WSDLPortType.SOAPAction)]); end; end; { Return Return Param Names } {$IFDEF _DEBUG} if DefaultReturnParamNames <> SDefaultReturnParamNames then WriteFmt(sRegParamNames, [WSDLPortType.LangName, Escape(DefaultReturnParamNames)]); {$ENDIF} { Flag the registry if this interface is 'encoded' vs. 'literal' However, only do this if we're generating client code - for servers we're always rpc|encoded } if not (wfServer in Global_WSDLGenFlags) then begin if (ioDocument in WSDLPortType.InvokeOptions) then WriteFmt(sRegInvokeOptDoc, [WSDLPortType.LangName]); if (ioLiteral in WSDLPortType.InvokeOptions) then WriteFmt(sRegInvokeOptLit, [WSDLPortType.LangName]); if (ioSOAP12 in WSDLPortType.InvokeOptions) then WriteFmt(sRegInvokeOptSOAP12, [WSDLPortType.LangName]); end; { Check operations } try WSDLOperations := WSDLPortType.Operations; for J := 0 to Length(WSDLOperations)-1 do begin WSDLOperation := WSDLOperations[J]; MethodHeading := False; ARegInfo.Reset; { Register information lost when we unwrapped} ReturnPart := nil; InputNamespace := ''; OutputNamespace := ''; ReturnName := ''; PartFlagList := ''; RegInfoStr := ''; if (WSDLPortType.InvokeOptions * [ioLiteral, ioDocument]) = [ioDocument] then begin if (WSDLOperation.InputWrapper <> nil) then InputNamespace := WSDLOperation.InputWrapper.DataType.Namespace; if (WSDLOperation.OutputWrapper <> nil) then OutputNamespace := WSDLOperation.OutputWrapper.DataType.Namespace; if OutputNamespace = WSDLPortType.Namespace then OutputNamespace := ''; WSDLParts := WSDLOperation.Parts; for K := 0 to Length(WSDLParts)-1 do begin WSDLPart := WSDLParts[K]; if WSDLPart.PartKind = pReturn then begin ReturnPart := WSDLPart; PartFlagList := GetPartFlagList(ReturnPart); ReturnName := Escape(ReturnPart.Name); Break; end; end; end; if (ReturnName <> '') or ((InputNamespace <> '') and (InputNamespace <> WSDLPortType.Namespace)) or ((OutputNamespace <> '') and (OutputNamespace <> WSDLPortType.Namespace)) or (PartFlagList <> '') or (WSDLOperation.Name <> WSDLOperation.LangName) then begin InternalName := Escape(WSDLOperation.LangName); ExternalName := Escape(WSDLOperation.Name); if ExternalName = InternalName then ExternalName := ''; if ReturnName <> '' then ARegInfo.SetAttr(InfoAttribute.iaMethReturnName, ReturnName); if ((InputNamespace <> '') and (InputNamespace <> WSDLPortType.Namespace)) then ARegInfo.SetAttr(InfoAttribute.iaMethRequestNamespace, InputNamespace); if ((OutputNamespace <> '') and (OutputNamespace <> WSDLPortType.Namespace)) then ARegInfo.SetAttr(InfoAttribute.iaMethResponseNamespace, OutputNamespace); if ARegInfo.HasAttr then RegInfoStr := ARegInfo.AsString(True); if (ExternalName <> '') or (RegInfoStr <> '') or (PartFlagList <> '') then begin if Verbose then begin WriteLn(sCppCommentIdent, [Format('%s.%s', [WSDLPortType.Name, InternalName])]); MethodHeading := True; end; if PartFlagList <> '' then WriteFmt(sRegMethodInfoCpp, [WSDLPortType.LangName, InternalName, ExternalName, RegInfoStr, PartFlagList]) else if RegInfoStr <> '' then WriteFmt(sRegMethodInfoCppNoOpts, [WSDLPortType.LangName, InternalName, ExternalName, RegInfoStr]) else WriteFmt(sRegMethodInfoCppNoInfo, [WSDLPortType.LangName, InternalName, ExternalName]); end; end; { Check parameter renames } WSDLParts := WSDLOperation.Parts; for K := 0 to Length(WSDLParts)-1 do begin WSDLPart := WSDLParts[K]; PartFlagList := ''; ParamNamespace := ''; RegInfoStr := ''; ARegInfo.Reset; if (WSDLPortType.InvokeOptions * [ioLiteral, ioDocument]) = [ioDocument] then begin // Don't bother with optional since parameters // are not really optional in Pascal/C++ PartFlagList := GetPartFlagList(WSDLPart, [pfOptional]); ParamNamespace := WSDLPart.DataType.Namespace; if ((InputNamespace <> '') and (ParamNamespace = InputNamespace)) or ((InputNamespace = '') and (ParamNamespace = WSDLPortType.Namespace)) then ParamNamespace := ''; end else begin // Rpc|lit if (WSDLPortType.InvokeOptions * [ioLiteral, ioDocument]) = [ioLiteral] then ParamNamespace := WSDLPart.DataType.Namespace; if WSDLPart.PartKind = pOut then PartFlagList := sIS_OUT; end; if ParamNamespace = XMLSchemaNamespace then ParamNamespace := ''; if ParamNamespace <> '' then ARegInfo.SetAttr(InfoAttribute.iaNamespace, ParamNamespace); if WSDLPart.DataType.RegInfo <> '' then ARegInfo.Load(WSDLPart.DataType.RegInfo); if ARegInfo.HasAttr then RegInfoStr := ARegInfo.AsString(True); InternalName := Escape(WSDLPart.LangName); ExternalName := Escape(WSDLPart.Name); if ExternalName = InternalName then ExternalName := ''; if (ExternalName <> '') or (RegInfoStr <> '') or (PartFlagList <> '' ) then begin if Verbose and (MethodHeading = False) then begin WriteLn(sCppCommentIdent, [Format('%s->%s', [WSDLPortType.Name, WSDLOperation.LangName])]); MethodHeading := True; end; if PartFlagList <> '' then WriteFmt(sRegParamInfoCpp, [WSDLPortType.LangName, WSDLOperation.LangName, InternalName, ExternalName, RegInfoStr, PartFlagList]) else if RegInfoStr <> '' then WriteFmt(sRegParamInfoCppNoOpts, [WSDLPortType.LangName, WSDLOperation.LangName, InternalName, ExternalName, RegInfoStr]) else WriteFmt(sRegParamInfoCppNoInfo, [WSDLPortType.LangName, WSDLOperation.LangName, InternalName, ExternalName]); end; end; end; finally {To keep formatting similar to PasWriter} end; end; { Register Types } WSDLTypeArray := FWSDLImporter.GetTypes; for I := 0 to Length(WSDLTypeArray)-1 do begin WSDLType := WSDLTypeArray[I]; WSDLType := UnwindType(WSDLType); { Skip unused types } if SkipType(WSDLType, True) then continue; WriteTypeRegistration(WSDLType); end; { Register PortTypes - for server implementation } if wfServer in Global_WSDLGenFlags then begin WSDLPortTypeArray := FWSDLImporter.GetPortTypes; for I := 0 to Length(WSDLPortTypeArray)-1 do begin WSDLPortType := WSDLPortTypeArray[I]; if Verbose then WriteLn(sCppCommentIdent, [Format(sServerImpl, [WSDLPortType.LangName])]); WriteFmt(sRegImpl, [WSDLPortType.LangName]); end; end; WriteStr(sInitRoutineEnd); end; procedure TWSDLCppWriter.WriteSourceFooter; begin if (wfTypesInNamespace in Global_WSDLGenFlags) then WriteTypeNamespace(''); end; end.
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // {$POINTERMATH ON} unit RN_DebugDraw; interface uses Math, RN_Helper; type TduDebugDrawPrimitives = ( DU_DRAW_POINTS, DU_DRAW_LINES, DU_DRAW_TRIS, DU_DRAW_QUADS ); /// Abstract debug draw interface. TduDebugDraw = class public procedure depthMask(state: Boolean); virtual; abstract; procedure texture(state: Boolean); virtual; abstract; /// Begin drawing primitives. /// @param prim [in] primitive type to draw, one of rcDebugDrawPrimitives. /// @param size [in] size of a primitive, applies to point size and line width only. procedure &begin(prim: TduDebugDrawPrimitives; size: Single = 1.0); virtual; abstract; /// Submit a vertex /// @param pos [in] position of the verts. /// @param color [in] color of the verts. procedure vertex(const pos: PSingle; color: Cardinal); overload; virtual; abstract; /// Submit a vertex /// @param x,y,z [in] position of the verts. /// @param color [in] color of the verts. procedure vertex(const x,y,z: Single; color: Cardinal); overload; virtual; abstract; /// Submit a vertex /// @param pos [in] position of the verts. /// @param color [in] color of the verts. procedure vertex(const pos: PSingle; color: Cardinal; uv: PSingle); overload; virtual; abstract; /// Submit a vertex /// @param x,y,z [in] position of the verts. /// @param color [in] color of the verts. procedure vertex(const x,y,z: Single; color: Cardinal; u,v: Single); overload; virtual; abstract; /// End drawing primitives. procedure &end; virtual; abstract; end; function duIntToCol(i, a: Integer): Cardinal; overload; procedure duIntToCol(i: Integer; col: PSingle); overload; procedure duCalcBoxColors(var colors: array of Cardinal; colTop, colSide: Cardinal); procedure duDebugDrawCylinderWire(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal; const lineWidth: Single); procedure duDebugDrawBoxWire(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal; const lineWidth: Single); procedure duDebugDrawArc(dd: TduDebugDraw; x0, y0, z0: Single; x1, y1, z1, h: Single; as0, as1: Single; col: Cardinal; const lineWidth: Single); procedure duDebugDrawArrow(dd: TduDebugDraw; const x0, y0, z0, x1, y1, z1, as0, as1: Single; col: Cardinal; const lineWidth: Single); procedure duDebugDrawCircle(dd: TduDebugDraw; x,y,z: Single; r: Single; col: Cardinal; const lineWidth: Single); procedure duDebugDrawCross(dd: TduDebugDraw; x,y,z: Single; size: Single; col: Cardinal; const lineWidth: Single); procedure duDebugDrawBox(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; const fcol: PCardinal); procedure duDebugDrawCylinder(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal); procedure duDebugDrawGridXZ(dd: TduDebugDraw; ox, oy, oz: Single; w, h: Integer; size: Single; const col: Cardinal; const lineWidth: Single); // Versions without begin/end, can be used to draw multiple primitives. procedure duAppendCylinderWire(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal); procedure duAppendBoxWire(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal); procedure duAppendBoxPoints(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal); procedure duAppendArc(dd: TduDebugDraw; const x0, y0, z0, x1, y1, z1, h, as0, as1: Single; col: Cardinal); procedure duAppendArrow(dd: TduDebugDraw; const x0, y0, z0, x1, y1, z1, as0, as1: Single; col: Cardinal); procedure duAppendCircle(dd: TduDebugDraw; x,y,z,r: Single; col: Cardinal); procedure duAppendCross(dd: TduDebugDraw; x,y,z: Single; s: Single; col: Cardinal); procedure duAppendBox(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; const col: PCardinal); procedure duAppendCylinder(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal); type TduDisplayList = class(TduDebugDraw) private m_pos: PSingle; m_color: PCardinal; m_size: Integer; m_cap: Integer; m_depthMask: Boolean; m_prim: TduDebugDrawPrimitives; m_primSize: Single; procedure resize(cap: Integer); public constructor Create(cap: Integer = 512); procedure depthMask(state: Boolean); override; procedure &begin(prim: TduDebugDrawPrimitives; size: Single = 1.0); override; procedure vertex(const x,y,z: Single; color: Cardinal); override; procedure vertex(const pos: PSingle; color: Cardinal); override; procedure &end(); override; procedure clear(); procedure draw(dd: TduDebugDraw); end; function duRGBA(r,g,b,a: Byte): Cardinal; function duRGBAf(fr,fg,fb,fa: Single): Cardinal; function duMultCol(const col: Cardinal; const d: Cardinal): Cardinal; function duDarkenCol(col: Cardinal): Cardinal; function duLerpCol(ca,cb,u: Cardinal): Cardinal; implementation function duRGBA(r,g,b,a: Byte): Cardinal; begin Result := r or (g shl 8) or (b shl 16) or (a shl 24); end; function duRGBAf(fr,fg,fb,fa: Single): Cardinal; var r,g,b,a: Byte; begin r := Trunc(fr*255.0); g := Trunc(fg*255.0); b := Trunc(fb*255.0); a := Trunc(fa*255.0); Result := duRGBA(r,g,b,a); end; function duMultCol(const col: Cardinal; const d: Cardinal): Cardinal; var r,g,b,a: Cardinal; begin r := col and $ff; g := (col shr 8) and $ff; b := (col shr 16) and $ff; a := (col shr 24) and $ff; Result := duRGBA((r*d) shr 8, (g*d) shr 8, (b*d) shr 8, a); end; function duDarkenCol(col: Cardinal): Cardinal; begin Result := ((col shr 1) and $007f7f7f) or (col and $ff000000); end; function duLerpCol(ca,cb,u: Cardinal): Cardinal; var ra,ga,ba,aa,rb,gb,bb,ab,r,g,b,a: Cardinal; begin ra := ca and $ff; ga := (ca shr 8) and $ff; ba := (ca shr 16) and $ff; aa := (ca shr 24) and $ff; rb := cb and $ff; gb := (cb shr 8) and $ff; bb := (cb shr 16) and $ff; ab := (cb shr 24) and $ff; r := (ra*(255-u) + rb*u) div 255; g := (ga*(255-u) + gb*u) div 255; b := (ba*(255-u) + bb*u) div 255; a := (aa*(255-u) + ab*u) div 255; Result := duRGBA(r,g,b,a); end; function duTransCol(c,a: Cardinal): Cardinal; begin Result := (a shl 24) or (c and $00ffffff); end; function bit(a, b: Integer): Integer; begin Result := (a and (1 shl b)) shr b; end; function duIntToCol(i,a: Integer): Cardinal; var r,g,b: Integer; begin r := bit(i, 1) + bit(i, 3) * 2 + 1; g := bit(i, 2) + bit(i, 4) * 2 + 1; b := bit(i, 0) + bit(i, 5) * 2 + 1; Result := duRGBA(r*63,g*63,b*63,a); end; procedure duIntToCol(i: Integer; col: PSingle); var r,g,b: Integer; begin r := bit(i, 0) + bit(i, 3) * 2 + 1; g := bit(i, 1) + bit(i, 4) * 2 + 1; b := bit(i, 2) + bit(i, 5) * 2 + 1; col[0] := 1 - r*63.0/255.0; col[1] := 1 - g*63.0/255.0; col[2] := 1 - b*63.0/255.0; end; procedure duCalcBoxColors(var colors: array of Cardinal; colTop, colSide: Cardinal); begin //if (!colors) Result :=; colors[0] := duMultCol(colTop, 250); colors[1] := duMultCol(colSide, 140); colors[2] := duMultCol(colSide, 165); colors[3] := duMultCol(colSide, 217); colors[4] := duMultCol(colSide, 165); colors[5] := duMultCol(colSide, 217); end; procedure duDebugDrawCylinderWire(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal; const lineWidth: Single); begin if (dd = nil) then Exit; dd.&begin(DU_DRAW_LINES, lineWidth); duAppendCylinderWire(dd, minx,miny,minz, maxx,maxy,maxz, col); dd.&end(); end; procedure duDebugDrawBoxWire(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal; const lineWidth: Single); begin if (dd = nil) then Exit; dd.&begin(DU_DRAW_LINES, lineWidth); duAppendBoxWire(dd, minx,miny,minz, maxx,maxy,maxz, col); dd.&end(); end; procedure duDebugDrawArc(dd: TduDebugDraw; x0, y0, z0: Single; x1, y1, z1, h: Single; as0, as1: Single; col: Cardinal; const lineWidth: Single); begin if (dd = nil) then Exit; dd.&begin(DU_DRAW_LINES, lineWidth); duAppendArc(dd, x0,y0,z0, x1,y1,z1, h, as0, as1, col); dd.&end(); end; procedure duDebugDrawArrow(dd: TduDebugDraw; const x0, y0, z0, x1, y1, z1, as0, as1: Single; col: Cardinal; const lineWidth: Single); begin if (dd = nil) then Exit; dd.&begin(DU_DRAW_LINES, lineWidth); duAppendArrow(dd, x0,y0,z0, x1,y1,z1, as0, as1, col); dd.&end(); end; procedure duDebugDrawCircle(dd: TduDebugDraw; x,y,z: Single; r: Single; col: Cardinal; const lineWidth: Single); begin if (dd = nil) then Exit; dd.&begin(DU_DRAW_LINES, lineWidth); duAppendCircle(dd, x,y,z, r, col); dd.&end(); end; procedure duDebugDrawCross(dd: TduDebugDraw; x,y,z: Single; size: Single; col: Cardinal; const lineWidth: Single); begin if (dd = nil) then Exit; dd.&begin(DU_DRAW_LINES, lineWidth); duAppendCross(dd, x,y,z, size, col); dd.&end(); end; procedure duDebugDrawBox(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; const fcol: PCardinal); begin if (dd = nil) then Exit; dd.&begin(DU_DRAW_QUADS); duAppendBox(dd, minx,miny,minz, maxx,maxy,maxz, fcol); dd.&end(); end; procedure duDebugDrawCylinder(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal); begin if (dd = nil) then Exit; dd.&begin(DU_DRAW_TRIS); duAppendCylinder(dd, minx,miny,minz, maxx,maxy,maxz, col); dd.&end(); end; procedure duDebugDrawGridXZ(dd: TduDebugDraw; ox, oy, oz: Single; w, h: Integer; size: Single; const col: Cardinal; const lineWidth: Single); var i: Integer; begin if (dd = nil) then Exit; dd.&begin(DU_DRAW_LINES, lineWidth); for i := 0 to h do begin dd.vertex(ox,oy,oz+i*size, col); dd.vertex(ox+w*size,oy,oz+i*size, col); end; for i := 0 to w do begin dd.vertex(ox+i*size,oy,oz, col); dd.vertex(ox+i*size,oy,oz+h*size, col); end; dd.&end(); end; procedure duAppendCylinderWire(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal); const NUM_SEG = 16; var dir: array [0..NUM_SEG*2-1] of Single; init: Boolean; a,cx,cz,rx,rz: Single; i,j: Integer; begin if (dd = nil) then Exit; init := false; if (not init) then begin init := true; for i := 0 to NUM_SEG - 1 do begin a := i/NUM_SEG*PI*2; dir[i*2] := Cos(a); dir[i*2+1] := Sin(a); end; end; cx := (maxx + minx)/2; cz := (maxz + minz)/2; rx := (maxx - minx)/2; rz := (maxz - minz)/2; i := 0; j := NUM_SEG-1; while (i < NUM_SEG) do begin dd.vertex(cx+dir[j*2+0]*rx, miny, cz+dir[j*2+1]*rz, col); dd.vertex(cx+dir[i*2+0]*rx, miny, cz+dir[i*2+1]*rz, col); dd.vertex(cx+dir[j*2+0]*rx, maxy, cz+dir[j*2+1]*rz, col); dd.vertex(cx+dir[i*2+0]*rx, maxy, cz+dir[i*2+1]*rz, col); j := i; Inc(i); end; i := 0; while (i < NUM_SEG) do begin dd.vertex(cx+dir[i*2+0]*rx, miny, cz+dir[i*2+1]*rz, col); dd.vertex(cx+dir[i*2+0]*rx, maxy, cz+dir[i*2+1]*rz, col); Inc(i, NUM_SEG div 4); end; end; procedure duAppendBoxWire(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal); begin if (dd = nil) then Exit; // Top dd.vertex(minx, miny, minz, col); dd.vertex(maxx, miny, minz, col); dd.vertex(maxx, miny, minz, col); dd.vertex(maxx, miny, maxz, col); dd.vertex(maxx, miny, maxz, col); dd.vertex(minx, miny, maxz, col); dd.vertex(minx, miny, maxz, col); dd.vertex(minx, miny, minz, col); // bottom dd.vertex(minx, maxy, minz, col); dd.vertex(maxx, maxy, minz, col); dd.vertex(maxx, maxy, minz, col); dd.vertex(maxx, maxy, maxz, col); dd.vertex(maxx, maxy, maxz, col); dd.vertex(minx, maxy, maxz, col); dd.vertex(minx, maxy, maxz, col); dd.vertex(minx, maxy, minz, col); // Sides dd.vertex(minx, miny, minz, col); dd.vertex(minx, maxy, minz, col); dd.vertex(maxx, miny, minz, col); dd.vertex(maxx, maxy, minz, col); dd.vertex(maxx, miny, maxz, col); dd.vertex(maxx, maxy, maxz, col); dd.vertex(minx, miny, maxz, col); dd.vertex(minx, maxy, maxz, col); end; procedure duAppendBoxPoints(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal); begin if (dd = nil) then Exit; // Top dd.vertex(minx, miny, minz, col); dd.vertex(maxx, miny, minz, col); dd.vertex(maxx, miny, minz, col); dd.vertex(maxx, miny, maxz, col); dd.vertex(maxx, miny, maxz, col); dd.vertex(minx, miny, maxz, col); dd.vertex(minx, miny, maxz, col); dd.vertex(minx, miny, minz, col); // bottom dd.vertex(minx, maxy, minz, col); dd.vertex(maxx, maxy, minz, col); dd.vertex(maxx, maxy, minz, col); dd.vertex(maxx, maxy, maxz, col); dd.vertex(maxx, maxy, maxz, col); dd.vertex(minx, maxy, maxz, col); dd.vertex(minx, maxy, maxz, col); dd.vertex(minx, maxy, minz, col); end; procedure duAppendBox(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; const col: PCardinal); const inds: array [0..6*4-1] of Byte = ( 7, 6, 5, 4, 0, 1, 2, 3, 1, 5, 6, 2, 3, 7, 4, 0, 2, 6, 7, 3, 0, 4, 5, 1 ); var verts: array [0..8*3-1] of Single; i: Integer; begin if (dd = nil) then Exit; { minx, miny, minz, maxx, miny, minz, maxx, miny, maxz, minx, miny, maxz, minx, maxy, minz, maxx, maxy, minz, maxx, maxy, maxz, minx, maxy, maxz, }; verts[0*3+0] := minx; verts[0*3+1] := miny; verts[0*3+2] := minz; verts[1*3+0] := maxx; verts[1*3+1] := miny; verts[1*3+2] := minz; verts[2*3+0] := maxx; verts[2*3+1] := miny; verts[2*3+2] := maxz; verts[3*3+0] := minx; verts[3*3+1] := miny; verts[3*3+2] := maxz; verts[4*3+0] := minx; verts[4*3+1] := maxy; verts[4*3+2] := minz; verts[5*3+0] := maxx; verts[5*3+1] := maxy; verts[5*3+2] := minz; verts[6*3+0] := maxx; verts[6*3+1] := maxy; verts[6*3+2] := maxz; verts[7*3+0] := minx; verts[7*3+1] := maxy; verts[7*3+2] := maxz; for i := 0 to 5 do begin dd.vertex(@verts[inds[i*4+0]*3], col[i]); dd.vertex(@verts[inds[i*4+1]*3], col[i]); dd.vertex(@verts[inds[i*4+2]*3], col[i]); dd.vertex(@verts[inds[i*4+3]*3], col[i]); end; end; procedure duAppendCylinder(dd: TduDebugDraw; minx, miny, minz: Single; maxx, maxy, maxz: Single; col: Cardinal); const NUM_SEG = 16; var dir: array [0..NUM_SEG*2-1] of Single; init: Boolean; i, j, a, b, c: Integer; ang, cx, cz, rx, rz: Single; col2: Cardinal; begin if (dd = nil) then Exit; init := false; if (not init) then begin init := true; for i := 0 to NUM_SEG - 1 do begin ang := i/NUM_SEG*PI*2; dir[i*2] := cos(ang); dir[i*2+1] := sin(ang); end; end; col2 := duMultCol(col, 160); cx := (maxx + minx)/2; cz := (maxz + minz)/2; rx := (maxx - minx)/2; rz := (maxz - minz)/2; for i := 2 to NUM_SEG - 1 do begin a := 0; b := i-1; c := i; dd.vertex(cx+dir[a*2+0]*rx, miny, cz+dir[a*2+1]*rz, col2); dd.vertex(cx+dir[b*2+0]*rx, miny, cz+dir[b*2+1]*rz, col2); dd.vertex(cx+dir[c*2+0]*rx, miny, cz+dir[c*2+1]*rz, col2); end; for i := 2 to NUM_SEG - 1 do begin a := 0; b := i; c := i-1; dd.vertex(cx+dir[a*2+0]*rx, maxy, cz+dir[a*2+1]*rz, col); dd.vertex(cx+dir[b*2+0]*rx, maxy, cz+dir[b*2+1]*rz, col); dd.vertex(cx+dir[c*2+0]*rx, maxy, cz+dir[c*2+1]*rz, col); end; i := 0; j := NUM_SEG-1; while (i < NUM_SEG) do begin dd.vertex(cx+dir[i*2+0]*rx, miny, cz+dir[i*2+1]*rz, col2); dd.vertex(cx+dir[j*2+0]*rx, miny, cz+dir[j*2+1]*rz, col2); dd.vertex(cx+dir[j*2+0]*rx, maxy, cz+dir[j*2+1]*rz, col); dd.vertex(cx+dir[i*2+0]*rx, miny, cz+dir[i*2+1]*rz, col2); dd.vertex(cx+dir[j*2+0]*rx, maxy, cz+dir[j*2+1]*rz, col); dd.vertex(cx+dir[i*2+0]*rx, maxy, cz+dir[i*2+1]*rz, col); j := i; Inc(i); end; end; procedure evalArc(const x0, y0, z0, dx, dy, dz, h, u: Single; res: PSingle); begin res[0] := x0 + dx * u; res[1] := y0 + dy * u + h * (1-(u*2-1)*(u*2-1)); res[2] := z0 + dz * u; end; procedure vcross(dest: PSingle; const v1,v2: PSingle); begin dest[0] := v1[1]*v2[2] - v1[2]*v2[1]; dest[1] := v1[2]*v2[0] - v1[0]*v2[2]; dest[2] := v1[0]*v2[1] - v1[1]*v2[0]; end; procedure vnormalize(v: PSingle); var d: Single; begin d := 1.0 / sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] := v[0] * d; v[1] := v[1] * d; v[2] := v[2] * d; end; procedure vsub(dest: PSingle; const v1,v2: PSingle); begin dest[0] := v1[0]-v2[0]; dest[1] := v1[1]-v2[1]; dest[2] := v1[2]-v2[2]; end; function vdistSqr(const v1,v2: PSingle): Single; var x,y,z: Single; begin x := v1[0]-v2[0]; y := v1[1]-v2[1]; z := v1[2]-v2[2]; Result := x*x + y*y + z*z; end; procedure appendArrowHead(dd: TduDebugDraw; const p, q: PSingle; const s: Single; col: Cardinal); const eps = 0.001; var ax,ay,az: array [0..2] of Single; begin //if (!dd) Result :=; if (vdistSqr(p,q) < eps*eps) then Exit; ay[0] := 0; ay[1] := 1; ay[2] := 0; vsub(@az[0], q, p); vnormalize(@az[0]); vcross(@ax[0], @ay[0], @az[0]); vcross(@ay[0], @az[0], @ax[0]); vnormalize(@ay[0]); dd.vertex(p, col); // dd.vertex(p[0]+az[0]*s+ay[0]*s/2, p[1]+az[1]*s+ay[1]*s/2, p[2]+az[2]*s+ay[2]*s/2, col); dd.vertex(p[0]+az[0]*s+ax[0]*s/3, p[1]+az[1]*s+ax[1]*s/3, p[2]+az[2]*s+ax[2]*s/3, col); dd.vertex(p, col); // dd.vertex(p[0]+az[0]*s-ay[0]*s/2, p[1]+az[1]*s-ay[1]*s/2, p[2]+az[2]*s-ay[2]*s/2, col); dd.vertex(p[0]+az[0]*s-ax[0]*s/3, p[1]+az[1]*s-ax[1]*s/3, p[2]+az[2]*s-ax[2]*s/3, col); end; procedure duAppendArc(dd: TduDebugDraw; const x0, y0, z0, x1, y1, z1, h, as0, as1: Single; col: Cardinal); const NUM_ARC_PTS = 8; const PAD = 0.05; const ARC_PTS_SCALE = (1.0-PAD*2) / NUM_ARC_PTS; var dx,dy,dz,len,u: Single; prev,pt,p,q: array [0..2] of Single; i: Integer; begin //if (!dd) Result :=; dx := x1 - x0; dy := y1 - y0; dz := z1 - z0; len := sqrt(dx*dx + dy*dy + dz*dz); //float prev[3]; evalArc(x0,y0,z0, dx,dy,dz, len*h, PAD, @prev[0]); for i := 1 to NUM_ARC_PTS do begin u := PAD + i * ARC_PTS_SCALE; //float pt[3]; evalArc(x0,y0,z0, dx,dy,dz, len*h, u, @pt[0]); dd.vertex(prev[0],prev[1],prev[2], col); dd.vertex(pt[0],pt[1],pt[2], col); prev[0] := pt[0]; prev[1] := pt[1]; prev[2] := pt[2]; end; // End arrows if (as0 > 0.001) then begin //float p[3], q[3]; evalArc(x0,y0,z0, dx,dy,dz, len*h, PAD, @p[0]); evalArc(x0,y0,z0, dx,dy,dz, len*h, PAD+0.05, @q[0]); appendArrowHead(dd, @p[0], @q[0], as0, col); end; if (as1 > 0.001) then begin //float p[3], q[3]; evalArc(x0,y0,z0, dx,dy,dz, len*h, 1-PAD, @p[0]); evalArc(x0,y0,z0, dx,dy,dz, len*h, 1-(PAD+0.05), @q[0]); appendArrowHead(dd, @p[0], @q[0], as1, col); end; end; procedure duAppendArrow(dd: TduDebugDraw; const x0, y0, z0, x1, y1, z1, as0, as1: Single; col: Cardinal); var p,q: array [0..2] of Single; begin if (dd = nil) then Exit; dd.vertex(x0,y0,z0, col); dd.vertex(x1,y1,z1, col); // End arrows p[0] := x0; p[1] := y0; p[2] := z0; q[0] := x1; q[1] := y1; q[2] := z1; if (as0 > 0.001) then appendArrowHead(dd, @p[0], @q[0], as0, col); if (as1 > 0.001) then appendArrowHead(dd, @q[0], @p[0], as1, col); end; procedure duAppendCircle(dd: TduDebugDraw; x,y,z,r: Single; col: Cardinal); const NUM_SEG = 40; var dir: array [0..40*2-1] of Single; init: Boolean; i,j: Integer; a: Single; begin if (dd = nil) then Exit; init := false; if (not init) then begin init := true; for i := 0 to NUM_SEG - 1 do begin a := i/NUM_SEG*Pi*2; dir[i*2] := cos(a); dir[i*2+1] := sin(a); end; end; i := 0; j := NUM_SEG-1; while (i < NUM_SEG) do begin dd.vertex(x+dir[j*2+0]*r, y, z+dir[j*2+1]*r, col); dd.vertex(x+dir[i*2+0]*r, y, z+dir[i*2+1]*r, col); j := i; Inc(i); end; end; procedure duAppendCross(dd: TduDebugDraw; x,y,z: Single; s: Single; col: Cardinal); begin if (dd = nil) then Exit; dd.vertex(x-s,y,z, col); dd.vertex(x+s,y,z, col); dd.vertex(x,y-s,z, col); dd.vertex(x,y+s,z, col); dd.vertex(x,y,z-s, col); dd.vertex(x,y,z+s, col); end; constructor TduDisplayList.Create(cap: Integer = 512); begin inherited Create; m_cap := cap; m_depthMask := true; m_prim := DU_DRAW_LINES; m_primSize := 1.0; if (cap < 8) then cap := 8; resize(cap); end; procedure TduDisplayList.resize(cap: Integer); var newPos: PSingle; newColor: PCardinal; begin GetMem(newPos, cap*3*sizeof(Single)); if (m_size <> 0)then Move(m_pos^, newPos^, sizeof(Single)*3*m_size); FreeMem(m_pos); m_pos := newPos; GetMem(newColor, cap*3*sizeof(Cardinal)); if (m_size <> 0) then Move(m_color^, newColor^, sizeof(Cardinal)*3*m_size); FreeMem(m_color); m_color := newColor; m_cap := cap; end; procedure TduDisplayList.clear(); begin m_size := 0; end; procedure TduDisplayList.depthMask(state: Boolean); begin m_depthMask := state; end; procedure TduDisplayList.&begin(prim: TduDebugDrawPrimitives; size: Single); begin clear(); m_prim := prim; m_primSize := size; end; procedure TduDisplayList.vertex(const x,y,z: Single; color: Cardinal); var p: PSingle; begin if (m_size+1 >= m_cap) then resize(m_cap*2); p := @m_pos[m_size*3]; p[0] := x; p[1] := y; p[2] := z; m_color[m_size] := color; Inc(m_size); end; procedure TduDisplayList.vertex(const pos: PSingle; color: Cardinal); begin vertex(pos[0],pos[1],pos[2],color); end; procedure TduDisplayList.&end(); begin end; procedure TduDisplayList.draw(dd: TduDebugDraw); var i: Integer; begin //if (!dd) then Exit; //if (!m_size) then Exit; dd.depthMask(m_depthMask); dd.&begin(m_prim, m_primSize); for i := 0 to m_size - 1 do dd.vertex(@m_pos[i*3], m_color[i]); dd.&end(); end; end.
unit SMCnst; interface {Chinese Traditional strings} const strMessage = '列印...'; strSaveChanges = '確定儲存變更到資料庫?'; strErrSaveChanges = '無法儲存資料! 請檢查伺服器連線或資料正確性.'; strDeleteWarning = '確定要刪除資料表 %s?'; strEmptyWarning = '確定要清空資料表 %s?'; const PopUpCaption: array [0..24] of string[33] = ('新增紀錄', '插入紀錄', '編輯紀錄', '刪除紀錄', '-', '列印 ...', '輸出 ...', '過濾 ...', '搜尋 ...', '-', '儲存變更', '取消變更', '更新', '-', '選取/取消選取 紀錄', '選取紀錄', '選取全部紀錄', '-', '取消選取紀錄', '取消選取全部紀錄', '-', '儲存欄位 layout', '還原欄位 layout', '-', '設定...'); const //for TSMSetDBGridDialog SgbTitle = ' 標題 '; SgbData = ' 資料 '; STitleCaption = '標題:'; STitleAlignment = '對齊:'; STitleColor = '背景:'; STitleFont = '字型:'; SWidth = '寬度:'; SWidthFix = 'characters'; SAlignLeft = '向左對齊'; SAlignRight = '向右對齊'; SAlignCenter = '置中對齊'; const //for TSMDBFilterDialog strEqual = '等於'; strNonEqual = '不等於'; strNonMore = '不大於'; strNonLess = '不小於'; strLessThan = '小於'; strLargeThan = '大於'; strExist = '空值'; strNonExist = '非空值'; strIn = '在清單中'; strBetween = '介於'; strLike = 'like'; strOR = '或'; strAND = '且'; strField = '欄位'; strCondition = '條件'; strValue = '值'; strAddCondition = ' 定義更多條件:'; strSelection = ' 依照下列條件選擇紀錄:'; strAddToList = '新增清單'; strEditInList = '編輯清單'; strDeleteFromList = '刪除清單'; strTemplate = '過濾樣本視窗'; strFLoadFrom = '載入...'; strFSaveAs = '儲存為..'; strFDescription = '描述'; strFFileName = '檔案名稱'; strFCreate = '新建: %s'; strFModify = '修改: %s'; strFProtect = '防止覆寫'; strFProtectErr = '檔案不可覆寫!'; const //for SMDBNavigator SFirstRecord = '第一筆紀錄'; SPriorRecord = '上一筆記錄'; SNextRecord = '下一筆記錄'; SLastRecord = '最後一筆記錄'; SInsertRecord = '新增紀錄'; SCopyRecord = '複製紀錄'; SDeleteRecord = '刪除紀錄'; SEditRecord = '編輯紀錄'; SFilterRecord = '過濾條件'; SFindRecord = '搜尋紀錄'; SPrintRecord = '列印紀錄'; SExportRecord = '匯出紀錄'; SPostEdit = '儲存變更'; SCancelEdit = '取消變更'; SRefreshRecord = '更新資料'; SChoice = '選擇一筆記錄'; SClear = '清除選取的紀錄'; SDeleteRecordQuestion = '刪除紀錄?'; SDeleteMultipleRecordsQuestion = '確定要刪除選取的紀錄?'; SRecordNotFound = '找不到紀錄'; SFirstName = '第一筆'; SPriorName = '上一筆'; SNextName = '下一筆'; SLastName = '最後一筆'; SInsertName = '新增'; SCopyName = '複製'; SDeleteName = '刪除'; SEditName = '編輯'; SFilterName = '過濾'; SFindName = '搜尋'; SPrintName = '列印'; SExportName = '匯出'; SPostName = '儲存'; SCancelName = '取消'; SRefreshName = '更新'; SChoiceName = '選擇'; SClearName = '清除'; SBtnOk = '確定 (&O)'; SBtnCancel = '取消 (&C)'; SBtnLoad = '載入'; SBtnSave = '儲存'; SBtnCopy = '複製'; SBtnPaste = '貼上'; SBtnClear = '清除'; SRecNo = 'rec.'; SRecOf = ' of '; const //for EditTyped etValidNumber = '合法數字'; etValidInteger = '合法整數'; etValidDateTime = '合法日期/時間'; etValidDate = '合法日期'; etValidTime = '合法時間'; etValid = '合法'; etIsNot = '不是'; etOutOfRange = '數值 %s 超出範圍 %s..%s'; SApplyAll = '套用到全部'; implementation end.
unit caStructures; {$INCLUDE ca.inc} interface uses // Standard Delphi units Windows, SysUtils, Classes, Math, Contnrs, // ca units caClasses, caUtils, caCell, caMatrix, caVector, caTypes; type //--------------------------------------------------------------------------- // IcaUniquePairItem //--------------------------------------------------------------------------- IcaUniquePairItem = interface ['{B69EDC95-151F-43C7-9E31-CB8232F242C7}'] function GetItem1: Integer; function GetItem1AsString: String; function GetItem2: Integer; function GetItem2AsString: String; procedure SetItem1(const Value: Integer); procedure SetItem2(const Value: Integer); // Properties property Item1: Integer read GetItem1 write SetItem1; property Item2: Integer read GetItem2 write SetItem2; property Item1AsString: String read GetItem1AsString; property Item2AsString: String read GetItem2AsString; end; //--------------------------------------------------------------------------- // TcaUniquePairItem //--------------------------------------------------------------------------- TcaUniquePairItem = class(TInterfacedObject, IcaUniquePairItem) private FItem1: Integer; FItem2: Integer; // Property methods function GetItem1: Integer; function GetItem1AsString: String; function GetItem2: Integer; function GetItem2AsString: String; procedure SetItem1(const Value: Integer); procedure SetItem2(const Value: Integer); public property Item1: Integer read GetItem1 write SetItem1; property Item2: Integer read GetItem2 write SetItem2; property Item1AsString: String read GetItem1AsString; property Item2AsString: String read GetItem2AsString; end; //--------------------------------------------------------------------------- // IcaUniquePairList //--------------------------------------------------------------------------- IcaUniquePairList = interface ['{5A7E6C1C-67C2-4A4C-B94A-01F63AF273D5}'] // Property methods function GetItemCount: Integer; function GetPair(Index: Integer): TcaUniquePairItem; function GetPairCount: Integer; function GetReverseItems: Boolean; function GetZeroBased: Boolean; procedure SetItemCount(const Value: Integer); procedure SetReverseItems(const Value: Boolean); procedure SetZeroBased(const Value: Boolean); // Properties property ItemCount: Integer read GetItemCount write SetItemCount; property PairCount: Integer read GetPairCount; property Pairs[Index: Integer]: TcaUniquePairItem read GetPair; default; property ReverseItems: Boolean read GetReverseItems write SetReverseItems; property ZeroBased: Boolean read GetZeroBased write SetZeroBased; end; //--------------------------------------------------------------------------- // TcaUniquePairList //--------------------------------------------------------------------------- TcaUniquePairList = class(TInterfacedObject, IcaUniquePairList) private FItemCount: Integer; FList: TObjectList; FReverseItems: Boolean; FZeroBased: Boolean; // Property methods function GetItemCount: Integer; function GetPair(Index: Integer): TcaUniquePairItem; function GetPairCount: Integer; function GetReverseItems: Boolean; function GetZeroBased: Boolean; procedure SetItemCount(const Value: Integer); procedure SetReverseItems(const Value: Boolean); procedure SetZeroBased(const Value: Boolean); // Private methods procedure BuildPairList; public constructor Create; destructor Destroy; override; // Properties property ItemCount: Integer read GetItemCount write SetItemCount; property PairCount: Integer read GetPairCount; property Pairs[Index: Integer]: TcaUniquePairItem read GetPair; default; property ReverseItems: Boolean read GetReverseItems write SetReverseItems; property ZeroBased: Boolean read GetZeroBased write SetZeroBased; end; //--------------------------------------------------------------------------- // IcaCustomIntegerSet //--------------------------------------------------------------------------- IcaCustomIntegerSet = interface ['{DB360B2F-D77A-4F04-A891-8D10C28D61BC}'] // Property methods function GetChoose: Integer; function GetFrom: Integer; procedure SetChoose(const Value: Integer); procedure SetFrom(const Value: Integer); // Input properties property Choose: Integer read GetChoose write SetChoose; property From: Integer read GetFrom write SetFrom; // Output properties end; //--------------------------------------------------------------------------- // TcaCustomIntegerSet //--------------------------------------------------------------------------- TcaCustomIntegerSet = class(TInterfacedObject, IcaCustomIntegerSet) private FChoose: Integer; FFrom: Integer; // Property methods function GetChoose: Integer; function GetFrom: Integer; procedure SetChoose(const Value: Integer); procedure SetFrom(const Value: Integer); public constructor Create; destructor Destroy; override; // Input properties property Choose: Integer read GetChoose write SetChoose; property From: Integer read GetFrom write SetFrom; // Output properties end; //--------------------------------------------------------------------------- // IcaPermutation //--------------------------------------------------------------------------- IcaPermutation = interface ['{D3D6C372-EED2-4533-AF5F-97BDD2955B56}'] end; //--------------------------------------------------------------------------- // TcaPermutation //--------------------------------------------------------------------------- TcaPermutation = class(TInterfacedObject, IcaCustomIntegerSet, IcaPermutation) private FBase: IcaCustomIntegerSet; protected public constructor Create; destructor Destroy; override; // Implementor property Base: IcaCustomIntegerSet read FBase implements IcaCustomIntegerSet; end; //--------------------------------------------------------------------------- // IcaPermutationList //--------------------------------------------------------------------------- IcaPermutationList = interface ['{AA6CFB07-278A-48C1-877C-451647AC6716}'] // Property methods function GetPermutation(Index: Integer): IcaPermutation; // Properties property Items[Index: Integer]: IcaPermutation read GetPermutation; end; //--------------------------------------------------------------------------- // TcaPermutationList //--------------------------------------------------------------------------- TcaPermutationList = class(TInterfacedObject, IcaCustomIntegerSet, IcaPermutationList) private FBase: IcaCustomIntegerSet; FList: TInterfaceList; // Property methods function GetPermutation(Index: Integer): IcaPermutation; protected public constructor Create; destructor Destroy; override; // Implementor property Base: IcaCustomIntegerSet read FBase implements IcaCustomIntegerSet; // Properties property Items[Index: Integer]: IcaPermutation read GetPermutation; end; implementation //--------------------------------------------------------------------------- // TcaUniquePairItem //--------------------------------------------------------------------------- function TcaUniquePairItem.GetItem1: Integer; begin Result := FItem1; end; function TcaUniquePairItem.GetItem1AsString: String; begin Result := IntToStr(FItem1); end; function TcaUniquePairItem.GetItem2: Integer; begin Result := FItem2; end; function TcaUniquePairItem.GetItem2AsString: String; begin Result := IntToStr(FItem2); end; procedure TcaUniquePairItem.SetItem1(const Value: Integer); begin FItem1 := Value; end; procedure TcaUniquePairItem.SetItem2(const Value: Integer); begin FItem2 := Value; end; //--------------------------------------------------------------------------- // TcaUniquePairList //--------------------------------------------------------------------------- constructor TcaUniquePairList.Create; begin inherited; FList := TObjectList.Create(True); FZeroBased := True; FReverseItems := False; end; destructor TcaUniquePairList.Destroy; begin FList.Free; inherited; end; // Private methods procedure TcaUniquePairList.BuildPairList; var Index1: Integer; Index2: Integer; Index2Start: Integer; Item: TcaUniquePairItem; Offset: Integer; begin Offset := 1 - Ord(FZeroBased); FList.Clear; for Index1 := 0 to FItemCount - 1 do begin if FReverseItems then Index2Start := 0 else Index2Start := Index1 + 1; for Index2 := Index2Start to FItemCount - 1 do begin Item := TcaUniquePairItem.Create; Item.Item1 := Index1 + Offset; Item.Item2 := Index2 + Offset; FList.Add(Item); end; end; end; // Property methods function TcaUniquePairList.GetItemCount: Integer; begin Result := FItemCount; end; function TcaUniquePairList.GetPair(Index: Integer): TcaUniquePairItem; begin Result := TcaUniquePairItem(FList[Index]); end; function TcaUniquePairList.GetPairCount: Integer; begin Result := FList.Count; end; function TcaUniquePairList.GetReverseItems: Boolean; begin Result := FReverseItems; end; function TcaUniquePairList.GetZeroBased: Boolean; begin Result := FZeroBased; end; procedure TcaUniquePairList.SetItemCount(const Value: Integer); begin FItemCount := Value; BuildPairList; end; procedure TcaUniquePairList.SetReverseItems(const Value: Boolean); begin FReverseItems := Value; BuildPairList; end; procedure TcaUniquePairList.SetZeroBased(const Value: Boolean); begin FZeroBased := Value; BuildPairList; end; //--------------------------------------------------------------------------- // TcaCustomIntegerSet //--------------------------------------------------------------------------- constructor TcaCustomIntegerSet.Create; begin inherited; end; destructor TcaCustomIntegerSet.Destroy; begin inherited; end; function TcaCustomIntegerSet.GetChoose: Integer; begin Result := FChoose; end; function TcaCustomIntegerSet.GetFrom: Integer; begin Result := FFrom; end; procedure TcaCustomIntegerSet.SetChoose(const Value: Integer); begin FChoose := Value; end; procedure TcaCustomIntegerSet.SetFrom(const Value: Integer); begin FFrom := Value; end; //--------------------------------------------------------------------------- // TcaPermutation //--------------------------------------------------------------------------- constructor TcaPermutation.Create; begin inherited; FBase := TcaCustomIntegerSet.Create; end; destructor TcaPermutation.Destroy; begin inherited; end; //--------------------------------------------------------------------------- // TcaPermutationList //--------------------------------------------------------------------------- constructor TcaPermutationList.Create; begin inherited; FBase := TcaCustomIntegerSet.Create; FList := TInterfaceList.Create; end; destructor TcaPermutationList.Destroy; begin FList.Free; inherited; end; function TcaPermutationList.GetPermutation(Index: Integer): IcaPermutation; begin Result := FList[Index] as IcaPermutation; end; end.
unit func_ccreg_set16; interface implementation type TEnum16 = (_a00,_a01,_a02,_a03,_a04,_a05,_a06,_a07,_a08,_a09,_a10,_a11,_a12,_a13,_a14,_a15); TSet16 = packed set of TEnum16; function F(a: TSet16): TSet16; external 'CAT' name 'func_ccreg_set16'; procedure Test; var a, r: TSet16; begin a := [_a01]; R := F(a); Assert(a = r); end; initialization Test(); finalization end.
{ Planarity Check O(NE) Demoucron-Malgrange Alg. Implementation O(N4) Input: G: UnDirected Simple Graph N: Number of vertices Output: Reference: West By Behdad } program PlanarityCheck; const MaxN = 50 + 2; type TSet = set of 0 .. MaxN; TBridge = record V, A, F : TSet; {Vertices, Adj. Vertices, Faces} D : Integer; {Number of Faces} end; TVertex = record F : TSet; {Faces} E : Boolean; {Embedded} B : Integer; {Bridge Number} end; var N, BN, FN : Integer; {Number of Vertices, Bridges, Faces} G, H : array [1 .. MaxN, 1 .. MaxN] of Boolean; E : array [1 .. MaxN, 1 .. MaxN, 1 .. 2] of Integer; Br : array [1 .. MaxN] of TBridge; Vr : array [1 .. MaxN] of TVertex; procedure NoSolution; begin Writeln('Graph is not planar'); Halt; end; procedure Found; begin Writeln('Graph is planar'); end; procedure EmbedEdge (I, J, Aa, Bb : Integer; Fl : Boolean); begin G[I, J] := False; G[J, I] := G[I, J]; H[I, J] := True ; H[J, I] := H[I, J]; if Fl then begin E[I, J, 1] := Aa; E[I, J, 2] := Bb; E[J, I] := E[I, J]; end; with Vr[I] do begin E := True; F := F + [Aa, Bb]; B := 0; end; with Vr[J] do begin E := True; F := F + [Aa, Bb]; B := 0; end; end; procedure ChangeEdge (I, J, Aa, Bb : Integer); begin if E[I, J, 1] = Aa then E[I, J, 1] := Bb else if E[I, J, 2] = Aa then E[I, J, 2] := Bb; E[J, I] := E[I, J]; with Vr[I] do F := F - [Aa] + [Bb]; with Vr[J] do F := F - [Aa] + [Bb]; end; procedure UpdateBridges; forward; procedure Initialize; var I, J : Integer; Mark : array [1 .. MaxN] of Boolean; function Dfs (V, P : Integer) : Boolean; var I : Integer; Fl : Boolean; begin Mark[V] := True; for I := 1 to N do if G[V, I] then begin Fl := Mark[I]; if (Mark[I] and (I <> P)) or (not Mark[I] and Dfs(I, V)) then begin if Fl then J := I; if J <> 0 then EmbedEdge(V, I, 1, 2, True); if not Fl and (I = J) then J := 0; Dfs := True; Exit; end; end; Dfs := False; end; begin BN := 0; FillChar(Mark, SizeOf(Mark), 0); Dfs(1, 0); FN := 2; UpdateBridges; end; procedure UpdateBridgeFaces (B : Integer); var I : Integer; begin with Br[B] do begin F := [1 .. N]; for I := 1 to N do if I in A then F := F * Vr[I].F; D := 0; for I := 1 to N do if I in F then Inc(D); end; end; procedure UpdateBridges; var Mark : array [1 .. MaxN] of Boolean; procedure FindBridgeVertices (V : Integer); var I : Integer; begin Include(Br[BN].V, V); Vr[V].B := BN; Mark[V] := True; for I := 1 to N do if G[V, I] then if not Vr[I].E and not Mark[I] then FindBridgeVertices(I) else if Vr[I].E then Include(Br[BN].A, I); end; var I, J : Integer; begin FillChar(Mark, SizeOf(Mark), 0); for I := 1 to N do with Vr[I] do if not E and (B = 0) then begin Inc(BN); FillChar(Br[BN], SizeOf(Br[BN]), 0); FindBridgeVertices(I); UpdateBridgeFaces(BN); end; end; procedure RelaxBridge (B : Integer); var Mark : array [1 .. MaxN] of Boolean; X, Y, J : Integer; function FindPath (V : Integer) : Boolean; var I : Integer; begin Mark[V] := True; for I := 1 to N do if not Mark[I] and G[V, I] and ((I in Br[B].A) or ((I in Br[B].V) and FindPath(I))) then begin if not Mark[I] then Y := I; EmbedEdge(V, I, J, FN, True); FindPath := True; Exit; end; FindPath := False; end; var I, X2 : Integer; S : TSet; begin FillChar(Mark, SizeOf(Mark), 0); Inc(FN); for I := 1 to N do if I in Br[B].F then begin J := I; Break; end; for I := 1 to N do if I in Br[B].A then begin X := I; FindPath(X); Break; end; for I := 1 to N do if I in Br[B].V then Vr[I].B := 0; Br[B] := Br[BN]; Dec(BN); X2 := X; repeat for I := 1 to N do if H[X, I] and ((E[X, I, 1] = J) or (E[X, I, 2] = J)) then Break; ChangeEdge(X, I, J, FN); X := I; until X = Y; EmbedEdge(X2, Y, J, FN, False); for I := 1 to BN do if J in Br[I].F then UpdateBridgeFaces(I); UpdateBridges; end; procedure RelaxEdge (X, Y : Integer); var I, J, X2 : Integer; begin for J := FN downto 0 do if J in Vr[X].F * Vr[Y].F then Break; if J = 0 then NoSolution; Inc(FN); X2 := X; repeat for I := 1 to N do if H[X, I] and ((E[X, I, 1] = J) or (E[X, I, 2] = J)) then Break; ChangeEdge(X, I, J, FN); X := I; until X = Y; EmbedEdge(X2, Y, J, FN, True); for I := 1 to BN do if J in Br[I].F then UpdateBridgeFaces(I); end; procedure Planar; var I, J : Integer; procedure FindMin (var I : Integer); var J : Integer; begin I := 1; for J := 1 to BN do if Br[I].D > Br[J].D then I := J; if BN = 0 then I := 0; end; begin BN := 0; Initialize; repeat FindMin(I); if I <> 0 then begin if Br[I].D = 0 then NoSolution; RelaxBridge(I); end; for I := 1 to N do for J := 1 to I - 1 do if G[I, J] and Vr[I].E and Vr[J].E then RelaxEdge(I, J); until BN = 0; end; begin Planar; Found; end.
unit frmAddCertificateU; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, dialogs, IBServices; type TfrmAddCertificate = class(TForm) Label1: TLabel; edID: TEdit; OKBtn: TButton; CancelBtn: TButton; Label2: TLabel; Label3: TLabel; edKey: TEdit; procedure OKBtnClick(Sender: TObject); private FIBLicensingService: TIBLicensingService; { Private declarations } public { Public declarations } property LicensingService : TIBLicensingService read FIBLicensingService write FIBLicensingService; end; implementation {$R *.dfm} procedure TfrmAddCertificate.OKBtnClick(Sender: TObject); begin with LicensingService do begin ID := trim(edID.text); Key := trim(edKey.text); try AddLicense; self.ModalResult := mrOK; except ShowMessage('The certificate could not be validated based on the information given. Please recheck the id and key information.'); end; end; end; end.
unit untEasySelectDialog; interface uses Windows, Messages, SysUtils, Variants, cxClasses, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ExtCtrls, ADODB, cxBlobEdit, cxCheckBox, DBClient, Grids, DBGrids, cxGridCustomPopupMenu, cxGridPopupMenu, cxImage, cxTextEdit, Menus, untEasyButtons, untEasyPageControl, untEasyGroupBox, untEasySplitter, untEasyMenus, untEasyMenuStylers; type //选择框样式 ssSimple可附属到其它控件 ssNormal 弹出模态对话框 TSelectStyle = (ssSimple, ssNormal); //选择框返回值事件 resDoubleClick又再Grid时返回值并关闭 //resButtonClic 单击指定按钮时返回值并关闭 TReturnEventStyle = (resDoubleClick, resButtonClick, resAllClick); TfrmEasySelectDialog = class(TForm) pnlTop: TPanel; pnlClient: TPanel; grdSelectMain: TcxGrid; grdSelectMainDBTableView1: TcxGridDBTableView; grdSelectMainLevel1: TcxGridLevel; cxGridPopupMenu1: TcxGridPopupMenu; EasyNetscapeSplitter1: TEasyNetscapeSplitter; EasyPanel1: TEasyPanel; EasyPageControl1: TEasyPageControl; EasyTabSheet1: TEasyTabSheet; EasyPanel2: TEasyPanel; btnRefresh: TEasyBitButton; btnCancel: TEasyBitButton; SaveDialogExport: TSaveDialog; btnOK: TEasyBitButton; cxStyleRepository1: TcxStyleRepository; cxStyle1: TcxStyle; cxStyle2: TcxStyle; EasyPopupMenu1: TEasyPopupMenu; EasyMenuOfficeStyler1: TEasyMenuOfficeStyler; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; N4: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure grdSelectMainDBTableView1CustomDrawIndicatorCell( Sender: TcxGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxCustomGridIndicatorItemViewInfo; var ADone: Boolean); procedure grdSelectMainDBTableView1Editing( Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; var AAllow: Boolean); procedure FormShow(Sender: TObject); procedure N1Click(Sender: TObject); procedure N3Click(Sender: TObject); procedure N2Click(Sender: TObject); private { Private declarations } FMultiSelect : Boolean; FSelectStyle : TSelectStyle; FReturnEventStyle: TReturnEventStyle; FOleDBData : OleVariant; //数据集 FGridFields, //Grid显示列字段 FGridFieldsCaption, //Grid显示列标题 FGridFieldsWidth : TStrings; //Grid显示列宽度 ADataSource : TDataSource; ATmpClientDataSet: TClientDataSet; function GetMultiSelect: Boolean; procedure SetMultiSelect(const Value: Boolean); function GetSelectStyle: TSelectStyle; procedure SetSelectStyle(const Value: TSelectStyle); function GetReturnEventStyle: TReturnEventStyle; procedure SetReturnEventStyle(const Value: TReturnEventStyle); function GetOleDBData: OleVariant; procedure SetOleDBData(const Value: OleVariant); function GetGridFields: TStrings; function GetGridFieldsCaption: TStrings; procedure SetGridFields(const Value: TStrings); procedure SetGridFieldsCaption(const Value: TStrings); function GetGridFieldsWidth: TStrings; procedure SetGridFieldsWidth(const Value: TStrings); // //动态创建Grid列 procedure GenerateColumns(AGridView: TcxGridDBTableView); procedure GenerateTmpDataSet(ASrcClientDataSet, ADestClientDataSet: TClientDataSet); procedure SelectedSet(ACds: TClientDataSet; AType: Integer); public { Public declarations } AClientDataSet : TClientDataSet; property MultiSelect: Boolean read GetMultiSelect write SetMultiSelect; property SelectStyle: TSelectStyle read GetSelectStyle write SetSelectStyle; property ReturnEventStyle: TReturnEventStyle read GetReturnEventStyle write SetReturnEventStyle; property OleDBData: OleVariant read GetOleDBData write SetOleDBData; //用Assign赋值 property GridFields: TStrings read GetGridFields write SetGridFields; property GridFieldsCaption: TStrings read GetGridFieldsCaption write SetGridFieldsCaption; property GridFieldsWidth: TStrings read GetGridFieldsWidth write SetGridFieldsWidth; end; var frmEasySelectDialog: TfrmEasySelectDialog; implementation uses cxGridDBDataDefinitions; {$R *.dfm} { TfrmEasySelectDialog } function TfrmEasySelectDialog.GetMultiSelect: Boolean; begin Result := FMultiSelect; end; procedure TfrmEasySelectDialog.SetMultiSelect(const Value: Boolean); begin FMultiSelect := Value; end; procedure TfrmEasySelectDialog.FormCreate(Sender: TObject); begin FMultiSelect := False; FSelectStyle := ssNormal; FReturnEventStyle := resButtonClick; FGridFields := TStringList.Create; FGridFieldsCaption := TStringList.Create; FGridFieldsWidth := TStringList.Create; AClientDataSet := TClientDataSet.Create(Self); ATmpClientDataSet := TClientDataSet.Create(Self); ADataSource := TDataSource.Create(Self); end; function TfrmEasySelectDialog.GetSelectStyle: TSelectStyle; begin Result := FSelectStyle; end; procedure TfrmEasySelectDialog.SetSelectStyle(const Value: TSelectStyle); begin FSelectStyle := Value; end; function TfrmEasySelectDialog.GetReturnEventStyle: TReturnEventStyle; begin Result := FReturnEventStyle; end; procedure TfrmEasySelectDialog.SetReturnEventStyle(const Value: TReturnEventStyle); begin FReturnEventStyle := Value; end; function TfrmEasySelectDialog.GetOleDBData: OleVariant; begin Result := FOleDBData; end; procedure TfrmEasySelectDialog.SetOleDBData(const Value: OleVariant); begin FOleDBData := Value; end; procedure TfrmEasySelectDialog.FormDestroy(Sender: TObject); begin AClientDataSet.Free; ATmpClientDataSet.Free; ADataSource.DataSet := nil; ADataSource.Free; FGridFields.Free; FGridFieldsCaption.Free; FGridFieldsWidth.Free; end; function TfrmEasySelectDialog.GetGridFields: TStrings; begin Result := FGridFields; end; function TfrmEasySelectDialog.GetGridFieldsCaption: TStrings; begin Result := FGridFieldsCaption; end; procedure TfrmEasySelectDialog.SetGridFields(const Value: TStrings); begin FGridFields := Value; end; procedure TfrmEasySelectDialog.SetGridFieldsCaption(const Value: TStrings); begin FGridFieldsCaption := Value; end; function TfrmEasySelectDialog.GetGridFieldsWidth: TStrings; begin Result := FGridFieldsWidth; end; procedure TfrmEasySelectDialog.SetGridFieldsWidth(const Value: TStrings); begin FGridFieldsWidth := Value; end; procedure TfrmEasySelectDialog.grdSelectMainDBTableView1CustomDrawIndicatorCell( Sender: TcxGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxCustomGridIndicatorItemViewInfo; var ADone: Boolean); var AIndicatorViewInfo: TcxGridIndicatorRowItemViewInfo; ATextRect : TRect; ACV : TcxCanvas; begin if not (AViewInfo is TcxGridIndicatorRowItemViewInfo) then Exit; aCV := ACanvas; ATextRect := AViewInfo.ContentBounds; AIndicatorViewInfo := AViewInfo as TcxGridIndicatorRowItemViewInfo; InflateRect(ATextRect, -2, -1); //这个if段是为了在行号处把把选中的行号跟别的区分开,可不用 if AIndicatorViewInfo.GridRecord.Selected then begin aCV.Font.Style := Canvas.Font.Style + [fsBold]; aCV.Font.Color := clRed; end else begin aCV.Font.Style := Canvas.Font.Style - [fsBold]; acv.Font.Color := Canvas.Font.Color; end; Sender.LookAndFeelPainter.DrawHeader(ACanvas, AViewInfo.ContentBounds, ATextRect, [], cxBordersAll, cxbsNormal, taCenter, cxClasses.vaCenter, False, False, IntToStr(AIndicatorViewInfo.GridRecord.Index + 1), // AStyle.Font, AStyle.TextColor, AStyle.Color); acv.Font,acv.font.Color,acv.Brush.color ); ADone := True; end; procedure TfrmEasySelectDialog.grdSelectMainDBTableView1Editing( Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; var AAllow: Boolean); begin if MultiSelect then begin if grdSelectMainDBTableView1.Controller.FocusedColumnIndex <> 0 then AAllow := False else AAllow := True; end else AAllow := False; end; procedure TfrmEasySelectDialog.GenerateTmpDataSet(ASrcClientDataSet, ADestClientDataSet: TClientDataSet); var I, J : Integer; ATmpName : string; ATmpFieldDef: TFieldDef; AFieldNameList: TStrings; begin if ASrcClientDataSet.FieldDefs.Count = 0 then Exit; AFieldNameList := TStringList.Create; ADestClientDataSet.Close; ADestClientDataSet.FieldDefs.Clear; if MultiSelect then begin ATmpFieldDef := ADestClientDataSet.FieldDefs.AddFieldDef; with ATmpFieldDef do begin Name := 'myselected'; DataType := ftBoolean; end; for I := 0 to ASrcClientDataSet.FieldDefs.Count - 1 do begin ATmpName := ASrcClientDataSet.FieldDefs[I].Name; AFieldNameList.Add(ATmpName); ATmpFieldDef := ASrcClientDataSet.FieldDefs[I]; ADestClientDataSet.FieldDefs.AddFieldDef; ADestClientDataSet.FieldDefs[I + 1].Assign(ATmpFieldDef); end; ADestClientDataSet.CreateDataSet; ASrcClientDataSet.First; for I := 0 to ASrcClientDataSet.RecordCount - 1 do begin ADestClientDataSet.Append; ADestClientDataSet.Fields[0].Value := False; for J := 0 to AFieldNameList.Count - 1 do ADestClientDataSet.Fields[J + 1].Value := ASrcClientDataSet.Fields[J].Value; ASrcClientDataSet.Next; end; ADestClientDataSet.First; end else begin for I := 0 to ASrcClientDataSet.FieldDefs.Count - 1 do begin ATmpName := ASrcClientDataSet.FieldDefs[I].Name; AFieldNameList.Add(ATmpName); ATmpFieldDef := ASrcClientDataSet.FieldDefs[I]; ADestClientDataSet.FieldDefs.AddFieldDef; ADestClientDataSet.FieldDefs[I].Assign(ATmpFieldDef); end; ADestClientDataSet.CreateDataSet; ASrcClientDataSet.First; for I := 0 to ASrcClientDataSet.RecordCount - 1 do begin ADestClientDataSet.Append; ADestClientDataSet.Fields[0].Value := False; for J := 0 to AFieldNameList.Count - 1 do ADestClientDataSet.Fields[J].Value := ASrcClientDataSet.Fields[J].Value; ASrcClientDataSet.Next; end; ADestClientDataSet.First; end; end; procedure TfrmEasySelectDialog.GenerateColumns( AGridView: TcxGridDBTableView); var ATmpColumn: TcxGridDBColumn; I : Integer; begin //如果允许多选就增加复选框列 if MultiSelect then begin ATmpColumn := AGridView.CreateColumn; with ATmpColumn do begin PropertiesClass := TcxCheckBoxProperties; Width := 30; Options.Sorting := False; DataBinding.FieldName := 'myselected'; Caption := ''; end; end; for I := 0 to GridFields.Count - 1 do begin ATmpColumn := AGridView.CreateColumn; with ATmpColumn do begin DataBinding.FieldName := GridFields.Strings[I]; if GridFieldsCaption.Count - 1 >= I then Caption := GridFieldsCaption.Strings[I]; HeaderAlignmentHorz := taCenter; if GridFieldsWidth.Count - 1 >= I then begin if StrToInt(GridFieldsWidth.Strings[I]) > 0 then Width := StrToInt(GridFieldsWidth.Strings[I]); end; end; end; AGridView.DataController.DataSource := ADataSource; end; procedure TfrmEasySelectDialog.FormShow(Sender: TObject); var AFooterItem: TcxDataSummaryItem; begin GenerateTmpDataSet(AClientDataSet, ATmpClientDataSet); ADataSource.DataSet := ATmpClientDataSet; //生成Grid列 GenerateColumns(grdSelectMainDBTableView1); with grdSelectMainDBTableView1.DataController.Summary do begin BeginUpdate; AFooterItem := FooterSummaryItems.Add; with (AFooterItem as TcxGridDBTableSummaryItem) do begin if grdSelectMainDBTableView1.ColumnCount > 0 then begin Column := grdSelectMainDBTableView1.Columns[0]; FieldName := grdSelectMainDBTableView1.Columns[0].DataBinding.FieldName; Format := '合计:0'; Kind := skCount; end; end; EndUpdate; end; end; procedure TfrmEasySelectDialog.SelectedSet(ACds: TClientDataSet; AType: Integer); var ABookMark: TBookmark; I: Integer; begin ACds.DisableControls; ABookMark := ACds.GetBookmark; ACds.First; if AType = 0 then //全选 begin for I := 0 to ACds.RecordCount - 1 do begin ACds.Edit; ACds.FieldByName('myselected').AsBoolean := True; ACds.Next; end; end else if AType = 1 then //全不选 begin for I := 0 to ACds.RecordCount - 1 do begin ACds.Edit; ACds.FieldByName('myselected').AsBoolean := False; ACds.Next; end; end else if AType = 2 then //反选 begin for I := 0 to ACds.RecordCount - 1 do begin ACds.Edit; ACds.FieldByName('myselected').AsBoolean := not ACds.FieldByName('myselected').AsBoolean; ACds.Next; end; end; ACds.GotoBookmark(ABookMark); ACds.FreeBookmark(ABookMark); ACds.EnableControls; end; procedure TfrmEasySelectDialog.N1Click(Sender: TObject); begin SelectedSet(ATmpClientDataSet, 0); end; procedure TfrmEasySelectDialog.N3Click(Sender: TObject); begin SelectedSet(ATmpClientDataSet, 1); end; procedure TfrmEasySelectDialog.N2Click(Sender: TObject); begin SelectedSet(ATmpClientDataSet, 2); end; end.
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // {$POINTERMATH ON} unit RN_DetourNode; interface uses RN_DetourNavMeshHelper; const //enum dtNodeFlags DT_NODE_OPEN = $01; DT_NODE_CLOSED = $02; DT_NODE_PARENT_DETACHED = $04; // parent of the node is not adjacent. Found using raycast. type TdtNodeIndex = Word; PdtNodeIndex = ^TdtNodeIndex; const DT_NULL_IDX: TdtNodeIndex = $ffff; // Inverse of 0 type PdtNode = ^TdtNode; TdtNode = record pos: array [0..2] of Single; ///< Position of the node. cost: Single; ///< Cost from previous node to current node. total: Single; ///< Cost up to the node. pidx: Cardinal; ///< Index to parent node. state: Byte; ///< extra state information. A polyRef can have multiple nodes with different extra info. see DT_MAX_STATES_PER_NODE flags: Byte; ///< Node flags. A combination of dtNodeFlags. id: TdtPolyRef; ///< Polygon ref the node corresponds to. end; const DT_MAX_STATES_PER_NODE = 4; // number of extra states per node. See dtNode::state type TdtNodePool = class private m_nodes: PdtNode; m_first: PdtNodeIndex; m_next: PdtNodeIndex; m_maxNodes: Integer; m_hashSize: Integer; m_nodeCount: Integer; public constructor Create(maxNodes, hashSize: Integer); destructor Destroy; override; //inline void operator=(const dtNodePool&) {} procedure clear(); // Get a dtNode by ref and extra state information. If there is none then - allocate // There can be more than one node for the same polyRef but with different extra state information function getNode(id: TdtPolyRef; state: Byte = 0): PdtNode; function findNode(id: TdtPolyRef; state: Byte): PdtNode; function findNodes(id: TdtPolyRef; var nodes: array of PdtNode; maxNodes: Integer): Cardinal; function getNodeIdx(node: PdtNode): Cardinal; function getNodeAtIdx(idx: Cardinal): PdtNode; function getMemUsed(): Integer; property getMaxNodes: Integer read m_maxNodes; property getHashSize: Integer read m_hashSize; function getFirst(bucket: Integer): TdtNodeIndex; function getNext(i: Integer): TdtNodeIndex; property getNodeCount: Integer read m_nodeCount; end; TdtNodeQueue = class private m_heap: array of PdtNode; m_capacity: Integer; m_size: Integer; procedure bubbleUp(i: Integer; node: PdtNode); procedure trickleDown(i: Integer; node: PdtNode); public constructor Create(n: Integer); destructor Destroy; override; //inline void operator=(dtNodeQueue&) {} procedure clear(); function top(): PdtNode; function pop(): PdtNode; procedure push(node: PdtNode); procedure modify(node: PdtNode); function empty(): Boolean; function getMemUsed(): Integer; property getCapacity: Integer read m_capacity; end; implementation uses RN_DetourCommon; {$ifdef DT_POLYREF64} // From Thomas Wang, https://gist.github.com/badboy/6267743 function dtHashRef(a: TdtPolyRef): Cardinal; begin a := (not a) + (a shl 18); // a = (a << 18) - a - 1; a := a xor (a shr 31); a := a * 21; // a = (a + (a << 2)) + (a << 4); a := a xor (a shr 11); a := a + (a shl 6); a := a xor (a shr 22); Result := Cardinal(a); end {$else} function dtHashRef(a: TdtPolyRef): Cardinal; begin {$Q-} a := a + not (a shl 15); a := a xor (a shr 10); a := a + (a shl 3); a := a xor (a shr 6); a := a + not (a shl 11); a := a xor (a shr 16); Result := Cardinal(a); {$Q+} end; {$endif} ////////////////////////////////////////////////////////////////////////////////////////// constructor TdtNodePool.Create(maxNodes, hashSize: Integer); begin inherited Create; m_maxNodes := maxNodes; m_hashSize := hashSize; Assert(dtNextPow2(m_hashSize) = m_hashSize); Assert(m_maxNodes > 0); GetMem(m_nodes, sizeof(TdtNode)*m_maxNodes); GetMem(m_next, sizeof(TdtNodeIndex)*m_maxNodes); GetMem(m_first, sizeof(TdtNodeIndex)*hashSize); //dtAssert(m_nodes); //dtAssert(m_next); //dtAssert(m_first); FillChar(m_first[0], sizeof(TdtNodeIndex)*m_hashSize, $ff); FillChar(m_next[0], sizeof(TdtNodeIndex)*m_maxNodes, $ff); end; destructor TdtNodePool.Destroy; begin FreeMem(m_nodes); FreeMem(m_next); FreeMem(m_first); inherited; end; procedure TdtNodePool.clear(); begin FillChar(m_first[0], sizeof(TdtNodeIndex)*m_hashSize, $ff); m_nodeCount := 0; end; function TdtNodePool.findNodes(id: TdtPolyRef; var nodes: array of PdtNode; maxNodes: Integer): Cardinal; var n: Integer; bucket: Cardinal; i: TdtNodeIndex; begin n := 0; bucket := dtHashRef(id) and (m_hashSize-1); i := m_first[bucket]; while (i <> DT_NULL_IDX) do begin if (m_nodes[i].id = id) then begin if (n >= maxNodes) then Exit(n); nodes[n] := @m_nodes[i]; Inc(n); end; i := m_next[i]; end; Result := n; end; function TdtNodePool.findNode(id: TdtPolyRef; state: Byte): PdtNode; var bucket: Cardinal; i: TdtNodeIndex; begin bucket := dtHashRef(id) and (m_hashSize-1); i := m_first[bucket]; while (i <> DT_NULL_IDX) do begin if (m_nodes[i].id = id) and (m_nodes[i].state = state) then Exit(@m_nodes[i]); i := m_next[i]; end; Result := nil; end; function TdtNodePool.getNode(id: TdtPolyRef; state: Byte = 0): PdtNode; var bucket: Cardinal; i: TdtNodeIndex; node: PdtNode; begin bucket := dtHashRef(id) and (m_hashSize-1); i := m_first[bucket]; node := nil; while (i <> DT_NULL_IDX) do begin if (m_nodes[i].id = id) and (m_nodes[i].state = state) then Exit(@m_nodes[i]); i := m_next[i]; end; if (m_nodeCount >= m_maxNodes) then Exit(nil); i := TdtNodeIndex(m_nodeCount); Inc(m_nodeCount); // Init node node := @m_nodes[i]; node.pidx := 0; node.cost := 0; node.total := 0; node.id := id; node.state := state; node.flags := 0; m_next[i] := m_first[bucket]; m_first[bucket] := i; Result := node; end; function TdtNodePool.getNodeIdx(node: PdtNode): Cardinal; begin if (node = nil) then Exit(0); Result := Cardinal(node - m_nodes)+1; end; function TdtNodePool.getNodeAtIdx(idx: Cardinal): PdtNode; begin if (idx = 0) then Exit(nil); Result := @m_nodes[idx-1]; end; function TdtNodePool.getMemUsed(): Integer; begin Result := sizeof(Self) + sizeof(TdtNode)*m_maxNodes + sizeof(TdtNodeIndex)*m_maxNodes + sizeof(TdtNodeIndex)*m_hashSize; end; function TdtNodePool.getFirst(bucket: Integer): TdtNodeIndex; begin Result := m_first[bucket]; end; function TdtNodePool.getNext(i: Integer): TdtNodeIndex; begin Result := m_next[i]; end; ////////////////////////////////////////////////////////////////////////////////////////// procedure TdtNodeQueue.clear(); begin m_size := 0; end; function TdtNodeQueue.top(): PdtNode; begin Result := m_heap[0]; end; function TdtNodeQueue.pop(): PdtNode; var reslt: PdtNode; begin reslt := m_heap[0]; Dec(m_size); trickleDown(0, m_heap[m_size]); Result := reslt; end; procedure TdtNodeQueue.push(node: PdtNode); begin Inc(m_size); bubbleUp(m_size-1, node); end; procedure TdtNodeQueue.modify(node: PdtNode); var i: Integer; begin for i := 0 to m_size - 1 do begin if (m_heap[i] = node) then begin bubbleUp(i, node); Exit; end; end; end; function TdtNodeQueue.empty(): Boolean; begin Result := m_size = 0; end; function TdtNodeQueue.getMemUsed(): Integer; begin Result := sizeof(Self) + sizeof(PdtNode)*(m_capacity+1); end; constructor TdtNodeQueue.Create(n: Integer); begin m_capacity := n; Assert(m_capacity > 0); SetLength(m_heap, (m_capacity+1)); //dtAssert(m_heap); end; destructor TdtNodeQueue.Destroy; begin //dtFree(m_heap); //Delphi: array disposal is automatic inherited; end; procedure TdtNodeQueue.bubbleUp(i: Integer; node: PdtNode); var parent: Integer; begin parent := (i-1) div 2; // note: (index > 0) means there is a parent while ((i > 0) and (m_heap[parent].total > node.total)) do begin m_heap[i] := m_heap[parent]; i := parent; parent := (i-1) div 2; end; m_heap[i] := node; end; procedure TdtNodeQueue.trickleDown(i: Integer; node: PdtNode); var child: Integer; begin child := (i*2)+1; while (child < m_size) do begin if (((child+1) < m_size) and (m_heap[child].total > m_heap[child+1].total)) then begin Inc(child); end; m_heap[i] := m_heap[child]; i := child; child := (i*2)+1; end; bubbleUp(i, node); end; end.
unit f05_peminjaman; interface uses csv_parser, buku_handler, utilitas, user_handler, peminjaman_handler, tipe_data; { DEKLARASI FUNGSI DAN PROSEDUR } procedure simpan_ke_array(temp: peminjaman; var data_peminjaman: tabel_peminjaman); procedure pinjam(var data_peminjaman: tabel_peminjaman; var data_buku: tabel_buku; username: string); { IMPLEMENTASI FUNGSI DAN PROSEDUR } implementation procedure simpan_ke_array(temp: peminjaman; var data_peminjaman: tabel_peminjaman); { DESKRIPSI : prosedur untuk menyimpan peminjaman baru ke data peminjaman } { PARAMETER : temp bertipe peminjaman, data_peminjaman bertipe tabel_peminjaman } begin data_peminjaman.t[data_peminjaman.sz] := temp; data_peminjaman.sz := data_peminjaman.sz+1; end; procedure pinjam(var data_peminjaman: tabel_peminjaman; var data_buku: tabel_buku; username: string); { DESKRIPSI : prosedur untuk meminjam buku } { PARAMETER : data_peminjaman bertipe tabel_peminjaman, data_buku bertipe tabel_peminjaman, dan username bertipe string } { KAMUS LOKAL } var id, tanggal: string; i: integer; peminjaman_temp: peminjaman; { ALGORITMA } begin write('Masukkan id buku yang ingin dipinjam: '); readln(id); i := findID(data_buku, id); { VALIDASI OPSIONAL } if(i <> -1) then // Jika buku tersebut tidak ada di perpustakaan begin write('Masukkan tanggal hari ini: '); readln(tanggal); if (StringToInt(data_buku.t[i].Jumlah_Buku) > 0) then begin peminjaman_temp.Username := username; peminjaman_temp.ID_Buku := id; peminjaman_temp.Tanggal_Peminjaman := tanggal; peminjaman_temp.Tanggal_Batas_Pengembalian := TambahDenda(tanggal); peminjaman_temp.Status_Pengembalian := 'False'; writeln('Buku ',data_buku.t[i].Judul_Buku ,' berhasil dipinjam!'); writeln('Tersisa ', StringToInt(data_buku.t[i].Jumlah_Buku)-1 ,' buku ',data_buku.t[i].Judul_Buku); writeln('Terima kasih sudah meminjam'); //update jumlah pada array buku data_buku.t[i].Jumlah_Buku := IntToString(StringToInt(data_buku.t[i].Jumlah_Buku)-1); simpan_ke_array(peminjaman_temp, data_peminjaman); end else //jumlah =0 begin writeln('Buku ', data_buku.t[i].Judul_Buku ,' sedang habis!'); writeln('Coba lain kali.'); end; end else writeln('Buku dengan ID tersebut tidak ada di perpustakan kami.') end; end.
{ Copyright (c) 2005-2006, Loginov Dmitry Sergeevich All rights reserved. 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 OWNER 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. } unit PolyFuncs; interface uses Matrix; const matGaluaErrorValue = 'Степень поля Галуа задана неверно'; matGaluaTableNotFound = 'Таблица Галуа не найдена'; matGaluaBadElem = 'Элементы поля Галуа заданы неверно'; {Генерация поля сложения или умножения} procedure GenerateGaluaTable(Ws: TWorkspace; TableName: string; Value: Integer; TabSum: Boolean = True); {Деление полиномов. Поддерживаются вычисления в конечных полях Галуа} procedure DivPolinoms(Ws: TWorkspace; DelimName, DelitName, ChastnName, OstatName: string; GaluaValue: Integer = 0; ClearGalua: Boolean = True); {Суммирование полиномов (можно в поле Галуа)} procedure SumPolinoms(Ws: TWorkspace; Pol1, Pol2, PolResult: string; GaluaValue: Integer = 0; ClearGalua: Boolean = True); {Умножение полиномов (можно в поле Галуа)} procedure MulPolinoms(Ws: TWorkspace; Pol1, Pol2, PolResult: string; GaluaValue: Integer = 0; ClearGalua: Boolean = True); {Простой сдвиг строк массива вправо или влево} function Shift(Ws: TWorkspace; SourAr, DestAr: string; Value: Integer; Rigth: Boolean = True): string; {Циклический сдвиг строк массива вправо или влево} function CirShift(Ws: TWorkspace; SourAr, DestAr: string; Value: Integer; Rigth: Boolean = True): string; implementation procedure GenerateGaluaTable(Ws: TWorkspace; TableName: string; Value: Integer; TabSum: Boolean = True); var Rows, Cols, I: Integer; TempRow: string; begin with Ws do begin if Value <= 1 then DoError(matGaluaErrorValue); CheckResAr(TableName); TempRow := GenName(); Rows := Value; Cols := Value; NewArray(TableName, Rows, Cols, True); if TabSum then NewArray(TempRow, 0, Value - 1, 1) else NewArray(TempRow, 1, Value - 1, 1); if TabSum then for I := 1 to Rows do begin PasteSubmatrix(TempRow, TableName, I, 1); CirShift(Ws, TempRow, TempRow, 1, False); end else for I := 2 to Rows do begin PasteSubmatrix(TempRow, TableName, I, 2); CirShift(Ws, TempRow, TempRow, 1, False); end; Clear(TempRow); end; end; function GetGaluaVal(Ws: TWorkspace; TableName: string; Val1, Val2: Real): Real; var Galua, Cols, Rows, Value1, Value2: Integer; begin with Ws do begin if TableName = '+' then Result := Val1 + Val2 else if TableName = '*' then Result := Val1 * Val2 else begin if Find(TableName) = -1 then DoError(matGaluaTableNotFound); Value1 := Round(Val1); Value2 := Round(Val2); GetSize(TableName, Rows, Cols); if Cols <> Rows then DoError(matGaluaTableNotFound); Galua := Cols; if (Value1 < 0) or (Value1 >= Galua) or (Value2 < 0) or (Value2 >= Galua) then DoError(matGaluaBadElem); Result := Elem[TableName, Value1 + 1, Value2 + 1]; end; end; end; procedure DivPolinoms(Ws: TWorkspace; DelimName, DelitName, ChastnName, OstatName: string; GaluaValue: Integer = 0; ClearGalua: Boolean = True); var J: Integer; StDelim, StDelit, StChastn, PosOstat: Integer; KoefChastn, NeedValue: Real; Delimoe, Delitel, SumTable, MulTable: string; iDelimoe, iDelitel, iChastnName, iOstatName: Integer; function Stepen(VektorName: string): Integer; var I, Cols, Ind: Integer; begin with Ws do begin Ind := GetIndex(VektorName); Cols := GetCols(Ind); Result := -1; for I := Cols downto 1 do if ElemI[Ind, 1, I] <> 0 then begin Result := I - 1; Exit; end; end; end; // function Stepen function FindGalua(TableName: string; Index, Value: Real): Real; var I, Cols: Integer; begin with Ws do begin Cols := GetCols(TableName); if GetRows(TableName) <> Cols then DoError(matGaluaTableNotFound); Result := -1; for I := 1 to Cols do if Round(Elem[TableName, I, Round(Index) + 1]) = Round(Value) then begin Result := I - 1; Exit; end; end; end; // function FindGalua begin with Ws do begin CheckResAr(ChastnName, False); CheckResAr(OstatName, False); Delimoe := GenName(); Delitel := GenName(); SumTable := GenName('SumTable'); MulTable := GenName('MulTable'); if (GetRows(DelimName) > 1) or (GetRows(DelitName) > 1) then DoError(matIsNotVektor); if (GaluaValue = 1) or (GaluaValue < 0) then DoError(matGaluaErrorValue); if Stepen(DelimName) <> -1 then if Stepen(DelitName) > Stepen(DelimName) then begin CopyArray(DelimName, OstatName); NewArray(ChastnName, 1, 1, True); CopySubmatrix(OstatName, OstatName, 1, 1, 1, Stepen(OstatName) + 1); Exit; end; if Stepen(DelitName) = -1 then DoError(matDivsionByZero) else if Stepen(DelimName) = -1 then begin Resize(ChastnName, 1, 1); Elem[ChastnName, 1, 1] := 0; Resize(OstatName, 1, 1); Elem[OstatName, 1, 1] := 0; end else begin //Генерируем таблицы Галуа if GaluaValue > 1 then begin if (Find(SumTable) = -1) or (GetCols(SumTable) <> GaluaValue) or (GetRows(SumTable) <> GaluaValue) then GenerateGaluaTable(Ws, SumTable, GaluaValue, True); // Таблица сложения if (Find(MulTable) = -1) or (GetCols(MulTable) <> GaluaValue) or (GetRows(MulTable) <> GaluaValue) then GenerateGaluaTable(Ws, MulTable, GaluaValue, False); // Таблица умножения end; // Копируем делимое во временную переменную CopySubmatrix(DelimName, Delimoe, 1, 1, 1, Stepen(DelimName) + 1); IDelimoe := GetIndex(Delimoe); // Копируем делитель во временную переменную CopySubmatrix(DelitName, Delitel, 1, 1, 1, Stepen(DelitName) + 1); iDelitel := GetIndex(Delitel); // Создаем массив частного IChastnName := NewArray(ChastnName, 1, Stepen(DelimName) - Stepen(DelitName) + 1, True); // Начинаем цикл деления while true do begin StDelim := Stepen(Delimoe); StDelit := Stepen(Delitel); if StDelit > StDelim then DoError('Степень делителя оказалась больше, чем степень делимого'); StChastn := StDelim - StDelit; // Определяем, какое число нужно в вычитании, чтобы получить ноль if GaluaValue > 1 then begin NeedValue := FindGalua(SumTable, ElemI[IDelimoe, 1, StDelim + 1], 0); KoefChastn := FindGalua(MulTable, ElemI[IDelitel, 1, StDelit + 1], NeedValue); end else KoefChastn := ElemI[IDelimoe, 1, StDelim + 1] / ElemI[IDelitel, 1, StDelit + 1]; // Помещаем найденное значение в массив частного ElemI[IChastnName, 1, StChastn + 1] := KoefChastn; // Создаем нулевой массив OstatName IOstatName := NewArray(OstatName, 1, StDelim + 1, True); // Заполняем этот массив for J := 1 to StDelit + 1 do begin PosOstat := StChastn + J; if GaluaValue > 1 then ElemI[IOstatName, 1, PosOstat] := GetGaluaVal(Ws, MulTable, KoefChastn, ElemI[IDelitel, 1, J]) else ElemI[IOstatName, 1, PosOstat] := KoefChastn * ElemI[IDelitel, 1, J]; end; // Производим вычитание for J := 1 to StDelim + 1 do begin if GaluaValue > 1 then ElemI[IOstatName, 1, J] := GetGaluaVal(Ws, SumTable, ElemI[IDelimoe, 1, J], ElemI[IOstatName, 1, J]) else ElemI[IOstatName, 1, J] := ElemI[IDelimoe, 1, J] - ElemI[IOstatName, 1, J]; end; if Stepen(OstatName) < 0 then NewArray(OstatName, 1, 1, True) else Resize(OstatName, 1, Stepen(OstatName) + 1); // Формируем делимое из остатка // Если степень остатка меньше степени частного, то выход if Stepen(OstatName) < Stepen(Delitel) then Break; CopySubmatrix(OstatName, Delimoe, 1, 1, 1, Stepen(OstatName) + 1); end; end; Clear(Delimoe); Clear(Delitel); if ClearGalua then begin Clear(SumTable); Clear(MulTable); end; end; end; // procedure DivPolinoms procedure SumPolinoms(Ws: TWorkspace; Pol1, Pol2, PolResult: string; GaluaValue: Integer = 0; ClearGalua: Boolean = True); var Len, I, MinLen, St: Integer; MaxPol, SumTable, TempRes: string; Ind1, Ind2, IndRes: Integer; begin with Ws do begin CheckResAr(PolResult); SumTable := GenName('SumTable'); TempRes := GenName(); Ind1 := GetIndex(Pol1); Ind2 := GetIndex(Pol2); if (GetRows(Ind1) > 1) or (GetRows(Ind2) > 1) then DoError(matIsNotVektor); if (GaluaValue = 1) or (GaluaValue < 0) then DoError(matGaluaErrorValue); if GaluaValue > 1 then if (Find(SumTable) = -1) or (GetCols(SumTable) <> GaluaValue) or (GetRows(SumTable) <> GaluaValue) then GenerateGaluaTable(Ws, SumTable, GaluaValue, True); // Таблица сложения Len := GetCols(Ind1); MinLen := GetCols(Ind2); MaxPol := Pol1; if GetCols(Ind2) > GetCols(Ind1) then begin Len := MinLen; MinLen := GetCols(Ind1); MaxPol := Pol2; end; // Создаем временный результирующий массив IndRes := NewArray(TempRes, 1, Len, True); if GaluaValue = 0 then begin for I := 1 to MinLen do ElemI[IndRes, 1, I] := ElemI[Ind1, 1, I] + ElemI[Ind2, 1, I]; for I := MinLen + 1 to Len do ElemI[IndRes, 1, I] := Elem[MaxPol, 1, I]; end else begin for I := 1 to MinLen do ElemI[IndRes, 1, I] := GetGaluaVal(Ws, SumTable, ElemI[Ind1, 1, I], ElemI[Ind2, 1, I]); for I := MinLen + 1 to Len do ElemI[IndRes, 1, I] := GetGaluaVal(Ws, SumTable, Elem[MaxPol, 1, I], 0); end; // Определяем степень полученного многочлена St := 0; for I := Len downto 1 do if ElemI[IndRes, 1, I] <> 0 then begin St := I; Break; end; if St > 0 then CopySubmatrix(TempRes, TempRes, 1, 1, 1, St) else NewArray(TempRes, 1, 1, True); RenameArray(TempRes, PolResult); if ClearGalua then Clear(SumTable); end; end; procedure MulPolinoms(Ws: TWorkspace; Pol1, Pol2, PolResult: string; GaluaValue: Integer = 0; ClearGalua: Boolean = True); var I, J, Cols1, Cols2, ColsRes, St: Integer; Tmp1, Tmp2: Real; SumTable, MulTable, TempRes: string; IndRes, Ind1, Ind2: Integer; begin with Ws do begin CheckResAr(PolResult); TempRes := GenName; SumTable := GenName('SumTable'); MulTable := GenName('MulTable'); Ind1 := GetIndex(Pol1); Ind2 := GetIndex(Pol2); if (GetRows(Ind1) > 1) or (GetRows(Ind2) > 1) then DoError(matIsNotVektor); if (GaluaValue = 1) or (GaluaValue < 0) then DoError(matGaluaErrorValue); if GaluaValue > 1 then begin if (Find(SumTable) = -1) or (GetCols(SumTable) <> GaluaValue) or (GetRows(SumTable) <> GaluaValue) then GenerateGaluaTable(Ws, SumTable, GaluaValue, True); // Таблица сложения if (Find(MulTable) = -1) or (GetCols(MulTable) <> GaluaValue) or (GetRows(MulTable) <> GaluaValue) then GenerateGaluaTable(Ws, MulTable, GaluaValue, False); // Таблица сложения end; Cols1 := GetCols(Ind1); Cols2 := GetCols(Ind2); // Определяем число элементов рез. вектора ColsRes := Cols1 + Cols2 - 1; IndRes := NewArray(TempRes, 1, ColsRes, True); if GaluaValue = 0 then for I := Cols2 downto 1 do begin Tmp2 := ElemI[Ind2, 1, I]; for J := Cols1 downto 1 do begin Tmp1 := ElemI[Ind1, 1, J]; if (Tmp2 <> 0) and (Tmp1 <> 0) then ElemI[IndRes, 1, I + J - 1] := ElemI[IndRes, 1, I + J - 1] + Tmp1 * Tmp2; end; end; if GaluaValue > 1 then for I := Cols2 downto 1 do begin Tmp2 := ElemI[Ind2, 1, I]; for J := Cols1 downto 1 do begin Tmp1 := ElemI[Ind1, 1, J]; if (Tmp2 <> 0) and (Tmp1 <> 0) then ElemI[IndRes, 1, I + J - 1] := GetGaluaVal(Ws, SumTable, ElemI[IndRes, 1, I + J - 1], GetGaluaVal(Ws, MulTable, Tmp1, Tmp2)); end; end; // Обрезаем лишние нули St := 0; for I := ColsRes downto 1 do if ElemI[IndRes, 1, I] <> 0 then begin St := I; Break; end; if St > 0 then CopySubmatrix(TempRes, TempRes, 1, 1, 1, St) else NewArray(TempRes, 1, 1, True); RenameArray(TempRes, PolResult); if ClearGalua then begin Clear(SumTable); Clear(MulTable); end; end; end; function Shift(Ws: TWorkspace; SourAr, DestAr: string; Value: Integer; Rigth: Boolean = True): string; var Rows, Cols, CopyColCnt: Integer; Submatrix, TempRes: string; begin with Ws do begin Result := CheckResAr(DestAr); GetSize(SourAr, Rows, Cols); Submatrix := GenName(); TempRes := GenName(); Value := abs(Value); CopyColCnt := Cols - Value; if CopyColCnt < 1 then NewArray(TempRes, Rows, Cols, True) else if Rigth then begin CopySubmatrix(SourAr, Submatrix, 1, Rows, 1, CopyColCnt); Clear(DestAr); PasteSubmatrix(Submatrix, TempRes, 1, Value + 1); end else begin CopySubmatrix(SourAr, Submatrix, 1, Rows, Value + 1, CopyColCnt); NewArray(TempRes, Rows, Cols, True); PasteSubmatrix(Submatrix, TempRes, 1, 1); end; RenameArray(TempRes, DestAr); Clear(Submatrix); end; end; function CirShift(Ws: TWorkspace; SourAr, DestAr: string; Value: Integer; Rigth: Boolean = True): string; var I, ShiftCount: Integer; Rows, Cols: Integer; Submatrix1, Submatrix2, TempRes: string; begin with Ws do begin Result := CheckResAr(DestAr); GetSize(SourAr, Rows, Cols); Submatrix1 := GenName; Submatrix2 := GenName; TempRes := GenName; CopyArray(SourAr, TempRes); Value := abs(Value); ShiftCount := Value mod Cols; if not Rigth then ShiftCount := Cols - ShiftCount; if (Cols > 1) then for I := 1 to ShiftCount do begin Clear(Submatrix1); CopySubmatrix(TempRes, Submatrix1, 1, Rows, 1, Cols - 1); Clear(Submatrix2); CopySubmatrix(TempRes, Submatrix2, 1, Rows, Cols, 1); PasteSubmatrix(Submatrix2, TempRes, 1, 1); PasteSubmatrix(Submatrix1, TempRes, 1, 2); end; RenameArray(TempRes, DestAr); Clear(Submatrix1); Clear(Submatrix2); end; end; end.
unit SearchStorehouseProduct; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap; type TSearchStoreHouseProductW = class(TDSWrap) private FProductID: TFieldWrap; FID: TFieldWrap; FIDComponentGroup: TFieldWrap; FAmount: TFieldWrap; FStorehouseID: TFieldWrap; public constructor Create(AOwner: TComponent); override; property ProductID: TFieldWrap read FProductID; property ID: TFieldWrap read FID; property IDComponentGroup: TFieldWrap read FIDComponentGroup; property Amount: TFieldWrap read FAmount; property StorehouseID: TFieldWrap read FStorehouseID; end; TQuerySearchStorehouseProduct = class(TQueryBase) procedure FDQueryUpdateError(ASender: TDataSet; AException: EFDException; ARow: TFDDatSRow; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction); private FW: TSearchStoreHouseProductW; { Private declarations } public constructor Create(AOwner: TComponent); override; function SearchByGroupID(AStorehouseID, AIDComponentGroup: Integer) : Integer; function SearchByID(AID: Integer): Integer; function SearchByProductID(AProductID: Integer): Integer; property W: TSearchStoreHouseProductW read FW; { Public declarations } end; implementation {$R *.dfm} uses StrHelper, FireDAC.Phys.SQLiteWrapper; constructor TQuerySearchStorehouseProduct.Create(AOwner: TComponent); begin inherited; FW := TSearchStoreHouseProductW.Create(FDQuery); end; procedure TQuerySearchStorehouseProduct.FDQueryUpdateError(ASender: TDataSet; AException: EFDException; ARow: TFDDatSRow; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction); var AE: ESQLiteNativeException; begin inherited; if not (AException is ESQLiteNativeException) then Exit; AE := AException as ESQLiteNativeException; //UNIQUE constraint failed if AE.ErrorCode = 2067 then AException.Message := 'Строка(и) уже сохранена(ы) на складе'; end; function TQuerySearchStorehouseProduct.SearchByGroupID(AStorehouseID, AIDComponentGroup: Integer): Integer; begin Assert(AStorehouseID > 0); Assert(AIDComponentGroup > 0); Result := SearchEx([TParamRec.Create(W.StorehouseID.FullName, AStorehouseID), TParamRec.Create(W.IDComponentGroup.FullName, AIDComponentGroup)]); end; function TQuerySearchStorehouseProduct.SearchByID(AID: Integer): Integer; begin Assert(AID > 0); Result := SearchEx([TParamRec.Create(W.ID.FullName, AID)]); end; function TQuerySearchStorehouseProduct.SearchByProductID (AProductID: Integer): Integer; begin Assert(AProductID > 0); Result := SearchEx([TParamRec.Create(W.ProductID.FullName, AProductID)]); end; constructor TSearchStoreHouseProductW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FProductID := TFieldWrap.Create(Self, 'ProductID'); FStorehouseID := TFieldWrap.Create(Self, 'StorehouseID'); FIDComponentGroup := TFieldWrap.Create(Self, 'IDComponentGroup'); FAmount := TFieldWrap.Create(Self, 'Amount'); end; end.
unit Buf.History; interface uses Vcl.Graphics, System.DateUtils, System.Classes, SQLite3, SQLiteTable3, SQLLang, HGM.Controls.VirtualTable; type THistoryFormat = (hfText, hfImage, hfList, hfOther); THistoryItem = record private FID: Integer; FFormat: THistoryFormat; FDate: TDate; FTime: TTime; FDesc: string; procedure SetDate(const Value: TDate); procedure SetDesc(const Value: string); procedure SetFormat(const Value: THistoryFormat); procedure SetID(const Value: Integer); procedure SetTime(const Value: TTime); public property ID: Integer read FID write SetID; property Date: TDate read FDate write SetDate; property Time: TTime read FTime write SetTime; property Desc: string read FDesc write SetDesc; property Format: THistoryFormat read FFormat write SetFormat; end; THistory = class(TTableData<THistoryItem>) const tnHistory = 'HISTORY'; fnID = 'HI_ID'; fnFormat = 'HI_FORMAT'; fnDate = 'HI_DATE'; fnTime = 'HI_TIME'; fnDesc = 'HI_DESC'; fnData = 'HI_DATA'; private FDB: TSQLiteDatabase; public procedure Reload(Date: TDate; DescFilter: string); procedure DropTable; function Insert(var Item: THistoryItem; Image: TBitmap): Integer; overload; function Insert(var Item: THistoryItem; Text: string): Integer; overload; function Insert(var Item: THistoryItem; Files: TStringList): Integer; overload; constructor Create(AOwner: TTableEx; ADB: TSQLiteDatabase); overload; function GetImage(ID: Integer): TBitmap; function GetText(ID: Integer): string; property DB: TSQLiteDatabase read FDB; end; implementation { THistoryItem } procedure THistoryItem.SetDate(const Value: TDate); begin FDate := Value; end; procedure THistoryItem.SetDesc(const Value: string); begin FDesc := Value; end; procedure THistoryItem.SetFormat(const Value: THistoryFormat); begin FFormat := Value; end; procedure THistoryItem.SetID(const Value: Integer); begin FID := Value; end; procedure THistoryItem.SetTime(const Value: TTime); begin FTime := Value; end; { THistory } constructor THistory.Create(AOwner: TTableEx; ADB: TSQLiteDatabase); begin inherited Create(AOwner); FDB := ADB; if not FDB.TableExists(tnHistory) then begin with SQL.CreateTable(tnHistory) do begin AddField(fnID, ftInteger, True, True); AddField(fnDesc, ftString); AddField(fnFormat, ftInteger); AddField(fnDate, ftDateTime); AddField(fnTime, ftDateTime); AddField(fnData, ftBlob); FDB.ExecSQL(GetSQL); EndCreate; end; end; end; procedure THistory.DropTable; begin with SQL.Delete(tnHistory) do begin FDB.ExecSQL(GetSQL); EndCreate; end; Clear; end; function THistory.GetImage(ID: Integer): TBitmap; var Table: TSQLiteTable; Mem: TMemoryStream; begin with SQL.Select(tnHistory) do begin AddField(fnData); WhereFieldEqual(fnID, ID); Table := FDB.GetTable(GetSQL); if Table.RowCount > 0 then begin Mem := Table.FieldAsBlob(0); Mem.Position := 0; Result := TBitmap.Create; Result.LoadFromStream(Mem); end; Table.Free; EndCreate; end; end; function THistory.GetText(ID: Integer): string; var Table: TSQLiteTable; Mem: TStringStream; begin with SQL.Select(tnHistory) do begin AddField(fnData); WhereFieldEqual(fnID, ID); Table := FDB.GetTable(GetSQL); if Table.RowCount > 0 then begin Mem := TStringStream.Create; Mem.LoadFromStream(Table.FieldAsBlob(0)); Mem.Position := 0; Result := Mem.DataString; Mem.Free; end; Table.Free; EndCreate; end; end; function THistory.Insert(var Item: THistoryItem; Image: TBitmap): Integer; var Mem: TMemoryStream; begin with SQL.InsertInto(tnHistory) do begin AddValue(fnDesc, Item.Desc); AddValue(fnDate, DateOf(Item.Date)); AddValue(fnTime, TimeOf(Item.Time)); AddValue(fnFormat, Ord(hfImage)); FDB.ExecSQL(GetSQL); Item.Format := hfImage; Item.ID := FDB.GetLastInsertRowID; EndCreate; end; with SQl.UpdateBlob(tnHistory) do begin BlobField := fnData; WhereFieldEqual(fnID, Item.ID); Mem := TMemoryStream.Create; Image.SaveToStream(Mem); FDB.UpdateBlob(GetSQL, Mem); Mem.Free; EndCreate; end; inherited Insert(0, Item); Result := 0; end; function THistory.Insert(var Item: THistoryItem; Text: string): Integer; var Mem: TStringStream; begin with SQL.InsertInto(tnHistory) do begin AddValue(fnDesc, Item.Desc); AddValue(fnDate, DateOf(Item.Date)); AddValue(fnTime, TimeOf(Item.Time)); AddValue(fnFormat, Ord(hfText)); FDB.ExecSQL(GetSQL); Item.Format := hfText; Item.ID := FDB.GetLastInsertRowID; EndCreate; end; with SQl.UpdateBlob(tnHistory) do begin BlobField := fnData; WhereFieldEqual(fnID, Item.ID); Mem := TStringStream.Create(Text); FDB.UpdateBlob(GetSQL, Mem); Mem.Free; EndCreate; end; inherited Insert(0, Item); Result := 0; end; function THistory.Insert(var Item: THistoryItem; Files: TStringList): Integer; var Mem: TStringStream; begin with SQL.InsertInto(tnHistory) do begin AddValue(fnDesc, Item.Desc); AddValue(fnDate, DateOf(Item.Date)); AddValue(fnTime, TimeOf(Item.Time)); AddValue(fnFormat, Ord(hfList)); FDB.ExecSQL(GetSQL); Item.Format := hfList; Item.ID := FDB.GetLastInsertRowID; EndCreate; end; with SQl.UpdateBlob(tnHistory) do begin BlobField := fnData; WhereFieldEqual(fnID, Item.ID); Mem := TStringStream.Create(Files.Text); FDB.UpdateBlob(GetSQL, Mem); Mem.Free; EndCreate; end; inherited Insert(0, Item); Result := 0; end; procedure THistory.Reload(Date: TDate; DescFilter: string); var Table: TSQLiteTable; Item: THistoryItem; begin BeginUpdate; Clear; with SQL.Select(tnHistory) do begin AddField(fnID); AddField(fnFormat); AddField(fnDate); AddField(fnTime); AddField(fnDesc); WhereFieldEqual(fnDate, DateOf(Date)); if DescFilter <> '' then WhereFieldLike(fnDesc, '%'+DescFilter+'%'); OrderBy(fnTime, True); Table := FDB.GetTable(GetSQL); EndCreate; while not Table.EOF do begin Item.ID := Table.FieldAsInteger(0); Item.Format := THistoryFormat(Table.FieldAsInteger(1)); Item.Date := DateOf(Table.FieldAsDateTime(2)); Item.Time := TimeOf(Table.FieldAsDateTime(3)); Item.Desc := Table.FieldAsString(4); Add(Item); Table.Next; end; Table.Free; end; EndUpdate; end; end.
unit FIToolkit.Reports.Builder.HTML; interface uses System.Classes, System.SysUtils, System.RegularExpressions, Xml.XMLIntf, FIToolkit.Reports.Builder.Intf, FIToolkit.Reports.Builder.Types; type THTMLReportBuilder = class (TInterfacedObject, IReportBuilder, ITemplatableTextReport) strict private FOutput : TStream; FOwnsOutput : Boolean; FTemplate : ITextReportTemplate; private function Encode(const Value : String) : String; function ExcludeClosingTag(const TemplateElement : String) : String; function ExtractClosingTag(const TemplateElement : String) : String; function FindClosingTag(const TemplateElement : String; out ClosingTag : TMatch) : Boolean; function GenerateHTMLHead : String; procedure WriteLine(const Text : String); public constructor Create(Output : TStream; OwnsOutput : Boolean = False); destructor Destroy; override; procedure AddFooter(FinishTime : TDateTime); procedure AddHeader(const Title : String; StartTime : TDateTime); procedure AddTotalSummary(const Items : array of TSummaryItem); procedure AppendRecord(Item : TReportRecord); procedure BeginProjectSection(const Title : String; const ProjectSummary : array of TSummaryItem); procedure BeginReport; procedure EndProjectSection; procedure EndReport; procedure SetTemplate(const Template : ITextReportTemplate); end; IHTMLReportTemplate = interface (ITextReportTemplate) ['{C2CC3425-2FEC-4F41-A122-9FA3F8CC16D5}'] function GetCSS : String; function GetJavaScript : String; end; THTMLReportTemplate = class abstract (TInterfacedObject, IHTMLReportTemplate) strict private FCSS, FFooterElement, FHeaderElement, FJavaScript, FMessageElement, FProjectMessagesElement, FProjectSectionElement, FProjectSummaryElement, FProjectSummaryItemElement, FTotalSummaryElement, FTotalSummaryItemElement : String; private procedure Parse(const TemplateSource : IXMLDocument); protected constructor Create(XMLStream : TStream); public function GetCSS : String; function GetFooterElement : String; function GetHeaderElement : String; function GetJavaScript : String; function GetMessageElement : String; function GetProjectMessagesElement : String; function GetProjectSectionElement : String; function GetProjectSummaryElement : String; function GetProjectSummaryItemElement : String; function GetTotalSummaryElement : String; function GetTotalSummaryItemElement : String; end; THTMLReportCustomTemplate = class (THTMLReportTemplate) public constructor Create(const FileName : TFileName); end; THTMLReportDefaultTemplate = class (THTMLReportTemplate) public constructor Create; end; implementation uses System.Types, System.IOUtils, System.NetEncoding, Xml.XMLDoc, Winapi.ActiveX, FIToolkit.Reports.Builder.Exceptions, FIToolkit.Reports.Builder.Consts, FIToolkit.Commons.Utils; { THTMLReportBuilder } procedure THTMLReportBuilder.AddFooter(FinishTime : TDateTime); begin WriteLine( FTemplate.GetFooterElement .Replace(STR_HTML_FINISH_TIME, Encode(DateTimeToStr(FinishTime))) ); end; procedure THTMLReportBuilder.AddHeader(const Title : String; StartTime : TDateTime); begin WriteLine( FTemplate.GetHeaderElement .Replace(STR_HTML_REPORT_TITLE, Encode(Title)) .Replace(STR_HTML_START_TIME, Encode(DateTimeToStr(StartTime))) ); end; procedure THTMLReportBuilder.AddTotalSummary(const Items : array of TSummaryItem); var sSummaryItem, sAllSummaryItems : String; Item : TSummaryItem; begin for Item in Items do begin sSummaryItem := FTemplate.GetTotalSummaryItemElement .Replace(STR_HTML_SUMMARY_MESSAGE_TYPE_KEYWORD, Encode(Item.MessageTypeKeyword)) .Replace(STR_HTML_SUMMARY_MESSAGE_TYPE_NAME, Encode(Item.MessageTypeName)) .Replace(STR_HTML_SUMMARY_MESSAGE_COUNT, Encode(Item.MessageCount.ToString)); sAllSummaryItems := Iff.Get<String>( sAllSummaryItems.IsEmpty, sSummaryItem, sAllSummaryItems + sLineBreak + sSummaryItem); end; WriteLine( FTemplate.GetTotalSummaryElement .Replace(STR_HTML_TOTAL_SUMMARY_ITEMS, sAllSummaryItems) ); end; procedure THTMLReportBuilder.AppendRecord(Item : TReportRecord); begin WriteLine( FTemplate.GetMessageElement .Replace(STR_HTML_MESSAGE_TYPE_KEYWORD, Encode(Item.MessageTypeKeyword)) .Replace(STR_HTML_FILE_NAME, Encode(Item.FileName)) .Replace(STR_HTML_LINE, Encode(Item.Line.ToString)) .Replace(STR_HTML_COLUMN, Encode(Item.Column.ToString)) .Replace(STR_HTML_MESSAGE_TYPE_NAME, Encode(Item.MessageTypeName)) .Replace(STR_HTML_MESSAGE_TEXT, Encode(Item.MessageText)) .Replace(STR_HTML_SNIPPET, Encode(Item.Snippet)) ); end; procedure THTMLReportBuilder.BeginProjectSection(const Title : String; const ProjectSummary : array of TSummaryItem); var sSummaryItem, sAllSummaryItems, sSummary : String; Item : TSummaryItem; begin for Item in ProjectSummary do begin sSummaryItem := FTemplate.GetProjectSummaryItemElement .Replace(STR_HTML_SUMMARY_MESSAGE_TYPE_KEYWORD, Encode(Item.MessageTypeKeyword)) .Replace(STR_HTML_SUMMARY_MESSAGE_TYPE_NAME, Encode(Item.MessageTypeName)) .Replace(STR_HTML_SUMMARY_MESSAGE_COUNT, Encode(Item.MessageCount.ToString)); sAllSummaryItems := Iff.Get<String>( sAllSummaryItems.IsEmpty, sSummaryItem, sAllSummaryItems + sLineBreak + sSummaryItem); end; sSummary := FTemplate.GetProjectSummaryElement.Replace(STR_HTML_PROJECT_SUMMARY_ITEMS, sAllSummaryItems); WriteLine( ExcludeClosingTag(FTemplate.GetProjectSectionElement) .Replace(STR_HTML_PROJECT_TITLE, Encode(Title)) .Replace(STR_HTML_PROJECT_SUMMARY, sSummary) ); WriteLine(ExcludeClosingTag(FTemplate.GetProjectMessagesElement)); end; procedure THTMLReportBuilder.BeginReport; begin WriteLine('<!DOCTYPE html>'); WriteLine('<html>'); WriteLine(GenerateHTMLHead); WriteLine('<body>'); WriteLine('<div id="' + STR_HTML_REPORT_ROOT_ID + '">'); end; constructor THTMLReportBuilder.Create(Output : TStream; OwnsOutput : Boolean); begin inherited Create; FOutput := Output; FOwnsOutput := OwnsOutput; end; destructor THTMLReportBuilder.Destroy; begin if FOwnsOutput then FreeAndNil(FOutput); inherited Destroy; end; function THTMLReportBuilder.Encode(const Value : String) : String; begin Result := TNetEncoding.HTML.Encode(Value); end; procedure THTMLReportBuilder.EndProjectSection; begin WriteLine(ExtractClosingTag(FTemplate.GetProjectMessagesElement)); WriteLine(ExtractClosingTag(FTemplate.GetProjectSectionElement)); end; procedure THTMLReportBuilder.EndReport; begin WriteLine('</div>'); WriteLine('</body>'); WriteLine('</html>'); end; function THTMLReportBuilder.ExcludeClosingTag(const TemplateElement : String) : String; var ClosingTag : TMatch; begin Result := TemplateElement; if FindClosingTag(Result, ClosingTag) then Delete(Result, ClosingTag.Index, ClosingTag.Length); end; function THTMLReportBuilder.ExtractClosingTag(const TemplateElement : String) : String; var ClosingTag : TMatch; begin if FindClosingTag(TemplateElement, ClosingTag) then Result := Copy(TemplateElement, ClosingTag.Index, ClosingTag.Length) else Result := String.Empty; end; function THTMLReportBuilder.FindClosingTag(const TemplateElement : String; out ClosingTag : TMatch) : Boolean; var AllClosingTags : TMatchCollection; begin Result := False; AllClosingTags := TRegEx.Matches(TemplateElement, '<\/[a-z0-9]*>', [roIgnoreCase]); if AllClosingTags.Count > 0 then begin ClosingTag := AllClosingTags[AllClosingTags.Count-1]; Exit(True); end; end; function THTMLReportBuilder.GenerateHTMLHead : String; var HTMLTemplate : IHTMLReportTemplate; begin Result := '<head>' + sLineBreak + '<meta charset="UTF-8">' + sLineBreak + '<title>' + Encode(RSReportTitle) + '</title>' + sLineBreak; if Supports(FTemplate, IHTMLReportTemplate, HTMLTemplate) then begin Result := Result + '<style>' + sLineBreak + HTMLTemplate.GetCSS + sLineBreak + '</style>' + sLineBreak; Result := Result + '<script type="text/javascript">' + sLineBreak + HTMLTemplate.GetJavaScript + sLineBreak + '</script>' + sLineBreak; end; Result := Result + '</head>'; end; procedure THTMLReportBuilder.SetTemplate(const Template : ITextReportTemplate); begin if Assigned(Template) then FTemplate := Template else raise EInvalidReportTemplate.Create; end; procedure THTMLReportBuilder.WriteLine(const Text : String); var TextBytes : TBytes; begin TextBytes := TEncoding.UTF8.GetBytes(Text + sLineBreak); FOutput.WriteData(TextBytes, Length(TextBytes)); end; { THTMLReportTemplate } constructor THTMLReportTemplate.Create(XMLStream : TStream); var XML : IXMLDocument; begin inherited Create; XML := TXMLDocument.Create(nil); try XML.LoadFromStream(XMLStream); Parse(XML); except Exception.RaiseOuterException(EReportTemplateParseError.Create); end; end; function THTMLReportTemplate.GetCSS : String; begin Result := FCSS; end; function THTMLReportTemplate.GetFooterElement : String; begin Result := FFooterElement; end; function THTMLReportTemplate.GetHeaderElement : String; begin Result := FHeaderElement; end; function THTMLReportTemplate.GetJavaScript : String; begin Result := FJavaScript; end; function THTMLReportTemplate.GetMessageElement : String; begin Result := FMessageElement; end; function THTMLReportTemplate.GetProjectMessagesElement : String; begin Result := FProjectMessagesElement; end; function THTMLReportTemplate.GetProjectSectionElement : String; begin Result := FProjectSectionElement; end; function THTMLReportTemplate.GetProjectSummaryElement : String; begin Result := FProjectSummaryElement; end; function THTMLReportTemplate.GetProjectSummaryItemElement : String; begin Result := FProjectSummaryItemElement; end; function THTMLReportTemplate.GetTotalSummaryElement : String; begin Result := FTotalSummaryElement; end; function THTMLReportTemplate.GetTotalSummaryItemElement : String; begin Result := FTotalSummaryItemElement; end; procedure THTMLReportTemplate.Parse(const TemplateSource : IXMLDocument); var RootNode, TotalSummaryNode, ProjectSectionNode, ProjectSummaryNode, ProjectMessagesNode : IXMLNode; begin //FI:C101 RootNode := TemplateSource.Node.ChildNodes[STR_RPTXML_ROOT_NODE]; TotalSummaryNode := RootNode.ChildNodes[STR_RPTXML_TOTAL_SUMMARY_NODE]; ProjectSectionNode := RootNode.ChildNodes[STR_RPTXML_PROJECT_SECTION_NODE]; ProjectSummaryNode := ProjectSectionNode.ChildNodes[STR_RPTXML_PROJECT_SUMMARY_NODE]; ProjectMessagesNode := ProjectSectionNode.ChildNodes[STR_RPTXML_PROJECT_MESSAGES_NODE]; FCSS := RootNode .ChildNodes[STR_RPTXML_CSS_NODE].Text; FJavaScript := RootNode .ChildNodes[STR_RPTXML_JAVASCRIPT_NODE].Text; FHeaderElement := RootNode .ChildNodes[STR_RPTXML_HEADER_NODE] .ChildNodes[STR_RPTXML_ELEMENT_NODE].Text; FTotalSummaryElement := TotalSummaryNode .ChildNodes[STR_RPTXML_ELEMENT_NODE].Text; FTotalSummaryItemElement := TotalSummaryNode .ChildNodes[STR_RPTXML_TOTAL_SUMMARY_ITEM_NODE] .ChildNodes[STR_RPTXML_ELEMENT_NODE].Text; FProjectSectionElement := ProjectSectionNode .ChildNodes[STR_RPTXML_ELEMENT_NODE].Text; FProjectSummaryElement := ProjectSummaryNode .ChildNodes[STR_RPTXML_ELEMENT_NODE].Text; FProjectSummaryItemElement := ProjectSummaryNode .ChildNodes[STR_RPTXML_PROJECT_SUMMARY_ITEM_NODE] .ChildNodes[STR_RPTXML_ELEMENT_NODE].Text; FProjectMessagesElement := ProjectMessagesNode .ChildNodes[STR_RPTXML_ELEMENT_NODE].Text; FMessageElement := ProjectMessagesNode .ChildNodes[STR_RPTXML_MESSAGE_NODE] .ChildNodes[STR_RPTXML_ELEMENT_NODE].Text; FFooterElement := RootNode .ChildNodes[STR_RPTXML_FOOTER_NODE] .ChildNodes[STR_RPTXML_ELEMENT_NODE].Text; end; { THTMLReportCustomTemplate } constructor THTMLReportCustomTemplate.Create(const FileName : TFileName); var FS : TFileStream; begin try FS := TFile.Open(FileName, TFileMode.fmOpen, TFileAccess.faRead, TFileShare.fsRead); try inherited Create(FS); finally FS.Free; end; except Exception.RaiseOuterException(EReportTemplateLoadError.Create); end; end; { THTMLReportDefaultTemplate } constructor THTMLReportDefaultTemplate.Create; var RS : TResourceStream; begin try RS := TResourceStream.Create(HInstance, STR_RES_HTML_REPORT_DEFAULT_TEMPLATE, RT_RCDATA); try inherited Create(RS); finally RS.Free; end; except Exception.RaiseOuterException(EReportTemplateLoadError.Create); end; end; initialization CoInitialize(nil); finalization CoUninitialize; end.
unit uDependenteDAO; interface uses System.Classes, SysUtils, Data.SqlExpr, uDependente, uDM, uDMClient; type TDependenteDAO = class private FSQL: TSQLQuery; public procedure Salvar(const ADependente: TDependente; const AEmTransacao: boolean = false); end; implementation { TDependenteDAO } procedure TDependenteDAO.Salvar(const ADependente: TDependente; const AEmTransacao: boolean = false); var iIdDependente: Integer; begin try FSQL := TSQLQuery.Create(nil); FSQL.SQLConnection := DM.SQLConnection; FSQL.CommandText := ''; if not AEmTransacao then DM.IniciarTransacao; iIdDependente := DMClient.GerarIDTabela('DEPENDENTE'); try FSQL.SQL.Add ('Insert into DEPENDENTE ( ID_DEPENDENTE, NOME, IS_CALCULAR_IR, IS_CALCULAR_INSS, ID_FUNCIONARIO)'); FSQL.SQL.Add('VALUES (:id, :nome, :calc_ir, :calc_inss, :id_func) '); FSQL.Params.ParamByName('id').AsInteger := iIdDependente; FSQL.Params.ParamByName('nome').AsString := ADependente.Nome; if ADependente.IsCalculaIR then FSQL.Params.ParamByName('calc_ir').AsSmallint := 1 else FSQL.Params.ParamByName('calc_ir').AsSmallint := 0; if ADependente.IsCalculaINSS then FSQL.Params.ParamByName('calc_inss').AsSmallint := 1 else FSQL.Params.ParamByName('calc_inss').AsSmallint := 0; FSQL.Params.ParamByName('id_func').AsINteger := ADependente.Id_Funcionario; FSQL.ExecSQL; finally FSQL.Free; if not AEmTransacao then DM.ConfirmarTransacao; end; except on E: Exception do if not AEmTransacao then DM.CancelarTransacao; end; end; end.
unit ThumbFile; ///////////////////////////////////////////////////////////// // // // Copyright: © 2002 Renate Schaaf // // // // For personal use, do not distribute. // // // ///////////////////////////////////////////////////////////// interface uses Windows, Graphics, SyncObjs; type PThumbFileHeader = ^TThumbFileHeader; TThumbFileHeader = packed record Signature: DWord; RealFilesize: DWord; NumberThumbs: Longint; void1: Longint; void2: Longint; void3: Longint; //for future use end; PThumbInfo = ^TThumbInfo; TThumbInfo = packed record //DataSize: longint; //to know how much to skip to get to the next //not necessary, is stored in BitmapInfoHeader Tag: Longint; //for user's use, like storing valid/unvalid BitmapInfo: TBitmapInfo; end; type TThumbFile = class //a TThumbFile stores and gives access to a //collection of (device independent) bitmaps. //they are all pf24 bit, because I'm lazy. private fNumThumbs: Longint; fOffsets: array of Longint; fStart: PByte; //pointer to start of file fEnd: PByte; //pointer to (current) end of file fReadBuff: PByte; //current pointer into the file fCurrOffset: Longint; //current offset into the file fMaxFilesize, fFileSize: DWord; fFilename: string; fSaveLock: TCriticalSection; fgrowing: boolean; function inList(i: Longint): boolean; function LocateInfo(i: Longint): PByte; procedure Grow; function GetTag(i: integer): Longint; procedure SetTag(i: integer; const value: Longint); function GetThumbInfo(i: integer): TThumbInfo; procedure SetThumbInfo(i: integer; const value: TThumbInfo); function GetThumbRect(i: integer): TRect; protected property ThumbInfo[i: integer]: TThumbInfo read GetThumbInfo write SetThumbInfo; public constructor Create(const filename: string); destructor Destroy; override; procedure CleanUp(aTagValue: Longint); //axe all thumbs that have Tag aTagValue; procedure AddThumb(ABmp: TBitmap); procedure GetThumb(ABmp: TBitmap; Index: Longint); procedure DrawThumb(ACanvas: TCanvas; Index: Longint; Dest: TRect); property filename: string read fFilename; property Tag[i: Longint]: Longint read GetTag write SetTag; property ThumbCount: Longint read fNumThumbs; property ThumbRect[i: integer]: TRect read GetThumbRect; end; implementation uses SysUtils, Classes; const MySig = $6751AFFE; { TThumbFile } procedure TThumbFile.AddThumb(ABmp: TBitmap); var DIB: TDIBSection; Info: PThumbInfo; Buff: PByte; step1, step2, step: DWord; begin {make new TThumbinfo record, fill in data, save ThumbInfo, flush bits of aBmp, using GetObject(aBmp,aDib), update foffsets, fFileSize, fEnd )} if ABmp = nil then raise Exception.Create('AddThumb: Bitmap must be created.'); ABmp.PixelFormat := pf24bit; //to be safe FillChar(DIB, SizeOf(DIB), 0); if GetObject(ABmp.Handle, SizeOf(DIB), @DIB) = 0 then RaiseLastOSError else begin step1:=SizeOf(TThumbInfo); step2:=Dib.dsbmih.biSizeImage; step:=step1+step2; if fFilesize>=fMaxFileSize-step then grow; fSaveLock.Enter; try Buff:=fEnd; Info:=PThumbInfo(Buff); Info^.Tag:=0; Info^.BitmapInfo.bmiHeader := DIB.dsbmih; //the rest can stay dirty inc(fNumThumbs); if Length(fOffsets) < fNumThumbs then SetLength(fOffsets, Length(fOffsets) + 20); fOffsets[fNumThumbs - 1] := fFileSize; inc(Buff, step1); fEnd := Buff; move{DKC17}(DIB.dsBm.bmBits^, Buff^, step2); inc(fEnd, step2); inc(fFileSize, step); finally fSaveLock.Leave; end; end; end; procedure TThumbFile.CleanUp(aTagValue: integer); begin {Make TempFile (filestream), flush data with right tag into Tempfile, write TempFile's header, save, close. Unmap filename, close, erase. Rename TempFile to filename, create file mapping, update offsets, fStart, fEnd, fFilesize, fCurrOffset does nothing so far} end; constructor TThumbFile.Create(const filename: string); var fh, mh: integer; fs, ms: DWord; TH: TThumbFileHeader; st: TFileStream; i, off, doff: integer; Info: PThumbInfo; begin fFilename:=Filename; if FileExists(filename) then begin {open file, create file mapping, read Thumbfile-header, make array of offsets into the file} fh := FileOpen(filename, fmOpenReadWrite or fmShareExclusive); if fh < 0 then RaiseLastOSError; //that would cause the object to be freed immediately, or? //I mean, that's what i want... fs := GetFileSize(fh, nil); ms := fs; end else begin {create file} fh := FileCreate(filename); if fh < 0 then RaiseLastOSError; FileClose(fh); FillChar(TH, SizeOf(TThumbFileHeader), 0); TH.Signature := MySig; TH.RealFilesize := SizeOf(TThumbFileHeader); st := TFileStream.Create(filename, fmOpenReadWrite); try st.position := 0; st.Write(TH, SizeOf(TThumbFileHeader)) finally st.Free; end; fh := FileOpen(filename, fmOpenReadWrite or fmShareExclusive); if fh < 0 then RaiseLastOSError; fs := GetFileSize(fh, nil); ms := fs + 5 * 1024 * 1024; //grow in chunks of 5MB. Could be made a property end; mh := CreateFileMapping(fh, nil, PAGE_READWRITE, 0, ms, nil); if mh = 0 then begin CloseHandle(fh); RaiseLastOSError; end; CloseHandle(fh); fStart := MapViewOfFile(mh, FILE_MAP_WRITE, 0, 0, 0); CloseHandle(mh); if fStart=nil then RaiseLastOSError; TH := PThumbFileHeader(fStart)^; if TH.Signature <> MySig then begin UnmapViewOfFile(fStart); raise Exception.Create(filename + ' is not a valid thumb file'); end; fFileSize := TH.RealFilesize; fEnd := fStart; inc(fEnd, fFileSize); fMaxFilesize := ms; fNumThumbs := TH.NumberThumbs; SetLength(fOffsets, fNumThumbs + 20); fReadBuff := fStart; off := SizeOf(TThumbFileHeader); inc(fReadBuff, off); Info := PThumbInfo(fReadBuff); fOffsets[0]:=off; for i := 0 to fNumThumbs - 2 do begin fOffsets[i] := off; doff := Info^.BitmapInfo.bmiHeader.biSizeImage + SizeOf(TThumbInfo); inc(off, doff); inc(fReadBuff, doff); Info := PThumbInfo(fReadBuff); end; if fNumThumbs>0 then fOffsets[fNumThumbs - 1] := off; fCurrOffset:=off; fSaveLock := TCriticalSection.Create; end; destructor TThumbFile.Destroy; var ph: PThumbFileHeader; begin {flush file mapping, unmap view} fSaveLock.Enter; ph := PThumbFileHeader(fStart); ph^.RealFilesize := fFileSize; ph^.Signature := MySig; FlushViewOfFile(fStart, 0); UnmapViewOfFile(fStart); fSaveLock.Leave; fSaveLock.Free; inherited; end; procedure TThumbFile.DrawThumb(ACanvas: TCanvas; Index: integer; Dest: TRect); var Bits: PByte; Info: PBitmapInfo; begin if inList(Index) then begin Bits := LocateInfo(Index); Info:=@PThumbInfo(Bits)^.BitmapInfo; inc(Bits, SizeOf(TThumbInfo)); with Dest do StretchDIBits(ACanvas.Handle, Left, Top, Right - Left, Bottom - Top, 0, 0, Info.bmiHeader.biWidth, Info.bmiHeader.biHeight, Bits, Info^, DIB_RGB_COLORS, SRCCopy); end; end; function TThumbFile.GetTag(i: integer): Longint; begin Result := -1; if inList(i) then Result := PThumbInfo(LocateInfo(i))^.Tag; end; procedure TThumbFile.GetThumb(ABmp: TBitmap; Index: integer); var DIB: TDIBSection; Info: PThumbInfo; Buff: PByte; begin {read data at index, make aBmp the right size, Use GetObject(aBmp, aDib), move bitmap data from file to aDib.dsBm.bmBits^. aBmp.modified:=true. } if ABmp = nil then raise Exception.Create('GetThumb: Bitmap must have been created.'); if inList(Index) then begin Buff := LocateInfo(Index); Info := PThumbInfo(Buff); with Info^.BitmapInfo.bmiHeader do begin ABmp.Width := 0; ABmp.PixelFormat := pf24bit; ABmp.Width := biWidth; ABmp.Height := biHeight; end; inc(Buff, SizeOf(TThumbInfo)); FillChar(DIB, SizeOf(DIB), 0); GetObject(ABmp.Handle, SizeOf(DIB), @DIB); move(Buff^, DIB.dsBm.bmBits^, Info^.BitmapInfo.bmiHeader.biSizeImage); ABmp.Modified := true; end; end; function TThumbFile.GetThumbInfo(i: integer): TThumbInfo; begin FillChar(Result, SizeOf(TThumbInfo), 0); if inList(i) then {go to fOffsets[i], read in ThumbInfo} Result := PThumbInfo(LocateInfo(i))^; end; function TThumbFile.GetThumbRect(i: integer): TRect; var bih: PBitmapInfoHeader; begin Result := Rect(0, 0, 0, 0); if inList(i) then begin bih := @PThumbInfo(LocateInfo(i))^.BitmapInfo.bmiHeader; Result := Rect(0, 0, bih^.biWidth, bih^.biHeight); end; end; procedure TThumbFile.Grow; var ph: PThumbFileHeader; ms: DWord; step: DWord; fh, mh: integer; begin {flush file mapping, unmap view} step := 5 * 1024 * 1025; if fFileSize > High(DWord) - step then raise Exception.Create('TThumbfile: File cannot grow anymore.'); //it could but I don't want it to. ms := fFileSize + step; fSaveLock.Enter; fgrowing:=true; try ph := PThumbFileHeader(fStart); ph^.RealFilesize := fFileSize; ph^.Signature := MySig; FlushViewOfFile(fStart, 0); UnmapViewOfFile(fStart); fh := FileOpen(fFilename, fmOpenReadWrite or fmShareExclusive); if fh < 0 then RaiseLastOSError; mh := CreateFileMapping(fh, nil, PAGE_READWRITE, 0, ms, nil); CloseHandle(fh); if mh = 0 then RaiseLastOSError; fStart := MapViewOfFile(mh, FILE_MAP_WRITE, 0, 0, 0); CloseHandle(mh); if fStart = nil then RaiseLastOSError; fEnd := fStart; inc(fEnd, fFileSize); fReadBuff:=fStart; inc(fReadBuff,fCurrOffset); fMaxFilesize:=ms; finally fgrowing:=false; fSaveLock.Leave; end; end; function TThumbFile.inList(i: integer): boolean; begin if fgrowing then begin Result:=false; exit; end; Result := (i >= 0) and (i < fNumThumbs); if not Result then raise Exception.Create('Index out of bounds'); end; function TThumbFile.LocateInfo(i: integer): PByte; begin Result := nil; if inList(i) then begin inc(fReadBuff,fOffsets[i]-fCurrOffset); fCurrOffset:=fOffsets[i]; Result := fReadBuff; end; end; procedure TThumbFile.SetTag(i: integer; const value: Longint); begin if inList(i) then PThumbInfo(LocateInfo(i))^.Tag := value; end; procedure TThumbFile.SetThumbInfo(i: integer; const value: TThumbInfo); var PInfo: PThumbInfo; begin if inList(i) then begin PInfo := PThumbInfo(LocateInfo(i)); PInfo^ := value; end; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Win.ComObjWrapper; interface {$HPPEMIT LEGACYHPP} uses System.Classes, System.Win.ComObj; type { TComComponent } TWrappedComObject = class; TComComponent = class; TGetComClassEvent = procedure(Sender: TComComponent; var ComClass: TComClass) of object; TComObjectEvent = procedure(Sender: TComComponent; const ComObject: TWrappedComObject) of object; TComComponent = class(TComponent) private FDescription: string; FGUID: TGUID; FOnGetComClass: TGetComClassEvent; FOnCreated: TComObjectEvent; FOnDestroy: TComObjectEvent; procedure SetGUIDString(const Value: string); procedure RegisterClass; virtual; procedure UnregisterClass; virtual; function GetGUIDString: string; protected procedure DoCreated(const ComObj: TWrappedComObject); virtual; procedure DoDestroy(const ComObj: TWrappedComObject); virtual; function GetComClass: TComClass; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function CreateObject: IUnknown; property Description: string read FDescription write FDescription; property GUID: string read GetGUIDString write SetGUIDString; property OnGetComClass: TGetComClassEvent read FOnGetComClass write FOnGetComClass; property OnCreated: TComObjectEvent read FOnCreated write FOnCreated; property OnDestroy: TComObjectEvent read FOnDestroy write FOnDestroy; end; { TWrappedComObject } TWrappedComObject = class(TComObject) private FComComponent: TComComponent; protected property ComComponent: TComComponent read FComComponent; public destructor Destroy; override; procedure AfterConstruction; override; procedure Initialize; override; end; implementation uses Winapi.Windows, Winapi.ActiveX, System.SysUtils, System.RTLConsts, System.Generics.Collections; type TCOMServer = class(TComServerObject) private FObjectCount: Integer; FFactoryCount: Integer; FHelpFileName: string; procedure FactoryFree(Factory: TComObjectFactory); protected function CountObject(Created: Boolean): Integer; override; function CountFactory(Created: Boolean): Integer; override; function GetHelpFileName: string; override; function GetServerFileName: string; override; function GetServerKey: string; override; function GetServerName: string; override; function GetStartSuspended: Boolean; override; function GetTypeLib: ITypeLib; override; procedure SetHelpFileName(const Value: string); override; public destructor Destroy; override; end; var COMComponents: TThreadList<TComComponent>; COMServersList: TList<TComServer>; COMClassesList: TList<TComClass>; procedure CheckForDuplicateGUID(const AGUID: TGUID); var I: Integer; Component: TCOMComponent; begin if COMComponents = nil then raise Exception.Create(SNoCOMClassesRegistered); with COMComponents.LockList do try for I := 0 to Count - 1 do begin Component := Items[I]; if IsEqualGUID(StringToGUID(Component.GUID), AGUID) then raise Exception.CreateFmt(SGUIDAlreadyDefined, [GUIDToString(AGUID)]); end; finally COMComponents.UnlockList; end; end; function ShortToLongFileName(FileName: string): string; var FindData: TWin32FindData; Search: THandle; begin Result := ''; // Strip off one directory level at a time starting with the file name // and store it into the result. FindFirstFile will return the long file // name from the short file name. while (True) do begin Search := Winapi.Windows.FindFirstFile(PChar(FileName), FindData); if Search = INVALID_HANDLE_VALUE then Break; Result := string('\') + FindData.cFileName + Result; { do not localize } FileName := ExtractFileDir(FileName); Winapi.Windows.FindClose(Search); // Found the drive letter followed by the colon. if Length(FileName) <= 2 then Break; end; Result := ExtractFileDrive(FileName) + Result; end; function GetModuleFileName: string; var Buffer: array[0..MAX_PATH + 1] of Char; begin SetString(Result, Buffer, Winapi.Windows.GetModuleFileName(MainInstance, Buffer, Length(Buffer))); Result := ShortToLongFileName(Result); end; function GetModuleName: string; begin Result := ChangeFileExt(ExtractFileName(GetModuleFileName), ''); end; function COMServer(ComClass: TComClass): TCOMServer; var Idx: Integer; begin if COMClass = nil then raise Exception.Create(SNoCOMClassSpecified); if COMClassesList = nil then COMClassesList := TList<TComClass>.Create; Idx := COMClassesList.IndexOf(ComClass); if Idx = -1 then begin COMClassesList.Add(ComClass); Result := TCOMServer.Create; if COMServersList = nil then COMServersList := TList<TComServer>.Create; COMServersList.Add(Result); end else Result := COMServersList.Items[Idx]; end; { TCOMServer } function TCOMServer.CountFactory(Created: Boolean): Integer; begin if Created then Result := AtomicIncrement(FFactoryCount) else Result := AtomicDecrement(FFactoryCount); end; function TCOMServer.CountObject(Created: Boolean): Integer; begin if Created then Result := AtomicIncrement(FObjectCount) else Result := AtomicDecrement(FObjectCount); end; destructor TCOMServer.Destroy; begin ComClassManager.ForEachFactory(Self, FactoryFree); inherited; end; procedure TCOMServer.FactoryFree(Factory: TComObjectFactory); begin Factory.Free; end; function TCOMServer.GetHelpFileName: string; begin Result := FHelpFileName; end; function TCOMServer.GetServerFileName: string; begin Result := GetModuleFileName; end; function TCOMServer.GetServerKey: string; begin Result := 'LocalServer32'; { do not localize } end; function TCOMServer.GetServerName: string; begin Result := GetModuleName; end; function TCOMServer.GetStartSuspended: Boolean; begin Result := False; end; function TCOMServer.GetTypeLib: ITypeLib; begin Result := nil; end; procedure TCOMServer.SetHelpFileName(const Value: string); begin FHelpFileName := Value; end; { TComComponent } constructor TComComponent.Create(AOwner: TComponent); begin inherited; if COMComponents = nil then COMComponents := TThreadList<TComComponent>.Create; FGUID := IUnknown; with COMComponents.LockList do try Add(Self); finally COMComponents.UnlockList; end; end; function TComComponent.CreateObject: IUnknown; begin RegisterClass; Result := CreateComObject(StringToGUID(GUID)); end; destructor TComComponent.Destroy; begin UnregisterClass; if COMComponents <> nil then with COMComponents.LockList do try Remove(Self); finally COMComponents.UnlockList; end; inherited; end; procedure TComComponent.DoCreated(const ComObj: TWrappedComObject); begin if Assigned(FOnCreated) then FOnCreated(Self, ComObj); end; procedure TComComponent.DoDestroy(const ComObj: TWrappedComObject); begin if Assigned(FOnDestroy) then FOnDestroy(Self, ComObj); end; function TComComponent.GetComClass: TComClass; begin Result := nil; if Assigned(FOnGetComClass) then FOnGetComClass(Self, Result); end; function TComComponent.GetGUIDString: string; begin Result := GUIDToString(FGUID); end; procedure TComComponent.RegisterClass; var ComClass: TComClass; Factory: TComObjectFactory; begin if (csDesigning in ComponentState) then exit; if not (csLoading in ComponentState) and not IsEqualGUID(IUnknown, StringToGUID(GUID)) then begin Factory := ComClassManager.GetFactoryFromClassID(StringToGUID(GUID)); if Factory = nil then begin ComClass := GetComClass; if Assigned(ComClass) then begin Factory := TComObjectFactory.Create(COMServer(ComClass), ComClass, StringToGUID(GUID), ClassName, FDescription, ciMultiInstance, tmApartment); Factory.RegisterClassObject; end else raise Exception.CreateFmt(SNoComClass, [Classname]); end; end; end; procedure TComComponent.SetGUIDString(const Value: string); begin if CompareText(GUID, Value) <> 0 then begin if not IsEqualGUID(FGUID, IUnknown) then UnregisterClass; if not (csDesigning in ComponentState) and (Length(Value) > 0) and not IsEqualGUID(StringToGUID(Value), IUnknown) then CheckForDuplicateGUID(StringToGUID(Value)); if Value = '' then FGUID := IUnknown else FGUID := StringToGUID(Value); end; end; procedure TComComponent.UnregisterClass; var Factory: TComObjectFactory; begin if not (csLoading in ComponentState) and not IsEqualGUID(FGUID, IUnknown) then begin Factory := ComClassManager.GetFactoryFromClassID(FGUID); if Factory <> nil then Factory.Free; end; end; { TWrappedComObject } procedure TWrappedComObject.AfterConstruction; begin inherited; // FComComponent is assigned in the Initialize method if Assigned(FComComponent) then FComComponent.DoCreated(Self); end; destructor TWrappedComObject.Destroy; var FoundComComponent: Boolean; begin if Assigned(FComComponent) then begin FoundComComponent := False; if COMComponents <> nil then with COMComponents.LockList do try FoundComComponent := IndexOf(FComComponent) >= 0; finally COMComponents.UnlockList; end; if FoundComComponent then begin FComComponent.DoDestroy(Self); inherited; end else begin // FComComponent was already freed. Do not call DoDestroy. // Also do not call inherited.Destroy because FFactory has // also been freed. // The following code is equivalent to TComObject.Destroy if Assigned(SafeCallErrorProc) then begin // if (FFactory <> nil) and not FNonCountedObject then // FFactory.ComServer.CountObject(False); if RefCount > 0 then CoDisconnectObject(Self, 0); end; end end else inherited; end; procedure TWrappedComObject.Initialize; var I: Integer; ComComponent: TComComponent; begin inherited; with COMComponents.LockList do try for I := 0 to Count - 1 do begin ComComponent := Items[I]; if IsEqualGUID(Factory.ClassID, ComComponent.FGUID) then begin FComComponent := ComComponent; Break; end; end; if FComComponent = nil then raise Exception.CreateFmt(SNoComComponent, [GUIDToString(Factory.ClassID)]); finally ComComponents.UnlockList; end; end; initialization finalization FreeAndNil(COMComponents); if Assigned(COMServersList) then while COMServersList.Count > 0 do COMServersList.Delete(0); FreeAndNil(COMServersList); FreeAndNil(COMClassesList); end.
(* WG_Sky: MM 2020 Sky test to evaluate quality of RNG *) PROGRAM WG_Sky; USES {$IFDEF FPC} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Strings, WinCrt, WinGraph, RandUnit; PROCEDURE Skytest(dc: HDC; wnd: HWnd; r: TRect); FAR; CONST BORDER = 20; (* Padding in pixel *) VAR x, y, n, i: INTEGER; width, height: INTEGER; BEGIN Randomize; width := r.right - r.left - 2 * BORDER; height := r.bottom - r.top - 2 * BORDER; InitRandSeed(0); n := 5000; FOR i := 1 to n do begin x := Random(width) + BORDER; y := Random(height) + BORDER; MoveTo(dc, x-2, y); LineTo(dc, x+3, y); MoveTo(dc, x, y - 2); LineTo(dc, x, y + 3); end; (* FOR *) END; (*Redraw_Example*) PROCEDURE Redraw_Example2(dc: HDC; wnd: HWnd; r: TRect); FAR; BEGIN (*... draw anything ...*) END; (*Redraw_Example2*) PROCEDURE MousePressed_Example(dc: HDC; wnd: HWnd; x, y: INTEGER); FAR; BEGIN WriteLn('mouse pressed at: ', x, ', ', y); (*InvalidateRect(wnd, NIL, TRUE);*) END; (*MousePressed_Exmple*) BEGIN (*WG_Test*) redrawProc := Skytest; mousePressedProc := MousePressed_Example; WGMain; END. (*WG_Test*)
{*************************************************************** * * Project : WSZipCodeServer * Unit Name: ServerMain * Purpose : Demonstrates serving Address informaiton data back to client after query on ZIP code * Version : 1.0 * Date : Wed 25 Apr 2001 - 01:48:02 * Author : <unknown> * History : * Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com> * ****************************************************************} unit ServerMain; interface uses {$IFDEF Linux} QControls, QGraphics, QForms, QDialogs, {$ELSE} windows, messages, graphics, controls, forms, dialogs, {$ENDIF} SysUtils, Classes, IdBaseComponent, IdComponent, IdTCPServer; type TformMain = class(TForm) IdTCPServer1: TIdTCPServer; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure IdTCPServer1Connect(AThread: TIdPeerThread); procedure IdTCPServer1Execute(AThread: TIdPeerThread); private ZipCodeList: TStrings; public end; var formMain: TformMain; implementation {$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF} procedure TformMain.FormCreate(Sender: TObject); begin ZipCodeList := TStringList.Create; ZipCodeList.LoadFromFile(ExtractFilePath(Application.EXEName) + 'ZipCodes.dat'); end; procedure TformMain.FormDestroy(Sender: TObject); begin ZipCodeList := nil; ZipCodeList.Free; end; procedure TformMain.IdTCPServer1Connect(AThread: TIdPeerThread); begin AThread.Connection.WriteLn('Indy Zip Code Server Ready.'); end; procedure TformMain.IdTCPServer1Execute(AThread: TIdPeerThread); var sCommand: string; begin with AThread.Connection do begin sCommand := ReadLn; if SameText(sCommand, 'QUIT') then begin Disconnect; end else if SameText(Copy(sCommand, 1, 8), 'ZipCode ') then begin WriteLn(ZipCodeList.Values[Copy(sCommand, 9, MaxInt)]); end; end; end; end.
unit AImprimeEtiqueta; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, ComCtrls, Componentes1, ExtCtrls, PainelGradiente, Mask, numericos, UnClientes, StdCtrls, Grids, CGrades, Buttons, UnDados, UnImpressaoEtiquetaCotacao, UnDadosProduto, UnCrystal,Clipbrd, DB, DBClient, Tabela, CBancoDados, UnProdutos; type TFImprimiEtiqueta = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; PageControl1: TPageControl; PModelo1: TTabSheet; BFechar: TBitBtn; PanelColor3: TPanelColor; PanelColor4: TPanelColor; GCores: TRBStringGridColor; ECliente: TEditColor; Label1: TLabel; Label2: TLabel; EOrdemCompra: TEditColor; EEtiquetaInicial: Tnumerico; Label3: TLabel; Label4: TLabel; EQtdEtiquetas: Tnumerico; BImprimir: TBitBtn; CVisualizar: TCheckBox; BEtiPequena: TBitBtn; GProdutos: TRBStringGridColor; BComposicao: TBitBtn; BPeqHering: TBitBtn; BCaixa: TBitBtn; BAmostra: TBitBtn; BitBtn1: TBitBtn; Aux: TRBSQL; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure GProdutosCarregaItemGrade(Sender: TObject; VpaLinha: Integer); procedure GProdutosMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); procedure GCoresCarregaItemGrade(Sender: TObject; VpaLinha: Integer); procedure GCoresMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); procedure GCoresDadosValidos(Sender: TObject; var VpaValidos: Boolean); procedure PageControl1Change(Sender: TObject); procedure BFecharClick(Sender: TObject); procedure GCoresKeyPress(Sender: TObject; var Key: Char); procedure GProdutosDepoisExclusao(Sender: TObject); procedure BImprimirClick(Sender: TObject); procedure BEtiPequenaClick(Sender: TObject); procedure GProdutosDadosValidos(Sender: TObject; var VpaValidos: Boolean); procedure BComposicaoClick(Sender: TObject); procedure BPeqHeringClick(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure BCaixaClick(Sender: TObject); procedure BAmostraClick(Sender: TObject); private { Private declarations } VprCodCliente : Integer; VprCotacoes : TList; VprDModelo1 : TRBDEtiModelo1; VprDEtiProduto : TRBDEtiProduto; VprDEtiCor : TRBDEtiCor; FunEtiCotacao : TRBDFunEtiCotacao; procedure CarregaTitulosGrades; procedure CarEtiModelo1; procedure CarDCliente; procedure CarDModelo1; procedure CarDEtiquetaMedia; procedure CarDEtiquetaCaixa; procedure CarDEtiquetaPequena; procedure CarDEtiquetaAmostra; public { Public declarations } procedure ImprimeEtiquetas(VpaCotacoes : TList); end; var FImprimiEtiqueta: TFImprimiEtiqueta; implementation uses APrincipal, FunObjeto, ConstMsg, constantes, FunSql, dmRave, funString; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFImprimiEtiqueta.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } FunEtiCotacao := TRBDFunEtiCotacao.cria; VprDModelo1 := TRBDEtiModelo1.cria; GProdutos.ADados := VprDModelo1.Produtos; CarregaTitulosGrades; end; { ******************* Quando o formulario e fechado ************************** } procedure TFImprimiEtiqueta.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } FunEtiCotacao.free; VprDModelo1.free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFImprimiEtiqueta.CarregaTitulosGrades; begin GProdutos.Cells[1,0] := 'Produto'; GProdutos.Cells[2,0] := 'Qtd Embalagem'; GProdutos.Cells[3,0] := 'Composição'; GCores.Cells[1,0] := 'Cor'; GCores.Cells[2,0] := 'Qtd Cotação'; GCores.Cells[3,0] := 'Qtd Etiqueta'; GCores.Cells[4,0] := 'UM'; GCores.Cells[5,0] := 'Qtd Embalagem'; GCores.Cells[6,0] := 'Referência Cliente'; end; {******************************************************************************} procedure TFImprimiEtiqueta.CarEtiModelo1; begin FunEtiCotacao.CarEtiModelo1(VprDModelo1.Produtos,VprCotacoes); if VprCotacoes.Count > 0 then begin VprDModelo1.OrdemCompra := trbdorcamento(VprCotacoes.Items[0]).OrdemCompra; VprDModelo1.DesDestino := trbdorcamento(VprCotacoes.Items[0]).desobservacao.Text; end; GProdutos.CarregaGrade; VprDModelo1.QtdEtiquetas := FunEtiCotacao.RQtdEtiquetaModelo1(VprDModelo1); EQtdEtiquetas.AsInteger := VprDModelo1.QtdEtiquetas; end; {******************************************************************************} procedure TFImprimiEtiqueta.CarDCliente; Var VpfDCotacao : TRBDOrcamento; begin if VprCotacoes.Count > 0 then begin VpfDCotacao := TRBDOrcamento(VprCotacoes.Items[0]); ECliente.Text := FunClientes.RNomCliente(IntToStr(VpfDCotacao.CodCliente)); VprCodCliente := VpfDCotacao.CodCliente; EOrdemCompra.Text := VpfDCotacao.OrdemCompra; end; end; {******************************************************************************} procedure TFImprimiEtiqueta.CarDEtiquetaAmostra; Var VpfLacoProduto, VpfLacoCor, VpfSeqEtiqueta: Integer; VpfDEtiPequena : TRBDEtiPequena; VpfDCor : TRBDEtiCor; VpfQtdPedido : Double; VpfNomproduto : string; begin FunEtiCotacao.CarEtiPequenas(VprDModelo1,true); ExecutacomandoSql(Aux,'Delete from ETIQUETAPRODUTO'); VpfSeqEtiqueta := 1; AdicionaSQLAbreTabela(Aux,'Select * from ETIQUETAPRODUTO'); for VpfLacoProduto := 1 to EEtiquetaInicial.AsInteger do begin Aux.Insert; aux.FieldByName('SEQETIQUETA').AsInteger := VpfSeqEtiqueta; aux.FieldByName('INDIMPRIMIR').AsString := 'N'; inc(VpfSeqEtiqueta); Aux.Post; end; for vpfLacoProduto := 0 to VprDModelo1.EtiPequenas.Count - 1 do begin VpfDEtiPequena := TRBDEtiPequena(VprDModelo1.EtiPequenas.Items[VpfLacoProduto]); Aux.Insert; Aux.FieldByName('SEQETIQUETA').AsInteger := VpfSeqEtiqueta; Aux.FieldByName('NOMPRODUTO').AsString := VpfDEtiPequena.DesProduto+ ' '+VpfDEtiPequena.DesMM; Aux.FieldByName('DESMM').AsString := VpfDEtiPequena.DesMM; aux.FieldByName('INDIMPRIMIR').AsString := 'S'; Aux.FieldByName('NOMCOR').AsString :=DeletaChars(DeleteAteChar(VpfDEtiPequena.DesCor,'('),')'); Aux.FieldByName('NOMCORMARISOL').AsString := VpfDEtiPequena.DesReferencia; Aux.FieldByName('NOMCORMARISOLCOMPLETA').AsString := CopiaAteChar(VpfDEtiPequena.DesCor,'('); Aux.FieldByName('DESQTDPRODUTO').AsString := VpfDEtiPequena.Qtd; VpfDEtiPequena.DesProduto := uppercase(RetiraAcentuacao(VpfDEtiPequena.DesProduto)); if ExistePalavra(VpfDEtiPequena.DesProduto,'ALGODAO') or ExistePalavra(VpfDEtiPequena.DesProduto,'ALG') or ExistePalavra(VpfDEtiPequena.DesProduto,'ALGODÃO') then Aux.FieldByName('INDALGODAO').AsString := 'S' else if ExistePalavra(VpfDEtiPequena.DesProduto,'POLIESTER') or ExistePalavra(VpfDEtiPequena.DesProduto,'POL') or ExistePalavra(VpfDEtiPequena.DesProduto,'POLIÉSTER') or ExistePalavra(VpfDEtiPequena.DesProduto,'ELASTICO') OR ExistePalavra(VpfDEtiPequena.DesProduto,'ELASTICO') then Aux.FieldByName('INDPOLIESTER').AsString := 'S'; inc(VpfSeqEtiqueta); aux.Post; end; end; {******************************************************************************} procedure TFImprimiEtiqueta.CarDEtiquetaCaixa; Var VpfLacoProduto, VpfLacoCor, VpfSeqEtiqueta, VpfQtdEtiqueta : Integer; VpfDProduto : TRBDEtiProduto; VpfDCor : TRBDEtiCor; VpfQtdProduto : Double; begin ExecutacomandoSql(Aux,'Delete from ETIQUETAPRODUTO'); VpfSeqEtiqueta := 1; AdicionaSQLAbreTabela(Aux,'Select * from ETIQUETAPRODUTO'); for VpfLacoProduto := 1 to EEtiquetaInicial.AsInteger do begin Aux.Insert; aux.FieldByName('SEQETIQUETA').AsInteger := VpfSeqEtiqueta; aux.FieldByName('INDIMPRIMIR').AsString := ''; inc(VpfSeqEtiqueta); Aux.Post; end; for vpfLacoProduto := 0 to VprDModelo1.Produtos.Count - 1 do begin VpfDProduto := TRBDEtiProduto(VprDModelo1.Produtos.Items[VpfLacoProduto]); VpfQtdEtiqueta := 0; for VpfLacoCor := 0 to VpfDProduto.Cores.Count - 1 do begin VpfDCor := TRBDEtiCor(VpfDProduto.Cores.Items[VpflacoCor]); VpfQtdProduto := VpfDCor.QtdEtiqueta; while VpfQtdProduto > 0 do begin Aux.Insert; Aux.FieldByName('SEQETIQUETA').AsInteger := VpfSeqEtiqueta; inc(VpfSeqEtiqueta); Aux.FieldByName('NOMCLIENTE').AsString := ECliente.Text; Aux.FieldByName('DESORDEMCOMPRA').AsString := EOrdemCompra.Text; Aux.FieldByName('NOMPRODUTO').AsString := VpfDProduto.NomProduto; Aux.FieldByName('DESUM').AsString := VpfDCor.UM; Aux.FieldByName('NOMCOR').AsString := VpfDCor.NomCor; if VpfQtdProduto > VpfDProduto.QtdEmbalagem then Aux.FieldByName('QTDPRODUTO').AsFloat := VpfDProduto.QtdEmbalagem else Aux.FieldByName('QTDPRODUTO').AsFloat := VpfQtdProduto; VpfQtdProduto := VpfQtdProduto - VpfDProduto.QtdEmbalagem; aux.Post; end; inc(VpfSeqEtiqueta); end; end; end; {******************************************************************************} procedure TFImprimiEtiqueta.CarDEtiquetaMedia; Var VpfLacoProduto, VpfLacoCor, VpfSeqEtiqueta, VpfQtdEtiqueta : Integer; VpfDProduto : TRBDEtiProduto; VpfDCor : TRBDEtiCor; begin ExecutacomandoSql(Aux,'Delete from ETIQUETAPRODUTO'); VpfSeqEtiqueta := 1; AdicionaSQLAbreTabela(Aux,'Select * from ETIQUETAPRODUTO'); for VpfLacoProduto := 1 to EEtiquetaInicial.AsInteger do begin Aux.Insert; aux.FieldByName('SEQETIQUETA').AsInteger := VpfSeqEtiqueta; aux.FieldByName('INDIMPRIMIR').AsString := ''; inc(VpfSeqEtiqueta); Aux.Post; end; for vpfLacoProduto := 0 to VprDModelo1.Produtos.Count - 1 do begin VpfDProduto := TRBDEtiProduto(VprDModelo1.Produtos.Items[VpfLacoProduto]); VpfQtdEtiqueta := 0; for VpfLacoCor := 0 to VpfDProduto.Cores.Count - 1 do begin VpfDCor := TRBDEtiCor(VpfDProduto.Cores.Items[VpflacoCor]); if VpfQtdEtiqueta = 0 then begin Aux.Insert; Aux.FieldByName('SEQETIQUETA').AsInteger := VpfSeqEtiqueta; Aux.FieldByName('NOMCLIENTE').AsString := ECliente.Text; Aux.FieldByName('DESORDEMCOMPRA').AsString := EOrdemCompra.Text; Aux.FieldByName('NOMPRODUTO').AsString := VpfDProduto.NomProduto; Aux.FieldByName('DESUM').AsString := VpfDCor.UM; end; inc(VpfQtdEtiqueta); case VpfQtdEtiqueta of 1 : begin Aux.FieldByName('NOMCOR').AsString := VpfDCor.NomCor; Aux.FieldByName('QTDPRODUTO').AsFloat := VpfDCor.QtdEtiqueta; end; 2 : begin Aux.FieldByName('NOMCOR2').AsString := VpfDCor.NomCor; Aux.FieldByName('QTDCOR2').AsFloat := VpfDCor.QtdEtiqueta; end; 3 : begin Aux.FieldByName('NOMCOR3').AsString := VpfDCor.NomCor; Aux.FieldByName('QTDCOR3').AsFloat := VpfDCor.QtdEtiqueta; end; 4 : begin Aux.FieldByName('NOMCOR4').AsString := VpfDCor.NomCor; Aux.FieldByName('QTDCOR4').AsFloat := VpfDCor.QtdEtiqueta; end; 5 : begin Aux.FieldByName('NOMCOR5').AsString := VpfDCor.NomCor; Aux.FieldByName('QTDCOR5').AsFloat := VpfDCor.QtdEtiqueta; end; end; if VpfQtdEtiqueta = 5 then begin aux.Post; VpfQtdEtiqueta := 0; end; inc(VpfSeqEtiqueta); end; if Aux.State = dsInsert then Aux.Post; end; end; {******************************************************************************} procedure TFImprimiEtiqueta.CarDEtiquetaPequena; var VpfLacoProduto, VpfLacoCor, VpfSeqEtiqueta: Integer; VpfDProduto : TRBDEtiProduto; VpfDCor : TRBDEtiCor; VpfQtdPedido : Double; VpfNomproduto : string; begin ExecutacomandoSql(Aux,'Delete from ETIQUETAPRODUTO'); VpfSeqEtiqueta := 1; AdicionaSQLAbreTabela(Aux,'Select * from ETIQUETAPRODUTO'); for VpfLacoProduto := 1 to EEtiquetaInicial.AsInteger do begin Aux.Insert; aux.FieldByName('SEQETIQUETA').AsInteger := VpfSeqEtiqueta; aux.FieldByName('INDIMPRIMIR').AsString := 'N'; inc(VpfSeqEtiqueta); Aux.Post; end; for vpfLacoProduto := 0 to VprDModelo1.Produtos.Count - 1 do begin VpfDProduto := TRBDEtiProduto(VprDModelo1.Produtos.Items[VpfLacoProduto]); for VpfLacoCor := 0 to VpfDProduto.Cores.Count - 1 do begin VpfDCor := TRBDEtiCor(VpfDProduto.Cores.Items[VpflacoCor]); VpfQtdPedido := VpfDCor.QtdEtiqueta; while (VpfQtdPedido > 0) do begin Aux.Insert; VpfNomproduto := VpfDProduto.NomProduto; Aux.FieldByName('SEQETIQUETA').AsInteger := VpfSeqEtiqueta; Aux.FieldByName('CODPRODUTO').AsString := VpfDProduto.CodProduto; Aux.FieldByName('DESMM').AsString := FunProdutos.RDesMMProduto(VpfNomproduto); Aux.FieldByName('NOMPRODUTO').AsString := VpfNomProduto; Aux.FieldByName('DESREFERENCIACLIENTE').AsString := VpfDCor.DesReferenciaCliente; Aux.FieldByName('DESCOMPOSICAO').AsString := VpfDProduto.DesComposicao; aux.FieldByName('INDIMPRIMIR').AsString := 'S'; Aux.FieldByName('DESUM').AsString := VpfDCor.UM; Aux.FieldByName('NOMCOR').AsString := VpfDCor.NomCor; if VpfQtdPedido > VpfDCor.QtdEmbalagem then Aux.FieldByName('QTDPRODUTO').AsFloat := VpfDCor.QtdEmbalagem else Aux.FieldByName('QTDPRODUTO').AsFloat := VpfQtdPedido; VpfQtdPedido := VpfQtdPedido - VpfDCor.QtdEmbalagem; inc(VpfSeqEtiqueta); aux.Post; end; end; end; end; {******************************************************************************} procedure TFImprimiEtiqueta.CarDModelo1; begin with VprDModelo1 do begin NomCliente := ECliente.text; OrdemCompra := EOrdemCompra.Text; QtdEtiquetas := EQtdEtiquetas.AsInteger; EtiInicial := EEtiquetaInicial.AsInteger; end; end; {******************************************************************************} procedure TFImprimiEtiqueta.ImprimeEtiquetas(VpaCotacoes : TList); begin VprCotacoes := VpaCotacoes; if VprCotacoes.Count > 0 then begin CarDCliente; CarEtiModelo1; Showmodal; end else close; end; {******************************************************************************} procedure TFImprimiEtiqueta.GProdutosCarregaItemGrade(Sender: TObject; VpaLinha: Integer); begin VprDEtiProduto := TRBDEtiProduto(VprDModelo1.Produtos.Items[VpaLinha -1]); GProdutos.Cells[1,VpaLinha] := VprDEtiProduto.NomProduto; GProdutos.Cells[2,VpaLinha] := FloatToStr(VprDEtiProduto.QtdEmbalagem); GProdutos.Cells[4,VpaLinha] := VprDEtiProduto.DesComposicao; end; {******************************************************************************} procedure TFImprimiEtiqueta.GProdutosMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); begin VprDEtiProduto := TRBDEtiProduto(VprDModelo1.Produtos.Items[VpaLinhaAtual -1]); GCores.ADados := VprDEtiProduto.Cores; GCores.CarregaGrade; end; {******************************************************************************} procedure TFImprimiEtiqueta.GCoresCarregaItemGrade(Sender: TObject; VpaLinha: Integer); begin if VprDEtiProduto.Cores.Count > 0 then begin VprDEtiCor := TRBDEtiCor(VprDEtiProduto.Cores.Items[VpaLinha-1]); GCores.Cells[1,VpaLinha] := VprDEtiCor.NomCor; GCores.Cells[2,VpaLinha] := FloatToStr(VprDEtiCor.QtdCotacao); GCores.Cells[3,VpaLinha] := FloatToStr(VprDEtiCor.QtdEtiqueta); GCores.Cells[4,VpaLinha] := VprDEtiCor.UM; GCores.Cells[5,VpaLinha] := FloatToStr(VprDEtiCor.QtdEmbalagem); GCores.Cells[6,VpaLinha] := VprDEtiCor.DesReferenciaCliente; end; end; {******************************************************************************} procedure TFImprimiEtiqueta.GCoresMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); begin if VprDEtiProduto.Cores.Count > 0 then begin VprDEtiCor := TRBDEtiCor(VprDEtiProduto.Cores.Items[VpaLinhaAtual - 1]); end; end; {******************************************************************************} procedure TFImprimiEtiqueta.GCoresDadosValidos(Sender: TObject; var VpaValidos: Boolean); begin VpaValidos := true; try VprDEtiCor.QtdEtiqueta := StrToFloat(GCores.Cells[3,GCores.Alinha]); VprDEtiCor.DesReferenciaCliente := GCores.Cells[6,GCores.ALinha]; except Aviso('QUANTIDADE DA ETIQUETA INVÁLIDA!!!'#13'A quantidade digitada da etiqueta não é um valor válido'); VpaValidos := false; end; if GCores.Cells[5,GCores.ALinha] <> '' then begin try VprDEtiCor.QtdEmbalagem := StrToFloat(GCores.Cells[5,GCores.Alinha]); except Aviso('QUANTIDADE DA EMBALAGEM INVÁLIDA!!!'#13'A quantidade digitada da embalagem não é um valor válido'); VpaValidos := false; end; end; end; {******************************************************************************} procedure TFImprimiEtiqueta.PageControl1Change(Sender: TObject); begin if PageControl1.ActivePage = PModelo1 then CarEtiModelo1; end; {******************************************************************************} procedure TFImprimiEtiqueta.BFecharClick(Sender: TObject); begin close; end; {******************************************************************************} procedure TFImprimiEtiqueta.GCoresKeyPress(Sender: TObject; var Key: Char); begin if key = '.' then key := ','; end; {******************************************************************************} procedure TFImprimiEtiqueta.GProdutosDepoisExclusao(Sender: TObject); begin VprDModelo1.QtdEtiquetas := FunEtiCotacao.RQtdEtiquetaModelo1(VprDModelo1); EQtdEtiquetas.AsInteger := VprDModelo1.QtdEtiquetas; end; {******************************************************************************} procedure TFImprimiEtiqueta.BImprimirClick(Sender: TObject); begin CarDEtiquetaMedia; dtRave := TdtRave.Create(self); dtRave.ImprimeEtiquetaMedia(CVisualizar.Checked); dtRave.Free; end; {******************************************************************************} procedure TFImprimiEtiqueta.BEtiPequenaClick(Sender: TObject); begin CarDModelo1; CarDEtiquetaPequena; dtRave := TdtRave.Create(self); dtRave.ImprimeEtiquetaPequena(CVisualizar.Checked); dtRave.Free; end; {******************************************************************************} procedure TFImprimiEtiqueta.GProdutosDadosValidos(Sender: TObject; var VpaValidos: Boolean); begin VpaValidos := true; VprDEtiProduto.NomProduto := GProdutos.Cells[1,GPRodutos.ALinha]; VprDEtiProduto.DesComposicao := GProdutos.Cells[3,GPRodutos.ALinha]; try VprDEtiProduto.QtdEmbalagem := StrToFloat(GProdutos.Cells[2,GProdutos.ALinha]); if VprDEtiProduto.QtdEmbalagem <> VprDEtiProduto.QtdEmbalagemAnterior then begin VprDEtiProduto.QtdEmbalagemAnterior := VprDEtiProduto.QtdEmbalagem; FunEtiCotacao.AlteraQtdEmbalagemCores(VprDEtiProduto); GCores.CarregaGrade; end; except Aviso('QUANTIDADE DA EMBALAGEM INVÁLIDA!!!'#13'A quantidade digitada da embalagem não é um valor válido'); VpaValidos := false; end; end; {******************************************************************************} procedure TFImprimiEtiqueta.BAmostraClick(Sender: TObject); begin CarDModelo1; CarDEtiquetaAmostra; dtRave := TdtRave.Create(self); dtRave.ImprimeEtiquetaAmostra(CVisualizar.Checked); dtRave.Free; end; procedure TFImprimiEtiqueta.BCaixaClick(Sender: TObject); begin CarDModelo1; CarDEtiquetaCaixa; dtRave := TdtRave.Create(self); dtRave.ImprimeEtiquetaCaixa(CVisualizar.Checked); dtRave.Free; end; {******************************************************************************} procedure TFImprimiEtiqueta.BComposicaoClick(Sender: TObject); begin CarDModelo1; CarDEtiquetaPequena; dtRave := TdtRave.Create(self); dtRave.ImprimeEtiquetaComposicao(CVisualizar.Checked); dtRave.Free; end; {******************************************************************************} procedure TFImprimiEtiqueta.BPeqHeringClick(Sender: TObject); begin CarDModelo1; CarDEtiquetaPequena; dtRave := TdtRave.Create(self); dtRave.ImprimeEtiquetaPequenaReferencia(CVisualizar.Checked); dtRave.Free; end; procedure TFImprimiEtiqueta.BitBtn1Click(Sender: TObject); var VpfDClientes : TRBDCliente; begin VpfDClientes := TRBDCliente.cria; VpfDClientes.CodCliente := VprCodCliente; FunClientes.CarDCliente(VpfDClientes); Clipboard.AsTExt := VpfDClientes.NomCliente+#13+VpfDClientes.DesEndereco+','+VpfDClientes.NumEndereco+' - '+VpfDClientes.DesComplementoEndereco+#13+ 'Bairro : '+VpfDClientes.DesBairro+ ' - '+VpfDClientes.DesCidade+'/'+VpfDClientes.DesUF+#13+ 'CEP : '+VpfDClientes.CepCliente; VpfDClientes.free; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFImprimiEtiqueta]); end.
unit CommonDataProvider.FD; interface uses CommonConnection.Intf, Data.DB, FDConnectionHelper, uGlobal, UIRestore, DataSetHelper, NGFDMemTable, DMBase, Spring.Container, Spring.Services, System.SysUtils, classes, Variants, System.DateUtils, FireDAC.UI.Intf, FireDAC.Stan.Intf, FireDAC.Comp.UI, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DApt; type TNG_FDConnection = class(TInterfacedObject, ICommonConnection) FConnectionProperties : ICommonConnectionProperties; FServerType : TDatabaseTypeOption; FFDConnection, FDefaultConnection : TFDConnection; // IDBConnection function GetConnectionProperties : ICommonConnectionProperties; function GetServerType: TDatabaseTypeOption; procedure SetServerType(Value: TDatabaseTypeOption); // Connection function GetConnection : TObject; procedure SetConnection(Value: TObject); // Connected function GetConnected: Boolean; procedure SetConnected(Value: Boolean); procedure SetConnectionString; //Events function GetAfterConnect: TNotifyEvent; procedure SetAfterConnect(Value: TNotifyEvent); function GetAfterDisconnect: TNotifyEvent; procedure SetAfterDisconnect(Value: TNotifyEvent); // Private procedure CreateDefaultConnection; procedure ReleaseDefaultConnection; procedure CreateConnectionProperties; procedure ReleaseConnectionProperties; public property Connection : TObject read GetConnection write SetConnection; property Connected : Boolean read GetConnected write SetConnected; constructor Create; destructor Destroy; override; end; TNG_FDDataProvider = class(TInterfacedObject, IFDMemTableProvider) private FDBConnection : ICommonConnection; FUseCloneDataProvider : Boolean; procedure CreateDBConnection; procedure ReleaseDBConnection; function GetDBConnection : ICommonConnection; // Private procedure MakeMultiRecordSetCDS(cds: TNGFDMemTable); procedure CreateFieldInfoCDS(ds : TDataSet; cdsMapping: TNGFDMemTable); procedure AssignParamValues(qry : TFDQuery; cds, cdsMapping : TNGFDMemTable); function ValidLogDataSets(cdsLog, cdsLogLink: TNGFDMemTable): Boolean; procedure AssignFieldValues(qry : TFDQuery; cds, cdsLog, cdsLogLink : TNGFDMemTable; TableName : string); procedure PrepareQuery(qry: TFDQuery; const SQL: string; Params: TParams); procedure DoCopyDataSet(qry : TFDQuery; cds : TNGFDMemTable); procedure DoCopyDataSetMulti(qry : TFDQuery; cds : TNGFDMemTable); // ICommonDataProvider procedure SetConnectionString(const ServerType : TDatabaseTypeOption; const HostName, DatabaseName, PortNumber, LoginName, LoginPassword: string; OSAuthentication: Boolean); function GetConnected: Boolean; procedure SetConnected(Value: Boolean); procedure CheckCDS(cds : TNGFDMemTable; cdsName: string; CheckActive : Boolean); function GetKeyFieldValue(cds: TNGFDMemTable; KeyFieldName: string) : Variant; function LocateKeyField(cds: TNGFDMemTable; KeyFieldName: string; KeyValue: Variant) : Boolean; function CanEditCDS(cds : TNGFDMemTable) : Boolean; function CanInsertCDS(cds: TNGFDMemTable): Boolean; function CanCancelCDS(cds: TNGFDMemTable): Boolean; function CanSaveCDS(cds: TNGFDMemTable): Boolean; function CanDeleteCDS(cds: TNGFDMemTable): Boolean; procedure PostCDS(cds : TNGFDMemTable); function GetServerDateTimeNow : TDateTime; function TextToListText(s : string) : string; function KeyFieldsToWhereAnd(TableAlias, KeyFields : string): string; function FieldToParam(FieldName: string): string; function AddFieldBrackets(FieldName: string): string; function GetQueryText(QryIndex: Integer; WhereAnd: string): string; function GetQueryTextTable(const TableName, TableAlias, WhereAnd, KeyFields, OrderBy : string) : string; procedure CreateParam(cds : TNGFDMemTable; ParamName: string; DataType : TFieldType; ParamValue : Variant); procedure CreateBlobParam(cds : TNGFDMemTable; ParamName: string; BlobType: TBlobType; Stream: TStream); procedure CreateDefaultParams(cds: TNGFDMemTable; PageSize, PageNum: Integer); procedure QryToCDS(qry : TFDQuery; cds: TNGFDMemTable; CreateFieldDefs: Boolean); procedure cdsOpenQryTextExt(QryText: string; cds : TNGFDMemTable; ExecQry, CreateFieldDefs : Boolean; LAppend: Boolean = False; LUseDP: Boolean = False); procedure cdsExecQryText(QryText: string; cds : TNGFDMemTable); procedure cdsOpenQryText(QryText: string; cds : TNGFDMemTable; CreateFieldDefs : Boolean; LAppend: Boolean = False; LUseDP: Boolean = False); procedure cdsExecQryIndex(QryIndex : Integer; WhereAnd: string; cds : TNGFDMemTable); procedure cdsOpenQryIndex(QryIndex : Integer; WhereAnd: string; cds : TNGFDMemTable; CreateFieldDefs : Boolean); procedure cdsOpenTable(const TableName, TableAlias, WhereAnd, OrderBy: string; cds : TNGFDMemTable; CreateFieldDefs : Boolean); procedure cdsOpenTableExt(const TableName, TableAlias, WhereAnd, OrderBy : string; cds : TNGFDMemTable; CreateFieldDefs : Boolean; var DataSetState : TomControlState); procedure cdsApplyUpdatesTable(cds : TNGFDMemTable; TableName, TableAlias, WhereAnd, KeyFields : string); procedure cdsApplyUpdates(cds : TNGFDMemTable); procedure cdsOpen(cds: TNGFDMemTable; CreateFieldDefs: Boolean; LAppend: Boolean = False; LUseDP: Boolean = False); procedure cdsOpenExt(cds: TNGFDMemTable; CreateFieldDefs: Boolean; var DataSetState : TomControlState); procedure cdsExec(cds: TNGFDMemTable); procedure ExecSQL(SQL : string); procedure BeginTransaction; procedure CommitTransaction; procedure RollbackTransaction; procedure ResetQuery(cds : TNGFDMemTable); procedure cdsParamGenerate(cds : TNGFDMemTable); function CloneDataProvider: ICommonDataProvider<TNGFDMemTable>; function GetUseCloneDataProvider: Boolean; procedure SetUseCloneDataProvider(Value : Boolean); function CheckTableAndField(const s: String): Boolean; public constructor Create; destructor Destroy; override; end; implementation { TNG_FDConnection } constructor TNG_FDConnection.Create; begin inherited; CreateDefaultConnection; CreateConnectionProperties; end; procedure TNG_FDConnection.CreateConnectionProperties; begin FConnectionProperties := ServiceLocator.GetService<ICommonConnectionProperties>; end; procedure TNG_FDConnection.CreateDefaultConnection; begin FDefaultConnection := TFDConnection.Create(nil); FDefaultConnection.LoginPrompt := False; FFDConnection := FDefaultConnection; end; destructor TNG_FDConnection.Destroy; begin ReleaseConnectionProperties; ReleaseDefaultConnection; inherited; end; procedure TNG_FDConnection.ReleaseConnectionProperties; begin if Assigned(FConnectionProperties) then begin {$IFNDEF AUTOREFCOUNT} GlobalContainer.Release(FConnectionProperties); {$ENDIF} FConnectionProperties := nil; end; end; procedure TNG_FDConnection.ReleaseDefaultConnection; begin FreeAndNil(FDefaultConnection); end; function TNG_FDConnection.GetAfterConnect: TNotifyEvent; begin Result := FFDConnection.AfterConnect; end; function TNG_FDConnection.GetAfterDisconnect: TNotifyEvent; begin Result := FFDConnection.AfterDisconnect; end; function TNG_FDConnection.GetConnected: Boolean; begin Result := FFDConnection.Connected; end; function TNG_FDConnection.GetConnection: TObject; begin Result := FFDConnection; end; function TNG_FDConnection.GetConnectionProperties: ICommonConnectionProperties; begin Result := FConnectionProperties; end; function TNG_FDConnection.GetServerType: TDatabaseTypeOption; begin Result := FServerType end; procedure TNG_FDConnection.SetAfterConnect(Value: TNotifyEvent); begin FFDConnection.AfterConnect := Value; end; procedure TNG_FDConnection.SetAfterDisconnect(Value: TNotifyEvent); begin FFDConnection.AfterDisconnect := Value; end; procedure TNG_FDConnection.SetConnected(Value: Boolean); begin if Value then FFDConnection.Open else begin if FFDConnection.Connected then FFDConnection.Close; end; end; procedure TNG_FDConnection.SetConnection(Value: TObject); begin CheckFalseFmt(Assigned(Value) and (Value is TFDConnection), Err_InvalidPointerInCodeRef, ['Value', 'TNG_FDConnection.SetConnection']); ReleaseDefaultConnection; FFDConnection := TFDConnection(Value); end; procedure TNG_FDConnection.SetConnectionString; begin if FServerType = dtoSQLite then begin FFDConnection.Params.Values['DriverID'] := 'SQLite'; FFDConnection.Params.Values['Database'] := FConnectionProperties.DatabaseName; end else if FServerType = dtoSQLServer then begin FFDConnection.Params.Values['DriverID'] := 'MSSQL'; FFDConnection.Params.Values['SERVER'] := FConnectionProperties.ServerName; FFDConnection.Params.Values['Database'] := FConnectionProperties.DatabaseName; FFDConnection.Params.Values['User_Name'] := FConnectionProperties.ServerLogin; FFDConnection.Params.Values['Password'] := FConnectionProperties.ServerPassword; if FConnectionProperties.OSAuthentication then FFDConnection.Params.Values['OSAuthent'] := 'YES' else FFDConnection.Params.Values['OSAuthent'] := 'NO'; end else begin raise EGlobalException.Create('Not Support Database Type!'); end; FConnectionProperties.ConnectionString := FFDConnection.ConnectionString; end; procedure TNG_FDConnection.SetServerType(Value: TDatabaseTypeOption); begin FServerType := Value; end; { TNG_FDDataProvider } function TNG_FDDataProvider.AddFieldBrackets(FieldName: string): string; begin Result := FieldName; if FieldName <= ' ' then exit; if Result[1] <> '[' then Result := '[' + Result; if Result[length(Result)] <> ']' then Result := Result + ']'; end; procedure TNG_FDDataProvider.AssignFieldValues(qry: TFDQuery; cds, cdsLog, cdsLogLink: TNGFDMemTable; TableName: string); var ValidLogs : Boolean; ChangeLogID : Integer; begin CheckFalseFmt(Assigned(qry) and qry.Active, Err_InvalidPointerInCodeRef, ['qry', 'TNG_FDDataProvider.AssignFieldValues']); CheckFalseFmt(Assigned(cds), Err_InvalidPointerInCodeRef, ['cds', 'TNG_FDDataProvider.AssignFieldValues']); ValidLogs := ValidLogDataSets(cdsLog, cdsLogLink); if ValidLogs then begin ChangeLogID := cdsLog.RecordCount + 1; cdsLog.Append; cdsLog.FieldByName('ChangeLogID').AsInteger := ChangeLogID; cdsLog.FieldByName('SystemGUID').AsWideString := NewGUID; cdsLog.FieldByName('TableName').AsWideString := TableName; cdsLog.FieldByName('ChangeTypeID').AsInteger := UpdateStatusToInt(cds.UpdateStatus); cdsLog.FieldByName('ChangeDate').AsDateTime := TTimeZone.Local.ToUniversalTime(Now); if (cds.FindField('SystemGUID') <> nil) and (not cds.FieldByName('SystemGUID').IsNull) then cdsLog.FieldByName('ItemGUID').asWideString := cds.FieldByName('SystemGUID').AsWideString else if (qry.FindField('SystemGUID') <> nil) and (not qry.FieldByName('SystemGUID').IsNull) then cdsLog.FieldByName('ItemGUID').asWideString := qry.FieldByName('SystemGUID').AsWideString; end; cds.ForEachField( function (Field: TField) : Boolean begin Result := (qry.FindField(Field.FieldName) <> nil) and ((not Field.IsNull) or (Field.NewValue <> Unassigned)); end, procedure (Field: TField) begin if ValidLogs then begin cdsLogLink.Append; cdsLogLink.FieldByName('ChangeLogID').AsInteger := ChangeLogID; cdsLogLink.FieldByName('FieldName').AsWideString := Field.FieldName; end; if Field.IsBlob then begin if ValidLogs then begin if not qry.EOF then TBlobField(cdsLogLink.FieldByName('OriginalValue')).Assign(qry.FieldByName(Field.FieldName)); TBlobField(cdsLogLink.FieldByName('NewValue')).Assign(Field); end; if (qry.State in [dsEdit, dsInsert]) then TBlobField(qry.FieldByName(Field.FieldName)).Assign(Field); end else if (Field.DataType <> ftAutoInc) and (qry.FieldByName(Field.FieldName).DataType <> ftAutoInc) then begin if (qry.FieldByName(Field.FieldName).Value <> Field.Value) then begin if ValidLogs then begin if not qry.EOF then cdsLogLink.FieldByName('OriginalValue').Value := qry.FieldByName(Field.FieldName).Value; cdsLogLink.FieldByName('NewValue').Value := Field.Value; end; if (qry.State in [dsEdit, dsInsert]) then qry.FieldByName(Field.FieldName).Value := Field.Value; end; end; if ValidLogs and (cdsLogLink.State = dsInsert) and (cdsLogLink.FieldByName('OriginalValue').Value <> cdsLogLink.FieldByName('NewValue').Value) then cdsLogLink.Post; end, nil ); if ValidLogs and (cdsLogLink.RecordCount > 0) then begin if cdsLog.State = dsInsert then cdsLog.Post; end; end; procedure TNG_FDDataProvider.AssignParamValues(qry: TFDQuery; cds, cdsMapping: TNGFDMemTable); var i : Integer; QryParam : TFDParam; begin for i := 0 to qry.Params.Count - 1 do begin QryParam := qry.Params[i]; if cdsMapping.Locate('ParamName', QryParam.Name, [loCaseInsensitive]) then QryParam.Value := cds.Fields[cdsMapping.FieldByName('FieldIndex').AsInteger].Value; end; end; procedure TNG_FDDataProvider.BeginTransaction; begin CheckFalse(GetConnected, RS_DatabaseNotConnected); TFDConnection(FDBConnection.Connection).Transaction.StartTransaction; end; function TNG_FDDataProvider.CanCancelCDS(cds: TNGFDMemTable): Boolean; begin Result := TDataSet.CanCancelDataSet(cds); end; function TNG_FDDataProvider.CanDeleteCDS(cds: TNGFDMemTable): Boolean; begin Result := TDataSet.CanDeleteDataSet(cds); end; function TNG_FDDataProvider.CanEditCDS(cds: TNGFDMemTable): Boolean; begin Result := TDataSet.CanEditDataSet(cds); end; function TNG_FDDataProvider.CanInsertCDS(cds: TNGFDMemTable): Boolean; begin Result := TDataSet.CanInsertDataSet(cds); end; function TNG_FDDataProvider.CanSaveCDS(cds: TNGFDMemTable): Boolean; begin Result := TDataSet.CanSaveDataSet(cds) or (cds.ChangeCount > 0); end; procedure TNG_FDDataProvider.cdsApplyUpdates(cds: TNGFDMemTable); var qry : TFDQuery; iqry : IObjCleaner; cdsDelta, cdsDelta2 : TNGFDMemTable; icdsDelta, icdsDelta2 : IObjCleaner; cdsMapping : TNGFDMemTable; icdsMapping : IObjCleaner; SearchRecord : Variant; SearchFields : string; begin PostCDS(cds); CheckFalse(GetConnected, RS_DatabaseNotConnected); if not (assigned(cds) and cds.Active and (cds.ChangeCount > 0)) then exit; // Create vars qry := TFDConnection(FDBConnection.Connection).CreateQuery; iqry := CreateObjCleaner(qry); cdsDelta := TNGFDMemTable.Create(nil); icdsDelta := CreateObjCleaner(cdsDelta); cdsDelta2 := TNGFDMemTable.Create(nil); icdsDelta2 := CreateObjCleaner(cdsDelta2); cdsMapping := TNGFDMemTable.Create(nil); icdsMapping := CreateObjCleaner(cdsMapping); // Initialize vars cdsDelta.Data := cds.Delta; cdsDelta2.Data := cds.Delta; PrepareQuery(qry, cds.SQL.Text, cds.Params); qry.Open; CreateFieldInfoCDS(cds, cdsMapping); cdsDelta.ForEachRecord(nil, procedure (ds : TDataSet) begin if cdsDelta.UpdateStatus = TUpdateStatus.usModified then begin cdsDelta2.RecNo := cdsDelta.RecNo - 1; SearchFields := cdsDelta2.GetFieldNames(',', True); SearchRecord := cdsDelta2.KeyFieldsValue(SearchFields); SearchFields := StringReplace(SearchFields, ',', ';', [rfReplaceAll]); if qry.Locate(SearchFields, SearchRecord, [loPartialKey]) then begin qry.Edit; AssignFieldValues(qry, cdsDelta, nil, nil, ''); qry.Post; end; end else if cdsDelta.UpdateStatus = TUpdateStatus.usInserted then begin AssignParamValues(qry, cdsDelta, cdsMapping); qry.Open; qry.Append; AssignFieldValues(qry, cdsDelta, nil, nil, ''); qry.Post; end else if cdsDelta.UpdateStatus = TUpdateStatus.usDeleted then begin SearchFields := cdsDelta.GetFieldNames(',', True); SearchRecord := cdsDelta.KeyFieldsValue(SearchFields); while qry.Locate(SearchFields, SearchRecord, []) do qry.Delete; end end ); cds.MergeChangeLog; end; procedure TNG_FDDataProvider.cdsApplyUpdatesTable(cds: TNGFDMemTable; TableName, TableAlias, WhereAnd, KeyFields: string); var qry : TFDQuery; iqry : IObjCleaner; cdsDelta, cdsDelta2 : TNGFDMemTable; icdsDelta, icdsDelta2 : IObjCleaner; cdsMapping : TNGFDMemTable; icdsMapping : IObjCleaner; begin PostCDS(cds); CheckFalse(GetConnected, RS_DatabaseNotConnected); if not (assigned(cds) and cds.Active and (cds.ChangeCount > 0)) then exit; // Create vars qry := TFDConnection(FDBConnection.Connection).CreateQuery; iqry := CreateObjCleaner(qry); cdsDelta := TNGFDMemTable.CreateDelta(nil, cds); icdsDelta := CreateObjCleaner(cdsDelta); cdsDelta2 := TNGFDMemTable.CreateDelta(nil, cds); icdsDelta2 := CreateObjCleaner(cdsDelta2); cdsMapping := TNGFDMemTable.Create(nil); icdsMapping := CreateObjCleaner(cdsMapping); qry.SQL.Text := GetQueryTextTable(TableName, TableAlias, WhereAnd, KeyFields, ''); CreateFieldInfoCDS(cds, cdsMapping); cdsDelta.ForEachRecord(nil, procedure (ds : TDataSet) begin qry.Close; if cdsDelta.UpdateStatus = TUpdateStatus.usModified then begin cdsDelta2.RecNo := cdsDelta.RecNo - 1; AssignParamValues(qry, cdsDelta2, cdsMapping); qry.Open; if not qry.EOF then begin qry.Edit; AssignFieldValues(qry, cdsDelta, nil, nil, TableName); qry.Post; end; end else if cdsDelta.UpdateStatus = TUpdateStatus.usInserted then begin qry.SQL.Text := GetQueryTextTable(TableName, TableAlias, 'and 1 = 0', '', ''); CreateFieldInfoCDS(cds, cdsMapping); AssignParamValues(qry, cdsDelta, cdsMapping); qry.Open; qry.Append; AssignFieldValues(qry, cdsDelta, nil, nil, TableName); qry.Post; end else if cdsDelta.UpdateStatus = TUpdateStatus.usDeleted then begin AssignParamValues(qry, cdsDelta, cdsMapping); qry.Open; AssignFieldValues(qry, cdsDelta, nil, nil, TableName); while not qry.EOF do qry.Delete; end end ); cds.MergeChangeLog; end; procedure TNG_FDDataProvider.cdsExec(cds: TNGFDMemTable); begin try cdsExecQryText(cds.SQL.Text, cds); except on E:Exception do raise EGlobalException.Create(E.Message); end; end; procedure TNG_FDDataProvider.cdsExecQryIndex(QryIndex : Integer; WhereAnd: string; cds : TNGFDMemTable); begin cdsExecQryText(GetQueryText(QryIndex, WhereAnd), cds); end; procedure TNG_FDDataProvider.cdsExecQryText(QryText: string; cds: TNGFDMemTable); begin cdsOpenQryTextExt(QryText, cds, True, False); end; procedure TNG_FDDataProvider.cdsOpen(cds: TNGFDMemTable; CreateFieldDefs : Boolean; LAppend: Boolean = False; LUseDP: Boolean = False); begin try cdsOpenQryText(cds.SQL.Text, cds, CreateFieldDefs); except on E:Exception do raise EGlobalException.Create(E.Message); end; end; procedure TNG_FDDataProvider.cdsOpenExt(cds: TNGFDMemTable; CreateFieldDefs: Boolean; var DataSetState: TomControlState); begin DataSetState := ocsLoading; try cdsOpen(cds, CreateFieldDefs); finally DataSetState := ocsIdle; end; end; procedure TNG_FDDataProvider.cdsOpenQryIndex(QryIndex : Integer; WhereAnd: string; cds : TNGFDMemTable; CreateFieldDefs : Boolean); begin cdsOpenQryText(GetQueryText(QryIndex, WhereAnd), cds, CreateFieldDefs); end; procedure TNG_FDDataProvider.cdsOpenQryText(QryText: string; cds: TNGFDMemTable; CreateFieldDefs : boolean; LAppend: Boolean = False; LUseDP: Boolean = False); begin cdsOpenQryTextExt(QryText, cds, False, CreateFieldDefs); end; procedure TNG_FDDataProvider.cdsOpenQryTextExt(QryText: string; cds: TNGFDMemTable; ExecQry, CreateFieldDefs: Boolean; LAppend: Boolean = False; LUseDP: Boolean = False); var qryAll : TFDQuery; iqryAll : IObjCleaner; cdsEvents : TNGFDMemTable; icdsEvents : IObjCleaner; begin CheckFalse(GetConnected, RS_DatabaseNotConnected); CheckFalseFmt(Assigned(cds), Err_InvalidPointerInCodeRef, ['cds', 'TNG_FDDataProvider.cdsOpenQryTextExt']); QryText := Trim(QryText); CheckFalseFmt(QryText > ' ', Err_InvalidPointerInCodeRef, ['QryText', 'TNG_FDDataProvider.cdsOpenQryTextExt']); cdsEvents := TNGFDMemTable.Create(nil); icdsEvents := CreateObjCleaner(cdsEvents); qryAll := (FDBConnection as TNG_FDConnection).FFDConnection.CreateQuery; iqryAll := CreateObjCleaner(qryAll); PrepareQuery(qryAll, QryText, cds.Params); if ExecQry then begin qryAll.ExecSQL; exit; end; qryAll.Open; try cdsEvents.CopyDataSetEvents(cds, True); QryToCDS(qryAll, cds, CreateFieldDefs); finally cds.CopyDataSetEvents(cdsEvents); end; end; procedure TNG_FDDataProvider.cdsOpenTable(const TableName, TableAlias, WhereAnd, OrderBy: string; cds: TNGFDMemTable; CreateFieldDefs : Boolean); begin cdsOpenQryText(GetQueryTextTable(TableName, TableAlias, WhereAnd, '', OrderBy), cds, CreateFieldDefs); end; procedure TNG_FDDataProvider.cdsOpenTableExt(const TableName, TableAlias, WhereAnd, OrderBy: string; cds: TNGFDMemTable; CreateFieldDefs: Boolean; var DataSetState: TomControlState); begin DataSetState := ocsLoading; try cdsOpenTable(TableName, TableAlias, WhereAnd, OrderBy, cds, CreateFieldDefs); finally DataSetState := ocsIdle; end; end; procedure TNG_FDDataProvider.cdsParamGenerate(cds: TNGFDMemTable); var qry : TFDQuery; iqry : IObjCleaner; i : Integer; qryParam : TFDParam; cdsParam : TParam; begin if cds.SQL.Text = '' then Exit; cds.Params.Clear; qry := (FDBConnection as TNG_FDConnection).FFDConnection.CreateQuery; iqry := CreateObjCleaner(qry); qry.SQL.Text := cds.SQL.Text; for i := 0 to qry.Params.Count - 1 do begin qryParam := qry.Params[i]; cdsParam := cds.Params.FindParam(qryParam.Name); if not Assigned(cdsParam) then begin cdsParam := cds.Params.AddParameter; cdsParam.Name := qryParam.Name; end; cdsParam.DataType := qryParam.DataType; end; end; procedure TNG_FDDataProvider.ReleaseDBConnection; begin {$IFNDEF AUTOREFCOUNT} GlobalContainer.Release(FDBConnection); {$ENDIF} FDBConnection := nil; end; procedure TNG_FDDataProvider.ResetQuery(cds: TNGFDMemTable); begin if not Assigned(cds) then exit; cds.Close; cds.Params.Clear; end; procedure TNG_FDDataProvider.CheckCDS(cds: TNGFDMemTable; cdsName: string; CheckActive: Boolean); begin TDataSet.CheckDataSet(cds, cdsName, CheckActive); end; function TNG_FDDataProvider.CheckTableAndField(const s: String): Boolean; begin Result := TFDConnection(FDBConnection.Connection).CheckTableAndField(s); end; function TNG_FDDataProvider.CloneDataProvider: ICommonDataProvider<TNGFDMemTable>; begin Result := ServiceLocator.GetService<ICommonDataProvider<TNGFDMemTable>>('FDConnection'); Result.DBConnection.ConnectionProperties.Assign(FDBConnection.ConnectionProperties); Result.DBConnection.SetConnectionString; Result.Connected := GetConnected; end; procedure TNG_FDDataProvider.CommitTransaction; begin CheckFalse(GetConnected, RS_DatabaseNotConnected); if TFDConnection(FDBConnection.Connection).InTransaction then TFDConnection(FDBConnection.Connection).Transaction.Commit; end; procedure TNG_FDDataProvider.CreateFieldInfoCDS(ds: TDataSet; cdsMapping: TNGFDMemTable); begin CheckFalseFmt(Assigned(ds) and ds.Active, Err_InvalidPointerInCodeRef, ['ds', 'TNG_FDDataProvider.CreateFieldInfoCDS']); CheckFalseFmt(Assigned(cdsMapping), Err_InvalidPointerInCodeRef, ['cdsMapping', 'TNG_FDDataProvider.CreateFieldInfoCDS']); cdsMapping.Close; cdsMapping.FieldDefs.Clear; cdsMapping.FieldDefs.Add('FieldName', ftWideString, 50, False); cdsMapping.FieldDefs.Add('DisplayName', ftWideString, 50, True); cdsMapping.FieldDefs.Add('ParamName', ftWideString, 50, True); cdsMapping.FieldDefs.Add('FieldIndex', ftInteger, 0, True); cdsMapping.CreateDataSet; // FieldName ds.ForEachField(nil, procedure (Field : TField) begin cdsMapping.Append; cdsMapping.FieldByName('FieldName').Value := Field.FieldName; cdsMapping.FieldByName('DisplayName').Value := Field.DisplayName; cdsMapping.FieldByName('ParamName').Value := FieldToParam(Field.FieldName); cdsMapping.FieldByName('FieldIndex').Value := Field.Index; cdsMapping.Post; end, nil ); end; procedure TNG_FDDataProvider.CreateParam(cds: TNGFDMemTable; ParamName: string; DataType: TFieldType; ParamValue: Variant); var p : TParam; begin CheckFalseFmt(Assigned(cds), Err_FalseConditionInCodeRef, ['cds', 'TNG_FDDataProvider.CreateParam']); if cds.Params.FindParam(ParamName) <> nil then p := cds.Params.FindParam(ParamName) else begin p := cds.Params.AddParameter; p.Name := ParamName; end; p.DataType := DataType; p.Value := ParamValue; end; destructor TNG_FDDataProvider.Destroy; begin ReleaseDBConnection; inherited; end; procedure TNG_FDDataProvider.DoCopyDataSet(qry: TFDQuery; cds: TNGFDMemTable); var Lcds : TNGFDMemTable; icds : IObjCleaner; Lcds2 : TNGFDMemTable; icds2 : IObjCleaner; begin checkFalseFmt(Assigned(Qry) and Qry.Active, Err_InvalidPointerInCodeRef, ['qry', 'TNG_FDDataProvider.DoCopyDataSet']); CheckCDS(cds, '', False); Lcds := TNGFDMemTable.Create(nil); icds := CreateObjCleaner(Lcds); Lcds2 := TNGFDMemTable.Create(nil); icds2 := CreateObjCleaner(Lcds2); MakeMultiRecordSetCDS(Lcds); DoCopyDataSetMulti(qry, cds); qry.NextRecordSet; if qry.Active then begin Lcds.append; TWideMemoField(Lcds.FieldByName('DataSet')).Value := cds.XMLData; Lcds.Post; while qry.Active do begin DoCopyDataSetMulti(qry, Lcds2); qry.NextRecordSet; end; cds.XMLData := Lcds.XMLData; end; cds.MergeChangeLog; end; procedure TNG_FDDataProvider.DoCopyDataSetMulti(qry: TFDQuery; cds: TNGFDMemTable); var cdsStructure : TNGFDMemTable; icdsStructure : IObjCleaner; begin checkFalseFmt(Assigned(Qry) and Qry.Active, Err_InvalidPointerInCodeRef, ['qry', 'TNG_FDDataProvider.DoCopyDataSet']); CheckCDS(cds, '', False); cdsStructure := TNGFDMemTable.Create(nil); icdsStructure := CreateObjCleaner(cdsStructure); cdsStructure.CloneCursor(cds, True, False); // Backup ReadOnly property cds.ForEachField( function (Field: TField) : Boolean begin Result := Field.ReadOnly; end, procedure (Field: TField) begin Field.ReadOnly := False; end, nil ); cds.CopyDataSet(qry); // Restore ReadOnly property cdsStructure.ForEachField( function (Field : TField): Boolean begin Result := Field.ReadOnly; end, procedure (Field: TField) begin cds.FieldByName(Field.FieldName).ReadOnly := True; end, nil ); cds.MergeChangeLog; end; constructor TNG_FDDataProvider.Create; begin inherited; CreateDBConnection; end; procedure TNG_FDDataProvider.CreateBlobParam(cds : TNGFDMemTable; ParamName: string; BlobType: TBlobType; Stream: TStream); var p : TParam; begin CheckFalseFmt(Assigned(cds), Err_FalseConditionInCodeRef, ['cds', 'TNG_FDDataProvider.CreateBlobParam']); if cds.Params.FindParam(ParamName) <> nil then p := cds.Params.FindParam(ParamName) else begin p := cds.Params.AddParameter; p.Name := ParamName; end; p.DataType := BlobType; P.LoadFromStream(Stream, BlobType); end; procedure TNG_FDDataProvider.CreateDBConnection; begin FDBConnection := TNG_FDConnection.Create; end; procedure TNG_FDDataProvider.CreateDefaultParams(cds: TNGFDMemTable; PageSize, PageNum: Integer); begin CheckCDS(cds, '', False); CreateParam(cds, 'PageSize', ftInteger, PageSize); CreateParam(cds, 'PageNum', ftInteger, PageNum); end; procedure TNG_FDDataProvider.ExecSQL(SQL: string); var cds : TNGFDMemTable; icds : IObjCleaner; begin cds := TNGFDMemTable.Create(nil); icds := CreateObjCleaner(cds); cds.SQL.Text := SQL; cdsExec(cds); end; function TNG_FDDataProvider.FieldToParam(FieldName: string): string; begin Result := StringReplace(FieldName, ' ', '_', [rfReplaceAll]); Result := StringReplace(Result, '/', '_', [rfReplaceAll]); Result := StringReplace(Result, '?', '_', [rfReplaceAll]); Result := StringReplace(Result, '-', '_', [rfReplaceAll]); end; function TNG_FDDataProvider.GetConnected: Boolean; begin Result := FDBConnection.Connected; end; function TNG_FDDataProvider.GetDBConnection: ICommonConnection; begin Result := FDBConnection; end; function TNG_FDDataProvider.GetKeyFieldValue(cds: TNGFDMemTable; KeyFieldName: string): Variant; begin Result := TDataSet(cds).KeyFieldsValue(KeyFieldName); end; function TNG_FDDataProvider.GetQueryText(QryIndex: Integer; WhereAnd: string): string; begin Result := StringReplace(DataModuleBase.GetQueryText(QryIndex), '--WHEREAND--', WhereAnd, [rfIgnoreCase, rfReplaceAll]); end; function TNG_FDDataProvider.GetQueryTextTable(const TableName, TableAlias, WhereAnd, KeyFields, OrderBy: string): string; begin Result := (FDBConnection as TNG_FDConnection).FFDConnection.GetQueryTextTable( TableName, TableAlias, WhereAnd, KeyFields, OrderBy); end; function TNG_FDDataProvider.GetServerDateTimeNow: TDateTime; var cds : TNGFDMemTable; icds : IObjCleaner; begin cds := TNGFDMemTable.Create(nil); icds := CreateObjCleaner(cds); cds.SQL.Text := 'select getDate()'; cdsOpen(cds, True); Result := cds.Fields[0].AsDateTime; end; function TNG_FDDataProvider.GetUseCloneDataProvider: Boolean; begin Result := FUseCloneDataProvider; end; function TNG_FDDataProvider.KeyFieldsToWhereAnd(TableAlias, KeyFields: string): string; var lstKeyFields : TStringList; ilstKeyFields : IObjCleaner; i : Integer; Alias : string; begin Result := ''; if KeyFields <= ' ' then exit; lstKeyFields := TStringList.Create; ilstKeyFields := CreateObjCleaner(lstKeyFields); lstKeyFields.Text := TextToListText(KeyFields); if TableAlias > ' ' then Alias := TableAlias + '.' else Alias := ''; for i := 0 to lstKeyFields.Count - 1 do Result := Result + #13#10' and ' + Alias + AddFieldBrackets(lstKeyFields[i]) + ' = :' + FieldToParam(lstKeyFields[i]); end; function TNG_FDDataProvider.LocateKeyField(cds: TNGFDMemTable; KeyFieldName: string; KeyValue: Variant): Boolean; begin Result := cds.Locate(KeyFieldName, KeyValue, []); end; procedure TNG_FDDataProvider.MakeMultiRecordSetCDS(cds: TNGFDMemTable); begin TDataSet.CheckDataSet(cds, 'cds', False); cds.Close; cds.FieldDefs.Clear; cds.FieldDefs.Add('DataSet', ftWideMemo, 0, True); cds.CreateDataSet; end; procedure TNG_FDDataProvider.PostCDS(cds: TNGFDMemTable); begin if Assigned(cds) and cds.Active and (cds.State in [dsEdit, dsInsert]) then cds.post; end; procedure TNG_FDDataProvider.PrepareQuery(qry: TFDQuery; const SQL: string; Params: TParams); var i: Integer; qryParam : TFDParam; cdsParam : TParam; begin if not Assigned(qry) then exit; qry.SQL.Text := SQL; if not Assigned(params) then exit; for i := 0 to qry.Params.Count - 1 do begin qryParam := qry.Params[i]; cdsParam := Params.FindParam(qryParam.Name); if Assigned(cdsParam) then begin if cdsParam.DataType = ftBlob then qryParam.Assign(cdsParam) else qryParam.Value := cdsParam.Value; end; end; end; procedure TNG_FDDataProvider.QryToCDS(qry: TFDQuery; cds: TNGFDMemTable; CreateFieldDefs: Boolean); begin checkFalseFmt(Assigned(Qry) and Qry.Active, Err_InvalidPointerInCodeRef, ['qry', 'TNG_FDDataProvider.QryToCDS']); cds.Close; if CreateFieldDefs then cds.CopyFieldDefs(qry) else cds.CreateDataSet; DoCopyDataSet(qry, cds); if cds.RecNo > 1 then cds.First; end; procedure TNG_FDDataProvider.RollbackTransaction; begin CheckFalse(GetConnected, RS_DatabaseNotConnected); if TFDConnection(FDBConnection.Connection).InTransaction then TFDConnection(FDBConnection.Connection).Transaction.Rollback; end; procedure TNG_FDDataProvider.SetConnected(Value: Boolean); begin FDBConnection.Connected := Value; end; procedure TNG_FDDataProvider.SetConnectionString( const ServerType: TDatabaseTypeOption; const HostName, DatabaseName, PortNumber, LoginName, LoginPassword: string; OSAuthentication: Boolean); begin FDBConnection.ServerType := ServerType; FDBConnection.ConnectionProperties.ServerName := HostName; FDBConnection.ConnectionProperties.DatabaseName := DatabaseName; FDBConnection.ConnectionProperties.PortNumber := PortNumber; FDBConnection.ConnectionProperties.ServerLogin := LoginName; FDBConnection.ConnectionProperties.ServerPassword := LoginPassword; FDBConnection.ConnectionProperties.OSAuthentication := OSAuthentication; FDBConnection.SetConnectionString; end; procedure TNG_FDDataProvider.SetUseCloneDataProvider(Value: Boolean); begin FUseCloneDataProvider := Value; end; function TNG_FDDataProvider.TextToListText(s: string): string; begin Result := StringReplace(StringReplace(s, ', ', '', [rfReplaceAll]), ',', #13#10, [rfReplaceAll]); end; function TNG_FDDataProvider.ValidLogDataSets(cdsLog, cdsLogLink: TNGFDMemTable): Boolean; begin Result := False; if not (assigned(cdsLog) and assigned(cdsLogLink)) then exit; if not (cdsLog.Active and cdsLogLink.Active) then exit; if cdsLog.FindField('SystemGUID') = nil then exit; if cdsLog.FindField('ChangeLogID') = nil then exit; if cdsLogLink.FindField('ChangeLogID') = nil then exit; if cdsLogLink.FindField('FieldName') = nil then exit; if cdsLogLink.FindField('OriginalValue') = nil then exit; if cdsLogLink.FindField('NewValue') = nil then exit; Result := True; end; initialization GlobalContainer.RegisterType<TNG_FDDataProvider>.Implements<IFDMemTableProvider>(CDP_IDENT_FD); end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q+,R+,S+,T-,V+,X+,Y+} {$M 65520,0,655360} {by Behdad Esfahbod Geometry Exam} program ProblemC; type Real = Extended; const MaxN = 50 + 1; MaxV = 1325 + 5; MaxD = 2 * MaxN + 3; Epsilon = 1E-5; type TPoint = record X, Y : Extended; end; TGVertex = array [0 .. MaxD] of Integer; {TVertex[0] is Degree of the vertex} TSegment = record A, B, C : Extended; P : array [1 .. 2] of TPoint; end; var N, K, V : Integer; Vs : array [1 .. MaxV] of TPoint; G : array [1 .. MaxV] of ^ TGVertex; E : array [1 .. MaxN, 0 .. MaxD] of Integer; {E[I, 0] is number of points on segment I} S : array [1 .. MaxN] of TSegment; Ans : Longint; P1, P2 : TPoint; I, J, I2, J2 : Integer; function D (P1, P2 : TPoint) : Extended; begin D := Sqrt(Sqr(P1.X - P2.X) + Sqr(P1.Y - P2.Y)); end; function Comp (A, B : Extended) : Integer; begin if Abs(A - B) < Epsilon then Comp := 0 else if A < B then Comp := -1 else Comp := 1; end; procedure ReadInput; begin Assign(Input, 'input.txt'); Reset(Input); Readln(N, K); for I := 1 to N do with S[I] do Readln(P[1].X, P[1].Y, P[2].X, P[2].Y); Close(Input); end; procedure WriteOutput; begin Assign(Output, 'output.txt'); ReWrite(Output); Writeln(Output, Ans); Close(Output); end; function AddVertex (P : TPoint) : Integer; var I : Integer; begin for I := 1 to V + 1 do if (Comp(P.X, Vs[I].X) = 0) and (Comp(P.Y, Vs[I].Y) = 0) then Break; if I = V + 1 then begin Inc(V); New(G[V + 1]); G[V + 1]^[0] := 0; Vs[V] := P; end; AddVertex := I; end; function InRange (A, I, J : Extended) : Boolean; begin InRange := ((Comp(I, A) <= 0) and (Comp(A, J) <= 0)) or ((Comp(I, A) >= 0) and (Comp(A, J) >= 0)); end; function Min (A, B : Extended) : Extended; begin if A <= B then Min := A else Min := B; end; function Max (A, B : Extended) : Extended; begin if A >= B then Max := A else Max := B; end; function IntersectSeg (var Q, R : TSegment; var P1, P2 : TPoint) : Integer; var INum : Integer; Z : Extended; begin Z := Q.A * R.B - Q.B * R.A; if Z = 0 then begin if (Q.C * R.B = Q.B * R.C) and (Q.A * R.C = Q.C * R.A) and (InRange(Q.P[1].X, R.P[1].X, R.P[2].X) or InRange(Q.P[2].X, R.P[1].X, R.P[2].X) or InRange(R.P[1].X, Q.P[1].X, Q.P[2].X) or InRange(R.P[2].X, Q.P[1].X, Q.P[2].X)) and (InRange(Q.P[1].Y, R.P[1].Y, R.P[2].Y) or InRange(Q.P[2].Y, R.P[1].Y, R.P[2].Y) or InRange(R.P[1].Y, Q.P[1].Y, Q.P[2].Y) or InRange(R.P[2].Y, Q.P[1].Y, Q.P[2].Y)) then begin IntersectSeg := 2; if Comp(Q.A, 0) = 0 then begin P1.X := Q.P[1].X; P1.Y := Min(Max(Q.P[1].Y, Q.P[2].Y), Max(R.P[1].Y, R.P[2].Y)); P2.X := Q.P[1].X; P2.Y := Max(Min(Q.P[1].Y, Q.P[2].Y), Min(R.P[1].Y, R.P[2].Y)); end else if Comp(Q.B / Q.A, 0) <= 0 then begin P1.X := Min(Max(Q.P[1].X, Q.P[2].X), Max(R.P[1].X, R.P[2].X)); P1.Y := Min(Max(Q.P[1].Y, Q.P[2].Y), Max(R.P[1].Y, R.P[2].Y)); P2.X := Max(Min(Q.P[1].X, Q.P[2].X), Min(R.P[1].X, R.P[2].X)); P2.Y := Max(Min(Q.P[1].Y, Q.P[2].Y), Min(R.P[1].Y, R.P[2].Y)); end else begin P1.X := Max(Min(Q.P[1].X, Q.P[2].X), Min(R.P[1].X, R.P[2].X)); P1.Y := Min(Max(Q.P[1].Y, Q.P[2].Y), Max(R.P[1].Y, R.P[2].Y)); P2.X := Min(Max(Q.P[1].X, Q.P[2].X), Max(R.P[1].X, R.P[2].X)); P2.Y := Max(Min(Q.P[1].Y, Q.P[2].Y), Min(R.P[1].Y, R.P[2].Y)); end; end else IntersectSeg := 0; Exit; end; P1.X := (Q.B * R.C - Q.C * R.B) / Z; P1.Y := (Q.C * R.A - Q.A * R.C) / Z; if not (InRange(P1.X, Q.P[1].X, Q.P[2].X) and InRange(P1.X, R.P[1].X, R.P[2].X) and InRange(P1.Y, Q.P[1].Y, Q.P[2].Y) and InRange(P1.Y, R.P[1].Y, R.P[2].Y)) then begin IntersectSeg := 0; Exit; end; IntersectSeg := 1; end; procedure FindLine (var S : TSegment); begin with S do begin A := (P[1].Y - P[2].Y); B := (P[2].X - P[1].X); C := - (A * P[1].X + B * P[1].Y); end; end; procedure AddVertexToSegment (J, K : Integer); var I : Integer; begin for I := 1 to E[J, 0] + 1 do if E[J, I] = K then Break; if I = E[J, 0] + 1 then begin Inc(E[J, 0]); E[J, E[J, 0]] := K; end; end; procedure FindVertices; var II : Integer; begin for I := 1 to N do with S[I] do begin FindLine(S[I]); II := AddVertex(P[1]); AddVertexToSegment(I, II); II := AddVertex(P[2]); AddVertexToSegment(I, II); end; for I := 1 to N do for J := 1 to I - 1 do begin I2 := IntersectSeg(S[I], S[J], P1, P2); if I2 > 0 then begin II := AddVertex(P1); AddVertexToSegment(I, II); AddVertexToSegment(J, II); if I2 > 1 then begin II := AddVertex(P2); AddVertexToSegment(I, II); AddVertexToSegment(J, II); end; end; end; end; function VComp (V1, V2 : TPoint) : Integer; begin if Comp(V1.X, V2.X) = 0 then VComp := Comp(V1.Y, V2.Y) else VComp := Comp(V1.X, V2.X); end; procedure AddEdgeToVertex (A, B : Integer); var I : Integer; begin for I := 1 to G[A]^[0] + 1 do if G[A]^[I] = B then Break; if I = G[A]^[0] + 1 then begin Inc(G[A]^[0]); G[A]^[G[A]^[0]] := B; end; end; procedure MakeEdges; begin for I := 1 to N do begin for J := 1 to E[I, 0] do for K := J + 1 to E[I, 0] do if VComp(Vs[E[I, J]], Vs[E[I, K]]) > 0 then begin I2 := E[I, J]; E[I, J] := E[I, K]; E[I, K] := I2; end; for J := 1 to E[I, 0] - 1 do begin AddEdgeToVertex(E[I, J], E[I, J + 1]); AddEdgeToVertex(E[I, J + 1], E[I, J]); end; end; end; function A (P1, P2 : TPoint) : Extended; var An : Extended; begin if Comp(P1.X, P2.X) = 0 then if Comp(P1.Y, P2.Y) <= 0 then An := Pi / 2 else An := 3 * Pi / 2 else begin An := ArcTan((P2.Y - P1.Y) / (P2.X - P1.X)); if Comp(P1.X, P2.X) > 0 then An := An + Pi; end; if Comp(An, 0) < 0 then An := An + 2 * Pi; if Comp(An, Pi) >= 0 then An := An - 2 * Pi; A := An; end; procedure FindFace (A, Indb : Integer); var Size, B, Ind, Ab, Bb, Ne, I, J : Integer; TT, TT2, TT3 : Extended; begin Size := 0; Ind := Indb; B := G[A]^[Ind]; Ab := A; Bb := B; repeat Ne := 1; TT := -1E10; for I := 1 to G[B]^[0] do if G[B]^[I] <> A then begin TT2 := ProblemC.A(Vs[B], Vs[G[B]^[I]]); TT3 := ProblemC.A(Vs[A], Vs[B]); TT2 := TT2 - TT3; if TT2 > TT then begin TT := TT2; Ne := I; end; end; Ind := Ne; A := B; B := G[B]^[Ind]; G[A]^[Ind] := G[A]^[G[A]^[0]]; Dec(G[A]^[0]); Inc(Size); until (A = Ab) and (B = Bb); if Size = K then Inc(Ans); end; procedure FindFaces; begin for I := 1 to V do while G[I]^[0] > 0 do FindFace(I, 1); end; procedure Solve; begin New(G[1]); G[1]^[0] := 0; FindVertices; MakeEdges; FindFaces; end; begin ReadInput; Solve; WriteOutput; end.
unit Teste.ChangeSetItem.Adapter; interface uses DUnitX.TestFramework, System.JSON, System.JSON.Readers, Vigilante.Infra.ChangeSetItem.DataAdapter; type [TestFixture] TChangeSetItemAdapterJSONTest = class private FChangeSetItem: TJSONObject; FAdapter: IChangeSetItemAdapter; procedure CarregarChange; procedure CarregarChangeSetDoisArquivos; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure CarregouAutor; [Test] procedure CarregouDescricao; [Test] procedure CarregouUmArquivo; [Test] procedure CarregouDoisArquivos; end; implementation uses System.IOUtils, System.SysUtils, System.Classes, Vigilante.Infra.ChangeSetItem.JSONDataAdapter, Teste.ChangeSet.JSONData; procedure TChangeSetItemAdapterJSONTest.Setup; begin CarregarChange; end; procedure TChangeSetItemAdapterJSONTest.TearDown; begin FreeAndNil(FChangeSetItem) end; procedure TChangeSetItemAdapterJSONTest.CarregouDescricao; const DESCRICAO = 'Descrição do commit'; begin Assert.AreEqual(DESCRICAO, FAdapter.DESCRICAO); end; procedure TChangeSetItemAdapterJSONTest.CarregouDoisArquivos; const ARQUIVO_CHANGESET1 = '/src/Classes/nomeDoArquivo.pas'; ARQUIVO_CHANGESET2 = '/src/Classes/nomeDoArquivo2.pas'; begin CarregarChangeSetDoisArquivos; Assert.AreEqual(2, Length(FAdapter.Arquivos)); Assert.AreEqual(ARQUIVO_CHANGESET1, FAdapter.Arquivos[0]); Assert.AreEqual(ARQUIVO_CHANGESET2, FAdapter.Arquivos[1]); end; procedure TChangeSetItemAdapterJSONTest.CarregouUmArquivo; const ARQUIVO_CHANGESET = '/src/Classes/nomeDoArquivo.pas'; begin Assert.AreEqual(1, Length(FAdapter.Arquivos)); Assert.AreEqual(ARQUIVO_CHANGESET, FAdapter.Arquivos[0]); end; procedure TChangeSetItemAdapterJSONTest.CarregarChange; begin if Assigned(FChangeSetItem) then FreeAndNil(FChangeSetItem); FChangeSetItem := TChangeSetJSONData.PegarChangeSetItem; FAdapter := TChangeSetItemAdapterJSON.Create(FChangeSetItem); end; procedure TChangeSetItemAdapterJSONTest.CarregarChangeSetDoisArquivos; begin if Assigned(FChangeSetItem) then FreeAndNil(FChangeSetItem); FChangeSetItem := TChangeSetJSONData.PegarChangeSetItemDoisArquivos; FAdapter := TChangeSetItemAdapterJSON.Create(FChangeSetItem); end; procedure TChangeSetItemAdapterJSONTest.CarregouAutor; begin Assert.AreEqual('Jose da Silva Sauro', FAdapter.Autor); end; initialization TDUnitX.RegisterTestFixture(TChangeSetItemAdapterJSONTest); end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 1024,0,0} { by Behdad Esfahbod Algorithmic Problems Book August '1999 Problem 10 O(N) Dynamic Method } program MaximumSumSubSequence; var I, J, BI, BJ : Integer; R, S, BS : Real; F : Text; begin Assign(F, 'input.txt'); Reset(F); BS := -1E30; I := 1; J := 0; while not Eof(F) do begin Inc(J); Readln(F, R); if S < 0 then begin I := J; S := 0; end; S := S + R; if S > BS then begin BI := I; BJ := J; BS := S; end; end; Close(F); Writeln(BI, ' ', BJ, ' ', BS : 0 : 3); end.
unit DrawObj; interface uses Windows, Classes, Forms, Archive, SysUtils, Controls, Figure, Global, StorageStruct; type TDrawObj = class(TObject) private FFormatText: UINT; FFont: LOGFONT; FPen: LOGPEN; FBrush: LOGBRUSH; FRect: TRect; FMarkerCursor: TCursor; FMarkerRect: TRect; FMarkerCount: Integer; FMarker: TPoint; FText: String; procedure DoGetMarkerCursor(MarkerID: Integer); procedure DoGetMarkerRect(MarkerID: Integer); procedure DoGetMarkerCount; procedure DoGetMarker(MarkerID: Integer); public constructor Create(ARect: TRect); virtual; destructor Destroy; override; function HitTest(P: TPoint; Selected: Boolean): Integer; function GetMarkerCursor(MarkerID: Integer): TCursor; virtual; function GetMarkerRect(MarkerID: Integer): TRect; virtual; function GetMarkerCount: Integer; virtual; function GetMarker(MarkerID: Integer): TPoint; virtual; procedure MoveTo(NewPosition: TRect); virtual; procedure MoveMarkerTo(MarkerID: Integer; P: TPoint); virtual; procedure Serialize(ar: TArchive); virtual; procedure DrawTracker(DC: HDC; State: TTrackerState); procedure Draw(DC: HDC); virtual; procedure SetPosition(ARect: TRect); property Position: TRect read FRect; property Pen: LOGPEN read FPen write FPen; property Brush: LOGBRUSH read FBrush write FBrush; property Font: LOGFONT read FFont write FFont; property FontFormat: UINT read FFormatText write FFormatText; property Text: String read FText write FText; end; TDrawRect = class(TDrawObj) private FPoints: TDrawPoint; FCountPoints: Integer; FRn: TPoint; FShape: TDrawShape; FName: String; FFysProp: TMultiStorageString; FAddProp: TMultiStorageString; procedure SetDrawShape(const Value: TDrawShape); procedure SetAddProp(const Value: TMultiStorageString); procedure SetFysProp(const Value: TMultiStorageString); public constructor Create(ARect: TRect); override; destructor Destroy; override; procedure Assign(Source: TDrawRect); procedure AddPoint(P: TPoint); procedure RemovePoint(Index: Integer); procedure RecalcBounds; procedure MoveTo(NewPosition: TRect); override; procedure MoveMarkerTo(MarkerID: Integer; P: TPoint); override; function GetMarkerCursor(MarkerID: Integer): TCursor; override; function GetMarkerRect(MarkerID: Integer): TRect; override; function GetMarkerCount: Integer; override; function GetMarker(MarkerID: Integer): TPoint; override; procedure Serialize(ar: TArchive); override; procedure Draw(DC: HDC); override; property Shape: TDrawShape read FShape write SetDrawShape; property NameFigure: String read FName write FName; property CountPoints: Integer read FCountPoints write FCountPoints; property Points: TDrawPoint read FPoints; property RoundNess: TPoint read FRn; property PropPhysical: TMultiStorageString read FFysProp write SetFysProp; property PropAdditional: TMultiStorageString read FAddProp write SetAddProp; function PtInFigure(P: TPoint): Boolean; end; function SelectBaseName(IDShape: TDrawShape): String; function GetDefaultFont: LOGFONT; var NUMBER_OBJ: LongInt; implementation uses CADFunction, ScaleData, Math; { Commont entry } function GetDefaultFont: LOGFONT; begin with Result do begin lfHeight:= Round(-8 * Screen.PixelsPerInch / 72); lfWidth:= 0; lfEscapement:= 0; lfOrientation:= 0; lfWeight:= FW_NORMAL; lfItalic:= 0; lfUnderline:= 0; lfStrikeOut:= 0; lfCharSet:= DEFAULT_CHARSET; lfOutPrecision:= OUT_DEFAULT_PRECIS; lfClipPrecision:= CLIP_DEFAULT_PRECIS; lfQuality:= DEFAULT_QUALITY; lfPitchAndFamily:= FF_ROMAN; StrCopy(lfFaceName, 'MS Sans Serif'); end; end; function SelectBaseName(IDShape: TDrawShape): String; begin Result:= 'Неизвестная' + IntToStr(NUMBER_OBJ); case IDShape of gfLine: Result:= 'Линия ' + IntToStr(NUMBER_OBJ); gfRectangle: Result:= 'Прямоугольник ' + IntToStr(NUMBER_OBJ); gfRoundRectangle: Result:= 'Округлый прямоугольник ' + IntToStr(NUMBER_OBJ); gfCircle: Result:= 'Круг ' + IntToStr(NUMBER_OBJ); gfEllipse: Result:= 'Эллипс ' + IntToStr(NUMBER_OBJ); gfPolyLine: Result:= 'Ломанная ' + IntToStr(NUMBER_OBJ); gfPolygon: Result:= 'Полигон ' + IntToStr(NUMBER_OBJ); gfBezier: Result:= 'Безье ' + IntToStr(NUMBER_OBJ); gfText: Result:= 'Текст ' + IntToStr(NUMBER_OBJ); end; end; { TDrawObj } constructor TDrawObj.Create(ARect: TRect); begin FRect:= ARect; FMarker:= Point(-1, -1); FMarkerRect:= Rect(-1, -1, -1, -1); FMarkerCount:= 8; FMarkerCursor:= crDefault; FPen.lopnStyle:= PS_SOLID; FPen.lopnWidth.x:= 1; FPen.lopnWidth.y:= 1; FPen.lopnColor:= RGB(0, 0, 0); FBrush.lbStyle:= BS_SOLID; FBrush.lbColor:= RGB(192, 192, 192); FBrush.lbHatch:= HS_VERTICAL; end; destructor TDrawObj.Destroy; begin inherited; end; procedure TDrawObj.Draw(DC: HDC); begin end; function TDrawObj.GetMarker(MarkerID: Integer): TPoint; begin DoGetMarker(MarkerID); Result:= FMarker; end; function TDrawObj.GetMarkerCount: Integer; begin DoGetMarkerCount; Result:= FMarkerCount;; end; function TDrawObj.GetMarkerCursor(MarkerID: Integer): TCursor; begin DoGetMarkerCursor(MarkerID); Result:= FMarkerCursor; end; function TDrawObj.GetMarkerRect(MarkerID: Integer): TRect; begin DoGetMarkerRect(MarkerID); Result:= FMarkerRect; end; procedure TDrawObj.MoveMarkerTo(MarkerID: Integer; P: TPoint); var R: TRect; begin R:= FRect; case MarkerID of 1: begin R.Left:= P.x; R.Top:= P.y; end; 2: R.Top:= P.y; 3: begin R.Right:= P.x; R.Top:= P.y; end; 4: R.Right:= P.x; 5: begin R.Right:= P.x; R.Bottom:= P.y; end; 6: R.Bottom:= P.y; 7: begin R.Left:= P.x; R.Bottom:= P.y; end; 8: R.Left:= P.x; end; MoveTo(R); end; procedure TDrawObj.MoveTo(NewPosition: TRect); begin if EqualRect(FRect, NewPosition) then Exit; FRect:= NewPosition; end; procedure TDrawObj.Serialize(ar: TArchive); var ft: Integer; begin if ar.IsStoring then // Save data begin ar.DataWrite(Integer(FFormatText)); ar.DataWrite(FFont); ar.DataWrite(FPen); ar.DataWrite(FBrush); ar.DataWrite(FRect); ar.DataWrite(FText); end else // Load data begin ar.DataRead(ft); FFormatText:= UINT(ft); ar.DataRead(FFont); ar.DataRead(FPen); ar.DataRead(FBrush); ar.DataRead(FRect); ar.DataRead(FText); end; end; procedure TDrawObj.SetPosition(ARect: TRect); begin FRect:= ARect; end; procedure TDrawObj.DoGetMarker(MarkerID: Integer); var xc, yc: Integer; begin FMarker:= Point(-1, -1); with FRect do begin xc:= Left + (Right - Left) div 2; yc:= Top + (Bottom - Top) div 2; case MarkerID of 1: FMarker:= Point(Left, Top); 2: FMarker:= Point(xc, Top); 3: FMarker:= Point(Right, Top); 4: FMarker:= Point(Right, yc); 5: FMarker:= Point(Right, Bottom); 6: FMarker:= Point(xc, Bottom); 7: FMarker:= Point(Left, Bottom); 8: FMarker:= Point(Left, yc); end; end; end; procedure TDrawObj.DoGetMarkerCount; begin FMarkerCount:= 8; end; procedure TDrawObj.DoGetMarkerCursor(MarkerID: Integer); begin FMarkerCursor:= crDefault; case MarkerID of 1, 5: FMarkerCursor:= crSizeNWSE; 2, 6: FMarkerCursor:= crSizeNS; 3, 7: FMarkerCursor:= crSizeNESW; 4, 8: FMarkerCursor:= crSizeWE; end; end; procedure TDrawObj.DoGetMarkerRect(MarkerID: Integer); var p: TPoint; begin p:= GetMarker(MarkerID); FMarkerRect:= Rect(p.x - DEFAULT_SPACE, p.y - DEFAULT_SPACE, p.x + SIZE_MARKER, p.y + SIZE_MARKER); end; procedure TDrawObj.DrawTracker(DC: HDC; State: TTrackerState); var i: Integer; p: TPoint; sm: Integer; begin sm:= DEFAULT_SPACE + SIZE_MARKER; case State of tsNormal: ; tsSelected, tsActive: for i:= 1 to GetMarkerCount do begin p:= GetMarker(i); PatBlt(DC, p.x - DEFAULT_SPACE, p.y - DEFAULT_SPACE, sm, sm, DSTINVERT); end; end; end; function TDrawObj.HitTest(P: TPoint; Selected: Boolean): Integer; var i: Integer; rc: TRect; begin if Selected then begin for i:= 1 to GetMarkerCount do begin rc:= GetMarkerRect(i); if PtInRect(rc, p) then begin Result:= i; Exit; end; end; end else if PtInRect(Position, p) then begin Result:= -1; Exit; end; Result:= 0; end; //************************************************************************* { TDrawRect } constructor TDrawRect.Create(ARect: TRect); begin inherited; // Тип фигуры FShape:= gfLine; // Загрузить шрифт по умолчанию FFont:= GetDefaultFont; // Выравнивание текста по умолчанию FFormatText:= DT_SINGLELINE or DT_LEFT or DT_TOP; // Текстовый параметр FText:= ''; // Имя фигуры FName:= SelectBaseName(FShape); // Округляющие значения для прямоугольника FRn:= Point(3 * PT_FYS, 3 * PT_FYS); // Количество точек полифигур FCountPoints:= 0; SetLength(FPoints, 0); // Списки свойств FFysProp:= TMultiStorageString.Create(DEFAULT_COUNT_PROP, COUNT_FYS_PROP); FAddProp:= TMultiStorageString.Create(DEFAULT_COUNT_PROP, COUNT_ADD_PROP); end; destructor TDrawRect.Destroy; begin FAddProp.Free; FFysProp.Free; Finalize(FPoints); FPoints:= nil; inherited; end; procedure TDrawRect.Draw(DC: HDC); var NewPen, OldPen: HPEN; NewBrush, OldBrush: HBRUSH; OldColorText, OldColorBack: COLORREF; OldBkMode: Integer; begin inherited; NewPen:= CreatePenIndirect(Pen); NewBrush:= CreateBrushIndirect(Brush); OldPen:= SelectObject(DC, NewPen); OldBrush:= SelectObject(DC, NewBrush); case FShape of gfRectangle: RectangleA(DC, Position); gfLine: LineA(DC, Position); gfEllipse: EllipseA(DC, Position); gfCircle: CircleA(DC, NormalizeRect(Position)); gfRoundRectangle: RoundRectangleA(DC, Position, FRn); gfPolygon: PolygonA(DC, FPoints); gfPolyLine: PolyLineA(DC, FPoints); gfBezier: BezierA(DC, FPoints); gfText: begin OldColorText:= SetTextColor(DC, Pen.lopnColor); OldColorBack:= SetBkColor(DC, Brush.lbColor); if (Brush.lbStyle = BS_SOLID) or (Brush.lbStyle = BS_HATCHED) then OldBkMode:= SetBkMode(DC, OPAQUE) else OldBkMode:= SetBkMode(DC, TRANSPARENT); TextOutA(DC, Text, NormalizeRect(Position), FFont, FFormatText); SetBkMode(DC, OldBkMode); SetBkColor(DC, OldColorBack); SetTextColor(DC, OldColorText); end; end; SelectObject(DC, OldBrush); SelectObject(DC, OldPen); DeleteObject(NewBrush); DeleteObject(NewPen); end; function TDrawRect.GetMarker(MarkerID: Integer): TPoint; var p: TPoint; begin if FShape in [gfPolygon, gfPolyLine, gfBezier] then begin Result:= FPoints[MarkerID - 1]; Exit; end; if (FShape = gfLine) and (MarkerID=2) then MarkerID:= 5 else if (FShape = gfRoundRectangle) and (MarkerID = 9) then begin p:= NormalizeRect(Position).BottomRight; p.x:= p.x - FRn.x div 2; p.y:= p.y - FRn.y div 2; Result:= p; Exit; end; DoGetMarker(MarkerID); Result:= FMarker; end; function TDrawRect.GetMarkerCount: Integer; begin DoGetMarkerCount; case FShape of gfLine: Result:= 2; gfRoundRectangle: Result:= FMarkerCount + 1; gfPolygon, gfPolyLine, gfBezier: Result:= Length(FPoints); else Result:= FMarkerCount; end; end; function TDrawRect.GetMarkerCursor(MarkerID: Integer): TCursor; begin if (FShape = gfLine) and (MarkerID = 2) then MarkerID:= 5 else if (FShape = gfRoundRectangle) and (MarkerID = 9) then begin Result:= crSizeAll; Exit; end; DoGetMarkerCursor(MarkerID); Result:= FMarkerCursor;; end; function TDrawRect.GetMarkerRect(MarkerID: Integer): TRect; begin DoGetMarkerRect(MarkerID); Result:= FMarkerRect; end; procedure TDrawRect.MoveMarkerTo(MarkerID: Integer; P: TPoint); var rc: TRect; begin if FShape in [gfPolygon, gfPolyLine, gfBezier] then begin if EqualPoint(FPoints[MarkerID-1], P) then Exit; FPoints[MarkerID - 1]:= P; RecalcBounds; Exit; end; if (FShape = gfLine) and (MarkerID = 2) then MarkerID:= 5 else if (FShape = gfRoundRectangle) and (MarkerID = 9) then begin rc:= NormalizeRect(Position); if (P.x > rc.Right - 1) then P.x:= rc.Right - 1 else if (P.x < rc.Left + (rc.Right - rc.Left) div 2) then P.x:= rc.Left + (rc.Right - rc.Left) div 2; if (P.y > rc.Bottom - 1) then P.y:= rc.Bottom - 1 else if (P.y < rc.Top + (rc.Bottom - rc.Top) div 2) then P.y:= rc.Top + (rc.Bottom - rc.Top) div 2; FRn.x:= 2 * (rc.Right - P.x); FRn.y:= 2 * (rc.Bottom - P.y); Exit; end; inherited; end; procedure TDrawRect.MoveTo(NewPosition: TRect); var i: Integer; r: TRect; begin if FShape in [gfPolygon, gfPolyLine, gfBezier] then begin if FCountPoints = 0 then Exit; r:= NormalizeRect(Position); if EqualRect(r, NewPosition) then Exit; for i:= 0 to High(FPoints) do begin FPoints[i].x:= FPoints[i].x + (NewPosition.Left - r.Left); FPoints[i].y:= FPoints[i].y + (NewPosition.Top - r.Top); end; SetPosition(NewPosition); end; inherited; end; procedure TDrawRect.Serialize(ar: TArchive); var i: Integer; begin inherited; if ar.IsStoring then //Save data begin ar.DataWrite(FPoints); ar.DataWrite(FRn); ar.DataWrite(Integer(FShape)); ar.DataWrite(FName); ar.DataWrite(FAddProp); ar.DataWrite(FFysProp); end else //Load data begin ar.DataRead(True); if Length(ar.Points) <> 0 then begin Finalize(FPoints); FPoints:= nil; SetLength(FPoints, Length(ar.Points)); for i:= 0 to High(ar.Points) do FPoints[i]:= ar.Points[i]; FCountPoints:= Length(FPoints); end; ar.DataRead(FRn); i:= 0; ar.DataRead(i); FShape:= TDrawShape(i); ar.DataRead(FName); ar.DataRead(FAddProp); ar.DataRead(FFysProp); end; end; procedure TDrawRect.RecalcBounds; var r: TRect; i: Integer; begin if Length(FPoints) = 0 then Exit; r:= Rect(FPoints[0].x, FPoints[0].y, FPoints[0].x, FPoints[0].y); for i:= 0 to High(FPoints) do begin if FPoints[i].x < r.Left then r.Left:= FPoints[i].x; if FPoints[i].x > r.Right then r.Right:= FPoints[i].x; if FPoints[i].y < r.Top then r.Top:= FPoints[i].y; if FPoints[i].y > r.Bottom then r.Bottom:= FPoints[i].y; end; if EqualRect(r, Position) then Exit; SetPosition(r); end; procedure TDrawRect.AddPoint(P: TPoint); begin if not (FShape in [gfPolygon, gfPolyLine, gfBezier]) then Exit; if Length(FPoints) > MAX_POINTS then Exit; SetLength(FPoints, Length(FPoints) + 1); FPoints[High(FPoints)]:= P; FCountPoints:= Length(FPoints); RecalcBounds; end; procedure TDrawRect.RemovePoint(Index: Integer); var tp: TDrawPoint; i: Integer; begin if not (FShape in [gfPolygon, gfPolyLine, gfBezier]) then Exit; if FCountPoints = 1 then Exit; SetLength(tp, Length(FPoints) - 1); try //****************************************** if Index = 1 then for i:= 1 to High(FPoints) do tp[i-1]:= FPoints[i] else if Index = Length(FPoints) then for i:= 0 to High(FPoints) - 1 do tp[i]:= FPoints[i] else begin for i:= 0 to Index - 1 do tp[i]:= FPoints[i]; for i:= Index to High(FPoints) do tp[i-1]:= FPoints[i]; end; //****************************************** Finalize(FPoints); FPoints:= nil; SetLength(FPoints, Length(tp)); for i:= 0 to High(tp) do FPoints[i]:= tp[i]; FCountPoints:= Length(FPoints); //****************************************** finally Finalize(tp); tp:= nil; end; RecalcBounds; end; function TDrawRect.PtInFigure(P: TPoint): Boolean; var rgn: HRGN; r: TRect; function PtInPolyFigure(const PtPoly: array of TPoint; Pt: TPoint): Boolean; var rgp: HRGN; begin rgp:= CreatePolygonRgn(PPoints(@PtPoly)^, High(PtPoly)+1, ALTERNATE); Result:= PtInRegion(rgp, Pt.X, Pt.Y); DeleteObject(rgp); end; begin Result:= False; r:= NormalizeRect(Position); InflateRect(r, SIZE_MARKER, SIZE_MARKER); case FShape of gfLine: Result:= PtInLine(Position, P) or (HitTest(P, True) <> 0); gfEllipse, gfCircle, gfRectangle, gfText: Result:= PtInRect(r, P); gfRoundRectangle: begin rgn:= CreateRoundRectRgn(r.Left, r.Top, r.Right, r.Bottom, FRn.x, FRn.y); Result:= PtInRegion(rgn, P.x, P.y); DeleteObject(rgn); end; gfPolyLine, gfPolygon, gfBezier: Result:= PtInPolyFigure(FPoints, P) or (HitTest(P, True) <> 0); end; end; procedure TDrawRect.SetDrawShape(const Value: TDrawShape); begin FShape:= Value; Inc(NUMBER_OBJ); FName:= SelectBaseName(Value); if FText = '' then FText:= FName; end; procedure TDrawRect.Assign(Source: TDrawRect); var i: Integer; begin with Self do begin SetPosition(Source.Position); FFormatText:= Source.FFormatText; FFont:= Source.Font; FPen:= Source.Pen; FBrush:= Source.Brush; FMarkerCursor:= Source.FMarkerCursor; FMarkerRect:= Source.FMarkerRect; FMarkerCount:= Source.FMarkerCount; FMarker:= Source.FMarker; FText:= Source.Text; FCountPoints:= Source.CountPoints; FRn:= Source.RoundNess; FShape:= Source.Shape; FName:= Source.NameFigure; if Length(Source.Fpoints) <> 0 then for i:= 0 to High(Source.FPoints) do FPoints[i]:= Source.FPoints[i]; end; end; procedure TDrawRect.SetAddProp(const Value: TMultiStorageString); begin FAddProp := Value; end; procedure TDrawRect.SetFysProp(const Value: TMultiStorageString); begin FFysProp := Value; end; end.
unit DockIntf; interface uses AppConstants, Client, Loan; type IDock = Interface(IInterface) ['{4D2068E2-715C-42F1-BA30-AC450E95F023}'] procedure DockForm(const fm: TForms; const title: string = ''); procedure AddRecentClient(ct: TClient); procedure AddRecentLoan(lln: TLoan); End; implementation end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Net.HttpClient.Linux; interface implementation uses System.Classes, System.Generics.Collections, System.SysUtils, System.Net.URLClient, System.Net.HttpClient, System.NetConsts, System.DateUtils, System.Types, Linuxapi.Curl, System.IOUtils, Posix.SysTypes, Posix.SysStat; type THTTPRequestMethod = (CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, TRACE, MERGE, PATCH, others); THTTPAuthSchemes = set of TCredentialsStorage.TAuthSchemeType; TLinuxHTTPClient = class(THTTPClient) private class constructor Create; class destructor Destroy; function GetServerCertInfoFromRequest(const ARequest: THTTPRequest; var ACertificate: TCertificate): Boolean; function GetCertInfo(ACertData: PCurlCertInfo; var ACertificate: TCertificate): Boolean; protected function DoExecuteRequest(const ARequest: THTTPRequest; var AResponse: THTTPResponse; const AContentStream: TStream): THTTPClient.TExecutionResult; override; function DoSetCredential(AnAuthTargetType: TAuthTargetType; const ARequest: THTTPRequest; const ACredential: TCredentialsStorage.TCredential): Boolean; override; function DoGetResponseInstance(const AContext: TObject; const AProc: TProc; const AsyncCallback: TAsyncCallback; const AsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: IURLRequest; const AContentStream: TStream): IAsyncResult; override; function DoGetHTTPRequestInstance(const AClient: THTTPClient; const ARequestMethod: string; const AURI: TURI): IHTTPRequest; override; function DoProcessStatus(const ARequest: IHTTPRequest; const AResponse: IHTTPResponse): Boolean; override; function DoGetSSLCertificateFromServer(const ARequest: THTTPRequest): TCertificate; override; procedure DoServerCertificateAccepted(const ARequest: THTTPRequest); override; procedure DoGetClientCertificates(const ARequest: THTTPRequest; const ACertificateList: TList<TCertificate>); override; function DoClientCertificateAccepted(const ARequest: THTTPRequest; const AnIndex: Integer): Boolean; override; class function CreateInstance: TURLClient; override; public constructor Create; end; TLinuxHTTPResponse = class; TLinuxHTTPRequest = class(THTTPRequest) private FRequest: PCurl; FHeaders: TDictionary<string, string>; FTempFileName: string; [Weak] FResponse: TLinuxHTTPResponse; FErrorBuff: array [0 .. CURL_ERROR_SIZE] of Byte; FLastMethodString: string; procedure InitRequest; procedure CleanupRequest; function ChooseAuthScheme(AAuthSchemes: THTTPAuthSchemes): LongInt; protected procedure DoPrepare; override; function GetHeaders: TNetHeaders; override; procedure AddHeader(const AName, AValue: string); override; function RemoveHeader(const AName: string): Boolean; override; function GetHeaderValue(const AName: string): string; override; procedure SetHeaderValue(const AName, Value: string); override; class function CurlReadData(buffer: Pointer; size: size_t; nitems: size_t; instream: Pointer): size_t; cdecl; static; class function CurlWriteData(buffer: Pointer; size: size_t; nitems: size_t; instream: Pointer): size_t; cdecl; static; class function CurlReadHeaders(buffer: Pointer; size: size_t; nitems: size_t; instream: Pointer): size_t; cdecl; static; public constructor Create(const AClient: THTTPClient; const ARequestMethod: string; const AURI: TURI); destructor Destroy; override; end; TLinuxHTTPResponse = class(THTTPResponse) private [Weak] FRequest: TLinuxHTTPRequest; FNativeHeaders: TStringList; FNativeStatusCode: string; FNativeStatusLine: string; FTotalReaded: Int64; FLeftToSend: Int64; function ReceiveData(buffer: Pointer; size: size_t; nitems: size_t): size_t; function ReceiveHeader(buffer: Pointer; size: size_t; nitems: size_t): size_t; function SendData(buffer: Pointer; size: size_t; nitems: size_t): size_t; protected procedure DoReadData(const AStream: TStream); override; function GetHeaders: TNetHeaders; override; function GetStatusCode: Integer; override; function GetStatusText: string; override; function GetVersion: THTTPProtocolVersion; override; function GetAuthSchemes: THTTPAuthSchemes; public constructor Create(const AContext: TObject; const AProc: TProc; const AAsyncCallback: TAsyncCallback; const AAsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: TLinuxHTTPRequest; const AContentStream: TStream); destructor Destroy; override; end; function MethodStringToHTTPMethod(const AMethodString: string): THTTPRequestMethod; var LMethod: string; begin LMethod := AMethodString.ToUpper; if LMethod = sHTTPMethodConnect then Result := THTTPRequestMethod.CONNECT else if LMethod = sHTTPMethodDelete then Result := THTTPRequestMethod.DELETE else if LMethod = sHTTPMethodGet then Result := THTTPRequestMethod.GET else if LMethod = sHTTPMethodHead then Result := THTTPRequestMethod.HEAD else if LMethod = sHTTPMethodOptions then Result := THTTPRequestMethod.OPTIONS else if LMethod = sHTTPMethodPost then Result := THTTPRequestMethod.POST else if LMethod = sHTTPMethodPut then Result := THTTPRequestMethod.PUT else if LMethod = sHTTPMethodTrace then Result := THTTPRequestMethod.TRACE else if LMethod = sHTTPMethodMerge then Result := THTTPRequestMethod.MERGE else if LMethod = sHTTPMethodPatch then Result := THTTPRequestMethod.PATCH else Result := THTTPRequestMethod.others; end; { TLinuxHTTPClient } constructor TLinuxHTTPClient.Create; begin inherited Initializer; end; class constructor TLinuxHTTPClient.Create; begin curl_global_init(CURL_GLOBAL_DEFAULT); end; class function TLinuxHTTPClient.CreateInstance: TURLClient; begin Result := TLinuxHTTPClient.Create; end; class destructor TLinuxHTTPClient.Destroy; begin curl_global_cleanup; end; function TLinuxHTTPClient.DoClientCertificateAccepted(const ARequest: THTTPRequest; const AnIndex: Integer): Boolean; begin { Not needed in Linux } Result := True; end; function TLinuxHTTPClient.DoExecuteRequest(const ARequest: THTTPRequest; var AResponse: THTTPResponse; const AContentStream: TStream): TLinuxHTTPClient.TExecutionResult; var LRequest: TLinuxHTTPRequest; LList: pcurl_slist; LMethod: THTTPRequestMethod; LSize: curl_off_t; //long LOption: CURLoption; LValue: TPair<string, string>; LCode: TCurlCode; LResponseCode: NativeInt; procedure RaiseCurlError(ARequest: TLinuxHTTPRequest; ACode: TCurlCode); var LError: string; begin LError := UTF8ToString(@ARequest.FErrorBuff[0]); if LError = '' then LError := UTF8ToString(curl_easy_strerror(ACode)); raise ENetHTTPClientException.CreateResFmt(@SNetHttpClientErrorAccessing, [ Integer(ACode), ARequest.FURL.ToString, LError]); end; begin Result := TExecutionResult.Success; LRequest := TLinuxHTTPRequest(ARequest); // Cleanup Response Headers SetLength(LRequest.FResponse.FHeaders, 0); LRequest.FResponse.FNativeHeaders.Clear; LRequest.FResponse.FTotalReaded := 0; LRequest.FResponse.FLeftToSend := 0; try LList := nil; try LMethod := MethodStringToHTTPMethod(LRequest.FMethodString); if LMethod in [THTTPRequestMethod.PUT, THTTPRequestMethod.POST] then begin LList := curl_slist_append(LList, MarshaledAString(UTF8String('Expect:'))); if Assigned(LRequest.FSourceStream) then begin LSize := LRequest.FSourceStream.Size - LRequest.FSourceStream.Position; if LSize < 0 then LSize := 0; end else LSize := 0; LRequest.FResponse.FLeftToSend := LSize; if LMethod = THTTPRequestMethod.PUT then LOption := CURLOPT_INFILESIZE_LARGE else LOption := CURLOPT_POSTFIELDSIZE; curl_easy_setopt(LRequest.FRequest, LOption, LSize); end; for LValue in LRequest.FHeaders do LList := curl_slist_append(LList, MarshaledAString(UTF8String(LValue.Key + ': ' + LValue.Value))); curl_easy_setopt(LRequest.FRequest, CURLOPT_HTTPHEADER, LList); LCode := curl_easy_perform(LRequest.FRequest); finally if LList <> nil then curl_slist_free_all(LList); end; case LCode of CURLE_OK: begin Result := TExecutionResult.Success; if curl_easy_getinfo(LRequest.FRequest, CURLINFO_RESPONSE_CODE, @LResponseCode) = CURLE_OK then TLinuxHTTPResponse(AResponse).FNativeStatusCode := LResponseCode.ToString; end; CURLE_SSL_ISSUER_ERROR, CURLE_SSL_CACERT: begin SetSecureFailureReasons([THTTPSecureFailureReason.InvalidCA]); Result := TExecutionResult.ServerCertificateInvalid; end; CURLE_SSL_INVALIDCERTSTATUS, CURLE_PEER_FAILED_VERIFICATION: begin SetSecureFailureReasons([THTTPSecureFailureReason.CertWrongUsage]); Result := TExecutionResult.ServerCertificateInvalid; end; CURLE_SSL_CACERT_BADFILE, CURLE_SSL_CIPHER: begin SetSecureFailureReasons([THTTPSecureFailureReason.InvalidCert]); Result := TExecutionResult.ServerCertificateInvalid; end; CURLE_SSL_CONNECT_ERROR, CURLE_SSL_ENGINE_NOTFOUND, CURLE_SSL_ENGINE_SETFAILED, CURLE_SSL_ENGINE_INITFAILED: begin SetSecureFailureReasons([THTTPSecureFailureReason.SecurityChannelError]); RaiseCurlError(LRequest, LCode); end; // CURLE_SSL_CERTPROBLEM: { Local client certificate problem } // Result := TExecutionResult.UnknownError; else RaiseCurlError(LRequest, LCode); end; finally // Update Headers & Cookies LRequest.FResponse.GetHeaders; end; end; procedure TLinuxHTTPClient.DoGetClientCertificates(const ARequest: THTTPRequest; const ACertificateList: TList<TCertificate>); begin inherited; { Not needed in Linux } end; function TLinuxHTTPClient.DoGetHTTPRequestInstance(const AClient: THTTPClient; const ARequestMethod: string; const AURI: TURI): IHTTPRequest; begin Result := TLinuxHTTPRequest.Create(AClient, ARequestMethod, AURI); end; function TLinuxHTTPClient.DoGetResponseInstance(const AContext: TObject; const AProc: TProc; const AsyncCallback: TAsyncCallback; const AsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: IURLRequest; const AContentStream: TStream): IAsyncResult; begin Result := TLinuxHTTPResponse.Create(AContext, AProc, AsyncCallback, AsyncCallbackEvent, ARequest as TLinuxHTTPRequest, AContentStream); end; function TLinuxHTTPClient.DoGetSSLCertificateFromServer(const ARequest: THTTPRequest): TCertificate; begin GetServerCertInfoFromRequest(ARequest, Result); end; function TLinuxHTTPClient.DoProcessStatus(const ARequest: IHTTPRequest; const AResponse: IHTTPResponse): Boolean; var LRequest: TLinuxHTTPRequest; LResponse: TLinuxHTTPResponse; begin LRequest := ARequest as TLinuxHTTPRequest; LResponse := AResponse as TLinuxHTTPResponse; // If the result is true then the while ends Result := True; if IsAutoRedirect(LResponse) then begin LRequest.FURL := ComposeRedirectURL(LRequest, LResponse); if IsAutoRedirectWithGET(LRequest, LResponse) then begin LRequest.FMethodString := sHTTPMethodGet; // Change to GET LRequest.FSourceStream := nil; // Dont send any data LRequest.RemoveHeader(sContentLength); LRequest.SetHeaderValue(sContentType, '');// Dont set content type end; Result := False; end; end; procedure TLinuxHTTPClient.DoServerCertificateAccepted(const ARequest: THTTPRequest); var LRequest: TLinuxHTTPRequest; begin inherited; LRequest := TLinuxHTTPRequest(ARequest); curl_easy_setopt(LRequest.FRequest, CURLOPT_SSL_VERIFYHOST, 0); curl_easy_setopt(LRequest.FRequest, CURLOPT_SSL_VERIFYPEER, 0); end; function TLinuxHTTPClient.DoSetCredential(AnAuthTargetType: TAuthTargetType; const ARequest: THTTPRequest; const ACredential: TCredentialsStorage.TCredential): Boolean; var LRequest: TLinuxHTTPRequest; LAuthSchemes: THTTPAuthSchemes; LCurlAuth: LongInt; begin LRequest := TLinuxHTTPRequest(ARequest); LAuthSchemes := LRequest.FResponse.GetAuthSchemes; if LAuthSchemes = [] then LAuthSchemes := [TCredentialsStorage.TAuthSchemeType.Basic]; LCurlAuth := LRequest.ChooseAuthScheme(LAuthSchemes); if AnAuthTargetType = TAuthTargetType.Server then begin curl_easy_setopt(LRequest.FRequest, CURLOPT_USERNAME, UTF8String(ACredential.UserName)); curl_easy_setopt(LRequest.FRequest, CURLOPT_PASSWORD, UTF8String(ACredential.Password)); curl_easy_setopt(LRequest.FRequest, CURLOPT_HTTPAUTH, LCurlAuth); end else begin curl_easy_setopt(LRequest.FRequest, CURLOPT_PROXYUSERNAME, UTF8String(ACredential.UserName)); curl_easy_setopt(LRequest.FRequest, CURLOPT_PROXYPASSWORD, UTF8String(ACredential.Password)); curl_easy_setopt(LRequest.FRequest, CURLOPT_PROXYAUTH, LCurlAuth); end; Result := True; end; function TLinuxHTTPClient.GetCertInfo(ACertData: PCurlCertInfo; var ACertificate: TCertificate): Boolean; var LDataList: pcurl_slist; LData: string; LPos: Integer; LKey, LValue: string; function GetDateFromGMT: TDateTime; begin LValue := LValue.Replace(' ', 'T', []); LPos := LValue.IndexOf(' '); if LPos > 0 then LValue := LValue.Substring(0, LPos); TryISO8601ToDate(LValue, Result); end; begin Result := False; if (ACertData <> nil) and (ACertData^.certinfo <> nil) and (ACertData^.certinfo^ <> nil) then begin Result := True; LDataList := ACertData^.certinfo^; repeat LData := UTF8ToString(LDataList^.data); LPos := LData.IndexOf(':'); LKey := LData.Substring(0, LPos); LValue := LData.Substring(LPos + 1); if SameText(LKey, 'Subject') then // do not localize ACertificate.Subject := LValue // do not localize else if SameText(LKey, 'Issuer') then // do not localize ACertificate.Issuer := LValue else if SameText(LKey, 'Expire date') then // do not localizev ACertificate.Expiry := GetDateFromGMT else if SameText(LKey, 'Start date') then // do not localize ACertificate.Start := GetDateFromGMT else if SameText(LKey, 'Signature Algorithm') then // do not localize ACertificate.AlgSignature := LValue else if SameText(LKey, 'Serial Number') then // do not localize ACertificate.SerialNum := LValue; LDataList := LDataList^.next; until LDataList = nil; end; end; function TLinuxHTTPClient.GetServerCertInfoFromRequest(const ARequest: THTTPRequest; var ACertificate: TCertificate): Boolean; var LRequest: TLinuxHTTPRequest; LCode: TCURLcode; LCertData: PCurlCertInfo; begin ACertificate := Default(TCertificate); LRequest := TLinuxHTTPRequest(ARequest); LCode := curl_easy_getinfo(LRequest.FRequest, CURLINFO_CERTINFO, @LCertData); if LCode = CURLE_OK then Result := GetCertInfo(LCertData, ACertificate) else raise ENetHTTPCertificateException.CreateRes(@SNetHttpCertificatesError); end; { TLinuxHTTPRequest } procedure TLinuxHTTPRequest.AddHeader(const AName, AValue: string); begin inherited; BaseAddHeader(AName, AValue); end; constructor TLinuxHTTPRequest.Create(const AClient: THTTPClient; const ARequestMethod: string; const AURI: TURI); begin inherited Create(AClient, ARequestMethod, AURI); FHeaders := TDictionary<string, string>.Create; InitRequest; end; destructor TLinuxHTTPRequest.Destroy; begin CleanupRequest; FHeaders.Free; if FTempFileName <> '' then TFile.Delete(FTempFileName); inherited Destroy; end; procedure TLinuxHTTPRequest.InitRequest; begin FRequest := curl_easy_init; { Setup common options for LibCurl } curl_easy_setopt(FRequest, CURLOPT_WRITEFUNCTION, @CurlReadData); curl_easy_setopt(FRequest, CURLOPT_WRITEDATA, Self); curl_easy_setopt(FRequest, CURLOPT_HEADERFUNCTION, @CurlReadHeaders); curl_easy_setopt(FRequest, CURLOPT_HEADERDATA, Self); curl_easy_setopt(FRequest, CURLOPT_CERTINFO, 1); curl_easy_setopt(FRequest, CURLOPT_TCP_KEEPALIVE, 1); curl_easy_setopt(FRequest, CURLOPT_NOPROGRESS, 1); curl_easy_setopt(FRequest, CURLOPT_ERRORBUFFER, @FErrorBuff[0]); end; procedure TLinuxHTTPRequest.CleanupRequest; begin if FRequest <> nil then begin curl_easy_cleanup(FRequest); FRequest := nil; end; end; class function TLinuxHTTPRequest.CurlReadData(buffer: Pointer; size, nitems: size_t; instream: Pointer): size_t; begin if instream <> nil then Result := TLinuxHTTPRequest(instream).FResponse.ReceiveData(buffer, size, nitems) else Result := 0; end; class function TLinuxHTTPRequest.CurlReadHeaders(buffer: Pointer; size: size_t; nitems: size_t; instream: Pointer): size_t; begin if instream <> nil then Result := TLinuxHTTPRequest(instream).FResponse.ReceiveHeader(buffer, size, nitems) else Result := 0; end; class function TLinuxHTTPRequest.CurlWriteData(buffer: Pointer; size, nitems: size_t; instream: Pointer): size_t; begin if instream <> nil then Result := TLinuxHTTPRequest(instream).FResponse.SendData(buffer, size, nitems) else Result := 0; end; function TLinuxHTTPRequest.ChooseAuthScheme(AAuthSchemes: THTTPAuthSchemes): LongInt; var LCurlAuths: LongInt; begin curl_easy_getinfo(FRequest, CURLINFO_HTTPAUTH_AVAIL, @LCurlAuths); if (TCredentialsStorage.TAuthSchemeType.NTLM in AAuthSchemes) and (LCurlAuths and CURLAUTH_NTLM <> 0) then Result := CURLAUTH_NTLM else if (TCredentialsStorage.TAuthSchemeType.Negotiate in AAuthSchemes) and (LCurlAuths and CURLAUTH_NEGOTIATE <> 0) then Result := CURLAUTH_NEGOTIATE else if (TCredentialsStorage.TAuthSchemeType.Digest in AAuthSchemes) and (LCurlAuths and CURLAUTH_DIGEST <> 0) then Result := CURLAUTH_DIGEST else if TCredentialsStorage.TAuthSchemeType.Basic in AAuthSchemes then Result := CURLAUTH_BASIC else Result := 0; end; procedure TLinuxHTTPRequest.DoPrepare; var LTmpFile: TFileStream; LDecompress: THTTPCompressionMethods; LEncodings: string; LAuthSchemes: THTTPAuthSchemes; LCurlAuth: LongInt; begin inherited; if (FLastMethodString <> '') and not SameText(FLastMethodString, FMethodString) then begin CleanupRequest; InitRequest; end; FLastMethodString := FMethodString; curl_easy_setopt(FRequest, CURLOPT_URL, UTF8String(FURL.ToString)); if FURL.Username <> '' then begin SetCredential(TCredentialsStorage.TCredential.Create(TAuthTargetType.Server, '', FURL.ToString, FURL.Username, FURL.Password)); curl_easy_setopt(FRequest, CURLOPT_USERNAME, UTF8String(FURL.Username)); curl_easy_setopt(FRequest, CURLOPT_PASSWORD, UTF8String(FURL.Password)); end; if FClient.ProxySettings.Host <> '' then begin curl_easy_setopt(FRequest, CURLOPT_PROXY, UTF8String(FClient.ProxySettings.Host)); if FClient.ProxySettings.Port > 0 then curl_easy_setopt(FRequest, CURLOPT_PROXYPORT, FClient.ProxySettings.Port); end; if FClientCertPath <> '' then begin if ExtractFileExt(FClientCertPath).ToLower = 'p12' then curl_easy_setopt(FRequest, CURLOPT_SSLCERTTYPE, UTF8String('P12')) else curl_easy_setopt(FRequest, CURLOPT_SSLCERTTYPE, UTF8String('PEM')); if curl_easy_setopt(FRequest, CURLOPT_SSLCERT, UTF8String(FClientCertPath)) <> CURLE_OK then raise ENetHTTPCertificateException.CreateRes(@SNetHttpCertificateImportError); end else begin if FClientCertificate <> nil then begin FTempFileName := TPath.GetTempFileName + '.pem'; LTmpFile := TFileStream.Create(FTempFileName, fmCreate, S_IRUSR); try FClientCertificate.Position := 0; LTmpFile.CopyFrom(FClientCertificate, FClientCertificate.Size); finally LTmpFile.Free; end; curl_easy_setopt(FRequest, CURLOPT_SSLCERTTYPE, UTF8String('PEM')); if curl_easy_setopt(FRequest, CURLOPT_SSLCERT, UTF8String(FTempFileName)) <> CURLE_OK then raise ENetHTTPCertificateException.CreateRes(@SNetHttpCertificateImportError); end; end; if FClientCertPassword <> '' then curl_easy_setopt(FRequest, CURLOPT_KEYPASSWD, UTF8String(FClientCertPath)); LDecompress := TLinuxHTTPClient(FClient).AutomaticDecompression; if TLinuxHTTPClient(FClient).AutomaticDecompression <> [] then begin if THTTPCompressionMethod.Any in LDecompress then LEncodings := #0 else begin LEncodings := ''; if THTTPCompressionMethod.Deflate in LDecompress then LEncodings := LEncodings + ', deflate'; // do not translate if THTTPCompressionMethod.GZip in LDecompress then LEncodings := LEncodings + ', gzip'; // do not translate if THTTPCompressionMethod.Brotli in LDecompress then LEncodings := LEncodings + ', br'; // do not translate LEncodings := Copy(LEncodings, 3, MaxInt); end; curl_easy_setopt(FRequest, CURLOPT_HTTP_CONTENT_DECODING, 1); curl_easy_setopt(FRequest, CURLOPT_ENCODING, UTF8String(LEncodings)); end; if TLinuxHTTPClient(FClient).UseDefaultCredentials then begin LAuthSchemes := FResponse.GetAuthSchemes; if LAuthSchemes <> [] then begin LCurlAuth := ChooseAuthScheme(LAuthSchemes); curl_easy_setopt(FRequest, CURLOPT_USERPWD, UTF8String(':')); curl_easy_setopt(FRequest, CURLOPT_HTTPAUTH, LCurlAuth); end; end; { Handle request methods } case MethodStringToHTTPMethod(FMethodString) of THTTPRequestMethod.GET, THTTPRequestMethod.CONNECT, THTTPRequestMethod.OPTIONS, THTTPRequestMethod.TRACE, THTTPRequestMethod.MERGE, THTTPRequestMethod.PATCH, THTTPRequestMethod.DELETE, THTTPRequestMethod.others: curl_easy_setopt(FRequest, CURLOPT_CUSTOMREQUEST, PUTF8Char(UTF8String(FMethodString))); THTTPRequestMethod.PUT: begin curl_easy_setopt(FRequest, CURLOPT_UPLOAD, 1); curl_easy_setopt(FRequest, CURLOPT_READFUNCTION, @CurlWriteData); curl_easy_setopt(FRequest, CURLOPT_READDATA, Self); end; THTTPRequestMethod.HEAD: begin curl_easy_setopt(FRequest, CURLOPT_CUSTOMREQUEST, UTF8String(FMethodString)); curl_easy_setopt(FRequest, CURLOPT_NOBODY, 1); end; THTTPRequestMethod.POST: begin curl_easy_setopt(FRequest, CURLOPT_POST, 1); curl_easy_setopt(FRequest, CURLOPT_READFUNCTION, @CurlWriteData); curl_easy_setopt(FRequest, CURLOPT_READDATA, Self); end; end; end; function TLinuxHTTPRequest.GetHeaders: TNetHeaders; var Value: TPair<string, string>; CntHeader: Integer; begin SetLength(Result, 500); // Max 500 headers CntHeader := 0; for Value in FHeaders do begin Result[CntHeader].Create(Value.Key, Value.Value); Inc(CntHeader); end; SetLength(Result, CntHeader); end; function TLinuxHTTPRequest.GetHeaderValue(const AName: string): string; begin Result := ''; FHeaders.TryGetValue(AName, Result); end; function TLinuxHTTPRequest.RemoveHeader(const AName: string): Boolean; begin Result := True; if GetHeaderValue(AName) = '' then Result := False else FHeaders.Remove(AName); end; procedure TLinuxHTTPRequest.SetHeaderValue(const AName, Value: string); begin inherited; FHeaders.AddOrSetValue(AName, Value); end; { TLinuxHTTPResponse } constructor TLinuxHTTPResponse.Create(const AContext: TObject; const AProc: TProc; const AAsyncCallback: TAsyncCallback; const AAsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: TLinuxHTTPRequest; const AContentStream: TStream); begin inherited Create(AContext, AProc, AAsyncCallback, AAsyncCallbackEvent, ARequest, AContentStream); FRequest := ARequest; FRequest.FResponse := Self; FNativeHeaders := TStringList.Create; end; destructor TLinuxHTTPResponse.Destroy; begin FNativeHeaders.Free; inherited; end; procedure TLinuxHTTPResponse.DoReadData(const AStream: TStream); begin inherited; // Do nothing end; function TLinuxHTTPResponse.GetHeaders: TNetHeaders; var I, P: Integer; LPos: Integer; LName: string; LValue: string; procedure AddOrSetHeader; var J: Integer; begin for J := 0 to P - 1 do begin if SameText(FHeaders[J].Name, LName) then begin FHeaders[J].Value := FHeaders[J].Value + ', ' + LValue; Exit; end; end; FHeaders[P].Create(LName, LValue); Inc(P); end; begin if Length(FHeaders) = 0 then begin SetLength(FHeaders, FNativeHeaders.Count); P := 0; for I := 0 to FNativeHeaders.Count - 1 do begin LPos := FNativeHeaders[I].IndexOf(':'); LName := FNativeHeaders[I].Substring(0, LPos); LValue := FNativeHeaders[I].Substring(LPos + 1).Trim; if SameText(LName, sSetCookie) then InternalAddCookie(LValue) else AddOrSetHeader; end; SetLength(Result, P); end; Result := FHeaders; end; function TLinuxHTTPResponse.GetStatusCode: Integer; begin TryStrToInt(FNativeStatusCode, Result); end; function TLinuxHTTPResponse.GetStatusText: string; begin Result := FNativeStatusLine; end; function TLinuxHTTPResponse.GetVersion: THTTPProtocolVersion; var LVersion: string; LValues: TArray<string>; begin if FNativeStatusLine <> '' then begin LValues := FNativeStatusLine.Split([' ']); LVersion := LValues[0]; if string.CompareText(LVersion, 'HTTP/1.0') = 0 then Result := THTTPProtocolVersion.HTTP_1_0 else if string.CompareText(LVersion, 'HTTP/1.1') = 0 then Result := THTTPProtocolVersion.HTTP_1_1 else if string.CompareText(LVersion, 'HTTP/2.0') = 0 then Result := THTTPProtocolVersion.HTTP_2_0 else Result := THTTPProtocolVersion.UNKNOWN_HTTP; end else Result := THTTPProtocolVersion.UNKNOWN_HTTP; end; function TLinuxHTTPResponse.ReceiveData(buffer: Pointer; size, nitems: size_t): size_t; var LAbort: Boolean; LContentLength: Int64; LStatusCode: Integer; LTotal: Integer; function GetEarlyStatusCode: Integer; var LTmp: TArray<string>; begin Result := GetStatusCode; if Result = 0 then begin LTmp := FNativeStatusLine.Split([' ']); if Length(LTmp) > 2 then begin FNativeStatusCode := LTmp[1]; Result := GetStatusCode; end; end; end; begin LAbort := False; LTotal := nitems * size; Inc(FTotalReaded, LTotal); LContentLength := GetContentLength; LStatusCode := GetEarlyStatusCode; FRequest.DoReceiveDataProgress(LStatusCode, LContentLength, FTotalReaded, LAbort); if not LAbort then Result := FStream.Write(buffer^, LTotal) else Result := 0 end; function TLinuxHTTPResponse.ReceiveHeader(buffer: Pointer; size, nitems: size_t): size_t; var LHeader: string; LPos: Integer; begin LHeader := UTF8ToString(buffer).Trim; LPos := LHeader.IndexOf(':'); if LPos > 0 then FNativeHeaders.Add(LHeader) else if LHeader <> '' then FNativeStatusLine := LHeader; Result := size * nitems; end; function TLinuxHTTPResponse.SendData(buffer: Pointer; size, nitems: size_t): size_t; begin if FLeftToSend > 0 then begin Result := FRequest.FSourceStream.Read(buffer^, size * nitems); Dec(FLeftToSend, Result); end else Result := 0; end; function TLinuxHTTPResponse.GetAuthSchemes: THTTPAuthSchemes; var LHeaders: TNetHeaders; LHeader: TNameValuePair; LAuths: TArray<string>; LAuth: string; i: Integer; begin Result := []; LHeaders := GetHeaders(); for LHeader in LHeaders do if SameText(LHeader.Name, sWWWAuthenticate) then begin LAuths := LHeader.Value.Split([',']); for i := 0 to Length(LAuths) - 1 do begin LAuth := LAuths[i].Trim.ToLower(); if LAuth = 'basic' then // do not translate Include(Result, TCredentialsStorage.TAuthSchemeType.Basic) else if LAuth = 'digest' then // do not translate Include(Result, TCredentialsStorage.TAuthSchemeType.Digest) else if LAuth = 'ntlm' then // do not translate Include(Result, TCredentialsStorage.TAuthSchemeType.NTLM) else if LAuth = 'negotiate' then // do not translate Include(Result, TCredentialsStorage.TAuthSchemeType.Negotiate); end; end; end; initialization TURLSchemes.RegisterURLClientScheme(TLinuxHTTPClient, 'HTTP'); TURLSchemes.RegisterURLClientScheme(TLinuxHTTPClient, 'HTTPS'); finalization TURLSchemes.UnRegisterURLClientScheme('HTTP'); TURLSchemes.UnRegisterURLClientScheme('HTTPS'); end.
unit frmServerGUIU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, VCL.Graphics, VCL.Controls, VCL.Forms, VCL.Dialogs, ReflectorsU, VCL.Buttons, System.Actions, VCL.ActnList, VCL.ComCtrls, System.UITypes, VCL.ExtCtrls, VCL.Imaging.jpeg, Vcl.ToolWin; type TfrmServerGUI = class(TForm) ToolBar1: TToolBar; ActionList: TActionList; ActionStartStop: TAction; ToolButton1: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ActionRefresh: TAction; StatusBar: TStatusBar; ToolButton5: TToolButton; ToolButton6: TToolButton; ActionConfig: TAction; Timer: TTimer; Image1: TImage; procedure FormCreate(Sender: TObject); procedure ActionStartStopExecute(Sender: TObject); procedure ActionStartStopUpdate(Sender: TObject); procedure ActionRefreshExecute(Sender: TObject); procedure ActionConfigExecute(Sender: TObject); procedure ActionConfigUpdate(Sender: TObject); procedure TimerTimer(Sender: TObject); private FReflectors: TReflectors; public { Public declarations } end; var frmServerGUI: TfrmServerGUI; implementation {$R *.dfm} uses frmNetReflectorU; procedure TfrmServerGUI.ActionConfigExecute(Sender: TObject); var LfrmNetReflector: TfrmNetReflector; begin LfrmNetReflector := TfrmNetReflector.Create(Self); try LfrmNetReflector.ShowModal; finally FreeAndNil(LfrmNetReflector); end; FReflectors.LoadSettings; end; procedure TfrmServerGUI.ActionConfigUpdate(Sender: TObject); begin ActionConfig.Enabled := not FReflectors.IsRunning; end; procedure TfrmServerGUI.ActionRefreshExecute(Sender: TObject); begin StatusBar.SimpleText := Format('%d reflector(s) active', [FReflectors.RunCount]) end; procedure TfrmServerGUI.ActionStartStopExecute(Sender: TObject); begin if FReflectors.IsRunning then begin if not FReflectors.Stop then begin MessageDlg('Failed to stop reflectors', mtError, [mbOK], 0); end; end else begin if not FReflectors.Start then begin MessageDlg('Failed to start reflectors', mtError, [mbOK], 0); end; end; ActionRefresh.Execute; end; procedure TfrmServerGUI.ActionStartStopUpdate(Sender: TObject); begin if FReflectors.IsRunning then begin ActionStartStop.Caption := 'Stop'; ActionStartStop.ImageIndex := 6; end else begin ActionStartStop.Caption := 'Start'; ActionStartStop.ImageIndex := 5; end; end; procedure TfrmServerGUI.FormCreate(Sender: TObject); begin FReflectors := TReflectors.Create(Self); FReflectors.LoadSettings; end; procedure TfrmServerGUI.TimerTimer(Sender: TObject); begin ActionRefresh.Execute; end; end.
unit CncFileManagerDevice; interface uses SysUtils, Classes, ComCtrls, JvAppStorage, JvAppIniStorage; type TCncFileManagerDevice = class(TComponent) constructor Create(AOwner : TComponent); override; private FDeviceName : string; FIniStorage : TJvCustomAppMemoryFileStorage; FDirList : TListItems; function GetMachineSelected : integer; virtual; procedure SetMachineSelected(Value : integer); virtual; protected public procedure GetMachineCollection(Dest : TCollection); virtual; property DeviceName : string read FDeviceName write FDeviceName; property MachineSelected : integer read GetMachineSelected write SetMachineSelected; property DirList : TListItems read FDirList; end; type TDiskFileManagerDevice = class(TCncFileManagerDevice) constructor Create(AOwner : TComponent; ADisk : string); private FDisk : string; public property Disk : string read FDisk; end; procedure Register; implementation constructor TCncFileManagerDevice.Create(AOwner : TComponent); begin inherited Create(AOwner); FDeviceName := ''; FDirList := TListItems.Create(nil); FIniStorage := nil; end; function TCncFileManagerDevice.GetMachineSelected : integer; begin result := FIniStorage.ReadInteger('MACHINE\MachineSelected', -1); end; procedure TCncFileManagerDevice.SetMachineSelected(Value : integer); begin FIniStorage.WriteInteger('MACHINE\MachineSelected', Value); end; procedure TCncFileManagerDevice.GetMachineCollection(Dest : TCollection); begin FIniStorage.ReadCollection('MACHINE', Dest, True, 'Cnc'); end; constructor TDiskFileManagerDevice.Create(AOwner : TComponent; ADisk : string); begin inherited Create(AOwner); FDisk := ADisk; FIniStorage := TJvAppIniFileStorage.Create(AOwner); FIniStorage.Path := 'ROOT'; FIniStorage.Location := flCustom; FIniStorage.FileName := ADisk+'\SYSTEM\CncFileManager.ini'; FDeviceName := FIniStorage.ReadString('DeviceName', 'Unknown device'); end; procedure Register; begin RegisterComponents('Exemples', [TCncFileManagerDevice]); end; end.
unit RakNetTypes; interface uses SocketIncludes; type //namespace RakNet { /// Forward declarations // RakPeerInterface = class; //class BitStream; //struct Packet; TsocketFamily = ( AF_INET, AF_INET6 ); TStartupResult = ( RAKNET_STARTED, RAKNET_ALREADY_STARTED, INVALID_SOCKET_DESCRIPTORS, INVALID_MAX_CONNECTIONS, SOCKET_FAMILY_NOT_SUPPORTED, SOCKET_PORT_ALREADY_IN_USE, SOCKET_FAILED_TO_BIND, SOCKET_FAILED_TEST_SEND, PORT_CANNOT_BE_ZERO, FAILED_TO_CREATE_NETWORK_THREAD, COULD_NOT_GENERATE_GUID, STARTUP_OTHER_FAILURE ); TConnectionAttemptResult = ( CONNECTION_ATTEMPT_STARTED, INVALID_PARAMETER, CANNOT_RESOLVE_DOMAIN_NAME, ALREADY_CONNECTED_TO_ENDPOINT, CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS, SECURITY_INITIALIZATION_FAILED ); /// Returned from RakPeerInterface::GetConnectionState() TConnectionState = ( /// Connect() was called, but the process hasn't started yet IS_PENDING, /// Processing the connection attempt IS_CONNECTING, /// Is connected and able to communicate IS_CONNECTED, /// Was connected, but will disconnect as soon as the remaining messages are delivered IS_DISCONNECTING, /// A connection attempt failed and will be aborted IS_SILENTLY_DISCONNECTING, /// No longer connected IS_DISCONNECTED, /// Was never connected, or else was disconnected long enough ago that the entry has been discarded IS_NOT_CONNECTED ); { TODO -oshadow_tj : convert this to delphi } ///// Given a number of bits, return how many bytes are needed to represent that. //#define BITS_TO_BYTES(x) (((x)+7)>>3) //#define BYTES_TO_BITS(x) ((x)<<3) // ///// \sa NetworkIDObject.h //typedef unsigned char UniqueIDType; //typedef unsigned short SystemIndex; //typedef unsigned char RPCIndex; //const int MAX_RPC_MAP_SIZE=((RPCIndex)-1)-1; //const int UNDEFINED_RPC_INDEX=((RPCIndex)-1); // ///// First byte of a network message //typedef unsigned char MessageID; // //typedef uint32_t BitSize_t; // //#if defined(_MSC_VER) && _MSC_VER > 0 //#define PRINTF_64_BIT_MODIFIER "I64" //#else //#define PRINTF_64_BIT_MODIFIER "ll" //#endif /// Used with the PublicKey structure TPublicKeyMode = ( /// The connection is insecure. You can also just pass 0 for the pointer to PublicKey in RakPeerInterface::Connect() PKM_INSECURE_CONNECTION, /// Accept whatever public key the server gives us. This is vulnerable to man in the middle, but does not require /// distribution of the public key in advance of connecting. PKM_ACCEPT_ANY_PUBLIC_KEY, /// Use a known remote server public key. PublicKey::remoteServerPublicKey must be non-zero. /// This is the recommended mode for secure connections. PKM_USE_KNOWN_PUBLIC_KEY, /// Use a known remote server public key AND provide a public key for the connecting client. /// PublicKey::remoteServerPublicKey, myPublicKey and myPrivateKey must be all be non-zero. /// The server must cooperate for this mode to work. /// I recommend not using this mode except for server-to-server communication as it significantly increases the CPU requirements during connections for both sides. /// Furthermore, when it is used, a connection password should be used as well to avoid DoS attacks. PKM_USE_TWO_WAY_AUTHENTICATION ); /// Passed to RakPeerInterface::Connect() TPublicKey = packed record /// How to interpret the public key, see above publicKeyMode: TPublicKeyMode; /// Pointer to a public key of length cat::EasyHandshake::PUBLIC_KEY_BYTES. See the Encryption sample. remoteServerPublicKey: PChar; /// (Optional) Pointer to a public key of length cat::EasyHandshake::PUBLIC_KEY_BYTES myPublicKey: PChar; /// (Optional) Pointer to a private key of length cat::EasyHandshake::PRIVATE_KEY_BYTES myPrivateKey: PChar; end; /// Describes the local socket to use for RakPeer::Startup TSocketDescriptor = packed record // SocketDescriptor(); // SocketDescriptor(unsigned short _port, const char *_hostAddress); /// The local port to bind to. Pass 0 to have the OS autoassign a port. port: Word; /// The local network card address to bind to, such as "127.0.0.1". Pass an empty string to use INADDR_ANY. hostAddress: Array[0..32] of char; /// IP version: For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. /// IPV6 is the newer internet protocol. Instead of addresses such as natpunch.jenkinssoftware.com, you may have an address such as fe80::7c:31f7:fec4:27de%14. /// Encoding takes 16 bytes instead of 4, so IPV6 is less efficient for bandwidth. /// On the positive side, NAT Punchthrough is not needed and should not be used with IPV6 because there are enough addresses that routers do not need to create address mappings. /// RakPeer::Startup() will fail if this IP version is not supported. /// \pre RAKNET_SUPPORT_IPV6 must be set to 1 in RakNetDefines.h for AF_INET6 socketFamily: TsocketFamily; remotePortRakNetWasStartedOn_PS3_PSP2: Word; // Required for Google chrome chromeInstance: _PP_Instance_; // Set to true to use a blocking socket (default, do not change unless you have a reason to) blockingSocket: Boolean; /// XBOX only: set IPPROTO_VDP if you want to use VDP. If enabled, this socket does not support broadcast to 255.255.255.255 extraSocketOptions: Integer; end; //extern bool NonNumericHostString( const char *host ); // ///// \brief Network address for a system ///// \details Corresponds to a network address<BR> ///// This is not necessarily a unique identifier. For example, if a system has both LAN and internet connections, the system may be identified by either one, depending on who is communicating<BR> ///// Therefore, you should not transmit the SystemAddress over the network and expect it to identify a system, or use it to connect to that system, except in the case where that system is not behind a NAT (such as with a dedciated server) ///// Use RakNetGUID for a unique per-instance of RakPeer to identify systems //struct RAK_DLL_EXPORT SystemAddress //{ // /// Constructors // SystemAddress(); // SystemAddress(const char *str); // SystemAddress(const char *str, unsigned short port); // // /// SystemAddress, with RAKNET_SUPPORT_IPV6 defined, holds both an sockaddr_in6 and a sockaddr_in // union// In6OrIn4 // { //#if RAKNET_SUPPORT_IPV6==1 // struct sockaddr_storage sa_stor; // sockaddr_in6 addr6; //#endif // // sockaddr_in addr4; // } address; // // /// This is not used internally, but holds a copy of the port held in the address union, so for debugging it's easier to check what port is being held // unsigned short debugPort; // // /// \internal Return the size to write to a bitStream // static int size(void); // // /// Hash the system address // static unsigned long ToInteger( const SystemAddress &sa ); // // /// Return the IP version, either IPV4 or IPV6 // /// \return Either 4 or 6 // unsigned char GetIPVersion(void) const; // // /// \internal Returns either IPPROTO_IP or IPPROTO_IPV6 // /// \sa GetIPVersion // unsigned int GetIPPROTO(void) const; // // /// Call SetToLoopback(), with whatever IP version is currently held. Defaults to IPV4 // void SetToLoopback(void); // // /// Call SetToLoopback() with a specific IP version // /// \param[in] ipVersion Either 4 for IPV4 or 6 for IPV6 // void SetToLoopback(unsigned char ipVersion); // // /// \return If was set to 127.0.0.1 or ::1 // bool IsLoopback(void) const; // // // Return the systemAddress as a string in the format <IP>|<Port> // // Returns a static string // // NOT THREADSAFE // // portDelineator should not be '.', ':', '%', '-', '/', a number, or a-f // const char *ToString(bool writePort=true, char portDelineator='|') const; // // // Return the systemAddress as a string in the format <IP>|<Port> // // dest must be large enough to hold the output // // portDelineator should not be '.', ':', '%', '-', '/', a number, or a-f // // THREADSAFE // void ToString(bool writePort, char *dest, char portDelineator='|') const; // // /// Set the system address from a printable IP string, for example "192.0.2.1" or "2001:db8:63b3:1::3490" // /// You can write the port as well, using the portDelineator, for example "192.0.2.1|1234" // /// \param[in] str A printable IP string, for example "192.0.2.1" or "2001:db8:63b3:1::3490". Pass 0 for \a str to set to UNASSIGNED_SYSTEM_ADDRESS // /// \param[in] portDelineator if \a str contains a port, delineate the port with this character. portDelineator should not be '.', ':', '%', '-', '/', a number, or a-f // /// \param[in] ipVersion Only used if str is a pre-defined address in the wrong format, such as 127.0.0.1 but you want ip version 6, so you can pass 6 here to do the conversion // /// \note The current port is unchanged if a port is not specified in \a str // /// \return True on success, false on ipVersion does not match type of passed string // bool FromString(const char *str, char portDelineator='|', int ipVersion=0); // // /// Same as FromString(), but you explicitly set a port at the same time // bool FromStringExplicitPort(const char *str, unsigned short port, int ipVersion=0); // // /// Copy the port from another SystemAddress structure // void CopyPort( const SystemAddress& right ); // // /// Returns if two system addresses have the same IP (port is not checked) // bool EqualsExcludingPort( const SystemAddress& right ) const; // // /// Returns the port in host order (this is what you normally use) // unsigned short GetPort(void) const; // // /// \internal Returns the port in network order // unsigned short GetPortNetworkOrder(void) const; // // /// Sets the port. The port value should be in host order (this is what you normally use) // /// Renamed from SetPort because of winspool.h http://edn.embarcadero.com/article/21494 // void SetPortHostOrder(unsigned short s); // // /// \internal Sets the port. The port value should already be in network order. // void SetPortNetworkOrder(unsigned short s); // // /// Old version, for crap platforms that don't support newer socket functions // bool SetBinaryAddress(const char *str, char portDelineator=':'); // /// Old version, for crap platforms that don't support newer socket functions // void ToString_Old(bool writePort, char *dest, char portDelineator=':') const; // // /// \internal sockaddr_in6 requires extra data beyond just the IP and port. Copy that extra data from an existing SystemAddress that already has it // void FixForIPVersion(const SystemAddress &boundAddressToSocket); // // bool IsLANAddress(void); // // SystemAddress& operator = ( const SystemAddress& input ); // bool operator==( const SystemAddress& right ) const; // bool operator!=( const SystemAddress& right ) const; // bool operator > ( const SystemAddress& right ) const; // bool operator < ( const SystemAddress& right ) const; // // /// \internal Used internally for fast lookup. Optional (use -1 to do regular lookup). Don't transmit this. // SystemIndex systemIndex; // // private: // //#if RAKNET_SUPPORT_IPV6==1 // void ToString_New(bool writePort, char *dest, char portDelineator) const; //#endif //}; // ///// Uniquely identifies an instance of RakPeer. Use RakPeer::GetGuidFromSystemAddress() and RakPeer::GetSystemAddressFromGuid() to go between SystemAddress and RakNetGUID ///// Use RakPeer::GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) to get your own GUID //struct RAK_DLL_EXPORT RakNetGUID //{ // RakNetGUID(); // explicit RakNetGUID(uint64_t _g) {g=_g; systemIndex=(SystemIndex)-1;} //// uint32_t g[6]; // uint64_t g; // // // Return the GUID as a string // // Returns a static string // // NOT THREADSAFE // const char *ToString(void) const; // // // Return the GUID as a string // // dest must be large enough to hold the output // // THREADSAFE // void ToString(char *dest) const; // // bool FromString(const char *source); // // static unsigned long ToUint32( const RakNetGUID &g ); // // RakNetGUID& operator = ( const RakNetGUID& input ) // { // g=input.g; // systemIndex=input.systemIndex; // return *this; // } // // // Used internally for fast lookup. Optional (use -1 to do regular lookup). Don't transmit this. // SystemIndex systemIndex; // static int size() {return (int) sizeof(uint64_t);} // // bool operator==( const RakNetGUID& right ) const; // bool operator!=( const RakNetGUID& right ) const; // bool operator > ( const RakNetGUID& right ) const; // bool operator < ( const RakNetGUID& right ) const; //}; // ///// Index of an invalid SystemAddress ////const SystemAddress UNASSIGNED_SYSTEM_ADDRESS = ////{ //// 0xFFFFFFFF, 0xFFFF ////}; //#ifndef SWIG //const SystemAddress UNASSIGNED_SYSTEM_ADDRESS; //const RakNetGUID UNASSIGNED_RAKNET_GUID((uint64_t)-1); //#endif ////{ //// {0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF} //// 0xFFFFFFFFFFFFFFFF ////}; // // //struct RAK_DLL_EXPORT AddressOrGUID //{ // RakNetGUID rakNetGuid; // SystemAddress systemAddress; // // SystemIndex GetSystemIndex(void) const {if (rakNetGuid!=UNASSIGNED_RAKNET_GUID) return rakNetGuid.systemIndex; else return systemAddress.systemIndex;} // bool IsUndefined(void) const {return rakNetGuid==UNASSIGNED_RAKNET_GUID && systemAddress==UNASSIGNED_SYSTEM_ADDRESS;} // void SetUndefined(void) {rakNetGuid=UNASSIGNED_RAKNET_GUID; systemAddress=UNASSIGNED_SYSTEM_ADDRESS;} // static unsigned long ToInteger( const AddressOrGUID &aog ); // const char *ToString(bool writePort=true) const; // void ToString(bool writePort, char *dest) const; // // AddressOrGUID() {} // AddressOrGUID( const AddressOrGUID& input ) // { // rakNetGuid=input.rakNetGuid; // systemAddress=input.systemAddress; // } // AddressOrGUID( const SystemAddress& input ) // { // rakNetGuid=UNASSIGNED_RAKNET_GUID; // systemAddress=input; // } // AddressOrGUID( Packet *packet ); // AddressOrGUID( const RakNetGUID& input ) // { // rakNetGuid=input; // systemAddress=UNASSIGNED_SYSTEM_ADDRESS; // } // AddressOrGUID& operator = ( const AddressOrGUID& input ) // { // rakNetGuid=input.rakNetGuid; // systemAddress=input.systemAddress; // return *this; // } // // AddressOrGUID& operator = ( const SystemAddress& input ) // { // rakNetGuid=UNASSIGNED_RAKNET_GUID; // systemAddress=input; // return *this; // } // // AddressOrGUID& operator = ( const RakNetGUID& input ) // { // rakNetGuid=input; // systemAddress=UNASSIGNED_SYSTEM_ADDRESS; // return *this; // } // // inline bool operator==( const AddressOrGUID& right ) const {return (rakNetGuid!=UNASSIGNED_RAKNET_GUID && rakNetGuid==right.rakNetGuid) || (systemAddress!=UNASSIGNED_SYSTEM_ADDRESS && systemAddress==right.systemAddress);} //}; // //typedef uint64_t NetworkID; // ///// This represents a user message from another system. //struct Packet //{ // /// The system that send this packet. // SystemAddress systemAddress; // // /// A unique identifier for the system that sent this packet, regardless of IP address (internal / external / remote system) // /// Only valid once a connection has been established (ID_CONNECTION_REQUEST_ACCEPTED, or ID_NEW_INCOMING_CONNECTION) // /// Until that time, will be UNASSIGNED_RAKNET_GUID // RakNetGUID guid; // // /// The length of the data in bytes // unsigned int length; // // /// The length of the data in bits // BitSize_t bitSize; // // /// The data from the sender // unsigned char* data; // // /// @internal // /// Indicates whether to delete the data, or to simply delete the packet. // bool deleteData; // // /// @internal // /// If true, this message is meant for the user, not for the plugins, so do not process it through plugins // bool wasGeneratedLocally; //}; // ///// Index of an unassigned player //const SystemIndex UNASSIGNED_PLAYER_INDEX = 65535; // ///// Unassigned object ID //const NetworkID UNASSIGNED_NETWORK_ID = (uint64_t) -1; // //const int PING_TIMES_ARRAY_SIZE = 5; // //struct RAK_DLL_EXPORT uint24_t //{ // uint32_t val; // // uint24_t() {} // inline operator uint32_t() { return val; } // inline operator uint32_t() const { return val; } // // inline uint24_t(const uint24_t& a) {val=a.val;} // inline uint24_t operator++() {++val; val&=0x00FFFFFF; return *this;} // inline uint24_t operator--() {--val; val&=0x00FFFFFF; return *this;} // inline uint24_t operator++(int) {uint24_t temp(val); ++val; val&=0x00FFFFFF; return temp;} // inline uint24_t operator--(int) {uint24_t temp(val); --val; val&=0x00FFFFFF; return temp;} // inline uint24_t operator&(const uint24_t& a) {return uint24_t(val&a.val);} // inline uint24_t& operator=(const uint24_t& a) { val=a.val; return *this; } // inline uint24_t& operator+=(const uint24_t& a) { val+=a.val; val&=0x00FFFFFF; return *this; } // inline uint24_t& operator-=(const uint24_t& a) { val-=a.val; val&=0x00FFFFFF; return *this; } // inline bool operator==( const uint24_t& right ) const {return val==right.val;} // inline bool operator!=( const uint24_t& right ) const {return val!=right.val;} // inline bool operator > ( const uint24_t& right ) const {return val>right.val;} // inline bool operator < ( const uint24_t& right ) const {return val<right.val;} // inline const uint24_t operator+( const uint24_t &other ) const { return uint24_t(val+other.val); } // inline const uint24_t operator-( const uint24_t &other ) const { return uint24_t(val-other.val); } // inline const uint24_t operator/( const uint24_t &other ) const { return uint24_t(val/other.val); } // inline const uint24_t operator*( const uint24_t &other ) const { return uint24_t(val*other.val); } // // inline uint24_t(const uint32_t& a) {val=a; val&=0x00FFFFFF;} // inline uint24_t operator&(const uint32_t& a) {return uint24_t(val&a);} // inline uint24_t& operator=(const uint32_t& a) { val=a; val&=0x00FFFFFF; return *this; } // inline uint24_t& operator+=(const uint32_t& a) { val+=a; val&=0x00FFFFFF; return *this; } // inline uint24_t& operator-=(const uint32_t& a) { val-=a; val&=0x00FFFFFF; return *this; } // inline bool operator==( const uint32_t& right ) const {return val==(right&0x00FFFFFF);} // inline bool operator!=( const uint32_t& right ) const {return val!=(right&0x00FFFFFF);} // inline bool operator > ( const uint32_t& right ) const {return val>(right&0x00FFFFFF);} // inline bool operator < ( const uint32_t& right ) const {return val<(right&0x00FFFFFF);} // inline const uint24_t operator+( const uint32_t &other ) const { return uint24_t(val+other); } // inline const uint24_t operator-( const uint32_t &other ) const { return uint24_t(val-other); } // inline const uint24_t operator/( const uint32_t &other ) const { return uint24_t(val/other); } // inline const uint24_t operator*( const uint32_t &other ) const { return uint24_t(val*other); } //}; // //} // namespace RakNet // //#endif implementation end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit REST.Backend.Exception; interface uses System.Classes, System.SysUtils; type EBackendError = class(Exception); EBackendServiceError = class(EBackendError); EBackendProviderError = class(EBackendError); EBackendAPIError = class(EBackendError); implementation end.
{****************************************************} {* NexusDB Client Messaging *} {* Provides the ability for NexusDB clients to send messages *} {* to other clients. *} {******************************************************************} {* Unit contains client side components *} {******************************************************************} {* Released as freeware *} {* Authors: Nathan Sutcliffe, Terry Haan *} {******************************************************************} { ResourceString: Dario 13/03/13 Nada para fazer } unit ncNXServRemoto; interface uses Windows, Classes, Messages, Forms, nxllComponent, nxllMemoryManager, nxllTypes, nxllTransport, nxllPluginBase, nxllDataMessageQueue, nxptBasePooledTransport, nxlgEventLog, ncNetMsg, nxllBDE, ncErros, ncClassesBase; const cm_ncnxProcessMsg = WM_USER + 4000; type TncnxProcessMsgProc = procedure (Msg : PnxDataMessage) of object; TncnxRemotePlugin = class(TnxBasePluginEngine) private FMsgQueue: TnxDataMessageQueue; FProcessMsgProc : TncnxProcessMsgProc; FHWnd: HWND; procedure PluginMsgHandler( var aMsg: TMessage ); procedure msgProcessMsg( var aMsg: TMessage ); message cm_ncnxProcessMsg; protected procedure LogEvent(aString: string); class function bpeIsRemote: Boolean; override; procedure ProcessReceivedMessage( aMsg: PnxDataMessage ); public constructor Create( aOwner: TComponent ); override; destructor Destroy; override; property ProcessMsgProc: TncnxProcessMsgProc read FProcessMsgProc write FProcessMsgProc; end; TncnxRemoteCmdHandler = class(TnxBasePluginCommandHandler) private procedure rmchSetPluginEngine( const aPlugin: TncnxRemotePlugin ); function rmchGetPluginEngine: TncnxRemotePlugin; public procedure bpchProcess( aMsg: PnxDataMessage; var aHandled: Boolean ); override; published property PluginEngine: TncnxRemotePlugin read rmchGetPluginEngine write rmchSetPluginEngine; end; TncSalvaTelaEv = procedure (Sender: TObject; aMaq: Word; aJpg: TMemoryStream) of object; TncProgressoArqEv = procedure(Perc: Integer; Etapa: Byte; NomeArq: String; Download: Boolean) of object; TncNXServRemoto = class(TncServidorBase) private FTransp : TnxBasePooledTransport; FRemPlugin : TncnxRemotePlugin; FCmdHandler : TncnxRemoteCmdHandler; FSalvaTelaEv : TncSalvaTelaEv; FOnProgressoArq : TncProgressoArqEv; FTicksLastCom : Cardinal; FEventLog : TnxBaseLog; FEventLogEnabled : Boolean; FWaitingSock : Boolean; function GetCmdHandler: TnxBaseCommandHandler; function GetSession: TnxStateComponent; procedure SetCmdHandler(const Value: TnxBaseCommandHandler); procedure SetSession(const Value: TnxStateComponent); procedure ProcessMsgProc(Msg : PnxDataMessage); procedure LogEvent(S: String); function ProcessRequest(aMsgID : TnxMsgID; aRequestData : Pointer; aRequestDataLen : TnxWord32; aReply : PPointer; aReplyLen : PnxWord32; aReplyType : TnxNetMsgDataType) : TnxResult; procedure SetEventLog(const Value: TnxBaseLog); procedure SetEventLogEnabled(const Value: Boolean); procedure OnTerminateSock(Sender: TObject); protected procedure SetAtivo(Valor: Boolean); override; procedure nmMsgComEv(var Msg : TnxDataMessage); message ncnmMsgComEv; procedure nmChecaLicEv(var Msg : TnxDataMessage); message ncnmChecaLicEv; procedure nmHorarioEv(var Msg : TnxDataMessage); message ncnmHorarioEv; procedure nmCapturaTelaEv(var Msg : TnxDataMessage); message ncnmCapturaTelaEv; procedure nmMonitorOnOffEv(var Msg : TnxDataMessage); message ncnmMonitorOnOffEv; procedure nmSalvaTelaEv(var Msg : TnxDataMessage); message ncnmSalvaTelaEv; procedure nmFinalizaProcessoEv(var Msg : TnxDataMessage); message ncnmFinalizaProcessoEv; procedure nmShutdownEv(var Msg : TnxDataMessage); message ncnmShutdownEv; procedure nmSuporteRemEv(var Msg : TnxDataMessage); message ncnmSuporteRemEv; procedure nmObtemProcessosEv(var Msg : TnxDataMessage); message ncnmObtemProcessosEv; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function KeepAlive: Integer; function Upload(aFonte, aDestino: String): Integer; override; function Download(aFonte, aDestino: String): Integer; override; function DownloadArqInterno(aArq: String; aVerCli: Integer; aDestino: String): Integer; override; function ObtemVersaoGuard(var Versao: Integer): Integer; override; function StartPrintTransfer(aArqInfo: TStrings; var aPos: Int64): Integer; override; function SendPTBlock(aArq: TGUID; aLast: Boolean; aTamanho: Integer; aPos: Int64; aBlock: Pointer): Integer; override; function SalvaStreamObj(Novo: Boolean; S: TStream): Integer; override; function ObtemStreamConfig(S: TStream): Integer; override; function ObtemStreamAvisos(S: TStream): Integer; override; function ObtemStreamListaObj(Cliente: Integer; TipoClasse: Integer; S: TStream): Integer; override; function ApagaObj(Cliente: Integer; TipoClasse: Integer; Chave: String): Integer; override; function ApagaMsgCli(aID: Integer): Integer; override; function SalvaApp(aApp: String): Integer; override; function AbreCaixa(aFunc: String; aSaldo: Currency; var NovoCx: Integer): Integer; override; function FechaCaixa(aFunc: String; aSaldo: Currency; aID: Integer): Integer; override; function CorrigeDataCaixa(aFunc: String; aID: Integer; aNovaAbertura, aNovoFechamento: TDateTime): integer; override; function AjustaPontosFid(aFunc: String; aCliente: Integer; aFator: Smallint; aPontos: Double; aObs: String): Integer; override; function CapturaTelaMaq(aMaq: Word): integer; override; function SalvaTelaMaq(aSessionID: Integer; aMaq: Word; S: TMemoryStream): integer; override; function LoginMaq(aSessao: TObject): Integer; override; function LogoutMaq(aMaq: Word): Integer; override; function AlteraSessao(aSessao: Tobject): Integer; override; function ForceRefreshSessao(aSessao: Integer): Integer; override; function SalvaCredTempo(aObj: TObject): Integer; override; function SalvaMovEst(aObj: TObject): Integer; override; function SalvaDebito(aObj: TObject): Integer; override; function SalvaLancExtra(aObj: TObject): Integer; override; function SalvaDebTempo(aObj: TObject): Integer; override; function SalvaImpressao(aObj: TObject): Integer; override; function SalvaLogAppUrl(S: TStream): Integer; override; function ObtemProcessos(aMaq: Word; aIDCliente, aIDReq: Integer): integer; override; function ObtemPatrocinios(aSL: TStrings): Integer; override; function GetLoginData(var aVer, aConta, aUsers: String): integer; function FinalizaProcesso(aMaq: Word; aProcessID: Integer): Integer; override; function SalvaProcessos(aIDCliente, aRequest: Integer; aSL: TStrings): Integer; override; function RefreshEspera: Integer; override; function AdicionaPassaporte(aMaq: Word; aSenha: String): Integer; override; function RegistraPaginasImpressas(aJobID: Cardinal; aMaq: Word; aPaginas: Integer; aImp, aDoc: String): Integer; override; function PararTempoMaq(aMaq: Word; aParar: Boolean): Integer; override; function TransferirMaq(aOrigem, aDestino: Word): Integer; override; function PermitirDownload(aSessao: Integer; aExe, aPermitir: Boolean): Integer; override; function DesativarFWSessao(aSessao: Integer; aDesativar: Boolean): Integer; override; function DesktopSincronizado(aSessao: Integer): integer; override; function MonitorOnOff(aMaq: Word; aOn: Boolean): integer; override; function PrintDocControl(aInfo: TStrings): Integer; override; function PreLogoutMaq(aMaq: Word): Integer; override; function CancLogoutMaq(aMaq: Word): Integer; override; function CancelaTran(aID: Integer; aFunc: String): integer; override; function SalvaClientPages(aPrinter: String; aJobID: Cardinal; aMaquina, aPaginas: Word): integer; override; function JobControl(aPrinterIndex: Integer; aJob: Cardinal; aControl: Byte): integer; override; function ObtemPastaServ(var NomePastaServ: String): Integer; override; function ArqFundoEnviado(NomeArq: String): Integer; override; function ObtemSenhaCli(Codigo: Integer; var Senha: String): Integer; override; function SalvaSenhaCli(Codigo: Integer; Senha: String): Integer; override; function LimpaFundo(Desktop: Boolean): Integer; override; function EnviarMsg(const aDe, aPara: Integer; const aTexto: String): Integer; override; function RefreshPrecos: integer; override; function ShutdownMaq(aMaq, aOper: Word): integer; override; function SuporteRem(aMaq, aTec: Word): Integer; override; function DisableAD(aSessao: Integer; aDisable: Boolean): integer; override; function ObtemSitesBloqueados(var S: String): Integer; override; function Login(aUsername, aSenha: String; aMaq: Word; aFuncAtual: Boolean; aRemoto: Boolean; aWndHandle: HWND; aProxyHandle: Integer; aSocket: Integer; aSession: Integer; aIP: String; var Handle: Integer): Integer; override; function ModoManutencao(aMaq: Word; aUsername, aSenha: String; aEntrar: Boolean): Integer; override; function SalvaLic(aLic: String): Integer; override; procedure Logout(Cliente: Integer); override; property TicksLastCom: Cardinal read FTicksLastCom; published property EventLog: TnxBaseLog read FEventLog write SetEventLog; property EventLogEnabled: Boolean read FEventLogEnabled write SetEventLogEnabled; property OnProgressoArq: TncProgressoArqEv read FOnProgressoArq write FOnProgressoArq; property Transp: TnxBasePooledTransport read FTransp write FTransp; property CmdHandler : TnxBaseCommandHandler read GetCmdHandler write SetCmdHandler; property Session : TnxStateComponent read GetSession write SetSession; property OnSalvaTela: TncSalvaTelaEv read FSalvaTelaEv write FSalvaTelaEv; end; var nxsr_ActiveFormHWND : HWND = 0; procedure Register; implementation uses SysUtils, nxstMessages, nxllFastMove, SyncObjs, nxllStreams, ncMsgCom, ncSessao, ncMovEst, ncCredTempo, ncDebTempo, ncDebito, ncImpressao, ncLancExtra, ncDebug, ncgPrevLogoff; // START resource string wizard section resourcestring SÉNecessárioInformarOEndereçoDoSe = 'É necessário informar o endereço do servidor NexCafé'; // END resource string wizard section type TThreadSockConn = class ( TThread ) private FTransp : TnxBasePooledTransport; Fexecuting : Boolean; protected procedure Execute; override; public constructor Create(aTransp: TnxBasePooledTransport); property Executing: Boolean read FExecuting; end; procedure Register; begin RegisterComponents('NexCafe', [TncNXServRemoto]); // do not localize end; { TncnxRemotePlugin } constructor TncnxRemotePlugin.Create(aOwner: TComponent); begin inherited; FMsgQueue := TnxDataMessageQueue.Create; FHWnd := Classes.AllocateHWnd(PluginMsgHandler); DebugMsg('TncnxRemotePlugin.Create - FHWND: ' + IntToStr(FHWND)); // do not localize FProcessMsgProc := nil; end; destructor TncnxRemotePlugin.Destroy; begin DebugMsg('TncnxRemotePlugin.Destroy'); // do not localize Classes.DeallocateHWnd(FHWnd); FreeAndNil(FMsgQueue); inherited; end; procedure TncnxRemotePlugin.LogEvent(aString: string); begin DebugMsg('TncnxRemotePlugin.'+aString); // do not localize end; class function TncnxRemotePlugin.bpeIsRemote: Boolean; begin Result := True; end; procedure TncnxRemotePlugin.ProcessReceivedMessage( aMsg: PnxDataMessage ); var M : PnxDataMessage; begin try with aMsg^ do LogEvent('ProcessReceivedMessage - dmMsg: ' + MsgToString(dmMsg) + ' - dmDataLen: ' + IntToStr(dmDataLen)); // do not localize except on E: Exception do try LogEvent('ProcessReceivedMessage - Exception: ' + E.Message); except end; // do not localize end; try M := nxGetZeroMem(SizeOf(TnxDataMessage)); if (aMsg^.dmDataLen > 0) then begin M^.dmData := nxGetMem(aMsg^.dmDataLen); nxMove(aMsg^.dmData^, M^.dmData^, aMsg^.dmDataLen); end; M^.dmMsg := aMsg^.dmMsg; M^.dmSource := aMsg^.dmSource; M^.dmSessionID := aMsg^.dmSessionID; M^.dmErrorCode := aMsg^.dmErrorCode; M^.dmDataLen := aMsg^.dmDataLen; Windows.PostMessage(FHWnd, cm_ncnxProcessMsg, Integer(M), 0); DebugMsg('Windwos.PostMessage - HWND: ' + IntToStr(FHwnd)); // do not localize { with aMsg^ do try FMsgQueue.Push( Self, dmMsg, dmSessionId, 0, 0, dmData, dmDataLen ); // Post a message to our window handle. This way, we don't call the events // in the context of the NexusDB thread. Also, we can return control to the // calling thread right away. finally Windows.PostMessage(FHWnd, cm_ncnxProcessMsg, 0, 0); DebugMsg('Windwos.PostMessage - HWND: ' + IntToStr(FHwnd)); end;} except on E: Exception do try LogEvent('ProcessReceviedMessage - Exception: '+E.Message); except end; // do not localize end; end; procedure TncnxRemotePlugin.msgProcessMsg( var aMsg: TMessage ); var M : PnxDataMessage; begin DebugMsg('TncnxRemotePlugin.msgProcessMsg'); // do not localize try M := PnxDataMessage(aMsg.WParam); try try DebugMsg('TncnxRemotePlugin.msgProcessMsg - dmMsg: '+MsgToString(M^.dmMsg)); except end; // do not localize if Assigned(FProcessMsgProc) then FProcessMsgProc(M) else DebugMsg('TncnxRemotePlugin.msgProcessMsg - FProcessMsgProc NOT ASSIGNED'); // do not localize finally if Assigned( M^.dmData) then nxFreeMem( M^.dmData); nxFreeMem(M); end; { Msg := FMsgQueue.Pop; while Assigned( Msg ) do begin try try LogEvent('msgProcessMsg - dmMsg: '+MsgToString(Msg^.dmMsg)); except end; if Assigned(FProcessMsgProc) then FProcessMsgProc(Msg); finally // better free the message if Assigned( Msg^.dmData ) then nxFreeMem( Msg^.dmData); nxFreeMem( Msg ); end; Msg := FMsgQueue.Pop; end;} except on E: Exception do DebugMsgEsp('TncnxRemotePlugin. msgProcessMsg - Exception: ' + E.Message, False, True); // do not localize end; end; procedure TncnxRemotePlugin.PluginMsgHandler(var aMsg: TMessage); begin DebugMsg('TncnxRemotePlugin.PluginMsgHandler - ' + IntToStr(aMsg.Msg)); // do not localize if aMsg.Msg = WM_QUERYENDSESSION then begin aMsg.Result := 1; DebugMsg('TncnxRemotePlugin.PluginMsgHandler - WM_QUERYENDSESSION'); // do not localize PrevLogoff; end else if aMsg.Msg = cm_ncnxProcessMsg then begin DebugMsg('TncnxRemotePlugin.PluginMsgHandler - Dispatch'); // do not localize Dispatch( aMsg ); end else begin DebugMsg('TncnxRemotePlugin.PluginMsgHandler - DEFWINDOWPROC - FHWND: '+IntToStr(FHWND)); // do not localize DefWindowProc( FHWnd, aMsg.Msg, aMsg.WParam, aMsg.LParam ); end; end; { TncnxRemoteCmdHandler } procedure TncnxRemoteCmdHandler.bpchProcess( aMsg: PnxDataMessage; var aHandled: Boolean); begin with aMsg^ do if (dmMsg>=ncnmFirstEv) and (dmMsg<=ncnmLastEv) then begin PluginEngine.ProcessReceivedMessage( aMsg ); aHandled := True; end else DebugMsg('TncnxRemoteCmdHandler.bpchProcess - dmMsg: ' + IntToStr(dmMsg) + ' - Fora da faixa de processamento'); // do not localize end; procedure TncnxRemoteCmdHandler.rmchSetPluginEngine( const aPlugin: TncnxRemotePlugin ); begin bpchSetPluginEngine( aPlugin ); end; function TncnxRemoteCmdHandler.rmchGetPluginEngine: TncnxRemotePlugin; begin Result := TncnxRemotePlugin( bpchPluginEngine ); end; { TncNXServRemoto } constructor TncNXServRemoto.Create(AOwner: TComponent); begin inherited; FEventLog := nil; FTicksLastCom := 0; FRemPlugin := TncnxRemotePlugin.Create(Self); FCmdHandler := TncnxRemoteCmdHandler.Create(Self); FCmdHandler.PluginEngine := FRemPlugin; FRemPlugin.ProcessMsgProc := Self.ProcessMsgProc; FTransp := nil; FSalvaTelaEv := nil; FOnProgressoArq := nil; end; function TncNXServRemoto.DesativarFWSessao(aSessao: Integer; aDesativar: Boolean): Integer; var Req: TnmDesativarFWSessaoReq; begin Req.nmSessao := aSessao; Req.nmDesativar := aDesativar; Result := ProcessRequest(ncnmDesativarFWSessao, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.DesktopSincronizado(aSessao: Integer): integer; var Req: TnmSessao; begin Req.nmSessao := aSessao; Result := ProcessRequest(ncnmDesktopSincronizado, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; destructor TncNXServRemoto.Destroy; begin DebugMsg('TncNXServRemoto - Destroy'); // do not localize FCmdHandler.Active := False; if Assigned(FCmdHandler) then FCmdHandler.Active := False; FCmdHandler.CommandHandler := nil; FreeAndNil(FCmdHandler); FreeAndNil(FRemPlugin); inherited; end; function TncNXServRemoto.DisableAD(aSessao: Integer; aDisable: Boolean): integer; var Req : TnmDisableAdReq; begin Req.nmSessao := aSessao; Req.nmDisable := aDisable; Result := ProcessRequest(ncnmDisableAd, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.Download(aFonte, aDestino: String): Integer; var S: TMemoryStream; Req : TnmNomeArq; begin Req.nmNomeArq := aFonte; S := TMemoryStream.Create; try if Assigned(FOnProgressoArq) then FOnProgressoArq(0, 0, aDestino, True); Result := ProcessRequest(ncnmDownloadArq, @Req, SizeOf(Req), @S, nil, nmdStream); if Result=0 then begin S.SaveToFile(aDestino); end; finally S.Free; end; if (Result=0) and Assigned(FOnProgressoArq) then FOnProgressoArq(100, 2, aDestino, True); end; function TncNXServRemoto.DownloadArqInterno(aArq: String; aVerCli: Integer; aDestino: String): Integer; var S: TMemoryStream; Req : TnmDownArqInt; begin Req.nmArq := aArq; Req.nmVer := aVerCli; S := TMemoryStream.Create; try Result := ProcessRequest(ncnmDownloadArqInterno, @Req, SizeOf(Req), @S, nil, nmdStream); if Result=0 then begin S.SaveToFile(aDestino); end; finally S.Free; end; end; function TncNXServRemoto.GetCmdHandler: TnxBaseCommandHandler; begin Result := FCmdHandler.CommandHandler; end; function TncNXServRemoto.GetSession: TnxStateComponent; begin Result := FRemPlugin.Session; end; function TncNXServRemoto.JobControl(aPrinterIndex: Integer; aJob: Cardinal; aControl: Byte): integer; var Req : TnmJobControl; begin Req.nmJob := aJob; Req.nmControl := aControl; Req.nmPrinterIndex := aPrinterIndex; Result := ProcessRequest(ncnmJobControl, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; procedure TncNXServRemoto.nmCapturaTelaEv(var Msg: TnxDataMessage); var M: PmsgCapturaTela; begin LogEvent('nmCapturaTelaEv'); // do not localize New(M); Move(Msg.dmData^, M^, Msg.dmDataLen); EnviaEvento(ncmc_CapturaTela, M); end; procedure TncNXServRemoto.nmChecaLicEv(var Msg: TnxDataMessage); begin LogEvent('nmChecaLicEv'); // do not localize EnviaEvento(ncmc_ChecaLicEv, nil); end; procedure TncNXServRemoto.nmFinalizaProcessoEv(var Msg: TnxDataMessage); var M : PmsgFinalizaProcesso; begin LogEvent('nmFinalizaProcessoEv'); // do not localize New(M); Move(Msg.dmData^, M^, Msg.dmDataLen); EnviaEvento(ncmc_FinalizaProcesso, M); end; procedure TncNXServRemoto.nmHorarioEv(var Msg: TnxDataMessage); var M : PmsgHorarioEv; begin LogEvent('nmHorarioEv'); // do not localize New(M); Move(Msg.dmData^, M^, Msg.dmDataLen); EnviaEvento(ncmc_HorarioEv, M); end; procedure TncNXServRemoto.nmMonitorOnOffEv(var Msg: TnxDataMessage); var M : PmsgMonitorOnOff; begin New(M); with TnmMonitorOnOff(Msg.dmData^) do begin DebugMsg('TncNXServRemoto.nmMonitorOnOffEv - nmMaq: ' + IntToStr(nmMaq) + ' - nmOn: ' + BoolStr[nmOn]); // do not localize M.msgMaq := nmMaq; M.msgOn := nmOn; end; EnviaEvento(ncmc_MonitorOnOffEv, M); end; procedure TncNXServRemoto.nmMsgComEv(var Msg: TnxDataMessage); var S: TMemoryStream; Dados : Pointer; begin LogEvent('nmMsgComEv'); // do not localize with TnmMsgCom(Msg.dmData^) do begin if ObtemTipoDados(nmMsgID)=tdStream then begin S := TMemoryStream.Create; S.SetSize(nmDataLength); Move(nmData, S.Memory^, nmDataLength); EnviaEvento(nmMsgID, S); end else begin GetMem(Dados, nmDataLength); Move(nmData, Dados^, nmDataLength); EnviaEvento(nmMsgID, Dados); end; end; end; procedure TncNXServRemoto.nmObtemProcessosEv(var Msg: TnxDataMessage); var M : PmsgObtemProcessos; begin New(M); Move(Msg.dmData^, M^, Msg.dmDataLen); EnviaEvento(ncmc_ObtemProcessos, M); end; procedure TncNXServRemoto.nmSalvaTelaEv(var Msg: TnxDataMessage); var S: TMemoryStream; begin if not Assigned(FSalvaTelaEv) then Exit; with TnmSalvaTela(Msg.dmData^) do begin S := TMemoryStream.Create; try S.SetSize(nmJpgLen); Move(nmJpg, S.Memory^, nmJpgLen); FSalvaTelaEv(Self, nmMaq, S); finally S.Free; end; end; end; procedure TncNXServRemoto.nmShutdownEv(var Msg: TnxDataMessage); var M : PmsgShutdown; begin New(M); Move(Msg.dmData^, M^, Msg.dmDataLen); EnviaEvento(ncmc_Shutdown, M); end; procedure TncNXServRemoto.nmSuporteRemEv(var Msg: TnxDataMessage); var M : PmsgSuporteRemEv; begin New(M); Move(Msg.dmData^, M^, Msg.dmDataLen); EnviaEvento(ncmc_SuporteRemEv, M); end; procedure TncNXServRemoto.ProcessMsgProc(Msg: PnxDataMessage); begin FTicksLastCom := GetTickCount; DebugMsg('TncNXServRemoto.ProcessMsgProc'); // do not localize Dispatch(Msg^); end; function TncNXServRemoto.ProcessRequest(aMsgID: TnxMsgID; aRequestData: Pointer; aRequestDataLen: TnxWord32; aReply: PPointer; aReplyLen: PnxWord32; aReplyType: TnxNetMsgDataType): TnxResult; var SaveTimeout : TnxWord32; begin if (aMsgID=ncnmDownloadArq) or (aMsgID=ncnmUploadArq) then begin SaveTimeout := FremPlugin.Timeout; if FRemPlugin.Timeout<60000 then FRemPlugin.Timeout := 60000; end; try Result := FRemPlugin.bpeProcessRequest(aMsgID, aRequestData, aRequestDataLen, aReply, aReplyLen, aReplyType); finally if (aMsgID=ncnmDownloadArq) or (aMsgID=ncnmUploadArq) then FRemPlugin.Timeout := SaveTimeout; end; // FTicksLastCom := GetTickCount; if (Result>ncerrUltimo) and (aMsgID<>ncnmLogout) then begin Result := ncerrConexaoPerdida; SetAtivo(False); end; end; procedure ProcessMsgConn; var Msg : TMsg; begin while PeekMessage(Msg, nxsr_ActiveFormHWND, 0, 0, PM_REMOVE) do begin TranslateMessage(Msg); DispatchMessage(Msg); end; end; function TncNXServRemoto.SendPTBlock(aArq: TGUID; aLast: Boolean; aTamanho: Integer; aPos: Int64; aBlock: Pointer): Integer; var Req : PnmSendPTBlock; ReqLen : Integer; begin ReqLen := SizeOf( TnmSendPTBlock ) - SizeOf( TnxVarMsgField ) + aTamanho + 1; nxGetZeroMem(Req, ReqLen); try Req^.nmArq := aArq; Req^.nmLast := aLast; Req^.nmTamanho := aTamanho; Move(aBlock^, Req^.nmBlock, aTamanho); Result := ProcessRequest(ncnmUploadArq, Req, ReqLen, nil, nil, nmdByteArray); finally nxFreeMem(Req); end; end; procedure TncNXServRemoto.SetAtivo(Valor: Boolean); var T : TThreadSockConn; Dummy: Integer; begin DebugMsg('TncNCServRemoto.SetAtivo - 0'); // do not localize try if Valor and Assigned(FTransp) then begin FTransp.Active := False; if Trim(FTransp.ServerName)='' then raise exception.Create(SÉNecessárioInformarOEndereçoDoSe); if Win32MajorVersion>5 then begin DebugMsg('TncNCServRemoto.SetAtivo A-1'); // do not localize T := TThreadSockConn.Create(FTransp); DebugMsg('TncNCServRemoto.SetAtivo A-2'); // do not localize FWaitingSock := True; T.Resume; while T.Executing do begin DebugMsg('TncNXServRemoto.SetAtivo - Waiting 1'); // do not localize MsgWaitForMultipleObjects(0, Dummy, False, 500, QS_ALLINPUT); DebugMsg('TncNXServRemoto.SetAtivo - Waiting 2'); // do not localize ProcessMsgConn; DebugMsg('TncNXServRemoto.SetAtivo - Waiting 3'); // do not localize end; DebugMsg('TncNCServRemoto.SetAtivo A-3'); // do not localize try T.Free; except end; end else begin DebugMsg('TncNXServRemoto.SetAtivo B-1'); // do not localize FTransp.Active := True; DebugMsg('TncNXServRemoto.SetAtivo B-2'); // do not localize end; DebugMsg('TncNCServRemoto.SetAtivo 4'); // do not localize if not FTransp.Active then begin DebugMsg('TncNCServRemoto.SetAtivo 5'); // do not localize raise EErroNexCafe.Create(ncerrFalhaConexao); end else DebugMsg('TncNCServRemoto.SetAtivo 6'); // do not localize end else DebugMsg('TncNCServRemoto.SetAtivo - FALSE'); // do not localize DebugMsg('TncNCServRemoto.SetAtivo 7'); // do not localize FRemPlugin.Active := Valor; DebugMsg('TncNCServRemoto.SetAtivo 8'); // do not localize FCmdHandler.Active := Valor; DebugMsg('TncNCServRemoto.SetAtivo 9'); // do not localize if Assigned(FRemPlugin.Session) then FRemPlugin.Session.Active := Valor; DebugMsg('TncNCServRemoto.SetAtivo 10'); // do not localize if (not Valor) and Assigned(FTransp) then FTransp.Active := False; DebugMsg('TncNCServRemoto.SetAtivo 11'); // do not localize if Assigned(FCmdHandler.CommandHandler) then FCmdHandler.CommandHandler.Active := True; DebugMsg('TncNCServRemoto.SetAtivo 12'); // do not localize except On E: EnxPooledTransportException do begin DebugMsg('TncNXServRemoto.SetAtivo - Valor: ' + BoolString[Valor] + // do not localize ' - Exception: ' + E.Message + // do not localize ' - ErrorCode: ' + IntToStr(E.ErrorCode) + // do not localize ' - OS Error: ' + IntToStr(E.OSError)); // do not localize Raise EErroNexCafe.Create(ncerrFalhaConexao); end; on E: EErroNexCafe do begin DebugMsg('TncNCServRemoto.SetAtivo - E: ErroNexCafe - '+E.Message); // do not localize raise EErroNexCafe.Create(E.CodigoErro); end; On E: Exception do begin DebugMsg('TncNCServRemoto.SetAtivo - E: Exception - '+E.Message); // do not localize raise; end; end; inherited; end; procedure TncNXServRemoto.SetCmdHandler(const Value: TnxBaseCommandHandler); begin FCmdHandler.CommandHandler := Value; end; procedure TncNXServRemoto.SetEventLog(const Value: TnxBaseLog); begin FEventLog := Value; FRemPlugin.EventLog := Value; FRemPlugin.EventLogEnabled := FEventLogEnabled; FCmdHandler.EventLog := Value; FCmdHandler.EventLogEnabled := FEventLogEnabled; end; procedure TncNXServRemoto.SetEventLogEnabled(const Value: Boolean); begin FEventLogEnabled := Value; FCmdHandler.EventLog := FEventLog; FCmdHandler.EventLogEnabled := Value; FRemPlugin.EventLog := FEventLog; FRemPlugin.EventLogEnabled := Value; end; procedure TncNXServRemoto.SetSession(const Value: TnxStateComponent); begin FRemPlugin.Session := Value; end; function TncNXServRemoto.EnviarMsg(const aDe, aPara: Integer; const aTexto: String): Integer; var SL : TStrings; S: TMemoryStream; begin SL := TStringList.Create; S := TMemoryStream.Create; try SL.Values['de'] := IntToStr(aDe); // do not localize SL.Values['para'] := IntToStr(aPara); // do not localize SL.Values['datahora'] := '0'; // do not localize SL.Values['id'] := '0'; // do not localize SL.Add(aTexto); SL.SaveToStream(S); Result := ProcessRequest(ncnmEnviaChat, S.Memory, S.Size, nil, nil, nmdByteArray); finally SL.Free; S.Free; end; end; function TncNXServRemoto.FechaCaixa(aFunc: String; aSaldo: Currency; aID: Integer): Integer; var Req: TnmFechaCaixaReq; begin Req.nmFunc := aFunc; Req.nmID := aID; Req.nmSaldo := aSaldo; Result := ProcessRequest(ncnmFechaCaixa, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.FinalizaProcesso(aMaq: Word; aProcessID: Integer): Integer; var Req: TnmFinalizaProcesso; begin Req.nmProcessID := aProcessID; Req.nmMaq := aMaq; Result := ProcessRequest(ncnmFinalizaProcesso, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.ForceRefreshSessao(aSessao: Integer): Integer; var Req : TnmSessao; begin Req.nmSessao := aSessao; Result := ProcessRequest(ncnmRefreshSessao, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.KeepAlive: Integer; begin Result := ProcessRequest(ncnmKeepAlive, nil, 0, nil, nil, nmdByteArray); end; procedure TncNXServRemoto.LogEvent(S: String); begin DebugMsg('TnxNCServRemoto.'+S); // do not localize end; function TncNXServRemoto.Login(aUsername, aSenha: String; aMaq: Word; aFuncAtual: Boolean; aRemoto: Boolean; aWndHandle: HWND; aProxyHandle: Integer; aSocket: Integer; aSession: Integer; aIP: String; var Handle: Integer): Integer; var Request : TnmLoginReq; ReplyLen : TnxWord32; P : Pointer; begin DebugMsg('TncNXServRemoto.Login - 1'); // do not localize Request.nmUsername := aUsername; DebugMsg('TncNXServRemoto.Login - 2'); // do not localize Request.nmSenha := aSenha; DebugMsg('TncNXServRemoto.Login - 3'); // do not localize Request.nmFuncAtual := aFuncAtual; DebugMsg('TncNXServRemoto.Login - 4'); // do not localize Request.nmProxyHandle := aProxyHandle; DebugMsg('TncNXServRemoto.Login - 5'); // do not localize Request.nmMaq := aMaq; DebugMsg('TncNXServRemoto.Login - 6'); // do not localize try DebugMsg('TncNXServRemoto.Login - 7'); // do not localize Result := ProcessRequest(ncnmLogin, @Request, SizeOf(Request), @P, @ReplyLen, nmdByteArray); DebugMsg('TncNXServRemoto.Login - 8: '+IntToStr(ReplyLen)); // do not localize Move(P^, Handle, SizeOf(Integer)); DebugMsg('TncNXServRemoto.Login - Result: ' + IntToStr(Result)); // do not localize finally if Assigned(P) then nxFreeMem(P); end; if Result = 0 then begin DebugMsg('TncNXServRemoto.Login - 9'); // do not localize inherited Login(aUsername, aSenha, aMaq, aFuncAtual, aRemoto, aWndHandle, aProxyHandle, aSocket, aSession, aIP, Handle); end; DebugMsg('TncNXServRemoto.Login - 10'); // do not localize end; procedure TncNXServRemoto.Logout(Cliente: Integer); begin inherited; ProcessRequest(ncnmLogout, @Cliente, SizeOf(Cliente), nil, nil, nmdByteArray); end; function TncNXServRemoto.ObtemStreamListaObj(Cliente, TipoClasse: Integer; S: TStream): Integer; var Request : TnmObtemListaReq; begin Request.nmCliente := Cliente; Request.nmTipoClasse := TipoClasse; Result := ProcessRequest(ncnmObtemLista, @Request, SizeOf(Request), @S, nil, nmdStream); end; function TncNXServRemoto.ObtemVersaoGuard(var Versao: Integer): Integer; var P : Pointer; ReplyLen : TnxWord32; begin try Result := ProcessRequest(ncnmObtemVersaoGuard, nil, 0, @P, @ReplyLen, nmdByteArray); Move(P^, Versao, SizeOf(Versao)); finally if Assigned(P) then nxFreeMem(P); end; end; procedure TncNXServRemoto.OnTerminateSock(Sender: TObject); begin DebugMsg('TncNXServRemoto.OnTerminateSock'); // do not localize FWaitingSock := False; end; function TncNXServRemoto.AlteraSessao(aSessao: Tobject): Integer; var S: TMemoryStream; begin S := TMemoryStream.Create; try TncSessao(aSessao).SalvaStream(S, False); S.Position := 0; Result := ProcessRequest(ncnmAlteraSessao, S.Memory, S.Size, nil, nil, nmdByteArray); finally S.Free; end; end; function TncNXServRemoto.ApagaMsgCli(aID: Integer): Integer; var Req: TnmApagaMsgCli; begin Req.nmMsgID := aID; Result := ProcessRequest(ncnmApagaMsgCli, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.ApagaObj(Cliente: Integer; TipoClasse: Integer; Chave: String): Integer; var Request : TnmObj; begin Request.nmCliente := Cliente; Request.nmTipoClasse := TipoClasse; Request.nmChave := Chave; Result := ProcessRequest(ncnmApagaObj, @Request, SizeOf(Request), nil, nil, nmdByteArray); end; function TncNXServRemoto.ArqFundoEnviado(NomeArq: String): Integer; var Request : TnmNomeArq; begin Request.nmNomeArq := NomeArq; Result := ProcessRequest(ncnmArqFundoEnviado, @Request, SizeOf(Request), nil, nil, nmdByteArray); end; function TncNXServRemoto.SalvaMovEst(aObj: TObject): Integer; var S: TMemoryStream; begin S := TMemoryStream.Create; try TncMovEst(aObj).SalvaStream(S, False); S.Position := 0; Result := ProcessRequest(ncnmSalvaMovEst, S.Memory, S.Size, nil, nil, nmdByteArray); finally S.Free; end; end; function TncNXServRemoto.SalvaProcessos(aIDCliente, aRequest: Integer; aSL: TStrings): Integer; var S: TMemoryStream; begin aSL.Insert(0, IntToStr(aIDCliente)); aSL.Insert(1, IntToStr(aRequest)); S := TMemoryStream.Create; try aSL.SaveToStream(S); S.Position := 0; Result := ProcessRequest(ncnmSalvaProcessos, S.Memory, S.Size, nil, nil, nmdByteArray); finally S.Free; end; end; function TncNXServRemoto.SalvaCredTempo(aObj: TObject): Integer; var S: TMemoryStream; begin S := TMemoryStream.Create; try TncCredTempo(aObj).SaveToStream(S); S.Position := 0; Result := ProcessRequest(ncnmSalvaCredTempo, S.Memory, S.Size, nil, nil, nmdByteArray); finally S.Free; end; end; function TncNXServRemoto.SalvaDebito(aObj: TObject): Integer; var S: TMemoryStream; begin S := TMemoryStream.Create; try TncDebito(aObj).SalvaStream(S, False); S.Position := 0; Result := ProcessRequest(ncnmSalvaDebito, S.Memory, S.Size, nil, nil, nmdByteArray); finally S.Free; end; end; function TncNXServRemoto.SalvaDebTempo(aObj: TObject): Integer; var S: TMemoryStream; begin S := TMemoryStream.Create; try TncDebTempo(aObj).SalvaStream(S, False); S.Position := 0; Result := ProcessRequest(ncnmSalvaDebTempo, S.Memory, S.Size, nil, nil, nmdByteArray); finally S.Free; end; end; function TncNXServRemoto.SalvaImpressao(aObj: TObject): Integer; var S: TMemoryStream; begin S := TMemoryStream.Create; try TncImpressao(aObj).SaveToStream(S); S.Position := 0; Result := ProcessRequest(ncnmSalvaImpressao, S.Memory, S.Size, nil, nil, nmdByteArray); finally S.Free; end; end; function TncNXServRemoto.SalvaApp(aApp: String): Integer; var SL : TStrings; S: TMemoryStream; begin SL := TStringList.Create; S := TMemoryStream.Create; try SL.Text := aApp; SL.SaveToStream(S); Result := ProcessRequest(ncnmSalvaApp, S.Memory, S.Size, nil, nil, nmdByteArray); finally SL.Free; S.Free; end; end; function TncNXServRemoto.SalvaClientPages(aPrinter: String; aJobID: Cardinal; aMaquina, aPaginas: Word): integer; var Req: TnmClientPages; begin Req.nmJobID := aJobID; Req.nmMaq := aMaquina; Req.nmImp := aPrinter; Req.nmPaginas := aPaginas; Result := ProcessRequest(ncnmSalvaClientPages, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.SalvaLancExtra(aObj: TObject): Integer; var S: TMemoryStream; begin S := TMemoryStream.Create; try TncLancExtra(aObj).SalvaStream(S, False); S.Position := 0; Result := ProcessRequest(ncnmSalvaLancExtra, S.Memory, S.Size, nil, nil, nmdByteArray); finally S.Free; end; end; function TncNXServRemoto.SalvaLic(aLic: String): Integer; var SL : TStrings; S : TMemoryStream; begin SL := TStringList.Create; try S := TMemoryStream.Create; try SL.Text := aLic; SL.SaveToStream(S); S.Position := 0; Result := ProcessRequest(ncnmSalvaLic, S.Memory, S.Size, nil, nil, nmdByteArray); finally S.Free; end; finally SL.Free; end; end; function TncNXServRemoto.SalvaLogAppUrl(S: TStream): Integer; begin Result := ProcessRequest(ncnmSalvaAppUrlLog, TMemoryStream(S).Memory, S.Size, nil, nil, nmdByteArray); end; function TncNXServRemoto.SalvaSenhaCli(Codigo: Integer; Senha: String): Integer; var Request : TnmSenhaCli; begin Request.nmCodigo := Codigo; Request.nmSenha := Senha; Result := ProcessRequest(ncnmSalvaSenhaCli, @Request, SizeOf(Request), nil, nil, nmdByteArray); end; function TncNXServRemoto.SalvaStreamObj(Novo: Boolean; S: TStream): Integer; const ID_Msg : Array[Boolean] of Integer = (ncnmAlteraObj, ncnmNovoObj); begin with FRemPlugin do Result := bpeProcessRequest(ID_Msg[Novo], TMemoryStream(S).Memory, S.Size, nil, nil, nmdByteArray); end; function TncNXServRemoto.CapturaTelaMaq(aMaq: Word): integer; var Req : TnmCapturaTela; begin Req.nmMaq := aMaq; Result := ProcessRequest(ncnmCapturaTelaMaq, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.SalvaTelaMaq(aSessionID: Integer; aMaq: Word; S: TMemoryStream): integer; var Req : PnmSalvaTela; ReqLen : Integer; begin ReqLen := SizeOf( TnmSalvaTela ) - SizeOf( TnxVarMsgField ) + S.Size + 1; nxGetZeroMem(Req, ReqLen); try Req^.nmMaq := aMaq; Req^.nmSession := aSessionID; Req^.nmJpgLen := S.Size; Move(S.Memory^, Req^.nmJpg, S.Size); Result := ProcessRequest(ncnmSalvaTelaMaq, Req, ReqLen, nil, nil, nmdByteArray); finally nxFreeMem(Req); end; end; function TncNXServRemoto.TransferirMaq(aOrigem, aDestino: Word): Integer; var Req : TnmTransferirMaqReq; begin Req.nmOrigem := aOrigem; Req.nmDestino := aDestino; Result := ProcessRequest(ncnmTransferirMaq, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.Upload(aFonte, aDestino: String): Integer; var Req : PnmUpload; S : TnxMemoryStream; ReqLen : Integer; begin if not FileExists(aFonte) then begin Result := ncerrArqNaoEncontrado; Exit; end; S := TnxMemoryStream.Create; try S.LoadFromFile(aFonte); ReqLen := SizeOf( TnmUpload ) - SizeOf( TnxVarMsgField ) + S.Size + 1; nxGetZeroMem(Req, ReqLen); try Req^.nmNomeArq := aDestino; Req.nmTamanho := S.Size; Move(S.Memory^, Req^.nmArq, S.Size); Result := ProcessRequest(ncnmUploadArq, Req, ReqLen, nil, nil, nmdByteArray); finally nxFreeMem(Req); end; finally S.Free; end; end; function TncNXServRemoto.LimpaFundo(Desktop: Boolean): Integer; var Req : TnmLimpaFundoReq; begin Req.nmDesktop := Desktop; Result := ProcessRequest(ncnmLimpaFundo, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.PararTempoMaq(aMaq: Word; aParar: Boolean): Integer; var Req : TnmPararTempoMaqReq; begin Req.nmMaq := aMaq; Req.nmParar := aParar; Result := ProcessRequest(ncnmPararTempoMaq, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.PermitirDownload(aSessao: Integer; aExe, aPermitir: Boolean): Integer; var Req: TnmPermitirDownloadReq; begin Req.nmSessao := aSessao; Req.nmPerm := aPermitir; Req.nmExe := aExe; Result := ProcessRequest(ncnmPermitirDownload, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.LoginMaq(aSessao: TObject): Integer; var S: TMemoryStream; begin S := TMemoryStream.Create; try TncSessao(aSessao).SalvaStream(S, False); S.Position := 0; Result := ProcessRequest(ncnmLoginMaq, S.Memory, S.Size, nil, nil, nmdByteArray); finally S.Free; end; end; function TncNXServRemoto.LogoutMaq(aMaq: Word): Integer; var Req : TnmLogoutMaqReq; begin DebugMsgEsp('TnxNXServRemoto.LogoutMaq - ' + IntToStr(aMaq), False, False); // do not localize Req.nmMaq := aMaq; Result := ProcessRequest(ncnmLogoutMaq, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.PreLogoutMaq(aMaq: Word): Integer; var Req : TnmLogoutMaqReq; begin DebugMsgEsp('TnxNXServRemoto.PreLogoutMaq - ' + IntToStr(aMaq), False, False); // do not localize Req.nmMaq := aMaq; Result := ProcessRequest(ncnmPreLogoutMaq, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.PrintDocControl(aInfo: TStrings): Integer; var S: AnsiString; begin S := aInfo.Text; Result := ProcessRequest(ncnmPrintDocControl, @s[1], Length(S), nil, nil, nmdByteArray); end; function TncNXServRemoto.CancelaTran(aID: Integer; aFunc: String): integer; var Req: TnmCancelaTranReq; begin Req.nmFunc := aFunc; Req.nmTran := aID; Result := ProcessRequest(ncnmCancelaTran, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.CancLogoutMaq(aMaq: Word): Integer; var Req : TnmLogoutMaqReq; begin Req.nmMaq := aMaq; Result := ProcessRequest(ncnmCancLogoutMaq, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.ObtemStreamConfig(S: TStream): Integer; begin Result := ProcessRequest(ncnmObtemStreamConfig, nil, 0, @S, nil, nmdStream); S.Position := 0; end; function TncNXServRemoto.ObtemSenhaCli(Codigo: Integer; var Senha: String): Integer; var Request : TnmSenhaCli; P : Pointer; ReplyLen : TnxWord32; begin Request.nmCodigo := Codigo; Request.nmSenha := ''; try Result := ProcessRequest(ncnmObtemSenhaCli, @Request, SizeOf(Request), @P, @ReplyLen, nmdByteArray); if Result=0 then Senha := PnmSenhaCli(P)^.nmSenha; finally if Assigned(P) then nxFreeMem(P); end; end; function TncNXServRemoto.ObtemSitesBloqueados(var S: String): Integer; var Stream: TnxMemoryStream; begin Stream := TnxMemoryStream.Create; try Result := ProcessRequest(ncnmObtemSitesBloq, nil, 0, @Stream, nil, nmdStream); if Result=0 then begin Stream.Position := 0; SetLength(S, Stream.Size); Stream.Read(S[1], Stream.Size); end; finally Stream.Free; end; end; function TncNXServRemoto.ObtemStreamAvisos(S: TStream): Integer; begin Result := ProcessRequest(ncnmAvisos, nil, 0, @S, nil, nmdStream); S.Position := 0; end; function TncNXServRemoto.ObtemPastaServ(var NomePastaServ: String): Integer; var ReplyLen : TnxWord32; P : Pointer; begin try Result := ProcessRequest(ncnmObtemPastaServ, nil, 0, @P, @ReplyLen, nmdByteArray); if Result=0 then NomePastaServ := PnmNomeArq(P)^.nmNomeArq; finally if Assigned(P) then nxFreeMem(P); end; end; function TncNXServRemoto.GetLoginData(var aVer, aConta, aUsers: String): integer; var S: TStream; sl : TStrings; str: String; begin S := TMemoryStream.Create; sl := TStringList.Create; try aVer := ''; aConta := ''; aUsers := ''; Result := ProcessRequest(ncnmGetLoginData, nil, 0, @S, nil, nmdStream); if Result=0 then begin S.Position := 0; sl.LoadFromStream(S); str := sl.Text; if str='sadsdfsdf' then Exit; if sl.Count>1 then begin aVer := sl[0]; aConta := sl[1]; sl.Delete(0); sl.Delete(0); aUsers := sl.Text; end; end; finally S.Free; end; end; function TncNXServRemoto.ObtemPatrocinios(aSL: TStrings): Integer; var S: TStream; begin S := TMemoryStream.Create; try Result := ProcessRequest(ncnmObtemPatrocinios, nil, 0, @S, nil, nmdStream); S.Position := 0; aSL.LoadFromStream(S); finally S.Free; end; end; function TncNXServRemoto.ObtemProcessos(aMaq: Word; aIDCliente, aIDReq: Integer): integer; var Req: TnmObtemProcessos; begin Req.nmMaq := aMaq; Req.nmIDCliente := aIDCliente; Req.nmIDRequest := aIDReq; Result := ProcessRequest(ncnmObtemProcessos, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.RefreshEspera: Integer; begin Result := ProcessRequest(ncnmRefreshEspera, nil, 0, nil, nil, nmdByteArray); end; function TncNXServRemoto.RefreshPrecos: integer; begin Result := ProcessRequest(ncnmRefreshPrecos, nil, 0, nil, nil, nmdByteArray); end; function TncNXServRemoto.ShutdownMaq(aMaq, aOper: Word): integer; var Req : TnmShutdown; begin Req.nmMaq := aMaq; Req.nmOper := aOper; Result := ProcessRequest(ncnmShutdown, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.StartPrintTransfer(aArqInfo: TStrings; var aPos: Int64): Integer; var S: TStream; ReplyLen : TnxWord32; begin S := TMemoryStream.Create; try aArqInfo.SaveToStream(S); S.Position := 0; ReplyLen := SizeOf(aPos); Result := ProcessRequest(ncnmStartPrintTransfer, S, S.Size, @aPos, @ReplyLen, nmdByteArray); finally S.Free; end; end; function TncNXServRemoto.SuporteRem(aMaq, aTec: Word): Integer; var Req : TnmSuporteRem; begin Req.nmMaq := aMaq; Req.nmTec := aTec; Result := ProcessRequest(ncnmSuporteRem, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.ModoManutencao(aMaq: Word; aUsername, aSenha: String; aEntrar: Boolean): Integer; var Req : TnmModoManutencaoReq; begin Req.nmMaq := aMaq; Req.nmUsername := aUsername; Req.nmSenha := aSenha; Req.nmEntrar := aEntrar; Result := ProcessRequest(ncnmModoManutencao, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.MonitorOnOff(aMaq: Word; aOn: Boolean): integer; var Req: TnmMonitorOnOff; ReplyLen : TnxWord32; begin Req.nmMaq := aMaq; Req.nmOn := aOn; Result := ProcessRequest(ncnmMonitorOnOff, @Req, SizeOf(Req), nil, @ReplyLen, nmdByteArray); end; function TncNXServRemoto.AbreCaixa(aFunc: String; aSaldo: Currency; var NovoCx: Integer): Integer; var Req: TnmAbreCaixaReq; P: Pointer; ReplyLen : TnxWord32; begin Req.nmFunc := aFunc; Req.nmSaldo := aSaldo; try Result := ProcessRequest(ncnmAbreCaixa, @Req, SizeOf(Req), @P, @ReplyLen, nmdByteArray); if Result=0 then NovoCx := PnmAbreCaixaRpy(P)^.nmID; finally if Assigned(P) then nxFreeMem(P); end; end; function TncNXServRemoto.CorrigeDataCaixa(aFunc: String; aID: Integer; aNovaAbertura, aNovoFechamento: TDateTime): integer; var Req: TnmCorrigeDataCaixaReq; begin Req.nmFunc := aFunc; Req.nmCaixa := aID; Req.nmNovaAbertura := aNovaAbertura; Req.nmNovoFechamento := aNovoFechamento; Result := ProcessRequest(ncnmCorrigeDataCaixa, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.AdicionaPassaporte(aMaq: Word; aSenha: String): Integer; var Req: TnmAdicionaPassaporteReq; begin Req.nmSenha := aSenha; Req.nmMaq := aMaq; Result := ProcessRequest(ncnmAdicionaPassaporte, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.AjustaPontosFid(aFunc: String; aCliente: Integer; aFator: Smallint; aPontos: Double; aObs: String): Integer; var Req: TnmAjustaPontosFid; begin Req.nmFunc := aFunc; Req.nmCliente := aCliente; Req.nmFator := aFator; Req.nmPontos := aPontos; Req.nmObs := aObs; Result := ProcessRequest(ncnmAjustaPontosFid, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; function TncNXServRemoto.RegistraPaginasImpressas(aJobID: Cardinal; aMaq: Word; aPaginas: Integer; aImp, aDoc: String): Integer; var Req: TnmPaginasImpressasReq; begin Req.nmJobID := aJobID; Req.nmMaq := aMaq; Req.nmPag := aPaginas; Req.nmImp := aImp; Req.nmDoc := aDoc; Result := ProcessRequest(ncnmPaginasImpressas, @Req, SizeOf(Req), nil, nil, nmdByteArray); end; { TThreadSockConn } constructor TThreadSockConn.Create(aTransp: TnxBasePooledTransport); begin inherited Create(True); FTransp := aTransp; FreeOnTerminate := False; FExecuting := True; DebugMsg('TThreadSockConn.Create'); // do not localize end; procedure TThreadSockConn.Execute; begin DebugMsg('TThreadSockConn.Execute - 1'); // do not localize try try DebugMsg('TThreadSockConn.Execute - 2'); // do not localize FTransp.Active := True; DebugMsg('TThreadSockConn.Execute - 3'); // do not localize except On E: Exception do DebugMsg('TThreadSockConn.Execute - Exception: ' + E.message); // do not localize end; finally FExecuting := False; DebugMsg('TThreadSockConn.Execute - Finally'); // do not localize end; end; initialization TncnxRemotePlugin.rcRegister; TncnxRemoteCmdHandler.rcRegister; finalization TncnxRemotePlugin.rcUnRegister; TncnxRemoteCmdHandler.rcUnRegister; end.
unit CCDAreaDlg; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, ComCtrls, Spin, Math; type TCCDAreaDialog = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; IAreaE: TEdit; Label1: TLabel; SpinButton1: TSpinButton; procedure IAreaEChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure SpinButton1DownClick(Sender: TObject); procedure SpinButton1UpClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var CCDAreaDialog: TCCDAreaDialog; implementation {$R *.dfm} procedure TCCDAreaDialog.IAreaEChange(Sender: TObject); var n :integer; begin OKBtn.Enabled := TRUE; n := StrToIntDef(IAreaE.Text,-MaxInt); if (IAreaE.Text ='')then OKBtn.Enabled := FALSE else if (n<0) then begin IAreaE.Clear; OKBtn.Enabled := FALSE; end else if (n>1024) then IAreaE.Text :='1024'; if (n<100) then OKBtn.Enabled := FALSE end; procedure TCCDAreaDialog.FormShow(Sender: TObject); begin if (StrToIntDef(IAreaE.Text,-MaxInt) < 0 ) then IAreaE.Text := '1024'; IAreaE.SetFocus; IAreaE.SelectAll; end; procedure TCCDAreaDialog.SpinButton1DownClick(Sender: TObject); begin IAreaE.Text := IntToStr(Max(100, StrToIntDef(IAreaE.Text,-MaxInt)-100)); end; procedure TCCDAreaDialog.SpinButton1UpClick(Sender: TObject); begin IAreaE.Text := FloatToStr(Max(100, Min(1024,StrToIntDef(IAreaE.Text,-MaxInt)+100))); end; end.
unit uMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,ADODB,DB,uDBUpgradeConst,uDBUpgrade, ComCtrls, ImgList, StdCtrls, ExtCtrls, PngImageList, RzPanel, RzSplit, AdvSplitter, Buttons, RzShellDialogs, Menus, RzTabs, XPMan, ToolWin, PngCustomButton, PngSpeedButton; type //配置信息 RUpgradeConfig = record //配置名称 ConfigName : string; //创建时间 CreateTime : string; //反射的数据库配置 ReverseDBADD : string; ReverseDBUID : string; ReverseDBPWD : string; ReverseDBName : string; //比对的源XML路径 SourceXML : string; //比对的目标数据库 DestDBADD : string; DestDBUID : string; DestDBPWD : string; DestDBName : string; end; TUpgradeConfig = array of RUpgradeConfig; TfrmMain = class(TForm) ADOConnSource: TADOConnection; PngImageList1: TPngImageList; OpenDialog1: TOpenDialog; ADOConnDest: TADOConnection; DBLoader1: TDBLoader; MainMenu1: TMainMenu; N1: TMenuItem; miReverse: TMenuItem; miCompare: TMenuItem; N4: TMenuItem; E1: TMenuItem; N2: TMenuItem; PageControl1: TPageControl; TabSheet2: TTabSheet; TabSheet3: TTabSheet; RzPageControl1: TRzPageControl; TabSheet10: TRzTabSheet; AdvSplitter1: TAdvSplitter; lvTable: TListView; lvColumn: TListView; TabSheet11: TRzTabSheet; AdvSplitter2: TAdvSplitter; lvView: TListView; memoViewContent: TMemo; TabSheet12: TRzTabSheet; AdvSplitter3: TAdvSplitter; lvTrigger: TListView; memoTriggerContent: TMemo; TabSheet13: TRzTabSheet; AdvSplitter4: TAdvSplitter; lvProcedure: TListView; memoProcedureContent: TMemo; TabSheet14: TRzTabSheet; AdvSplitter5: TAdvSplitter; lvFunction: TListView; memoFunctionContent: TMemo; TabSheet15: TRzTabSheet; lvForeignkey: TListView; TabSheet1: TRzTabSheet; AdvSplitter6: TAdvSplitter; lvIndexColumn: TListView; lvIndex: TListView; Panel1: TPanel; Button1: TButton; Panel2: TPanel; Button2: TButton; Panel3: TPanel; GroupBox1: TGroupBox; GroupBox2: TGroupBox; Panel4: TPanel; Panel5: TPanel; Panel6: TPanel; Memo1: TMemo; Panel7: TPanel; Panel9: TPanel; tvCompare: TTreeView; ImgLstTree: TPngImageList; treeConfigHistory: TTreeView; PopupMenu1: TPopupMenu; miConfigAdd: TMenuItem; miConfigEdit: TMenuItem; miConfigDelete: TMenuItem; RzPanel1: TRzPanel; BtnConfigAdd: TPngSpeedButton; BtnConfigEdit: TPngSpeedButton; BtnConfigDelete: TPngSpeedButton; btnReverse: TPngSpeedButton; btnCompare: TPngSpeedButton; N3: TMenuItem; nConfigAdd: TMenuItem; nConfigEdit: TMenuItem; nConfigDelete: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure lvTableClick(Sender: TObject); procedure lvViewClick(Sender: TObject); procedure lvTriggerClick(Sender: TObject); procedure lvProcedureClick(Sender: TObject); procedure lvFunctionClick(Sender: TObject); procedure lvTableChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure miReverseClick(Sender: TObject); procedure miCompareClick(Sender: TObject); procedure E1Click(Sender: TObject); procedure lvIndexClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure DBLoader1CreateSourceDB(Sender: TObject; Succeed: Boolean; errorMsg: string); procedure DBLoader1DeleteDestDB(Sender: TObject; Succeed: Boolean; errorMsg: string); procedure btnReverseClick(Sender: TObject); procedure btnCompareClick(Sender: TObject); procedure treeConfigHistoryKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure miConfigDeleteClick(Sender: TObject); procedure miConfigAddClick(Sender: TObject); procedure miConfigEditClick(Sender: TObject); procedure BtnConfigAddClick(Sender: TObject); procedure BtnConfigEditClick(Sender: TObject); procedure BtnConfigDeleteClick(Sender: TObject); procedure nConfigDeleteClick(Sender: TObject); procedure nConfigEditClick(Sender: TObject); procedure nConfigAddClick(Sender: TObject); private { Private declarations } //反射回来的数据 m_ReflexDB : TSQLDatabase; //从文件加载回来的数据 m_FileDB : TSQLDatabase; //待更新的目标数据库的数据 m_UpdateDb : TSQLDatabase; //配置信息 m_ConfigArray : TUpgradeConfig; private //比对两个数据库并生成比对结果的显示树 procedure InitCompareTree(SourceDB,DestDB : TSQLDatabase); //加载参数配置 procedure LoadConfig; //保存参数配置 procedure SaveConfig; //刷新参数配置显示 procedure RefreshTree; public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.dfm} uses uFrmSourceDB,uFrmCompareSet,uDataDefine,IniFiles, uFrmConfigAdd; { TForm1 } procedure TfrmMain.btnCompareClick(Sender: TObject); begin miCompareClick(sender); end; procedure TfrmMain.BtnConfigAddClick(Sender: TObject); begin miConfigAddClick(Sender); end; procedure TfrmMain.BtnConfigDeleteClick(Sender: TObject); begin miConfigDeleteClick(Sender); end; procedure TfrmMain.BtnConfigEditClick(Sender: TObject); begin miConfigEditClick(Sender); end; procedure TfrmMain.btnReverseClick(Sender: TObject); begin miReverseClick(Sender); end; procedure TfrmMain.Button1Click(Sender: TObject); begin OpenDialog1.FileName := ''; if treeConfigHistory.Selected <> nil then begin OpenDialog1.FileName := m_ConfigArray[treeConfigHistory.Selected.Index].SourceXML; end; if OpenDialog1.Execute then begin try m_ReflexDB.SaveToXml(OpenDialog1.FileName,Self); Application.MessageBox('保存成功','提示',MB_OK + MB_ICONINFORMATION); except on e : Exception do Application.MessageBox(PChar(Format('保存失败%s',[e.Message])),'提示',MB_OK + MB_ICONERROR); end; end; end; procedure TfrmMain.Button2Click(Sender: TObject); begin try Memo1.Lines.Clear; Memo1.Lines.Add('开始更新...'); DBLoader1.UpdateDB(m_FileDB,m_UpdateDb,ADOConnDest); Memo1.Lines.Add('开始完成...'); ShowMessage('更新完毕'); except on e : Exception do begin Memo1.Lines.Add('更新失败:' + e.Message); ShowMessage('更新失败:' + e.Message); end; end; end; procedure TfrmMain.DBLoader1CreateSourceDB(Sender: TObject; Succeed: Boolean; errorMsg: string); var strTypeName,strObjectName : string; strSucceed : string; begin {$region '翻译对象名'} if Sender is TSQLTable then begin strTypeName := '表'; strObjectName := TSQLTable(Sender).TableName; end; if Sender is TSQLIndex then begin strTypeName := '索引\键'; strObjectName := TSQLIndex(Sender).IndexName; end; if Sender is TSQLForeignkey then begin strTypeName := '外键'; strObjectName := TSQLForeignkey(Sender).ForeignkeyName; end; if Sender is TSQLTrigger then begin strTypeName := '触发器'; strObjectName := TSQLTrigger(Sender).TriggerName; end; if Sender is TSQLView then begin strTypeName := '视图'; strObjectName := TSQLView(Sender).ViewName; end; if Sender is TSQLProcedure then begin strTypeName := '存储过程'; strObjectName := TSQLProcedure(Sender).ProcedureName; end; if Sender is TSQLFunction then begin strTypeName := '函数'; strObjectName := TSQLFunction(Sender).FunctionName; end; {$endregion '翻译对象名'} strSucceed := '失败'; if Succeed then strSucceed := '成功'; Memo1.Lines.Add(Format('创建%s[%s]%s:%s',[strTypeName,strObjectName,strSucceed,errorMsg])); end; procedure TfrmMain.DBLoader1DeleteDestDB(Sender: TObject; Succeed: Boolean; errorMsg: string); var strTypeName,strObjectName : string; strSucceed : string; begin {$region '翻译对象名'} if Sender is TSQLTable then begin strTypeName := '主键'; strObjectName := TSQLTable(Sender).TableName; end; if Sender is TSQLForeignkey then begin strTypeName := '外键'; strObjectName := TSQLForeignkey(Sender).ForeignkeyName; end; if Sender is TSQLTrigger then begin strTypeName := '触发器'; strObjectName := TSQLTrigger(Sender).TriggerName; end; if Sender is TSQLIndex then begin strTypeName := '唯一约束'; strObjectName := TSQLIndex(Sender).IndexName; end; if Sender is TSQLView then begin strTypeName := '视图'; strObjectName := TSQLView(Sender).ViewName; end; if Sender is TSQLProcedure then begin strTypeName := '存储过程'; strObjectName := TSQLProcedure(Sender).ProcedureName; end; if Sender is TSQLFunction then begin strTypeName := '函数'; strObjectName := TSQLFunction(Sender).FunctionName; end; {$endregion '翻译对象名'} strSucceed := '失败'; if Succeed then strSucceed := '成功'; Memo1.Lines.Add(Format('删除%s[%s]%s:%s',[strTypeName,strObjectName,strSucceed,errorMsg])); end; procedure TfrmMain.E1Click(Sender: TObject); begin Close; end; procedure TfrmMain.FormCreate(Sender: TObject); begin m_ReflexDB := TSQLDatabase.Create; m_FileDB := TSQLDatabase.Create; m_UpdateDb := TSQLDatabase.Create; LoadConfig; RefreshTree; end; procedure TfrmMain.FormDestroy(Sender: TObject); begin lvTable.OnChange := nil; m_ReflexDB.Free; m_FileDB.Free; m_UpdateDb.Free; end; procedure TfrmMain.InitCompareTree(SourceDB, DestDB: TSQLDatabase); var i : integer; tab : TSQLTable; col : TSQLColumn; item,subItem : TTreeNode; j: Integer; begin tvCompare.Items.Clear; for i := 0 to SourceDB.TableList.Count - 1 do begin tab := SourceDB.TableList[i]; item := tvCompare.Items.AddChild(nil,''); item.Text := tab.TableName; case tab.UpdateType of utNone: begin item.ImageIndex := 0; item.SelectedIndex := 0; for j := 0 to tab.ColumnList.Count - 1 do begin col := tab.ColumnList.Items[j]; subItem := tvCompare.Items.AddChild(item,''); subItem.Text := col.ColumnName; subItem.ImageIndex := 0; subItem.SelectedIndex := 0; end; end; utAdd: begin item.ImageIndex := 1; item.SelectedIndex := 1; for j := 0 to tab.ColumnList.Count - 1 do begin col := tab.ColumnList.Items[j]; subItem := tvCompare.Items.AddChild(item,''); subItem.Text := col.ColumnName; subItem.ImageIndex := 1; subItem.SelectedIndex := 1; end; end; utUpdate: begin item.ImageIndex := 2; item.SelectedIndex := 2; for j := 0 to tab.ColumnList.Count - 1 do begin col := tab.ColumnList.Items[j]; subItem := tvCompare.Items.AddChild(item,''); subItem.Text := col.ColumnName; case col.UpdateType of utNone: begin subItem.ImageIndex := 0; subItem.SelectedIndex := 0; end; utAdd: begin subItem.ImageIndex := 1; subItem.SelectedIndex := 1; end; utUpdate: begin subItem.ImageIndex := 2; subItem.SelectedIndex := 2; end; end; end; tab := DestDB.FindTable(tab.TableName); for j := 0 to tab.ColumnList.Count - 1 do begin col := tab.ColumnList.Items[j]; if col.UpdateType <> utDelete then continue; subItem := tvCompare.Items.AddChild(item,''); subItem.Text := col.ColumnName; case col.UpdateType of utDelete: begin subItem.ImageIndex := 3; subItem.SelectedIndex := 3; end; end; end; end; end; end; for i := 0 to DestDB.TableList.Count - 1 do begin tab := DestDB.TableList[i]; if tab.UpdateType <> utDelete then continue; item := tvCompare.Items.AddChild(nil,''); item.Text := tab.TableName; case tab.UpdateType of utDelete: begin item.ImageIndex := 3; item.SelectedIndex := 3; for j := 0 to tab.ColumnList.Count - 1 do begin col := tab.ColumnList.Items[j]; subItem := tvCompare.Items.AddChild(item,''); subItem.Text := col.ColumnName; subItem.ImageIndex := 3; subItem.SelectedIndex := 3; end; end; end; end; end; procedure TfrmMain.LoadConfig; var ini : TIniFile; sections : TStrings; i: Integer; begin ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); try sections := TStringList.Create; try ini.ReadSections(sections); setlength(m_ConfigArray,sections.Count); for i := 0 to sections.Count-1 do begin m_ConfigArray[i].ConfigName := ini.ReadString(sections[i],'ConfigName',''); m_ConfigArray[i].CreateTime := ini.ReadString(sections[i],'CreateTime',''); m_ConfigArray[i].ReverseDBADD := ini.ReadString(sections[i],'ReverseDBADD',''); m_ConfigArray[i].ReverseDBUID := ini.ReadString(sections[i],'ReverseDBUID',''); m_ConfigArray[i].ReverseDBPWD := ini.ReadString(sections[i],'ReverseDBPWD',''); m_ConfigArray[i].ReverseDBName := ini.ReadString(sections[i],'ReverseDBName',''); m_ConfigArray[i].SourceXML := ini.ReadString(sections[i],'SourceXML',''); m_ConfigArray[i].DestDBADD := ini.ReadString(sections[i],'DestDBADD',''); m_ConfigArray[i].DestDBUID := ini.ReadString(sections[i],'DestDBUID',''); m_ConfigArray[i].DestDBPWD := ini.ReadString(sections[i],'DestDBPWD',''); m_ConfigArray[i].DestDBName := ini.ReadString(sections[i],'DestDBName',''); end; finally sections.Free; end; finally ini.Free; end; end; procedure TfrmMain.lvFunctionClick(Sender: TObject); var funcName : string; func : TSQLFunction; i : integer; begin if lvFunction.Selected = nil then exit; funcName := lvFunction.Selected.Caption; for i := 0 to m_ReflexDB.FunctionList.Count - 1 do begin func := m_ReflexDB.FunctionList[i]; if func.FunctionName = lvFunction.Selected.Caption then begin memoFunctionContent.Text := func.FunctionContent; end; end; end; procedure TfrmMain.lvIndexClick(Sender: TObject); var indexName : string; i,j,k: Integer; ind : TSQLIndex; tab : TSQLTable; indexcol : TSQLIndexColumn; item : TListItem; strTemp : string; begin if lvIndex.Selected = nil then exit; lvIndexColumn.Items.Clear; indexName := lvIndex.Selected.Caption; for i := 0 to m_ReflexDB.TableList.Count - 1 do begin tab := m_ReflexDB.TableList[i]; if tab.TableName = lvIndex.Selected.SubItems[0] then begin for j := 0 to tab.IndexList.Count - 1 do begin ind := tab.IndexList[j]; if ind.IndexName = indexName then begin for k := 0 to ind.ColumnList.Count - 1 do begin indexcol := ind.ColumnList[k]; item := lvIndexColumn.Items.Add; item.Caption := indexcol.ColumnName; strTemp := '升序'; if indexcol.Order = coDesc then strTemp := '降序'; item.SubItems.Add(strTemp); end; exit; end; end; end; end; end; procedure TfrmMain.lvProcedureClick(Sender: TObject); var procedureName : string; proc : TSQLProcedure; i : integer; begin if lvProcedure.Selected = nil then exit; procedureName := lvProcedure.Selected.Caption; for i := 0 to m_ReflexDB.ProcedureList.Count - 1 do begin proc := m_ReflexDB.ProcedureList[i]; if proc.ProcedureName = lvProcedure.Selected.Caption then begin memoProcedureContent.Text := proc.ProcedureContent; end; end; end; procedure TfrmMain.lvTableChange(Sender: TObject; Item: TListItem; Change: TItemChange); var tabName : string; tab : TSQLTable; i: Integer; begin tabName := Item.Caption; for i := 0 to m_ReflexDB.TableList.Count - 1 do begin tab := m_ReflexDB.TableList[i]; if tab.TableName = tabName then begin tab.UpdateData := Item.Checked; end; end; end; procedure TfrmMain.lvTableClick(Sender: TObject); var tabName : string; i,j: Integer; tab : TSQLTable; col : TSQLColumn; item : TListItem; strTemp : string; begin if lvTable.Selected = nil then exit; lvColumn.Items.Clear; tabName := lvTable.Selected.Caption; for i := 0 to m_ReflexDB.TableList.Count - 1 do begin tab := m_ReflexDB.TableList[i]; if tab.TableName = tabName then begin for j := 0 to tab.ColumnList.Count - 1 do begin col := tab.ColumnList[j]; item := lvColumn.Items.Add; item.Caption := col.ColumnName; item.SubItems.Add(col.GetDataTypeName); item.SubItems.Add(IntToStr(col.DataLength)); strTemp := ''; if col.AllowNull then strTemp := '√'; item.SubItems.Add(strTemp); item.SubItems.Add(col.DefaultValue); strTemp := ''; if col.Primary then strTemp := '√'; item.SubItems.Add(strTemp); strTemp := ''; if col.Identity then strTemp := '√'; item.SubItems.Add(strTemp); item.SubItems.Add(col.ColumnDescription); end; exit; end; end; end; procedure TfrmMain.lvTriggerClick(Sender: TObject); var TriggerName : string; Trigger : TSQLTrigger; i : integer; begin if lvTrigger.Selected = nil then exit; TriggerName := lvTrigger.Selected.Caption; for i := 0 to m_ReflexDB.TriggerList.Count - 1 do begin Trigger := m_ReflexDB.TriggerList[i]; if Trigger.TriggerName = lvTrigger.Selected.Caption then begin memoTriggerContent.Text := Trigger.TriggerContent; end; end; end; procedure TfrmMain.lvViewClick(Sender: TObject); var viewName : string; view : TSQLView; i : integer; begin if lvView.Selected = nil then exit; viewName := lvView.Selected.Caption; for i := 0 to m_ReflexDB.ViewList.Count - 1 do begin view := m_ReflexDB.ViewList[i]; if view.ViewName = lvView.Selected.Caption then begin memoViewContent.Text := view.ViewContent; end; end; end; procedure TfrmMain.miCompareClick(Sender: TObject); var connString,sourceFile : string; destDBConn : RDBConnection; is2000,is2005 : boolean; destDBVersion : string; begin frmCompareSet := TfrmCompareSet.Create(nil); try if treeConfigHistory.Selected <> nil then begin frmCompareSet.edtSourceFile.Text := m_ConfigArray[treeConfigHistory.Selected.Index].SourceXML; frmCompareSet.edtDestIP.Text := m_ConfigArray[treeConfigHistory.Selected.Index].DestDBADD; frmCompareSet.edtDestUser.Text := m_ConfigArray[treeConfigHistory.Selected.Index].DestDBUID; frmCompareSet.edtDestPassword.Text := m_ConfigArray[treeConfigHistory.Selected.Index].DestDBPWD; frmCompareSet.edtDestDBName.Text := m_ConfigArray[treeConfigHistory.Selected.Index].DestDBName; end; if frmCompareSet.ShowModal = mrOk then begin destDBConn := frmCompareSet.DestDBConn; sourceFile := frmCompareSet.edtSourceFile.Text; end else begin exit; end; finally frmCompareSet.Free; end; connString := 'Provider=SQLOLEDB.1;Persist Security Info=False;User ID=%s;' + 'Password=%s;Initial Catalog=%s;Data Source=%s'; connString := Format(connString,[destDBConn.strUser, destDBConn.strPassword,destDBConn.strDBName,destDBConn.strIp]); try if ADOConnDest.Connected then begin ADOConnDest.Close; end; ADOConnDest.ConnectionString := connString; ADOConnDest.Connected := true except on e : Exception do begin ADOConnDest.Close; ShowMessage(Format('目标数据库打开失败:%s!',[e.Message])); exit; end; end; m_FileDB.Clear; m_UpdateDb.Clear; m_FileDB.LoadFromXml(sourceFile,self); if not DBLoader1.GetDBVersion(ADOConnDest,destDBVersion) then begin if not Application.MessageBox('目标数据库无版本信息,您还要继续执行吗?', '警告',MB_OKCANCEL + MB_ICONWARNING) = mrcancel then Exit; end; if m_FileDB.DatabaseVersion = destDBVersion then begin if Application.MessageBox('源数据库与目标数据库的版本一致,您还要继续执行吗?', '警告',MB_OKCANCEL + MB_ICONWARNING) = mrcancel then Exit; end; is2000 := DBLoader1.IsSql2000(ADOConnDest); is2005 := DBLoader1.IsSql2005(ADOConnDest); if not (is2000 or is2005) then begin Application.MessageBox('未知的数据库版本','提示',MB_OK + MB_ICONERROR) ; exit; end; if is2000 then DBLoader1.Sqls := DBLoader1.GetSql2000Sqls; if is2005 then DBLoader1.Sqls := DBLoader1.GetSql2005Sqls; DBLoader1.LoadSchema(m_UpdateDb,ADOConnDest); m_FileDB.Compare(m_UpdateDb); InitCompareTree(m_FileDB,m_UpdateDb); PageControl1.ActivePageIndex := 1; end; procedure TfrmMain.miConfigAddClick(Sender: TObject); var tempConfig: RUpgradeConfig; i: Integer; begin frmConfigAdd := tfrmConfigAdd.Create(nil); try if frmConfigAdd.ShowModal = mrcancel then begin exit; end; tempConfig.ConfigName := Trim(frmConfigAdd.edtConfigName.Text); tempConfig.CreateTime := FormatDateTime('yyyy-MM-dd HH:nn:ss',Now); tempConfig.ReverseDBADD := frmConfigAdd.edtSourceIP.Text; tempConfig.ReverseDBUID := frmConfigAdd.edtSourceUser.Text; tempConfig.ReverseDBPWD := frmConfigAdd.edtSourcePassword.Text; tempConfig.ReverseDBName := frmConfigAdd.edtSourceDBName.Text; tempConfig.SourceXML := frmConfigAdd.edtSourceFile.Text; tempConfig.DestDBADD := frmConfigAdd.edtDestIP.Text; tempConfig.DestDBUID := frmConfigAdd.edtDestUser.Text; tempConfig.DestDBPWD := frmConfigAdd.edtDestPassword.Text; tempConfig.DestDBName := frmConfigAdd.edtDestDBName.Text; setLength(m_ConfigArray,length(m_ConfigArray) + 1); for i := length(m_ConfigArray) - 2 downto 0 do begin m_ConfigArray[i+1] := m_ConfigArray[i]; end; m_ConfigArray[0] := tempConfig; SaveConfig; RefreshTree; treeConfigHistory.Selected := treeConfigHistory.Items[0]; finally frmConfigAdd.Free; end; end; procedure TfrmMain.miConfigDeleteClick(Sender: TObject); var i,tempIndex: Integer; begin if (treeConfigHistory.Selected = nil) then begin exit; end; if Application.MessageBox('您确定要删除此配置信息吗?','提示',MB_OKCANCEL) = mrCancel then exit; tempIndex := treeConfigHistory.Selected.Index; for i := treeConfigHistory.Selected.Index to length(m_ConfigArray) - 2 do begin m_ConfigArray[i] := m_ConfigArray[i + 1]; end; SetLength(m_ConfigArray,length(m_ConfigArray) - 1); SaveConfig; RefreshTree; if treeConfigHistory.Items.Count > 0 then begin if treeConfigHistory.Items.Count > tempIndex then treeConfigHistory.Selected := treeConfigHistory.Items[tempIndex] else treeConfigHistory.Selected := treeConfigHistory.Items[treeConfigHistory.Items.Count - 1]; end; end; procedure TfrmMain.miConfigEditClick(Sender: TObject); var tempConfig: RUpgradeConfig; tempIndex : integer; begin if (treeConfigHistory.Selected = nil) then begin Application.MessageBox('请选择配置信息','提示',MB_OK + MB_ICONINFORMATION); exit; end; tempIndex := treeConfigHistory.Selected.Index; frmConfigAdd := TfrmConfigAdd.Create(nil); try with m_ConfigArray[treeConfigHistory.Selected.Index] do begin frmConfigAdd.edtConfigName.Text := ConfigName; frmConfigAdd.edtSourceIP.Text := ReverseDBADD; frmConfigAdd.edtSourceUser.Text := ReverseDBUID; frmConfigAdd.edtSourcePassword.Text := ReverseDBPWD; frmConfigAdd.edtSourceDBName.Text := ReverseDBName; frmConfigAdd.edtSourceFile.Text := SourceXML; frmConfigAdd.edtDestIP.Text := DestDBADD; frmConfigAdd.edtDestUser.Text := DestDBUID; frmConfigAdd.edtDestPassword.Text := DestDBPWD; frmConfigAdd.edtDestDBName.Text := DestDBName; end; if frmConfigAdd.ShowModal = mrcancel then exit; tempConfig.ConfigName := Trim(frmConfigAdd.edtConfigName.Text); tempConfig.CreateTime := FormatDateTime('yyyy-MM-dd HH:nn:ss',Now); tempConfig.ReverseDBADD := frmConfigAdd.edtSourceIP.Text; tempConfig.ReverseDBUID := frmConfigAdd.edtSourceUser.Text; tempConfig.ReverseDBPWD := frmConfigAdd.edtSourcePassword.Text; tempConfig.ReverseDBName := frmConfigAdd.edtSourceDBName.Text; tempConfig.SourceXML := frmConfigAdd.edtSourceFile.Text; tempConfig.DestDBADD := frmConfigAdd.edtDestIP.Text; tempConfig.DestDBUID := frmConfigAdd.edtDestUser.Text; tempConfig.DestDBPWD := frmConfigAdd.edtDestPassword.Text; tempConfig.DestDBName := frmConfigAdd.edtDestDBName.Text; m_ConfigArray[treeConfigHistory.Selected.Index] := tempConfig; treeConfigHistory.Selected.Text := tempConfig.ConfigName; SaveConfig; RefreshTree; treeConfigHistory.Selected := treeConfigHistory.Items[tempIndex]; finally frmConfigAdd.Free; end; end; procedure TfrmMain.miReverseClick(Sender: TObject); var i,j : integer; item : TListItem; tickCount : integer; connString,strTemp : string; dbConn : RDBConnection; is2000,is2005 : boolean; begin frmSetSourceDB := TFrmSetSourceDB.Create(nil); try if treeConfigHistory.Selected <> nil then begin frmSetSourceDB.edtSourceIP.Text := m_ConfigArray[treeConfigHistory.Selected.Index].ReverseDBADD; frmSetSourceDB.edtSourceUser.Text := m_ConfigArray[treeConfigHistory.Selected.Index].ReverseDBUID; frmSetSourceDB.edtSourcePassword.Text := m_ConfigArray[treeConfigHistory.Selected.Index].ReverseDBPWD; frmSetSourceDB.edtSourceDBName.Text := m_ConfigArray[treeConfigHistory.Selected.Index].ReverseDBName; end; if frmSetSourceDB.ShowModal = mrOk then begin dbConn := frmSetSourceDB.SourceDBConn; end else begin exit; end; finally frmSetSourceDB.Free; end; tickCount := GetTickCount; {$region '创建连接'} connString := 'Provider=SQLOLEDB.1;Persist Security Info=False;User ID=%s; ' + ' Password=%s;Initial Catalog=%s;Data Source=%s'; connString := Format(connString,[dbConn.strUser, dbConn.strPassword,dbConn.strDBName,dbConn.strIp]); try if ADOConnSource.Connected then begin ADOConnSource.Close; end; ADOConnSource.ConnectionString := connString; ADOConnSource.Connected := true; except on e : Exception do begin ADOConnSource.Close; ShowMessage(Format('目标数据库打开失败:%s!',[e.Message])); exit; end; end; {$endregion '创建连接'} m_ReflexDB.Clear; is2000 := DBLoader1.IsSql2000(ADOConnSource); is2005 := DBLoader1.IsSql2005(ADOConnSource); if not (is2000 or is2005) then begin Application.MessageBox('未知的数据库版本','提示',MB_OK + MB_ICONERROR) ; exit; end; if is2000 then DBLoader1.Sqls := DBLoader1.GetSql2000Sqls; if is2005 then DBLoader1.Sqls := DBLoader1.GetSql2005Sqls; DBLoader1.LoadSchema(m_ReflexDB,ADOConnSource); {$region '预览数据库框架'} lvTable.Items.Clear; lvView.Items.Clear; lvProcedure.Items.Clear; lvFunction.Items.Clear; lvForeignkey.Items.Clear; lvIndex.Items.Clear; for i := 0 to m_ReflexDB.TableList.Count - 1 do begin item := lvTable.Items.Add; item.ImageIndex := 0; item.Checked := m_ReflexDB.TableList[i].UpdateData; item.Caption := m_ReflexDB.TableList[i].TableName; item.SubItems.Add(m_ReflexDB.TableList[i].TableDescription); for j := 0 to m_ReflexDB.TableList[i].IndexList.Count - 1 do begin item := lvIndex.Items.Add; item.ImageIndex := 0; item.Caption := m_ReflexDB.TableList[i].IndexList[j].IndexName; item.SubItems.Add(m_ReflexDB.TableList[i].IndexList[j].TableName); strTemp := ''; if m_ReflexDB.TableList[i].IndexList[j].Clustered then strTemp := '√'; item.SubItems.Add(strTemp); strTemp := ''; if m_ReflexDB.TableList[i].IndexList[j].Unique then strTemp := '√'; item.SubItems.Add(strTemp); strTemp := ''; if m_ReflexDB.TableList[i].IndexList[j].IsPrimary then strTemp := '√'; item.SubItems.Add(strTemp); strTemp := ''; if m_ReflexDB.TableList[i].IndexList[j].IsConstraint then strTemp := '√'; item.SubItems.Add(strTemp); end; TRzTabSheet(lvIndex.Parent).Caption := Format('索引(%d)',[lvIndex.Items.Count]); end; TRzTabSheet(lvTable.Parent).Caption := Format('表(%d)',[lvTable.Items.Count]); for i := 0 to m_ReflexDB.ViewList.Count - 1 do begin item := lvView.Items.Add; item.ImageIndex := 1; item.Caption := m_ReflexDB.ViewList[i].ViewName; item.SubItems.Add(m_ReflexDB.ViewList[i].ViewDescription); end; TRzTabSheet(lvView.Parent).Caption := Format('视图(%d)',[lvView.Items.Count]); for i := 0 to m_ReflexDB.TriggerList.Count - 1 do begin item := lvTrigger.Items.Add; item.ImageIndex := 2; item.Caption := m_ReflexDB.TriggerList[i].TriggerName; item.SubItems.Add(m_ReflexDB.TriggerList[i].TriggerDescription); end; TRzTabSheet(lvTrigger.Parent).Caption := Format('触发器(%d)',[lvTrigger.Items.Count]); for i := 0 to m_ReflexDB.ProcedureList.Count - 1 do begin item := lvProcedure.Items.Add; item.ImageIndex := 3; item.Caption := m_ReflexDB.ProcedureList[i].ProcedureName; item.SubItems.Add(m_ReflexDB.ProcedureList[i].ProcedureDescription) end; TRzTabSheet(lvProcedure.Parent).Caption := Format('存储过程(%d)',[lvProcedure.Items.Count]); for i := 0 to m_ReflexDB.FunctionList.Count - 1 do begin item := lvFunction.Items.Add; item.ImageIndex := 4; item.Caption := m_ReflexDB.FunctionList[i].FunctionName; item.SubItems.Add(m_ReflexDB.FunctionList[i].FunctionDescription); end; TRzTabSheet(lvFunction.Parent).Caption := Format('函数(%d)',[lvFunction.Items.Count]); for i := 0 to m_ReflexDB.ForeignkeyList.Count - 1 do begin item := lvForeignkey.Items.Add; item.ImageIndex := 5; item.Caption := m_ReflexDB.ForeignkeyList[i].KeyTableName; item.SubItems.Add(m_ReflexDB.ForeignkeyList[i].KeyColumnName); item.SubItems.Add(m_ReflexDB.ForeignkeyList[i].RKeyTableName); item.SubItems.Add(m_ReflexDB.ForeignkeyList[i].RKeyColumnName); end; TRzTabSheet(lvForeignkey.Parent).Caption := Format('外键(%d)',[lvForeignkey.Items.Count]); {$endregion '预览数据库框架'} caption := Format('数据库自动升级:%0.2f秒',[(GetTickCount - tickCount)/1000]); PageControl1.ActivePageIndex := 0; end; procedure TfrmMain.nConfigAddClick(Sender: TObject); begin miConfigAddClick(Sender); end; procedure TfrmMain.nConfigDeleteClick(Sender: TObject); begin miConfigDeleteClick(Sender); end; procedure TfrmMain.nConfigEditClick(Sender: TObject); begin miConfigEditClick(Sender); end; procedure TfrmMain.RefreshTree; var i : integer; node: TTreeNode; begin treeConfigHistory.Items.Clear; for i := 0 to length(m_ConfigArray) - 1 do begin node := treeConfigHistory.Items.Add(nil,''); node.Text := m_ConfigArray[i].ConfigName; end; end; procedure TfrmMain.SaveConfig; var ini : TIniFile; i: Integer; sections : TStrings; begin ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); try sections := TStringList.Create; try ini.ReadSections(sections); for i := 0 to sections.Count - 1 do begin ini.EraseSection(sections[i]); end; finally sections.Free; end; for i := 0 to length(m_ConfigArray) - 1 do begin ini.WriteString(m_ConfigArray[i].ConfigName,'ConfigName',m_ConfigArray[i].ConfigName); ini.WriteString(m_ConfigArray[i].ConfigName,'CreateTime',m_ConfigArray[i].CreateTime); ini.WriteString(m_ConfigArray[i].ConfigName,'ReverseDBADD',m_ConfigArray[i].ReverseDBADD); ini.WriteString(m_ConfigArray[i].ConfigName,'ReverseDBUID',m_ConfigArray[i].ReverseDBUID); ini.WriteString(m_ConfigArray[i].ConfigName,'ReverseDBPWD',m_ConfigArray[i].ReverseDBPWD); ini.WriteString(m_ConfigArray[i].ConfigName,'ReverseDBName',m_ConfigArray[i].ReverseDBName); ini.WriteString(m_ConfigArray[i].ConfigName,'SourceXML',m_ConfigArray[i].SourceXML); ini.WriteString(m_ConfigArray[i].ConfigName,'DestDBADD',m_ConfigArray[i].DestDBADD); ini.WriteString(m_ConfigArray[i].ConfigName,'DestDBUID',m_ConfigArray[i].DestDBUID); ini.WriteString(m_ConfigArray[i].ConfigName,'DestDBPWD',m_ConfigArray[i].DestDBPWD); ini.WriteString(m_ConfigArray[i].ConfigName,'DestDBName',m_ConfigArray[i].DestDBName); end; finally ini.Free; end; end; procedure TfrmMain.treeConfigHistoryKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = 46 then begin miConfigDeleteClick(sender); end; end; end.
unit MainFormUnit; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Dialogs, //GLS GLScene, GLVectorFileObjects, Vcl.StdCtrls, GLBSP, GLMeshCSG, GLWin32Viewer, GLObjects, GLTexture, GLFile3DS, GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses, GLState, GLVectorGeometry, GLUtils; type TForm1 = class(TForm) GLScene1: TGLScene; GLFreeForm1: TGLFreeForm; GLCamera1: TGLCamera; GLSceneViewer1: TGLSceneViewer; GLMaterialLibrary1: TGLMaterialLibrary; GLFreeForm2: TGLFreeForm; GLFreeForm3: TGLFreeForm; Panel1: TPanel; ButtonClear: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; CheckBox1: TCheckBox; GLLightSource1: TGLLightSource; GLDummyCube1: TGLDummyCube; procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure FormMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure FormCreate(Sender: TObject); // Demo starts here above is just navigation. procedure ButtonClearClick(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure CheckBox1Click(Sender: TObject); private { Private declarations } public mx : Integer; my : Integer; Drag : Boolean; end; var Form1: TForm1; implementation {$R *.dfm} // Demo starts here above is just navigation. procedure TForm1.FormCreate(Sender: TObject); begin SetGLSceneMediaDir(); // scaled 40 GLFreeForm1.LoadFromFile('polyhedron.3ds'); // scaled 20, position.x = 16 GLFreeForm2.LoadFromFile('polyhedron.3ds'); end; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Drag := true; end; procedure TForm1.GLSceneViewer1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Drag := false; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if Drag then begin GLCamera1.MoveAroundTarget(my-Y,mx-X); end; mx := X; my := Y; end; procedure TForm1.FormMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin GLCamera1.AdjustDistanceToTarget(1.1); end; procedure TForm1.FormMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin GLCamera1.AdjustDistanceToTarget(1/1.1); end; procedure TForm1.ButtonClearClick(Sender: TObject); begin GLFreeForm3.MeshObjects.Clear; GLFreeForm3.StructureChanged; GLFreeForm1.Material.PolygonMode := pmFill; GLFreeForm2.Material.PolygonMode := pmFill; end; procedure TForm1.Button2Click(Sender: TObject); var Mesh : TMeshObject; begin ButtonClearClick(Sender); if GLFreeForm3.MeshObjects.Count = 0 then TMeshObject.CreateOwned(GLFreeForm3.MeshObjects).Mode := momFaceGroups; Mesh := GLFreeForm3.MeshObjects[0]; CSG_Operation(GLFreeForm1.MeshObjects.Items[0],GLFreeForm2.MeshObjects.Items[0],CSG_Union,Mesh,'1','2'); GLFreeForm3.StructureChanged; GLFreeForm1.Material.PolygonMode := pmLines; GLFreeForm2.Material.PolygonMode := pmLines; end; procedure TForm1.Button3Click(Sender: TObject); var Mesh : TMeshObject; begin ButtonClearClick(Sender); if GLFreeForm3.MeshObjects.Count = 0 then TMeshObject.CreateOwned(GLFreeForm3.MeshObjects).Mode := momFaceGroups; Mesh := GLFreeForm3.MeshObjects[0]; CSG_Operation(GLFreeForm1.MeshObjects.Items[0],GLFreeForm2.MeshObjects.Items[0],CSG_Subtraction,Mesh,'1','2'); GLFreeForm3.StructureChanged; GLFreeForm1.Material.PolygonMode := pmLines; GLFreeForm2.Material.PolygonMode := pmLines; end; procedure TForm1.Button4Click(Sender: TObject); var Mesh : TMeshObject; begin ButtonClearClick(Sender); if GLFreeForm3.MeshObjects.Count = 0 then TMeshObject.CreateOwned(GLFreeForm3.MeshObjects).Mode := momFaceGroups; Mesh := GLFreeForm3.MeshObjects[0]; CSG_Operation(GLFreeForm2.MeshObjects.Items[0],GLFreeForm1.MeshObjects.Items[0],CSG_Subtraction,Mesh,'1','2'); GLFreeForm3.StructureChanged; GLFreeForm1.Material.PolygonMode := pmLines; GLFreeForm2.Material.PolygonMode := pmLines; end; procedure TForm1.Button5Click(Sender: TObject); var Mesh : TMeshObject; begin ButtonClearClick(Sender); if GLFreeForm3.MeshObjects.Count = 0 then TMeshObject.CreateOwned(GLFreeForm3.MeshObjects).Mode := momFaceGroups; Mesh := GLFreeForm3.MeshObjects[0]; CSG_Operation(GLFreeForm1.MeshObjects.Items[0],GLFreeForm2.MeshObjects.Items[0],CSG_Intersection,Mesh,'1','2'); GLFreeForm3.StructureChanged; GLFreeForm1.Material.PolygonMode := pmLines; GLFreeForm2.Material.PolygonMode := pmLines; end; procedure TForm1.CheckBox1Click(Sender: TObject); begin if CheckBox1.Checked then begin GLMaterialLibrary1.Materials[0].Material.PolygonMode := pmFill; GLMaterialLibrary1.Materials[1].Material.PolygonMode := pmFill; end else begin GLMaterialLibrary1.Materials[0].Material.PolygonMode := pmLines; GLMaterialLibrary1.Materials[1].Material.PolygonMode := pmLines; end; GLFreeForm3.StructureChanged; end; end.
{ Copyright (C) 2012, 2014 Matthias Bolte <matthias@tinkerforge.com> Redistribution and use in source and binary forms of this file, with or without modification, are permitted. See the Creative Commons Zero (CC0 1.0) License for more details. } unit TimedSemaphore; {$ifdef FPC} {$mode OBJFPC}{$H+} {$else} {$ifdef MACOS}{$define DELPHI_MACOS}{$endif} {$endif} interface uses {$ifdef UNIX}CThreads,{$endif} {$ifdef MSWINDOWS}Windows{$else}SyncObjs{$endif}; type {$ifndef MSWINDOWS} { Manual-Reset Event } TEventWrapper = class private {$ifdef DELPHI_MACOS} event: TEvent; {$else} event: PRTLEvent; {$endif} public constructor Create; destructor Destroy; override; procedure WaitFor(const timeout: longint); procedure SetEvent; procedure ResetEvent; end; {$endif} { Semaphore with blocking lower bound, but without blocking upper bound } TTimedSemaphore = class private alive: boolean; {$ifdef MSWINDOWS} handle: THandle; {$else} mutex: TCriticalSection; event: TEventWrapper; available: longint; {$endif} public constructor Create; destructor Destroy; override; function Acquire(const timeout: longint): boolean; procedure Release; end; implementation constructor TTimedSemaphore.Create; begin inherited; alive := true; {$ifdef MSWINDOWS} handle := CreateSemaphore(nil, 0, 2147483647, nil); {$else} mutex := TCriticalSection.Create; event := TEventWrapper.Create; available := 0; {$endif} end; destructor TTimedSemaphore.Destroy; begin if (not alive) then begin exit; end; alive := false; Release; {$ifdef MSWINDOWS} CloseHandle(handle); {$else} event.Destroy; mutex.Destroy; {$endif} inherited Destroy; end; function TTimedSemaphore.Acquire(const timeout: longint): boolean; begin {$ifdef MSWINDOWS} if (timeout < 0) then begin result := WaitForSingleObject(handle, INFINITE) = WAIT_OBJECT_0; end else begin result := WaitForSingleObject(handle, timeout) = WAIT_OBJECT_0; end; {$else} result := false; mutex.Acquire; try if (available > 0) then begin Dec(available); result := true; if (available = 0) then begin event.ResetEvent(); end; end; finally mutex.Release; end; if not result then begin event.WaitFor(timeout); mutex.Acquire; try if (available > 0) then begin Dec(available); result := true; if (available = 0) then begin event.ResetEvent(); end; end; finally mutex.Release; end; end; {$endif} if (not alive) then begin result := false; end; end; procedure TTimedSemaphore.Release; begin {$ifdef MSWINDOWS} ReleaseSemaphore(handle, 1, nil); {$else} mutex.Acquire; try Inc(available); event.SetEvent(); finally mutex.Release; end; {$endif} end; {$ifndef MSWINDOWS} { TEventWrapper } constructor TEventWrapper.Create; begin {$ifdef DELPHI_MACOS} event := TEvent.Create(nil, true, false, '', false); {$else} event := RTLEventCreate; { This is a manual-reset event } {$endif} end; destructor TEventWrapper.Destroy; begin {$ifdef DELPHI_MACOS} event.Destroy; {$else} RTLEventDestroy(event); {$endif} inherited Destroy; end; procedure TEventWrapper.WaitFor(const timeout: longint); begin if (timeout < 0) then begin {$ifdef DELPHI_MACOS} event.WaitFor(INFINITE); {$else} RTLEventWaitFor(event); {$endif} end else begin {$ifdef DELPHI_MACOS} event.WaitFor(timeout); {$else} RTLEventWaitFor(event, timeout); {$endif} end; end; procedure TEventWrapper.SetEvent; begin {$ifdef DELPHI_MACOS} event.SetEvent(); {$else} RTLEventSetEvent(event); {$endif} end; procedure TEventWrapper.ResetEvent; begin {$ifdef DELPHI_MACOS} event.ResetEvent(); {$else} RTLEventResetEvent(event); {$endif} end; {$endif} end.
unit DACThread; interface uses Classes, Windows, Math, SysUtils, ltr34api, Dialogs, ltrapi, Config; type TDACThread = class(TThread) public stop:boolean; DAC_level:array of DOUBLE; debugFile: TextFile; destructor Free(); procedure CheckError(err: Integer); constructor Create(ltr34: pTLTR34; SuspendCreate : Boolean); procedure stopThread(); procedure Execute; override; private phltr34: pTLTR34; DATA:array[0..DAC_packSize-1] of Double; WORD_DATA:array[0..DAC_packSize-1] of Double; procedure updateDAC(channel: integer); end; implementation procedure TDACThread.updateDAC(channel: integer); var i, ulimit: Integer; ch_code: Double; summator, step: single; begin if DATA[channel]=DAC_level[channel] then exit; EnterCriticalSection(DACSection); DATA[channel]:= DAC_level[channel]; LeaveCriticalSection(DACSection); CheckError(LTR34_ProcessData(phltr34,@DATA,@WORD_DATA, phltr34.ChannelQnt, 0)); //1- указываем что значения в Вольтах CheckError(LTR34_Send(phltr34,@WORD_DATA, phltr34.ChannelQnt, DAC_possible_delay)); //writeln(debugFile, FloatToStr((DAC_level[channel]))); end; procedure TDACThread.stopThread(); var ch: Integer; begin for ch:=0 to phltr34.ChannelQnt-1 do begin DAC_level[ch]:= 0; updateDAC(ch); end; stop:=true; end; procedure TDACThread.CheckError(err: Integer); begin if err < LTR_OK then MessageDlg('LTR34: ' + LTR34_GetErrorString(err), mtError, [mbOK], 0); end; constructor TDACThread.Create(ltr34: pTLTR34; SuspendCreate : Boolean); var i: integer; begin Inherited Create(SuspendCreate); stop:=False; phltr34:= ltr34; SetLength(DAC_level, phltr34.ChannelQnt); EnterCriticalSection(DACSection); for i := 0 to ChannelsAmount - 1 do begin DAC_level[i]:= DAC_min_signal; end; LeaveCriticalSection(DACSection); end; destructor TDACThread.Free(); begin Inherited Free(); end; procedure TDACThread.Execute; var i: integer; begin System.Assign(debugFile, 'D:\Dac.txt'); ReWrite(debugFile); CheckError(LTR34_DACStart(phltr34)); while not stop do for i:=0 to ChannelsAmount-1 do updateDAC(i); LTR34_Reset(phltr34); CheckError(LTR34_DACStop(phltr34)); end; end.
unit int_not_i8; interface implementation var I: UInt8; procedure Test; begin I := 128; I := not I; end; initialization Test(); finalization Assert(I = 127); end.
unit ccuUtils; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ccuGrids, ccuDataStringGrid, StdCtrls, unicodeclasses; type PSearchRec = ^TSearchRec; procedure SetStdDirectoryW(var Dir: WideString); function GetStdDirectoryW(const Dir: WideString): WideString; function MyDgGetFirstEmptyRow(var dg: TccuDataStringGrid): Integer; procedure FindFilesW(APath, AFilter: WideString; var AList: TList); procedure FindFileNamesW(APath, AFilter: WideString; var AList: TUniStrings); //得到字符串中的下一部分 function GetNextPart(var str: String; Sep1: char = char(9); Sep2: char = ','; Position: integer = 1): String; implementation procedure SetStdDirectoryW(var Dir: WideString); begin if Dir[Length(Dir)] <> '\' then Dir := Dir + '\' end; function GetStdDirectoryW(const Dir: WideString): WideString; begin if Dir[Length(Dir)] <> '\' then Result := Dir + '\' else Result := Dir; end; function MyDgGetFirstEmptyRow(var dg: TccuDataStringGrid): Integer; var IntTmp: Integer; begin IntTmp := dg.GetFirstEmptyRow; if IntTmp = -1 then begin dg.RowCount := dg.RowCount + 1; dg.Row := dg.RowCount - 1; end else dg.Row := IntTmp; end; procedure FindFilesW(APath, AFilter: WideString; var AList: TList); var FSearchRec, DsearchRec: TSearchRec; Item: PSearchRec; FindResult: Integer; i: Integer; function IsDirNotation(ADirName: string): Boolean; begin Result := (ADirName = '.') or (ADirName = '..'); end; begin SetStdDirectoryW(APath); FindResult := FindFirst(APath + AFilter, faAnyFile + faHidden + faSysFile + faReadOnly, FSearchRec); try while FindResult = 0 do begin Item := @FSearchRec; AList.Add(Item); Item := nil; FindResult := FindNext(FSearchRec); end; FindResult := FindFirst(APath + '*.*', faDirectory, DSearchRec); while FindResult = 0 do begin if ((DSearchRec.Attr and faDirectory) = faDirectory) and not IsDirNotation(DsearchRec.Name) then FindFilesW(APath + DSearchRec.Name, '*.*', AList); FindResult := FindNext(DsearchRec); end; finally FindClose(FSearchRec); end; end; procedure FindFileNamesW(APath, AFilter: WideString; var AList: TUniStrings); var FSearchRec, DsearchRec: TSearchRec; Item: PSearchRec; FindResult: Integer; i: Integer; function IsDirNotation(ADirName: WideString): Boolean; begin Result := (ADirName = '.') or (ADirName = '..'); end; begin SetStdDirectoryW(APath); FindResult := FindFirst(APath + AFilter, faAnyFile + faHidden + faSysFile + faReadOnly, FSearchRec); try while FindResult = 0 do begin AList.Add(APath + FSearchRec.Name); FindResult := FindNext(FSearchRec); end; FindResult := FindFirst(APath + '*.*', faDirectory, DSearchRec); while FindResult = 0 do begin if ((DSearchRec.Attr and faDirectory) = faDirectory) and not IsDirNotation(DsearchRec.Name) then FindFileNamesW(APath + DSearchRec.Name, '*.*', AList); FindResult := FindNext(DsearchRec); end; finally FindClose(FSearchRec); FindClose(DsearchRec); end; end; //得到字符串中的下一部分 function GetNextPart(var str: String; Sep1: char = char(9); Sep2: char = ','; Position: integer = 1): String; var intPos: integer; begin intPos := pos(Sep1, str); if (intPos = 0) and (Sep2 <> '') then intPos := pos(Sep2, str); if intPos > 0 then begin result := Copy(str, 1, intPos - 1); Delete(str, 1, intPos); end else begin result := str; str := ''; end; if (intPos > 0) and (Position > 1) then result := GetNextPart(str, Sep1, Sep2, Position - 1); end; end.
unit AProdutos; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, DBTables, Db, DBCtrls, Grids, DBGrids, Buttons, Menus, formularios, PainelGradiente, Tabela, Componentes1, LabelCorMove, Localizacao, Mask, UnDadosProduto, EditorImagem, ImgList, numericos, UnProdutos, UnClassificacao,UnSistema, FMTBcd, SqlExpr,Clipbrd; type TFprodutos = class(TFormularioPermissao) Splitter1: TSplitter; CadClassificacao: TSQLQuery; Imagens: TImageList; CadProdutos: TSQLQuery; PainelGradiente1: TPainelGradiente; PanelColor2: TPanelColor; Arvore: TTreeView; PanelColor4: TPanelColor; BAlterar: TBitBtn; BExcluir: TBitBtn; BProdutos: TBitBtn; BitBtn1: TBitBtn; Localiza: TConsultaPadrao; BNovaClassificacao: TBitBtn; VisualizadorImagem1: TVisualizadorImagem; PanelColor1: TPanelColor; BFechar: TBitBtn; BitBtn4: TBitBtn; PopupMenu1: TPopupMenu; MNovaClassificacao: TMenuItem; MNovoProduto: TMenuItem; N1: TMenuItem; MAlterar: TMenuItem; MExcluir: TMenuItem; Consultar1: TMenuItem; Localizar1: TMenuItem; N2: TMenuItem; ImageList1: TImageList; PanelColor3: TPanelColor; AtiPro: TCheckBox; Aux: TSQLQuery; PanelColor6: TPanelColor; Shape2: TShape; VerFoto: TCheckBox; Esticar: TCheckBox; Panel1: TPanel; Foto: TImage; BEditarFoto: TBitBtn; MFichaTecnica: TMenuItem; N3: TMenuItem; StatusBar1: TStatusBar; BLocalizaClassificacao: TBitBtn; BMenuFiscal: TBitBtn; procedure FormCreate(Sender: TObject); procedure ArvoreExpanded(Sender: TObject; Node: TTreeNode); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ArvoreChange(Sender: TObject; Node: TTreeNode); procedure ArvoreCollapsed(Sender: TObject; Node: TTreeNode); procedure Alterar(Sender: TObject;Alterar : Boolean); Procedure Excluir(Sender : TObject); procedure BAlterarClick(Sender: TObject); procedure BExcluirClick(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure BNovaClassificacaoClick(Sender: TObject); procedure BProdutosClick(Sender: TObject); procedure BFecharClick(Sender: TObject); procedure FotoDblClick(Sender: TObject); procedure EsticarClick(Sender: TObject); procedure BitBtn4Click(Sender: TObject); procedure ArvoreDblClick(Sender: TObject); procedure VerFotoClick(Sender: TObject); procedure ArvoreKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ArvoreKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure AtiProClick(Sender: TObject); procedure BBAjudaClick(Sender: TObject); procedure MFichaTecnicaClick(Sender: TObject); procedure ArvoreDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure ArvoreDragDrop(Sender, Source: TObject; X, Y: Integer); procedure BLocalizaClassificacaoClick(Sender: TObject); procedure BMenuFiscalClick(Sender: TObject); private UnProduto : TFuncoesProduto; VprListar : boolean; VprQtdNiveis : Byte; VprVetorMascara : array [1..6] of byte; VprVetorNo: array [0..6] of TTreeNode; VprPrimeiroNo : TTreeNode; CifraInicial : string; function DesmontaMascara(var Vetor : array of byte; mascara:string):byte; procedure CarregaClassificacao(VpaVetorInfo : array of byte); procedure CarregaProduto(VpaNoSelecao : TTreeNode); procedure CarregaConsumoProduto(VpaNoSelecao : TTreeNode); procedure RecarregaLista; procedure ConfiguraPermissaoUsuario; public { Public declarations } end; var Fprodutos: TFprodutos; implementation uses APrincipal, fundata, constantes,funObjeto, constMsg, funstring, ANovaClassificacao, FunSql, ANovoProdutoPro, AMenuFiscalECF; {$R *.DFM} {***********************No fechamento do Formulario****************************} procedure TFprodutos.FormClose(Sender: TObject; var Action: TCloseAction); begin CurrencyString := CifraInicial; UnProduto.Destroy; CadProdutos.Close; CadClassificacao.Close; Action := CaFree; end; {************************Quanto criado novo formulario*************************} procedure TFprodutos.FormCreate(Sender: TObject); begin ConfiguraPermissaoUsuario; CifraInicial := CurrencyString; UnProduto := TFuncoesProduto.criar(self,FPrincipal.BaseDados); FillChar(VprVetorMascara, SizeOf(VprVetorMascara), 0); VprListar := true; if not FunProdutos.VerificaMascaraClaPro then PanelColor4.Enabled := false; VprQtdNiveis := DesmontaMascara(VprVetorMascara, varia.mascaraCLA); // busca em constantes CarregaClassificacao(VprVetorMascara); end; {******Desmonata a mascara pardão para a configuração das classificações*******} function TFprodutos.DesmontaMascara(var Vetor : array of byte; mascara:string):byte; var x:byte; posicao:byte; begin posicao:=0; x:=0; while Pos('.', mascara) > 0 do begin vetor[x]:=(Pos('.', mascara)-posicao)-1; inc(x); posicao:=Pos('.', mascara); mascara[Pos('.', mascara)] := '*'; end; vetor[x]:=length(mascara)-posicao; vetor[x+1] := 1; DesmontaMascara:=x+1; end; {************************carrega Classificacao*********************************} procedure TFprodutos.CarregaClassificacao(VpaVetorInfo : array of byte); var VpfNo : TTreeNode; VpfDClassificacao : TClassificacao; VpfTamanho, VpfNivel : word; begin Arvore.Items.Clear; VpfDClassificacao := TClassificacao.Cria; VpfDClassificacao.CodClassificacao:=''; VpfDClassificacao.Tipo := 'NA'; //NADA; Vpfno := arvore.Items.AddObject(arvore.Selected, 'Produtos', VpfDClassificacao); VprPrimeiroNo := VpfNo; VprVetorNo[0]:= VpfNo; Vpfno.ImageIndex:=0; Vpfno.SelectedIndex:=0; Arvore.Update; CadClassificacao.SQL.Clear; CadClassificacao.SQL.Add('SELECT * FROM CADCLASSIFICACAO '+ ' WHERE I_COD_EMP = ' + IntToStr(varia.CodigoEmpresa) + ' and c_tip_cla = ''P'''); if (puSomenteProdutos in varia.PermissoesUsuario) and (Varia.CodClassificacaoProdutos <> '') then CadClassificacao.SQL.Add('AND C_COD_CLA like '''+Varia.CodClassificacaoProdutos+'%''') else if (puSomenteMateriaPrima in varia.PermissoesUsuario) and (Varia.CodClassificacaoMateriaPrima <> '') then CadClassificacao.SQL.Add('AND C_COD_CLA like '''+Varia.CodClassificacaoMateriaPrima+'%'''); CadClassificacao.SQL.Add(' ORDER BY C_COD_CLA '); CadClassificacao.Open; while not(CadClassificacao.EOF) do begin VpfTamanho := VpaVetorInfo[0]; Vpfnivel := 0; while length(CadClassificacao.FieldByName('C_COD_CLA').AsString) <> VpfTamanho do begin inc(VpfNivel); Vpftamanho:=VpfTamanho+VpaVetorInfo[Vpfnivel]; end; VpfDClassificacao := TClassificacao.Create; VpfDClassificacao.CodClassificacao := CadClassificacao.FieldByName('C_COD_CLA').AsString; VpfDClassificacao.CodClassificacoReduzido := copy(VpfDClassificacao.CodClassificacao, (length(VpfDClassificacao.CodClassificacao)-VpaVetorInfo[Vpfnivel])+1, VpaVetorInfo[VpfNivel]); VpfDClassificacao.NomClassificacao := CadClassificacao.FieldByName('C_NOM_CLA').AsString; VpfDClassificacao.ProdutosCarregados := false; VpfDClassificacao.Tipo := 'CL'; VpfDClassificacao.ProdutosCarregados := false; Vpfno:=Arvore.Items.AddChildObject(VprVetorNo[VpfNivel], VpfDClassificacao.CodClassificacoReduzido + ' - '+ CadClassificacao.FieldByName('C_NOM_CLA').AsString, VpfDClassificacao); VprVetorNo[Vpfnivel+1]:=Vpfno; CadClassificacao.Next; end; CadClassificacao.Close; end; {********carregaProduto : serve para carregar o TreeView com as informações da base que estão na tabela Produtos.**********************} procedure TFprodutos.CarregaProduto(VpaNoSelecao : TTreeNode ); var VpfNo : TTreeNode; VpfDClassificacao : TClassificacao; VpfSeqProduto : Integer; begin VpfSeqProduto := -1; if not TClassificacao(TTreeNode(VpaNoSelecao).Data).ProdutosCarregados then begin VpfDClassificacao := TClassificacao(TTreeNode(VpaNoSelecao).Data); CadProdutos.Close; CadProdutos.sql.Clear; CadProdutos.sql.add(' Select ' + ' pro.i_seq_pro, pro.c_cod_cla, pro.c_ati_pro, ' + ' pro.c_cod_pro, pro.c_pat_fot, pro.c_nom_pro, moe.c_cif_moe, ' + ' pro.c_kit_pro ' + ' from CADPRODUTOS PRO, ' + ' MOVQDADEPRODUTO MOV, CADMOEDAS MOE ' + ' where PRO.I_COD_EMP = ' + IntToStr(varia.CodigoEmpresa) + ' and PRO.C_COD_CLA = ''' + VpfDClassificacao.CodClassificacao + ''''); if AtiPro.Checked then CadProdutos.sql.add(' and PRO.C_ATI_PRO = ''S'''); CadProdutos.sql.add(' and pro.I_seq_pro = mov.i_seq_pro ' + ' and mov.i_emp_fil = ' + IntTostr(varia.CodigoEmpFil) + ' and mov.I_COD_COR = 0 '+ ' and pro.i_cod_moe = moe.i_cod_moe' ); if config.NaArvoreOrdenarProdutoPeloCodigo then CadProdutos.sql.add(' Order by PRO.C_COD_PRO, PRO.I_SEQ_PRO') else CadProdutos.sql.add(' Order by PRO.C_NOM_PRO, PRO.I_SEQ_PRO'); CadProdutos.open; CadProdutos.First; while not CadProdutos.EOF do begin if VpfSeqProduto <> CadProdutos.FieldByName('I_SEQ_PRO').AsInteger Then begin VpfSeqProduto := CadProdutos.FieldByName('I_SEQ_PRO').AsInteger; VpfDClassificacao := TClassificacao.Create; VpfDClassificacao.CodProduto := CadProdutos.FieldByName('C_COD_PRO').AsString; VpfDClassificacao.tipo := 'PA'; VpfDClassificacao.DesPathFoto := CadProdutos.FieldByName('C_PAT_FOT').AsString; VpfDClassificacao.SeqProduto := CadProdutos.FieldByName('I_SEQ_PRO').AsInteger; if config.VerCodigoProdutos then // configura se mostra ou naum o codigo do produto.. Vpfno := Arvore.Items.AddChildObject(VpaNoSelecao, VpfDClassificacao.CodProduto + ' - ' + CadProdutos.FieldByName('C_NOM_PRO').AsString, VpfDClassificacao) else Vpfno := Arvore.Items.AddChildObject(VpaNoSelecao, CadProdutos.FieldByName('C_NOM_PRO').AsString,VpfDClassificacao); Vpfno.ImageIndex := 2; Vpfno.SelectedIndex := 2; end; CadProdutos.Next; end; TClassificacao(TTreeNode(VpaNoSelecao).Data).ProdutosCarregados := true; end; CadProdutos.Close; end; {******************************************************************************} procedure TFprodutos.ConfiguraPermissaoUsuario; begin BMenuFiscal.Visible := NomeModulo = 'PDV'; if NomeModulo = 'PDV' then begin AlterarVisibleDet([BEditarFoto,BNovaClassificacao,BProdutos,BAlterar,BExcluir,MNovaClassificacao,MNovoProduto, MAlterar,MExcluir],((NomeModulo = 'PDV') and Config.SistemaEstaOnline )); end; end; {******************************************************************************} procedure TFprodutos.CarregaConsumoProduto(VpaNoSelecao : TTreeNode); var VpfNo : TTreeNode; VpfDClassificacao : TClassificacao; begin if not TClassificacao(TTreeNode(VpaNoSelecao).Data).ProdutosCarregados then begin VpfDClassificacao := TClassificacao(TTreeNode(VpaNoSelecao).Data); CadProdutos.Close; CadProdutos.sql.Clear; CadProdutos.sql.add(' Select ' + ' pro.i_seq_pro, pro.c_cod_cla, pro.c_ati_pro, ' + ' pro.c_cod_pro, pro.c_pat_fot, pro.c_nom_pro, moe.c_cif_moe, ' + ' pro.c_kit_pro ' + ' from CADPRODUTOS PRO, MOVKIT KIT, ' + ' CADMOEDAS MOE ' + ' where PRO.I_COD_EMP = ' + IntToStr(varia.CodigoEmpresa) + ' and KIT.I_PRO_KIT = '+IntToStr(VpfDClassificacao.SeqProduto)+ ' and KIT.I_SEQ_PRO = PRO.I_SEQ_PRO'); if AtiPro.Checked then CadProdutos.sql.add(' and PRO.C_ATI_PRO = ''S'''); CadProdutos.sql.add(' and pro.i_cod_moe = moe.i_cod_moe' ); CadProdutos.sql.add(' Order by C_COD_PRO'); CadProdutos.open; CadProdutos.First; while not CadProdutos.EOF do begin VpfDClassificacao := TClassificacao.Create; VpfDClassificacao.CodProduto := CadProdutos.FieldByName('C_COD_PRO').AsString; VpfDClassificacao.tipo := 'PA'; VpfDClassificacao.DesPathFoto := CadProdutos.FieldByName('C_PAT_FOT').AsString; VpfDClassificacao.SeqProduto := CadProdutos.FieldByName('I_SEQ_PRO').AsInteger; if config.VerCodigoProdutos then // configura se mostra ou naum o codigo do produto.. Vpfno := Arvore.Items.AddChildObject(VpaNoSelecao, VpfDClassificacao.CodProduto + ' - ' + CadProdutos.FieldByName('C_NOM_PRO').AsString, VpfDClassificacao) else Vpfno := Arvore.Items.AddChildObject(VpaNoSelecao, CadProdutos.FieldByName('C_NOM_PRO').AsString,VpfDClassificacao); if FunProdutos.ExisteConsumo(VpfDClassificacao.SeqProduto) then begin Vpfno.ImageIndex := 3; Vpfno.SelectedIndex := 3; end else begin Vpfno.ImageIndex := 2; Vpfno.SelectedIndex := 2; end; CadProdutos.Next; end; TClassificacao(TTreeNode(VpaNoSelecao).Data).ProdutosCarregados := true; end; CadProdutos.Close; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Efetua as atividade basica nas tebelas de Produtos e Classificacao Inserção, Alteração e Exclusão )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {****************************************************************************** Inserção de Classificação e Produtos ListaDblClick : um duplo clique na lista da direita causa uma inserçao se estiver posicionado na primeira ou segunda posição da lista ****************************************************************************** } procedure TFprodutos.BNovaClassificacaoClick(Sender: TObject); var VpfDClassificacao :TClassificacao; VpfResultado : String; begin VpfResultado := ''; if (VprQtdNiveis <= arvore.Selected.Level) then VpfResultado := CT_FimInclusaoClassificacao; if VpfResultado = '' then begin VpfDClassificacao := TClassificacao.Create; VpfDClassificacao.CodClassificacao := TClassificacao(TTreeNode(arvore.Selected).Data).CodClassificacao; // envia o codigo pai para insercao; FNovaClassificacao := TFNovaClassificacao.CriarSDI(application,'', Fprincipal.VerificaPermisao('FNovaClassificacao')); if (FNovaClassificacao.Inseri(VpfDClassificacao,VprVetorMascara[arvore.Selected.Level+1], 'P')) then begin VpfDClassificacao.tipo := 'CL'; VpfDClassificacao.ProdutosCarregados := true; Arvore.Items.AddChildObject( TTreeNode(arvore.Selected),VpfDClassificacao.CodClassificacoReduzido + ' - ' + VpfDClassificacao.NomClassificacao,VpfDClassificacao); arvore.OnChange(sender,arvore.selected); Arvore.Update; end; end; if VpfResultado <> '' then aviso(VpfResultado); end; {***************Chama a rotina para cadastrar um novo produto******************} procedure TFprodutos.BProdutosClick(Sender: TObject); var VpfDClassificacao :TClassificacao; VpfDProduto : TRBDProduto; VpfNo : TTreeNode; VpfResultado : string; begin VpfResultado := ''; if (arvore.Selected.Level = 0) then VpfREsultado := CT_ClassificacacaoProdutoInvalida; if VpfResultado = '' then begin if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'PA' then VpfResultado := CT_ErroInclusaoProduto; if VpfResultado = '' then begin VpfDClassificacao := TClassificacao.Create; FNovoProdutoPro := TFNovoProdutoPro.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovoProdutoPro')); VpfDProduto := FNovoProdutoPro.NovoProduto(TClassificacao(TTreeNode(arvore.Selected).Data).CodClassificacao); if VpfDProduto <> nil then begin VpfDClassificacao.SeqProduto := VpfDProduto.SeqProduto; VpfDClassificacao.tipo := 'PA'; VpfDClassificacao.ProdutosCarregados := true; VpfDClassificacao.DesPathFoto := VpfDProduto.PatFoto; VpfDClassificacao.CodProduto := VpfDProduto.CodProduto; if config.VerCodigoProdutos then // configura se mostra ou naum o codigo do produto.. VpfNo:= Arvore.Items.AddChildObject( TTreeNode(arvore.Selected),VpfDClassificacao.CodProduto + ' - ' + VpfDProduto.NomProduto, VpfDClassificacao) else VpfNo:= Arvore.Items.AddChildObject( TTreeNode(arvore.Selected),VpfDProduto.NomProduto, VpfDClassificacao); VpfNo.ImageIndex := 2; VpfNo.SelectedIndex := 2; VpfDProduto.free; arvore.OnChange(sender,arvore.selected); Arvore.Update; end; end; end; if VpfResultado <> '' then aviso(VpfResultado); end; {****************alteração de Classificação e produtos*************************} procedure TFprodutos.Alterar(Sender: TObject; Alterar : Boolean); var VpfDClassificacao : TClassificacao; VpfDProduto : TRBDProduto; begin if (arvore.Selected.Level=0) then //não dá para alterar o primeiro item abort; VpfDClassificacao := TClassificacao(arvore.Selected.Data); if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'CL' then begin FNovaClassificacao := TFNovaClassificacao.CriarSDI(application,'',FPrincipal.VerificaPermisao('FNovaClassificacao')); if FNovaClassificacao.Alterar(VpfDClassificacao,'P', Alterar) then begin arvore.Selected.Text := VpfDClassificacao.CodClassificacoReduzido + ' - ' + VpfDClassificacao.NomClassificacao ; arvore.OnChange(sender,arvore.selected); arvore.Update; end; end else if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'PA' then begin FNovoProdutoPro := TFNovoProdutoPro.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovoProdutoPro')); VpfDProduto := FNovoProdutoPro.AlterarProduto(varia.codigoEmpresa,varia.CodigoEmpFil,VpfDClassificacao.SeqProduto); if VpfDProduto <> nil then begin VpfDClassificacao.CodProduto := VpfDProduto.CodProduto; VpfDClassificacao.DesPathFoto := VpfDProduto.PatFoto; if config.VerCodigoProdutos then // configura se mostra ou naum o codigo do produto.. arvore.Selected.Text := VpfDClassificacao.CodProduto+ ' - '+VpfDProduto.NomProduto else arvore.Selected.Text := VpfDProduto.NomProduto; arvore.OnChange(sender,arvore.selected); VpfDProduto.free; end; end; end; {*****************Exclusão de Classificação e produtos*************************} procedure TFprodutos.Excluir(Sender : TObject); var VpfNo : TTreeNode; VpfContaReg : Integer; begin if (arvore.Selected.Level=0) then abort; Vpfno := arvore.Selected; Vprlistar := false; if confirmacao(CT_DeletarItem) then begin try // caso seja uma classificacao if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'CL' then begin if (Arvore.Selected.HasChildren) then begin erro(CT_ErroExclusaoClassificaca); arvore.Selected := VpfNo; VprListar := true; abort; end; CadClassificacao.Close; CadClassificacao.SQL.Clear; CadClassificacao.SQL.Add('DELETE FROM CADCLASSIFICACAO WHERE I_COD_EMP = ' + IntToStr(varia.CodigoEmpresa) + ' and C_COD_CLA='''+ TClassificacao(TTreeNode(arvore.Selected).Data).CodClassificacao+''''+ ' and C_Tip_Cla = ''P'''); CadClassificacao.ExecSql; CadClassificacao.Close; TClassificacao(TTreeNode(arvore.selected).Data).Free; arvore.items.Delete(arvore.Selected); end else if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'PA' then begin UnProduto.LocalizaEstoqueProduto(Aux,TClassificacao(TTreeNode(arvore.Selected).Data).SeqProduto); VpfContaReg := 0; while not Aux.Eof do begin Inc(VpfContaReg); Aux.Next; if VpfContaReg > 3 then Break; end; if VpfContaReg <= 1 then begin FunProdutos.ExcluiProduto(TClassificacao(TTreeNode(arvore.Selected).Data).SeqProduto); TClassificacao(TTreeNode(arvore.selected).Data).Free; arvore.items.Delete(arvore.Selected); end else erro(CT_ErroDeletaRegistroPai); end; except erro(CT_ErroDeletaRegistroPai); end; end; Vprlistar := true; arvore.OnChange(sender,arvore.selected); end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Chamadas diversas dos Tree )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {*****cada deslocamento no TreeView causa uma mudança na lista da direita******} procedure TFprodutos.ArvoreChange(Sender: TObject; Node: TTreeNode); begin if VprListar then begin if TClassificacao(TTreeNode(node).Data).tipo = 'CL' then begin carregaProduto(node); Foto.Picture := nil; end else if (TClassificacao(TTreeNode(node).Data).tipo = 'PA') Then //and (paginas.ActivePage = caracteristica) then begin try if (VerFoto.Checked) and (TClassificacao(TTreeNode(node).Data).DesPathFoto <> '') then Foto.Picture.LoadFromFile(varia.DriveFoto + TClassificacao(TTreeNode(node).Data).DesPathFoto) else Foto.Picture := nil; except end; CarregaConsumoProduto(Node); end; arvore.Update; end; end; { *******************Cada vez que expandir um no*******************************} procedure TFprodutos.ArvoreExpanded(Sender: TObject; Node: TTreeNode); begin carregaProduto(node); if TClassificacao(TTreeNode(node).Data).tipo = 'CL' then begin node.SelectedIndex:=1; node.ImageIndex:=1; end; end; {********************Cada vez que voltar a expanção de um no*******************} procedure TFprodutos.ArvoreCollapsed(Sender: TObject; Node: TTreeNode); begin if TClassificacao(TTreeNode(node).Data).tipo = 'CL' then begin node.SelectedIndex:=0; node.ImageIndex:=0; end; end; {*************Chamada de alteração de produtos ou classificações***************} procedure TFprodutos.BAlterarClick(Sender: TObject); begin alterar(sender,true); // chamnada de alteração end; {************Chamada de Exclusão de produtos ou classificações*****************} procedure TFprodutos.BExcluirClick(Sender: TObject); begin Excluir(sender); end; { **************** se presionar a setas naum atualiza movimentos ************ } procedure TFprodutos.ArvoreKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key in[37..40] then VprListar := false; end; { ************ apos soltar setas atualiza movimentos ************************ } procedure TFprodutos.ArvoreKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin Vprlistar := true; ArvoreChange(sender,arvore.Selected); end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Chamadas diversas para visualizar dados dos produtos )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} procedure TFprodutos.BitBtn1Click(Sender: TObject); var Vpfcodigo, VpfSelect : string; somaNivel,nivelSelecao, laco : integer; begin VpfSelect :=' Select PRO.C_COD_PRO, PRO.C_COD_CLA, PRO.I_SEQ_PRO, PRO.C_NOM_PRO '+ ' from CADPRODUTOS PRO, MOVQDADEPRODUTO MOV ' + ' where C_NOM_PRO like ''@%'''; if AtiPro.Checked then Vpfselect := Vpfselect + ' and C_ATI_PRO = ''S'''; Vpfselect := Vpfselect + ' and PRO.I_SEQ_PRO = MOV.I_SEQ_PRO ' + ' and MOV.I_EMP_FIL = ' + IntTostr(varia.CodigoEmpFil) ; Vpfselect := Vpfselect + ' order by C_NOM_PRO asc'; Localiza.info.DataBase := Fprincipal.BaseDados; Localiza.info.ComandoSQL := Vpfselect; Localiza.info.caracterProcura := '@'; Localiza.info.ValorInicializacao := ''; Localiza.info.CamposMostrados[0] := 'C_COD_PRO'; Localiza.info.CamposMostrados[1] := 'C_NOM_PRO'; Localiza.info.CamposMostrados[2] := ''; Localiza.info.DescricaoCampos[0] := 'Código'; Localiza.info.DescricaoCampos[1] := 'Nome'; Localiza.info.DescricaoCampos[2] := ''; Localiza.info.TamanhoCampos[0] := 8; Localiza.info.TamanhoCampos[1] := 40; Localiza.info.TamanhoCampos[2] := 0; Localiza.info.CamposRetorno[0] := 'I_SEQ_PRO'; Localiza.info.CamposRetorno[1] := 'C_COD_CLA'; Localiza.info.SomenteNumeros := false; Localiza.info.CorFoco := FPrincipal.CorFoco; Localiza.info.CorForm := FPrincipal.CorForm; Localiza.info.CorPainelGra := FPrincipal.CorPainelGra; Localiza.info.TituloForm := 'Localizar Produtos'; if Localiza.execute then if localiza.retorno[0] <> '' Then begin SomaNivel := 1; NivelSelecao := 1; Vprlistar := false; arvore.Selected := VprPrimeiroNo; arvore.Selected.Collapse(true); while SomaNivel <= Length(localiza.retorno[1]) do begin Vpfcodigo := copy(localiza.retorno[1], SomaNivel, VprVetorMascara[nivelSelecao]); SomaNivel := SomaNivel + VprVetorMascara[nivelSelecao]; arvore.Selected := arvore.Selected.GetNext; while TClassificacao(arvore.Selected.Data).CodClassificacoReduzido <> VpfCodigo do arvore.Selected := arvore.Selected.GetNextChild(arvore.selected); inc(NivelSelecao); end; carregaProduto(arvore.selected); for laco := 0 to arvore.Selected.Count - 1 do if IntToStr(TClassificacao(arvore.Selected.Item[laco].Data).SeqProduto) = localiza.retorno[0] then begin arvore.Selected := arvore.Selected.Item[laco]; break; end; end; Vprlistar := true; ArvoreChange(sender,arvore.Selected); self.ActiveControl := arvore; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {****************************Fecha o Formulario corrente***********************} procedure TFprodutos.BFecharClick(Sender: TObject); begin close; end; {******************************************************************************} procedure TFprodutos.FotoDblClick(Sender: TObject); begin VisualizadorImagem1.execute(varia.DriveFoto + TClassificacao(arvore.Selected.Data).DesPathFoto); end; procedure TFprodutos.EsticarClick(Sender: TObject); begin Foto.Stretch := esticar.Checked; end; procedure TFprodutos.BitBtn4Click(Sender: TObject); begin Alterar(sender,false); end; procedure TFprodutos.ArvoreDblClick(Sender: TObject); begin if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'PA'then BAlterar.Click; end; procedure TFprodutos.VerFotoClick(Sender: TObject); begin if VerFoto.Checked then ArvoreChange(arvore,arvore.Selected) else Foto.Picture.Bitmap := nil; end; { ***************** altera a mostra entre produtos em atividades ou naum ******} procedure TFprodutos.AtiProClick(Sender: TObject); begin RecarregaLista; end; procedure TFprodutos.RecarregaLista; begin Vprlistar := false; arvore.Items.Clear; Vprlistar := true; CarregaClassificacao(VprVetorMascara); end; {******************************************************************************} procedure TFprodutos.BBAjudaClick(Sender: TObject); begin end; {******************************************************************************} procedure TFprodutos.MFichaTecnicaClick(Sender: TObject); begin if Arvore.Selected.Data <> nil then begin if (TObject(Arvore.Selected.Data) is TClassificacao) then begin if TClassificacao(Arvore.Selected.Data).Tipo = 'PA' then begin { FImpProduto := TFImpProduto.Create(application); FImpProduto.ImprimeProduto(IntTostr(TClassificacao(Arvore.Selected.Data).SeqProduto)); FImpProduto.free;} end; end; end; end; {******************************************************************************} procedure TFprodutos.ArvoreDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin accept := (Source is TTreeview); end; {******************************************************************************} procedure TFprodutos.ArvoreDragDrop(Sender, Source: TObject; X, Y: Integer); Var VpfNoDestino : TTreeNode; VpfResultado : String; begin VpfNoDestino := Arvore.GetNodeAt(x,y); if VpfNoDestino <> nil then begin if TComponent(Source).Name = 'Arvore' then begin if (TClassificacao(VpfNoDestino.Data).Tipo = 'CL') and (TClassificacao(Arvore.Selected.Data).Tipo = 'PA') then begin VpfResultado := FunProdutos.AlteraClassificacaoProduto(TClassificacao(Arvore.Selected.Data).SeqProduto,TClassificacao(VpfNoDestino.Data).CodClassificacao); if VpfResultado <> '' then StatusBar1.Panels[0].Text := VpfResultado else begin Arvore.Selected.MoveTo(VpfNoDestino,naAddChild); StatusBar1.Panels[0].Text := 'Alterado a classificação do produto com sucesso.'; end; end else StatusBar1.Panels[0].Text := 'Não foi possível alterar a classificação do produto porque o destino não é uma classificação.'; end; end; end; {******************************************************************************} procedure TFprodutos.BLocalizaClassificacaoClick(Sender: TObject); var codigo, select : string; somaNivel,nivelSelecao : integer; begin select :=' Select * from CADCLASSIFICACAO pro ' + ' where c_nom_CLA like ''@%'''+ ' and I_COD_EMP = '+IntToStr(VARIA.CodigoEmpresa)+ ' order by C_NOM_CLA'; Localiza.info.DataBase := Fprincipal.BaseDados; Localiza.info.ComandoSQL := select; Localiza.info.caracterProcura := '@'; Localiza.info.ValorInicializacao := ''; Localiza.info.CamposMostrados[0] := 'C_cod_CLA'; Localiza.info.CamposMostrados[1] := 'c_nom_CLA'; Localiza.info.CamposMostrados[2] := ''; Localiza.info.DescricaoCampos[0] := 'codigo'; Localiza.info.DescricaoCampos[1] := 'nome'; Localiza.info.DescricaoCampos[2] := ''; Localiza.info.TamanhoCampos[0] := 8; Localiza.info.TamanhoCampos[1] := 40; Localiza.info.TamanhoCampos[2] := 0; Localiza.info.CamposRetorno[0] := 'C_cod_cla'; Localiza.info.SomenteNumeros := false; Localiza.info.CorFoco := FPrincipal.CorFoco; Localiza.info.CorForm := FPrincipal.CorForm; Localiza.info.CorPainelGra := FPrincipal.CorPainelGra; Localiza.info.TituloForm := ' Localizar Classificação '; if Localiza.execute then if localiza.retorno[0] <> '' Then begin SomaNivel := 1; NivelSelecao := 1; Vprlistar := false; arvore.Selected := VprPrimeiroNo; arvore.Selected.Collapse(true); while SomaNivel <= Length(localiza.retorno[0]) do begin codigo := copy(localiza.retorno[0], SomaNivel, VprVetorMascara[nivelSelecao]); SomaNivel := SomaNivel + VprVetorMascara[nivelSelecao]; arvore.Selected := arvore.Selected.GetNext; while TClassificacao(arvore.Selected.Data).CodClassificacoReduzido <> Codigo do arvore.Selected := arvore.Selected.GetNextChild(arvore.selected); inc(NivelSelecao); end; end; Vprlistar := true; ArvoreChange(sender,arvore.Selected); self.ActiveControl := arvore; end; {******************************************************************************} procedure TFprodutos.BMenuFiscalClick(Sender: TObject); begin FMenuFiscalECF := TFMenuFiscalECF.CriarSDI(self,'',true); FMenuFiscalECF.ShowModal; FMenuFiscalECF.Free; end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.FilterCatColor; interface {$I FMX.Defines.inc} uses FMX.Filter; type TInvertFilter = class(TShaderFilter) protected class function FilterAttr: TFilterRec; override; public constructor Create; override; end; TMonochromeFilter = class(TShaderFilter) protected class function FilterAttr: TFilterRec; override; public constructor Create; override; end; TColorKeyAlphaFilter = class(TShaderFilter) protected class function FilterAttr: TFilterRec; override; public constructor Create; override; end; TMaskToAlphaFilter = class(TShaderFilter) protected class function FilterAttr: TFilterRec; override; public constructor Create; override; end; implementation { TInvertFilter } constructor TInvertFilter.Create; const DX: array [0..215] of byte = ( $00, $02, $FF, $FF, $FE, $FF, $22, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $5F, $00, $00, $00, $00, $02, $FF, $FF, $01, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $58, $00, $00, $00, $30, $00, $00, $00, $03, $00, $00, $00, $01, $00, $02, $00, $48, $00, $00, $00, $00, $00, $00, $00, $69, $6D, $70, $6C, $69, $63, $69, $74, $49, $6E, $70, $75, $74, $53, $61, $6D, $70, $6C, $65, $72, $00, $AB, $AB, $AB, $04, $00, $0C, $00, $01, $00, $01, $00, $01, $00, $00, $00, $00, $00, $00, $00, $70, $73, $5F, $32, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53, $68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $03, $B0, $1F, $00, $00, $02, $00, $00, $00, $90, $00, $08, $0F, $A0, $42, $00, $00, $03, $00, $00, $0F, $80, $00, $00, $E4, $B0, $00, $08, $E4, $A0, $02, $00, $00, $03, $00, $00, $07, $80, $00, $00, $E4, $81, $00, $00, $FF, $80, $01, $00, $00, $02, $00, $08, $0F, $80, $00, $00, $E4, $80, $FF, $FF, $00, $00 ); GL: PAnsiChar = '!!ARBfp1.0'#13+ 'TEMP R0;'#13+ 'TEX R0, fragment.texcoord[0], texture[0], 2D;'#13+ 'ADD result.color.xyz, R0.w, -R0;'#13+ 'MOV result.color.w, R0;'#13+ 'END'; GLES: PAnsiChar = 'uniform sampler2D texture0;'+ 'varying vec4 TEX0;'+ 'void main() {'+ 'gl_FragColor = texture2D(texture0, TEX0.xy);'+ 'gl_FragColor = vec4(gl_FragColor.a - gl_FragColor.rgb, gl_FragColor.a);'+ '}'; begin inherited; FShaders[FPassCount] := ShaderDevice.CreatePixelShader(@DX, GL, GLES); end; class function TInvertFilter.FilterAttr: TFilterRec; begin Result := FilterRec('Invert', 'An effect that inverts all colors.', [ ]); end; { TMonochromeFilter } constructor TMonochromeFilter.Create; const DX9PS2BIN: array [0..223] of byte = ( $00, $02, $FF, $FF, $FE, $FF, $1E, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $4F, $00, $00, $00, $00, $02, $FF, $FF, $01, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $48, $00, $00, $00, $30, $00, $00, $00, $03, $00, $00, $00, $01, $00, $02, $00, $38, $00, $00, $00, $00, $00, $00, $00, $69, $6E, $70, $75, $74, $00, $AB, $AB, $04, $00, $0C, $00, $01, $00, $01, $00, $01, $00, $00, $00, $00, $00, $00, $00, $70, $73, $5F, $32, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53, $68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $51, $00, $00, $05, $00, $00, $0F, $A0, $D0, $B3, $59, $3E, $59, $17, $37, $3F, $98, $DD, $93, $3D, $00, $00, $00, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $03, $B0, $1F, $00, $00, $02, $00, $00, $00, $90, $00, $08, $0F, $A0, $42, $00, $00, $03, $00, $00, $0F, $80, $00, $00, $E4, $B0, $00, $08, $E4, $A0, $08, $00, $00, $03, $00, $00, $07, $80, $00, $00, $E4, $80, $00, $00, $E4, $A0, $01, $00, $00, $02, $00, $08, $0F, $80, $00, $00, $E4, $80, $FF, $FF, $00, $00 ); ARBFP1: PAnsiChar = '!!ARBfp1.0'#13+ 'PARAM c[1] = { { 0.21259999, 0.71520001, 0.0722 } };'#13+ 'TEMP R0;'#13+ 'TEX R0, fragment.texcoord[0], texture[0], 2D;'#13+ 'DP3 result.color.xyz, R0, c[0];'#13+ 'MOV result.color.w, R0;'#13+ 'END'; GLSLF: PAnsiChar = 'vec4 _ret_0;'#13+ 'varying vec4 TEX0;'#13+ 'uniform sampler2D texture0;'#13+ 'void main()'#13+ '{'#13+ ' vec4 _color;'#13+ ' float _gray;'#13+ ' _color = texture2D(texture0, TEX0.xy);'#13+ ' _gray = dot(_color.xyz, vec3( 2.12599993E-001, 7.15200007E-001, 7.22000003E-002));'#13+ ' _ret_0 = vec4(_gray, _gray, _gray, _color.w);'#13+ ' gl_FragColor = _ret_0;'#13+ ' return;'#13+ '} '; begin inherited; FShaders[FPassCount] := ShaderDevice.CreatePixelShader(@DX9PS2BIN, ARBFP1, GLSLF); end; class function TMonochromeFilter.FilterAttr: TFilterRec; begin Result := FilterRec('Monochrome', 'Remaps colors so they fall within shades of a single color.', [ ]); end; { TColorKeyAlphaFilter } constructor TColorKeyAlphaFilter.Create; const DX9PS2BIN: array [0..435] of byte = ( $00, $02, $FF, $FF, $FE, $FF, $3A, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $BF, $00, $00, $00, $00, $02, $FF, $FF, $03, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $B8, $00, $00, $00, $58, $00, $00, $00, $02, $00, $00, $00, $01, $00, $02, $00, $64, $00, $00, $00, $00, $00, $00, $00, $74, $00, $00, $00, $02, $00, $01, $00, $01, $00, $06, $00, $80, $00, $00, $00, $00, $00, $00, $00, $90, $00, $00, $00, $03, $00, $00, $00, $01, $00, $02, $00, $A8, $00, $00, $00, $00, $00, $00, $00, $43, $6F, $6C, $6F, $72, $4B, $65, $79, $00, $AB, $AB, $AB, $01, $00, $03, $00, $01, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $54, $6F, $6C, $65, $72, $61, $6E, $63, $65, $00, $AB, $AB, $00, $00, $03, $00, $01, $00, $01, $00, $01, $00, $00, $00, $00, $00, $00, $00, $69, $6D, $70, $6C, $69, $63, $69, $74, $49, $6E, $70, $75, $74, $53, $61, $6D, $70, $6C, $65, $72, $00, $AB, $AB, $AB, $04, $00, $0C, $00, $01, $00, $01, $00, $01, $00, $00, $00, $00, $00, $00, $00, $70, $73, $5F, $32, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53, $68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $51, $00, $00, $05, $02, $00, $0F, $A0, $00, $00, $00, $00, $00, $00, $80, $3F, $00, $00, $00, $00, $00, $00, $00, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $03, $B0, $1F, $00, $00, $02, $00, $00, $00, $90, $00, $08, $0F, $A0, $42, $00, $00, $03, $00, $00, $0F, $80, $00, $00, $E4, $B0, $00, $08, $E4, $A0, $02, $00, $00, $03, $01, $00, $07, $80, $00, $00, $E4, $80, $00, $00, $E4, $A1, $23, $00, $00, $02, $01, $00, $07, $80, $01, $00, $E4, $80, $02, $00, $00, $03, $01, $00, $07, $80, $01, $00, $E4, $80, $01, $00, $00, $A1, $58, $00, $00, $04, $01, $00, $07, $80, $01, $00, $E4, $80, $02, $00, $00, $A0, $02, $00, $55, $A0, $05, $00, $00, $03, $01, $00, $01, $80, $01, $00, $55, $80, $01, $00, $00, $80, $05, $00, $00, $03, $01, $00, $01, $80, $01, $00, $AA, $80, $01, $00, $00, $80, $58, $00, $00, $04, $00, $00, $0F, $80, $01, $00, $00, $81, $00, $00, $E4, $80, $02, $00, $00, $A0, $01, $00, $00, $02, $00, $08, $0F, $80, $00, $00, $E4, $80, $FF, $FF, $00, $00 ); ARBFP1: PAnsiChar = '!!ARBfp1.0'#13+ 'PARAM c[3] = { program.local[0..1],'#13+ ' { 0 } };'#13+ 'TEMP R0;'#13+ 'TEMP R1;'#13+ 'TEX R0, fragment.texcoord[0], texture[0], 2D;'#13+ 'ADD R1.xyz, R0, -c[0];'#13+ 'ABS R1.xyz, R1;'#13+ 'SLT R1.xyz, R1, c[1].x;'#13+ 'MUL R1.x, R1, R1.y;'#13+ 'MUL R1.x, R1, R1.z;'#13+ 'CMP result.color, -R1.x, c[2].x, R0;'#13+ 'END'; GLSLF: PAnsiChar = 'vec3 _TMP0;'#13+ 'vec3 _a0007;'#13+ 'bvec3 _a0009;'#13+ 'varying vec4 TEX0;'#13+ 'uniform vec4 PSParam0;'#13+ 'uniform vec4 PSParam1;'#13+ 'uniform sampler2D texture0;'#13+ 'void main()'#13+ '{'#13+ ' vec4 _color;'#13+ ' _color = texture2D(texture0, TEX0.xy);'#13+ ' _a0007 = _color.xyz - PSParam0.xyz;'#13+ ' _TMP0 = abs(_a0007);'#13+ ' _a0009 = bvec3(_TMP0.x < PSParam1.x, _TMP0.y < PSParam1.x, _TMP0.z < PSParam1.x);'#13+ ' if (_a0009.x && _a0009.y && _a0009.z) { '#13+ ' _color.xyzw = vec4( 0.0, 0.0, 0.0, 0.0);'#13+ ' } // end if'#13+ ' gl_FragColor = _color;'#13+ ' return;'#13+ '} '; begin inherited; FShaders[FPassCount] := ShaderDevice.CreatePixelShader(@DX9PS2BIN, ARBFP1, GLSLF); end; class function TColorKeyAlphaFilter.FilterAttr: TFilterRec; begin Result := FilterRec('ColorKeyAlpha', 'An effect that makes pixels of a particular color transparent.', [ FilterValueRec('ColorKey', 'The color that becomes transparent.', TShaderValueType.vtFloat, 0, -1, 1), FilterValueRec('Tolerance', 'The tolerance in color differences.', TShaderValueType.vtFloat, 0.3, 0, 1) ]); end; { TMaskToAlphaFilter } constructor TMaskToAlphaFilter.Create; const DX9PS2BIN: array [0..223] of byte = ( $00, $02, $FF, $FF, $FE, $FF, $1E, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $4F, $00, $00, $00, $00, $02, $FF, $FF, $01, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $48, $00, $00, $00, $30, $00, $00, $00, $03, $00, $00, $00, $01, $00, $02, $00, $38, $00, $00, $00, $00, $00, $00, $00, $69, $6E, $70, $75, $74, $00, $AB, $AB, $04, $00, $0C, $00, $01, $00, $01, $00, $01, $00, $00, $00, $00, $00, $00, $00, $70, $73, $5F, $32, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53, $68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $03, $B0, $1F, $00, $00, $02, $00, $00, $00, $90, $00, $08, $0F, $A0, $42, $00, $00, $03, $00, $00, $0F, $80, $00, $00, $E4, $B0, $00, $08, $E4, $A0, $06, $00, $00, $02, $00, $00, $08, $80, $00, $00, $FF, $80, $05, $00, $00, $03, $01, $00, $07, $80, $00, $00, $E4, $80, $00, $00, $FF, $80, $01, $00, $00, $02, $01, $00, $08, $80, $00, $00, $00, $80, $01, $00, $00, $02, $00, $08, $0F, $80, $01, $00, $E4, $80, $FF, $FF, $00, $00 ); ARBFP1: PAnsiChar = '!!ARBfp1.0'#13+ 'TEMP R0;'#13+ 'TEX R0, fragment.texcoord[0], texture[0], 2D;'#13+ 'RCP R0.w, R0.w;'#13+ 'MUL result.color.xyz, R0, R0.w;'#13+ 'MOV result.color.w, R0.x;'#13+ 'END'; GLSLF: PAnsiChar = 'vec4 _ret_0;'#13+ 'varying vec4 TEX0;'#13+ 'uniform sampler2D texture0;'#13+ 'void main()'#13+ '{'#13+ ' vec4 _originalColor;'#13+ ' vec3 _rgb;'#13+ ' _originalColor = texture2D(texture0, TEX0.xy);'#13+ ' _rgb = _originalColor.xyz/_originalColor.w;'#13+ ' _ret_0 = vec4(_rgb.x, _rgb.y, _rgb.z, _originalColor.x);'#13+ ' gl_FragColor = _ret_0;'#13+ ' return;'#13+ '} '; begin inherited; FShaders[FPassCount] := ShaderDevice.CreatePixelShader(@DX9PS2BIN, ARBFP1, GLSLF); end; class function TMaskToAlphaFilter.FilterAttr: TFilterRec; begin Result := FilterRec('MaskToAlpha', 'Converts a grayscale image to a white image that is masked by alpha.', [ ]); end; initialization RegisterFilter('Color', TInvertFilter); RegisterFilter('Color', TMonochromeFilter); RegisterFilter('Color', TColorKeyAlphaFilter); RegisterFilter('Color', TMaskToAlphaFilter); end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Data.DBXClassRegistry; interface uses System.Classes, System.SysUtils ; type TAssemblyType = TObject; // TObject constructor is not virtual, so allow for virtual constructor // for registered Objects. // TClassRegistryObject = class public constructor Create; virtual; end; TRegistryClass = class of TClassRegistryObject; EClassRegistryError = class(Exception); TInstanceCreator = packed record private FClassName: UnicodeString; FObjectClass: TClass; FRegistryClass: TRegistryClass; function CreateInstance: TObject; end; TClassRegistryPackageItem = class private FUseCount: Integer; FPackageName: UnicodeString; FPackageHandle: HMODULE; constructor Create(PackageName: UnicodeString); public destructor Destroy; override; end; TClassRegistryItem = class private FClassName: UnicodeString; FObjectClass: TClass; FRegistryClass: TRegistryClass; FPackageItem: TClassRegistryPackageItem; procedure InitializeInstanceCreator(var InstanceCreator: TInstanceCreator); end; TClassRegistry = class private FLock: TThreadList; FClasses: TStringList; FPackages: TStringList; FCanDestroy: Boolean; class var ClassRegistry: TClassRegistry; function FindClass(ClassName: UnicodeString): TClassRegistryItem; function FindPackage(PackageName: UnicodeString): TClassRegistryPackageItem; public constructor Create; destructor Destroy; override; class function GetClassRegistry: TClassRegistry; procedure RegisterPackageClass(ClassName: UnicodeString; PackageName: UnicodeString); procedure RegisterClass(ClassName: UnicodeString; ObjectClass: TClass); overload; procedure RegisterClass(ClassName: UnicodeString; ObjectClass: TClass; AssemblyType: TAssemblyType); overload; procedure RegisterRegistryClass(ClassName: UnicodeString; RegistryClass: TRegistryClass); procedure UnregisterClass(ClassName: UnicodeString); function HasClass(ClassName: UnicodeString): Boolean; function CreateInstance(ClassName: UnicodeString): TObject; end; implementation uses Data.DBXCommonResStrs; { TClassRegistry } constructor TClassRegistry.Create; begin inherited Create; FLock := TThreadList.Create; FClasses := TStringList.Create; FClasses.Sorted := true; FPackages := TStringList.Create; FPackages.Sorted := true; FCanDestroy := true; end; destructor TClassRegistry.Destroy; var Index: Integer; begin if not FCanDestroy then raise EClassRegistryError.Create(SCannotFreeClassRegistry); FreeAndNil(FLock); if FClasses <> nil then for Index := 0 to FClasses.Count - 1 do FClasses.Objects[Index].Free; FreeAndNil(FClasses); if FPackages <> nil then for Index := 0 to FPackages.Count - 1 do FPackages.Objects[Index].Free; FreeAndNil(FPackages); end; function TClassRegistry.CreateInstance(ClassName: UnicodeString): TObject; var Item: TClassRegistryItem; InstanceCreator: TInstanceCreator; begin FLock.LockList; try Item := FindClass(ClassName); if Item = nil then raise EClassRegistryError.Create(Format(SNotRegistered, [ClassName])) else Item.InitializeInstanceCreator(InstanceCreator); finally FLock.UnlockList; end; // To improve performance, create the instance out of the critical section. // Result := InstanceCreator.CreateInstance; end; function TClassRegistry.FindClass(ClassName: UnicodeString): TClassRegistryItem; var Index: Integer; begin if FClasses.Find(ClassName, Index) then Result := TClassRegistryItem(FClasses.Objects[Index]) else Result := nil; end; function TClassRegistry.FindPackage( PackageName: UnicodeString): TClassRegistryPackageItem; var Index: Integer; begin if FPackages.Find(PackageName, Index) then Result := TClassRegistryPackageItem(FPackages.Objects[Index]) else Result := nil; end; class function TClassRegistry.GetClassRegistry: TClassRegistry; begin if TClassRegistry.ClassRegistry = nil then begin TClassRegistry.ClassRegistry := TClassRegistry.Create; TClassRegistry.ClassRegistry.FCanDestroy := false; end; Result := ClassRegistry; end; function TClassRegistry.HasClass(ClassName: UnicodeString): Boolean; var Index: Integer; begin Result := FClasses.Find(ClassName, Index); end; procedure TClassRegistry.RegisterClass(ClassName: UnicodeString; ObjectClass: TClass); begin if ObjectClass = nil then raise EClassRegistryError.Create(Format(SInvalidClassRegister, [ClassName])); RegisterClass(ClassName, ObjectClass, nil); end; procedure TClassRegistry.RegisterClass(ClassName: UnicodeString; ObjectClass: TClass; AssemblyType: TAssemblyType); var ClassItem: TClassRegistryItem; begin FLock.LockList; ClassItem := FindClass(ClassName); try if ClassItem <> nil then begin // Subtle. Get here on .net if RegisterPackageClass was called first // and then the initialization section is consequently invoked // and calls RegisterClass. The initial RegisterPackageClass did // not have the class reference, so it is nil. Corner case resulting // from a general system for static and dynamic linkage across native // and managed code. // if ClassItem.FObjectClass <> nil then raise EClassRegistryError.Create(Format(SAlreadyRegistered, [ClassName])); ClassItem.FObjectClass := ObjectClass; end else begin ClassItem := TClassRegistryItem.Create; try ClassItem.FClassName := ClassName; ClassItem.FObjectClass := ObjectClass; ClassItem.FRegistryClass := nil; FClasses.AddObject(ClassName, ClassItem); ClassItem := nil; finally ClassItem.Free; end; end; finally FLock.UnlockList; end; end; procedure TClassRegistry.RegisterRegistryClass(ClassName: UnicodeString; RegistryClass: TRegistryClass); var ClassItem: TClassRegistryItem; begin if RegistryClass = nil then raise EClassRegistryError.Create(Format(SInvalidClassRegister, [ClassName])); FLock.LockList; try ClassItem := FindClass(ClassName); if ClassItem <> nil then begin // Subtle. Get here on .net if RegisterPackageClass was called first // and then the initialization section is consequently invoked // and calls RegisterClass. The initial RegisterPackageClass did // not have the class reference, so it is nil. Corner case resulting // from a general system for static and dynamic linkage across native // and managed code. // if ClassItem.FObjectClass <> nil then raise EClassRegistryError.Create(Format(SAlreadyRegistered, [ClassName])); ClassItem.FObjectClass := nil; end else begin ClassItem := TClassRegistryItem.Create; try ClassItem.FClassName := ClassName; ClassItem.FObjectClass := nil; ClassItem.FRegistryClass := RegistryClass; FClasses.AddObject(ClassName, ClassItem); ClassItem := nil; finally ClassItem.Free; end; end; finally FLock.UnlockList; end; end; procedure TClassRegistry.RegisterPackageClass(ClassName, PackageName: UnicodeString); var ClassItem: TClassRegistryItem; PackageItem: TClassRegistryPackageItem; ClassItemCreated: Boolean; PackageItemCreated: Boolean; begin ClassItem := nil; PackageItem := nil; PackageItemCreated := False; ClassItemCreated := False; FLock.LockList; try ClassItem := FindClass(ClassName); if ClassItem <> nil then raise EClassRegistryError.Create(Format(SAlreadyRegistered, [ClassName])); PackageItem := FindPackage(PackageName); if PackageItem = nil then begin PackageItem := TClassRegistryPackageItem.Create(PackageName); PackageItemCreated := true; end else PackageItemCreated := false; ClassItem := FindClass(ClassName); ClassItemCreated := false; // native unit initialization section is invoked when the package was loaded. // if ClassItem = nil then begin ClassItem := TClassRegistryItem.Create; ClassItem.FClassName := ClassName; ClassItemCreated := true; end; ClassItem.FPackageItem := PackageItem; if PackageItemCreated then FPackages.AddObject(PackageName, PackageItem); inc(PackageItem.FUseCount); if ClassItemCreated then FClasses.AddObject(ClassName, ClassItem); ClassItem := nil; PackageItem := nil; finally if PackageItemCreated then PackageItem.Free; if ClassItemCreated then ClassItem.Free; FLock.UnlockList; end; end; procedure TClassRegistry.UnregisterClass(ClassName: UnicodeString); var ClassItem: TClassRegistryItem; Index: Integer; begin FLock.LockList; try if FClasses.Find(ClassName, Index) then begin ClassItem := FClasses.Objects[Index] as TClassRegistryItem; ClassItem.Free; FClasses.Delete(Index); end; finally FLock.UnlockList; end; end; { TInstanceCreator } function TInstanceCreator.CreateInstance: TObject; begin Result := nil; if FObjectClass <> nil then Result := FObjectClass.Create else if FRegistryClass <> nil then Result := FRegistryClass.Create; if Result = nil then raise EClassRegistryError.Create(Format(SInvalidClassRegister, [FClassName])); end; { TClassRegistryPackageItem } constructor TClassRegistryPackageItem.Create(PackageName: UnicodeString); begin inherited Create; FPackageName := PackageName; FPackageHandle := LoadPackage(PackageName); end; destructor TClassRegistryPackageItem.Destroy; begin UnloadPackage(FPackageHandle); inherited; end; { TClassRegistryItem } procedure TClassRegistryItem.InitializeInstanceCreator( var InstanceCreator: TInstanceCreator); begin InstanceCreator.FClassName := FClassName; InstanceCreator.FObjectClass := FObjectClass; InstanceCreator.FRegistryClass := FRegistryClass; end; { TClassRegistryObject } constructor TClassRegistryObject.Create; begin inherited Create; end; initialization finalization if TClassRegistry.ClassRegistry <> nil then begin TClassRegistry.ClassRegistry.FCanDestroy := true; FreeAndNil(TClassRegistry.ClassRegistry); end; end.
unit RTDebug; interface Uses Windows, Messages, SysUtils, Classes, MGRegistry; Const MG_RTD_AddReference =WM_USER+12123; MG_RTD_DelReference =MG_RTD_AddReference+1; MG_RTD_GetListHandle =MG_RTD_AddReference+2; REG_KEY ='\Software\MaxM_BeppeG\RTDebug\'; REG_LOGFILE ='Log File'; REG_LOGONFILE ='Log File Enabled'; type TRTDebugParameters =record processID, threadID :DWord; Level :Byte; theString :ShortString; StrColor :DWord; end; var LogFileName :String =''; LogOnFile :Boolean =False; function RTAssert(Level :Byte; Condition :Boolean; TrueStr, FalseStr :ShortString; StrColor :DWord=0) :Boolean; overload; function RTAssert(TrueStr :ShortString; StrColor :DWord=0) :Boolean; overload; function RTAssert(Condition :Boolean; TrueStr, FalseStr :ShortString; StrColor :DWord=0) :Boolean; overload; function RTAssert(Condition :Boolean; TrueStr :ShortString; StrColor :DWord=0) :Boolean; overload; function RTFileAssert(Filename :ShortString; Condition :Boolean; TrueStr, FalseStr :ShortString) :Boolean; function RTFileEmpty(Filename :ShortString) :Boolean; function GetLogFileName :String; implementation procedure AddLineToList(Level :Byte; theString :ShortString; StrColor :DWord); Var pCopyData :TCopyDataStruct; WinHandle :HWnd; begin WinHandle :=FindWindow('TRTDebugMainWin', Nil); if IsWindow(WinHandle) then begin pCopyData.cbData :=SizeOf(TRTDebugParameters); GetMem(pCopyData.lpData, SizeOf(TRTDebugParameters)); TRTDebugParameters(pCopyData.lpData^).processID :=GetCurrentProcessID; TRTDebugParameters(pCopyData.lpData^).ThreadID :=GetCurrentThreadID; TRTDebugParameters(pCopyData.lpData^).Level :=Level; TRTDebugParameters(pCopyData.lpData^).theString :=theString; TRTDebugParameters(pCopyData.lpData^).StrColor :=StrColor; SendMessage(WinHandle, WM_COPYDATA, 0, Integer(@pCopyData)); FreeMem(pCopyData.lpData); end; end; function RTAssert(Level :Byte; Condition :Boolean; TrueStr, FalseStr :ShortString; StrColor :DWord) :Boolean; begin Result :=Condition; if Result then AddLineToList(Level, TrueStr, StrColor) else AddLineToList(Level, FalseStr, StrColor); if (LogOnFile) and (LogFilename <> '') then RTFileAssert(LogFilename, Condition, TrueStr, FalseStr); end; function RTAssert(TrueStr :ShortString; StrColor :DWord=0) :Boolean; begin Result :=RTAssert(0, true, TrueStr, '', StrColor); end; function RTAssert(Condition :Boolean; TrueStr, FalseStr :ShortString; StrColor :DWord=0) :Boolean; begin Result :=RTAssert(0, Condition, TrueStr, FalseStr, StrColor); end; function RTAssert(Condition :Boolean; TrueStr :ShortString; StrColor :DWord=0) :Boolean; begin if Condition then Result :=RTAssert(0, true, TrueStr, '', StrColor) else Result :=False; end; function RTFileAssert(Filename :ShortString; Condition :Boolean; TrueStr, FalseStr :ShortString) :Boolean; Var ToWrite :PChar; theFile :TFileStream; begin if FileExists(FileName) then theFile :=TFileStream.Create(FileName, fmOpenWrite) else theFile :=TFileStream.Create(FileName, fmCreate); try Result :=False; theFile.Seek(0, soFromEnd); if Condition then ToWrite :=PChar(IntToHex(GetCurrentProcessID,8)+' '+ IntToHex(GetCurrentThreadID,8)+' '+ TrueStr+#13#10) else ToWrite :=PChar(IntToHex(GetCurrentProcessID,8)+' '+ IntToHex(GetCurrentThreadID,8)+' '+ FalseStr+#13#10); theFile.Write(ToWrite^, Length(ToWrite)); Result :=True; finally theFile.Free; end; end; function RTFileEmpty(Filename :ShortString) :Boolean; Var theFile :TFileStream; begin theFile :=TFileStream.Create(FileName, fmCreate); try Result :=False; theFile.Size :=0; Result :=True; finally theFile.Free; end; end; function GetLogFileName :String; Var xReg :TMGRegistry; begin xReg :=TMGRegistry.Create; if xReg.OpenKeyReadOnly(REG_KEY) then begin Result :=xReg.ReadString('', true, REG_LOGFILE); LogOnFile :=xReg.ReadBool(False, REG_LOGONFILE); end else begin Result :=''; LogOnFile :=False; end; xReg.Free; end; initialization LogFileName :=GetLogFileName; end.
{ SHA-1 implementation based on two Public Domain implementations by Steve Reid <steve@edmweb.com> Jordan Russell <jr-2010@jrsoftware.org> 100% Public Domain } unit SHAone; {$ifdef FPC}{$mode OBJFPC}{$H+}{$endif} interface uses {$ifdef FPC} Sockets {$else} {$ifdef MSWINDOWS} WinSock {$else} Posix.ArpaInet {$endif} {$endif}; type TSHAoneBlock = array [0..63] of byte; TSHAoneDigest = array [0..19] of byte; TSHAone = record state: array [0..4] of longword; count: uint64; buffer: TSHAoneBlock; end; TLongWordConverter = packed record case longword of 0: (bytes: array [0..3] of byte); 1: (total: longword); end; procedure SHAoneInit(var sha1: TSHAone); procedure SHAoneUpdate(var sha1: TSHAone; const data: array of byte); function SHAoneFinal(var sha1: TSHAone): TSHAoneDigest; implementation procedure SHAoneTransform(var sha1: TSHAone; const buffer: TSHAoneBlock); const K1 = $5A827999; K2 = $6ED9EBA1; K3 = $8F1BBCDC; K4 = $CA62C1D6; var i, k: longint; converter: TLongWordConverter; temp, A, B, C, D, E: longword; W: array [0..79] of longword; begin { convert buffer to 32-bit (big endian) numbers } for i := 0 to 15 do begin for k := 0 to 3 do begin converter.bytes[k] := buffer[i * 4 + k]; end; W[i] := htonl(converter.total); end; for i := 16 to 79 do begin temp := W[i - 3] xor W[i - 8] xor W[i - 14] xor W[i - 16]; W[i] := (temp shl 1) or (temp shr 31); end; A := sha1.state[0]; B := sha1.state[1]; C := sha1.state[2]; D := sha1.state[3]; E := sha1.state[4]; for i := 0 to 19 do begin temp := ((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + E + W[i] + K1; E := D; D := C; C := (B shl 30) or (B shr 2); B := A; A := temp; end; for i := 20 to 39 do begin temp := ((A shl 5) or (A shr 27)) + (B xor C xor D) + E + W[i] + K2; E := D; D := C; C := (B shl 30) or (B shr 2); B := A; A := temp; end; for i := 40 to 59 do begin temp := ((A shl 5) or (A shr 27)) + ((B and C) or (B and D) or (C and D)) + E + W[i] + K3; E := D; D := C; C := (B shl 30) or (B shr 2); B := A; A := temp; end; for i := 60 to 79 do begin temp := ((A shl 5) or (A shr 27)) + (B xor C xor D) + E + W[i] + K4; E := D; D := C; C := (B shl 30) or (B shr 2); B := A; A := temp; end; Inc(sha1.state[0], A); Inc(sha1.state[1], B); Inc(sha1.state[2], C); Inc(sha1.state[3], D); Inc(sha1.state[4], E); end; procedure SHAoneInit(var sha1: TSHAone); begin sha1.state[0] := $67452301; sha1.state[1] := $EFCDAB89; sha1.state[2] := $98BADCFE; sha1.state[3] := $10325476; sha1.state[4] := $C3D2E1F0; sha1.count := 0; end; procedure SHAoneUpdate(var sha1: TSHAone; const data: array of byte); var len, i, j: longword; buffer: TSHAoneBlock; begin len := Length(data); j := longword((sha1.count shr 3) and 63); Inc(sha1.count, len shl 3); if ((j + len) > 63) then begin i := 64 - j; Move(data[0], sha1.buffer[j], i); SHAoneTransform(sha1, sha1.buffer); while ((i + 63) < len) do begin Move(data[i], buffer[0], 64); SHAoneTransform(sha1, buffer); Inc(i, 64); end; j := 0; end else begin i := 0; end; Move(data[i], sha1.buffer[j], len - i); end; function SHAoneFinal(var sha1: TSHAone): TSHAoneDigest; var count: array of byte; i: longint; pad: array of byte; begin SetLength(count, 8); for i := 0 to 7 do begin count[i] := byte((sha1.count shr ((7 - (i and 7)) * 8)) and 255); { endian independent } end; SetLength(pad, 1); pad[0] := 128; SHAoneUpdate(sha1, pad); pad[0] := 0; while ((sha1.count and 504) <> 448) do begin SHAoneUpdate(sha1, pad); end; SHAoneUpdate(sha1, count); for i := 0 to 19 do begin result[i] := byte((sha1.state[i shr 2] shr ((3 - (i and 3)) * 8)) and 255); end; FillChar(sha1, SizeOf(sha1), 0); end; end.
unit uDbCustomObject; interface uses System.Classes, System.SysUtils, Data.DB, Datasnap.DBClient, uConexaoPadrao, ////// FireDAC //////// FireDAC.Phys.FB, FireDAC.Phys.MySQL, FireDAC.Comp.UI, FireDAC.DApt, FireDAC.Comp.Client, Datasnap.Provider; Type TOnMessageInfo = Procedure (sMessageInfo: string) of object; EdbObjectError = class(Exception); EControlObjectError = class(Exception); TCustomDbObject = class private FDataBaseName: string; //FDbConnectionType: TDbConnectionType; FOnMessageInfo: TOnMessageInfo; //FConnectionSide: TConnectionSide; FDbFDConnection : TFDConnection; fMessageInfo: String; //procedure SetDbConnectionType(const Value: TDbConnectionType); procedure SetOnMessageInfo(const Value: TOnMessageInfo); //procedure SetConnectionSide(const Value: TConnectionSide); procedure SetMessageInfo(const Value: String); function GetMessageInfo: String; protected FConexaoPadrao : TConexaoPadrao; function GetDataBaseName: String; Virtual; procedure SetDataBaseName(const Value: String); Virtual; {Procedure executada quando é associado um FDConnection a instância da classe} procedure SetDbFDConnection(const Value: TFDConnection); Virtual; {Método semelhante ao LeUltRegistro onde o Sufixo é o nome da Tabela associada ao Sequence} function GetSequence(Table, Field :string) :Integer; Virtual; public Constructor Create; Dynamic; Destructor Destroy; Override; {DataBase name ou ConnectionString ultilizada para os DataSets da classe de negócio} property DataBaseName :String read GetDataBaseName write SetDataBaseName; {String para troca de mensagem com o solicitante do serviço} property MessageInfo :String read GetMessageInfo write SetMessageInfo; {Evento Disparado qdo é atribuido o MessageInfo pelo método SetMessageInfo} Property OnMessageInfo :TOnMessageInfo read FOnMessageInfo write SetOnMessageInfo; {Ado Connetion para conexão via ADO} property DbFDConnection :TFDConnection read FDbFDConnection write SetDbFDConnection; property Conexao: TConexaoPadrao read FConexaoPadrao; end; implementation { TCustomDbObject } constructor TCustomDbObject.Create; begin FConexaoPadrao := ConexaoPadrao; fMessageInfo := ''; FDataBaseName := ''; FDbFDConnection := nil; end; destructor TCustomDbObject.Destroy; begin inherited; end; function TCustomDbObject.GetDataBaseName: String; begin Result := FDataBaseName; end; function TCustomDbObject.GetMessageInfo: String; begin result := fMessageInfo; end; function TCustomDbObject.GetSequence(Table, Field: string): Integer; begin end; procedure TCustomDbObject.SetDataBaseName(const Value: String); begin FDataBaseName := Value; end; procedure TCustomDbObject.SetDbFDConnection(const Value: TFDConnection); begin FDbFDConnection := Value; end; procedure TCustomDbObject.SetMessageInfo(const Value: String); begin fMessageInfo := Value; end; procedure TCustomDbObject.SetOnMessageInfo(const Value: TOnMessageInfo); begin FOnMessageInfo := Value; end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit Datasnap.DSProxyJavaAndroid; interface uses Data.DBXPlatform, Datasnap.DSCommonProxy, Datasnap.DSProxyWriter, Datasnap.DSCustomConnectorProxyWriter, System.SysUtils, System.Classes; type TDSClientProxyWriterJavaAndroid = class(TDSProxyWriter) private FUTF8Encoding: TEncoding; function GetEncoding: TEncoding; public function CreateProxyWriter: TDSCustomProxyWriter; override; function Properties: TDSProxyWriterProperties; override; function FileDescriptions: TDSProxyFileDescriptions; override; destructor Destroy; override; end; TDSCustomJavaAndroidProxyWriter = class abstract (TDSCustomConnectorProxyWriter) protected function GetCreateDataSetReader(const Param: TDSProxyParameter) : string; override; function GetCreateParamsReader(const Param: TDSProxyParameter) : string; override; procedure WriteInterface; override; procedure WriteJavaLine(const Line: string); overload; virtual; procedure WriteJavaLine; overload; virtual; procedure WriteImplementation; override; procedure WriteClassImplementation(const ProxyClass: TDSProxyClass; const ProxyClassNameList: TDBXStringList); virtual; procedure WriteMethodComment(const ProxyClass: TDSProxyClass; const ProxyMethod: TDSProxyMethod); virtual; procedure WriteMethodParametersMetadata(const ProxyClass: TDSProxyClass; const ProxyMethod: TDSProxyMethod; out MetadataGetterName: String); virtual; procedure WriteMethodImplementation(const ProxyClass: TDSProxyClass; const ProxyMethod: TDSProxyMethod; const MetadataGetterName: String); virtual; function GetJavaType(Param: TDSProxyParameter): String; function GetCastType(Param: TDSProxyParameter): String; procedure WriteResultObjectClass(const ProxyClass: TDSProxyClass; const ProxyMethod: TDSProxyMethod; out ResultObjectClassName: String); virtual; private procedure WriteSetterForInputParams(const ProxyMethod: TDSProxyMethod); procedure WriteGetterForOutputParams(const ProxyMethod : TDSProxyMethod); overload; procedure WriteGetterForOutputParams(const ProxyMethod: TDSProxyMethod; const ResultObjectClassName: String); overload; protected end; /// <summary> Writes a JavaAndroid proxy for a server application. </summary> TDSJavaAndroidProxyWriter = class(TDSCustomJavaAndroidProxyWriter) private FStreamWriter: TStreamWriter; FTargetUnitName: String; FIncludeClasses: TDBXStringArray; FExcludeClasses: TDBXStringArray; FIncludeMethods: TDBXStringArray; FExcludeMethods: TDBXStringArray; protected procedure DerivedWrite(const Line: string); override; procedure DerivedWriteLine; override; public property StreamWriter: TStreamWriter read FStreamWriter write FStreamWriter; property TargetUnitName: string read FTargetUnitName write FTargetUnitName; /// <summary> Array of classes to include in the generation /// </summary> property IncludeClasses: TDBXStringArray read FIncludeClasses write FIncludeClasses; /// <summary> Array of classes to exclude in the generation /// </summary> property ExcludeClasses: TDBXStringArray read FExcludeClasses write FExcludeClasses; /// <summary> Array of methods to include in the generation /// </summary> property IncludeMethods: TDBXStringArray read FIncludeMethods write FIncludeMethods; /// <summary> Array of methods to exclude in the generation /// </summary> property ExcludeMethods: TDBXStringArray read FExcludeMethods write FExcludeMethods; destructor Destroy; override; end; const sJavaAndroidRESTProxyWriter = 'Java (Android) REST'; implementation uses Data.DBXCommon, Datasnap.DSProxyUtils; type TUTF8EncodingNoBOM = class(TUTF8Encoding) public function GetPreamble: TBytes; override; end; const sDSProxyJavaAndroidLanguage = 'java_android'; function TDSCustomJavaAndroidProxyWriter.GetCastType (Param: TDSProxyParameter): String; begin if IsDBXValueTypeParameter(Param) then Exit('(' + Param.TypeName + ')'); case Param.DataType of TDBXDataTypes.JsonValueType: begin if Param.TypeName = 'TJSONObject' then Exit('(TJSONObject)'); if Param.TypeName = 'TJSONArray' then Exit('(TJSONArray)'); if Param.TypeName = 'TJSONValue' then Exit('(TJSONValue)'); if Param.TypeName = 'TJSONTrue' then Exit('(TJSONTrue)'); if Param.TypeName = 'TJSONFalse' then Exit('(TJSONFalse)'); if Param.TypeName = 'TJSONNull' then Exit('(TJSONNull)'); Exit('(TJSONObject)'); // it's a user defined type end; TDBXDataTypes.TableType: begin if Param.TypeName = 'TParams' then Exit('(TParams)'); if Param.TypeName = 'TDBXReader' then Exit('(TDBXReader)'); if Param.TypeName = 'TDataSet' then Exit('(TDataSet)'); Exit('UNKNOWN-' + Param.TypeName); end; else Result := ''; end; end; function TDSCustomJavaAndroidProxyWriter.GetCreateDataSetReader (const Param: TDSProxyParameter): string; begin Result := NullString; end; function TDSCustomJavaAndroidProxyWriter.GetCreateParamsReader (const Param: TDSProxyParameter): string; begin Result := NullString; end; procedure TDSCustomJavaAndroidProxyWriter.WriteInterface; begin WriteLine('package com.embarcadero.javaandroid;'); WriteLine; WriteLine('import java.util.Date;'); WriteLine; end; procedure TDSCustomJavaAndroidProxyWriter.WriteJavaLine (const Line: string); begin inherited WriteLine(Line); end; procedure TDSCustomJavaAndroidProxyWriter.WriteJavaLine; begin inherited WriteLine; end; function TDSCustomJavaAndroidProxyWriter.GetJavaType (Param: TDSProxyParameter): String; begin if Param = nil then Exit('void'); if IsDBXValueTypeParameter(Param) then Exit(Param.TypeName); case Param.DataType of TDBXDataTypes.AnsiStringType, TDBXDataTypes.WideStringType: begin Exit('String'); end; TDBXDataTypes.DatetimeType: Exit('Date'); // TDBXDataTypes.BlobType: TDBXDataTypes.BinaryBlobType: Exit('TStream'); TDBXDataTypes.BooleanType: begin Exit('boolean'); end; TDBXDataTypes.Int8Type, TDBXDataTypes.UInt8Type: begin Exit('int'); end; TDBXDataTypes.Int16Type, TDBXDataTypes.UInt16Type: begin Exit('int'); end; TDBXDataTypes.Int32Type, TDBXDataTypes.UInt32Type: begin Exit('int'); end; TDBXDataTypes.Int64Type, TDBXDataTypes.UInt64Type: begin Exit('long'); end; TDBXDataTypes.DoubleType: begin Exit('double'); end; TDBXDataTypes.SingleType: begin Exit('float'); end; TDBXDataTypes.CurrencyType: Exit('double'); TDBXDataTypes.TimeType: Exit('int'); TDBXDataTypes.DateType: begin Exit('int'); end; TDBXDataTypes.JsonValueType: begin if (Param.TypeName = 'TJSONObject') or (Param.TypeName = 'TJSONArray') or (Param.TypeName = 'TJSONValue') or (Param.TypeName = 'TJSONTrue') or (Param.TypeName = 'TJSONFalse') or (Param.TypeName = 'TJSONNull') then Exit(Param.TypeName); Exit('TJSONObject'); end; TDBXDataTypes.BcdType: Exit('???' + Param.TypeName + '???'); TDBXDataTypes.TimeStampType: Exit('???' + Param.TypeName + '???'); TDBXDataTypes.TableType: Exit(Param.TypeName); else raise EDSProxyException.Create('Unknown param type for ' + Param.TypeUnit + '.' + Param.TypeName); end; end; procedure TDSCustomJavaAndroidProxyWriter.WriteImplementation; var ProxyClassNameList: TDBXStringList; Item: TDSProxyClass; begin WriteJavaLine('public class DSProxy {'); Indent; ProxyClassNameList := TDBXStringList.Create; try Item := FirstClass; while Item <> nil do begin if ExtendedIncludeClass(Item) then WriteClassImplementation(Item, ProxyClassNameList); Item := Item.Next; end; finally FreeAndNil(ProxyClassNameList); end; Outdent; WriteJavaLine('}'); end; procedure TDSCustomJavaAndroidProxyWriter.WriteClassImplementation (const ProxyClass: TDSProxyClass; const ProxyClassNameList: TDBXStringList); var ClassMethodString: TStringBuilder; Methods: TDSProxyMethod; MetadataGetterName: String; begin ClassMethodString := TStringBuilder.Create; try WriteJavaLine('public static class ' + ProxyClass.ProxyClassName + ' extends DSAdmin {'); Indent; WriteJavaLine('public ' + ProxyClass.ProxyClassName + '(DSRESTConnection Connection) {'); Indent; WriteJavaLine('super(Connection);'); Outdent; WriteJavaLine('}'); Methods := ProxyClass.FirstMethod; while Methods <> nil do begin if ExtendedIncludeMethod(Methods) then begin WriteJavaLine(''); WriteJavaLine(''); WriteMethodParametersMetadata(ProxyClass, Methods, MetadataGetterName); WriteMethodComment(ProxyClass, Methods); WriteMethodImplementation(ProxyClass, Methods, MetadataGetterName); end; Methods := Methods.Next; end; Outdent; WriteJavaLine('}'); WriteJavaLine; ProxyClassNameList.Add(ClassMethodString.ToString(True)); finally ClassMethodString.Free; end; end; procedure TDSCustomJavaAndroidProxyWriter.WriteGetterForOutputParams (const ProxyMethod: TDSProxyMethod); var Param: TDSProxyParameter; CastTo: String; begin CastTo := ''; Param := GetReturnParam(ProxyMethod); if Assigned(Param) then // could be also a procedure without return value begin if (Param.DataType in [TDBXDataTypes.TableType, TDBXDataTypes.JsonValueType] ) or (IsDBXValueTypeParameter(Param)) then CastTo := GetCastType(Param); WriteJavaLine('return ' + CastTo + ' cmd.getParameter(' + IntToStr(ProxyMethod.ParameterCount - 1) + ').getValue().' + GetGetter(Param) + '();') end else WriteJavaLine('return;'); end; procedure TDSCustomJavaAndroidProxyWriter.WriteGetterForOutputParams (const ProxyMethod: TDSProxyMethod; const ResultObjectClassName: String); var ParIndex: Integer; ParName: String; begin WriteJavaLine(ResultObjectClassName + ' ret = new ' + ResultObjectClassName + '();'); ParIndex := 0; ForEachParameter(ProxyMethod, procedure(Param: TDSProxyParameter) begin if IsOutputParameter(Param) then begin ParName := C_Conditional (Param.ParameterDirection = TDBXParameterDirections.ReturnParameter, 'returnValue', Param.ParameterName); WriteJavaLine('ret.' + ParName + ' = ' + GetCastType(Param) + 'cmd.getParameter(' + IntToStr(ParIndex) + ').getValue().' + GetGetter(Param) + '();'); end; inc(ParIndex); end); WriteJavaLine('return ret;'); end; procedure TDSCustomJavaAndroidProxyWriter.WriteMethodComment(const ProxyClass : TDSProxyClass; const ProxyMethod: TDSProxyMethod); var Param: TDSProxyParameter; PName: string; TypeName: string; Direction: string; IsReturn: Boolean; AtTag: string; begin WriteJavaLine; Param := ProxyMethod.Parameters; if Param <> nil then begin WriteJavaLine('/**'); while Param <> nil do begin PName := Param.ParameterName; TypeName := Param.TypeName; Direction := NullString; IsReturn := False; if Param.ParameterDirection = TDBXParameterDirections.InOutParameter then Direction := ' [in/out]' else if Param.ParameterDirection = TDBXParameterDirections.OutParameter then Direction := ' [out]' else if Param.ParameterDirection = TDBXParameterDirections.InParameter then Direction := ' [in]' else if Param.ParameterDirection = TDBXParameterDirections.ReturnParameter then begin Direction := ''; PName := 'result'; IsReturn := True; end; AtTag := C_Conditional(IsReturn, '@return ', '@param '); WriteJavaLine(' * ' + AtTag + PName + Direction + ' - Type on server: ' + TypeName); Param := Param.Next; end; WriteJavaLine(' */'); end; end; procedure TDSCustomJavaAndroidProxyWriter.WriteMethodImplementation (const ProxyClass: TDSProxyClass; const ProxyMethod: TDSProxyMethod; const MetadataGetterName: String); var First: Boolean; UseResultObject: Boolean; ResultObjectClassName: String; sb: TStringBuilder; OutputParametersCount: Integer; begin OutputParametersCount := GetOutputParametersCount(ProxyMethod); UseResultObject := (OutputParametersCount >= 2) or (IsProcedure(ProxyMethod) and (OutputParametersCount = 1)); if UseResultObject then WriteResultObjectClass(ProxyClass, ProxyMethod, ResultObjectClassName); First := True; sb := TStringBuilder.Create; try if UseResultObject then sb.Append('public ' + ResultObjectClassName + ' ' + ProxyMethod.ProxyMethodName + '(') else sb.Append('public ' + GetJavaType(GetReturnParam(ProxyMethod)) + ' ' + ProxyMethod.ProxyMethodName + '('); ForEachInputParameter(ProxyMethod, procedure(Param: TDSProxyParameter) begin if not First then sb.Append(', '); sb.Append(GetJavaType(Param) + ' ' + Param.ParameterName); First := False; end); WriteJavaLine(sb.ToString + ') throws DBXException {'); // METHOD BODY /// //////////////// Indent; WriteJavaLine('DSRESTCommand cmd = getConnection().CreateCommand();'); if HasOnlyURLParams(ProxyMethod) then WriteJavaLine('cmd.setRequestType(DSHTTPRequestType.GET);') else WriteJavaLine('cmd.setRequestType(DSHTTPRequestType.POST);'); WriteJavaLine('cmd.setText("' + ProxyClass.ProxyClassName + '.' + ProxyMethod.ProxyMethodName + '");'); // WriteJavaLine('cmd.prepare(' + ProxyClass.ProxyClassName + '_' + // ProxyMethod.ProxyMethodName + ');'); WriteJavaLine('cmd.prepare(' + MetadataGetterName + '());'); WriteSetterForInputParams(ProxyMethod); WriteJavaLine('getConnection().execute(cmd);'); if UseResultObject then WriteGetterForOutputParams(ProxyMethod, ResultObjectClassName) else WriteGetterForOutputParams(ProxyMethod); Outdent; // END METHOD BODY /// //////////////// WriteJavaLine('}'); finally sb.Free; end; end; procedure TDSCustomJavaAndroidProxyWriter.WriteMethodParametersMetadata (const ProxyClass: TDSProxyClass; const ProxyMethod: TDSProxyMethod; out MetadataGetterName: String); var MetadataArrName: string; Param: TDSProxyParameter; MetadataParam: string; begin MetadataArrName := ProxyClass.ProxyClassName + '_' + ProxyMethod.ProxyMethodName + '_Metadata'; WriteJavaLine('private DSRESTParameterMetaData[] ' + MetadataArrName + ';'); // = new DSRESTParameterMetaData[] {'); // Indent; WriteJavaLine('private DSRESTParameterMetaData[] get_' + MetadataArrName + '() {'); Indent; WriteJavaLine('if (' + MetadataArrName + ' == null) {'); Indent; WriteJavaLine(MetadataArrName + ' = new DSRESTParameterMetaData[]{'); Indent; Param := ProxyMethod.Parameters; while Param <> nil do begin MetadataParam := '"' + Param.ParameterName + '", '; MetadataParam := MetadataParam + GetParameterDirection (Param.ParameterDirection) + ', '; MetadataParam := MetadataParam + GetParameterType(Param.DataType) + ', '; MetadataParam := MetadataParam + '"' + Param.TypeName + '"'; WriteJavaLine('new DSRESTParameterMetaData(' + MetadataParam + '),'); Param := Param.Next; end; Outdent; WriteJavaLine('};'); Outdent; WriteJavaLine('}'); WriteJavaLine('return ' + MetadataArrName + ';'); Outdent; WriteJavaLine('}'); MetadataGetterName := 'get_' + MetadataArrName; end; procedure TDSCustomJavaAndroidProxyWriter.WriteSetterForInputParams (const ProxyMethod: TDSProxyMethod); var ParIndex: Integer; begin ParIndex := 0; ForEachParameter(ProxyMethod, procedure(Param: TDSProxyParameter) begin if IsInputParameter(Param) then if IsDBXValueTypeParameter(Param) then begin WriteJavaLine('if (' + Param.ParameterName + ' != null) {'); Indent; WriteJavaLine('cmd.getParameter(' + IntToStr(ParIndex) + ').getValue().' + 'SetAsDBXValue(' + Param.ParameterName + ');'); Outdent; WriteJavaLine('} else {'); Indent; WriteJavaLine('cmd.getParameter(' + IntToStr(ParIndex) + ').getValue().SetTDBXNull("' + Param.TypeName + '");'); Outdent; WriteJavaLine('}'); inc(ParIndex); end else begin WriteJavaLine('cmd.getParameter(' + IntToStr(ParIndex) + ').getValue().' + GetSetter(Param) + '(' + Param.ParameterName + ');'); inc(ParIndex); end; end); end; procedure TDSCustomJavaAndroidProxyWriter.WriteResultObjectClass (const ProxyClass: TDSProxyClass; const ProxyMethod: TDSProxyMethod; out ResultObjectClassName: String); var MemberName: String; begin ResultObjectClassName := ProxyMethod.ProxyMethodName + 'Returns'; WriteJavaLine('public static class ' + ResultObjectClassName + ' {'); Indent; ForEachOutputParameter(ProxyMethod, procedure(Param: TDSProxyParameter) begin if Param.ParameterDirection = TDBXParameterDirections.ReturnParameter then MemberName := 'returnValue' else MemberName := Param.ParameterName; WriteJavaLine('public ' + GetJavaType(Param) + ' ' + MemberName + ';'); end); Outdent; WriteJavaLine('}'); end; { TDSJavaAndroidProxyWriter } procedure TDSJavaAndroidProxyWriter.DerivedWrite(const Line: string); begin if StreamWriter <> nil then StreamWriter.Write(Line) else ProxyWriters[sImplementation].Write(Line); end; procedure TDSJavaAndroidProxyWriter.DerivedWriteLine; begin if StreamWriter <> nil then StreamWriter.WriteLine else ProxyWriters[sImplementation].WriteLine; end; destructor TDSJavaAndroidProxyWriter.Destroy; begin FreeAndNil(FStreamWriter); inherited; end; function TDSClientProxyWriterJavaAndroid.CreateProxyWriter : TDSCustomProxyWriter; begin Result := TDSJavaAndroidProxyWriter.Create; end; destructor TDSClientProxyWriterJavaAndroid.Destroy; begin FreeAndNil(FUTF8Encoding); inherited; end; function TDSClientProxyWriterJavaAndroid.FileDescriptions : TDSProxyFileDescriptions; begin SetLength(Result, 1); Result[0].ID := sImplementation; // do not localize Result[0].DefaultFileExt := '.java'; end; function TDSClientProxyWriterJavaAndroid.GetEncoding: TEncoding; var LEncoding: TEncoding; begin if FUTF8Encoding = nil then begin LEncoding := TUTF8EncodingNoBOM.Create; if AtomicCmpExchange(Pointer(FUTF8Encoding), Pointer(LEncoding), nil) <> nil then LEncoding.Free {$IFDEF AUTOREFCOUNT} else FUTF8Encoding.__ObjAddRef {$ENDIF AUTOREFCOUNT}; end; Result := FUTF8Encoding; end; function TDSClientProxyWriterJavaAndroid.Properties: TDSProxyWriterProperties; begin Result.UsesUnits := 'Datasnap.DSProxyJavaAndroid'; Result.DefaultExcludeClasses := sDSMetadataClassName + ',' + sDSAdminClassName; // do not localize Result.DefaultExcludeMethods := sASMethodsPrefix; Result.Author := 'Embarcadero'; // do not localize Result.Comment := 'com\embarcadero\javaandroid'; // do not localize Result.Language := sDSProxyJavaAndroidLanguage; Result.Features := [feRESTClient]; Result.DefaultEncoding := GetEncoding; end; { TUTF8EncodingNoBOM } function TUTF8EncodingNoBOM.GetPreamble: TBytes; begin SetLength(Result, 0); end; initialization TDSProxyWriterFactory.RegisterWriter(sJavaAndroidRESTProxyWriter, TDSClientProxyWriterJavaAndroid); finalization TDSProxyWriterFactory.UnregisterWriter(sJavaAndroidRESTProxyWriter); end.
{********************************************} { TeeChart Pro Charting Library } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {********************************************} unit TeeFuncEdit; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons, QExtCtrls, QComCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, ComCtrls, {$ENDIF} TeeSelectList, TeEngine, TeeProcs, TeeEdiPeri, TeeSourceEdit, TeCanvas; type TTeeFuncEditor = class(TBaseSourceEditor, ITeeEventListener) PageControl1: TPageControl; TabSource: TTabSheet; TabOptions: TTabSheet; PanSingle: TPanel; Label1: TLabel; CBSingle: TComboFlat; LValues: TLabel; CBValues: TComboFlat; BNone: TButton; Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure CBSourcesChange(Sender: TObject); procedure BApplyClick(Sender: TObject); procedure CBSingleChange(Sender: TObject); procedure BNoneClick(Sender: TObject); procedure CBValuesChange(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { Private declarations } IOptions : TForm; ISources : TSelectListForm; Procedure FillSeries; // Fill selection combos... procedure TryCreateNewFunction; {$IFDEF CLR} protected {$ENDIF} procedure TeeEvent(Event: TTeeEvent); { interface } public { Public declarations } TheSeries : TChartSeries; Function FunctionClass:TTeeFunctionClass; end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses {$IFDEF CLR} Variants, {$ENDIF} TeeConst, Chart, TeePenDlg; { Helper functions } procedure FillTeeFunctions(ACombo:TComboBox); var t : Integer; begin With ACombo.Items do begin BeginUpdate; Clear; Add(TeeMsg_FunctionNone); With TeeSeriesTypes do for t:=0 to Count-1 do With Items[t] do if Assigned(FunctionClass) and (not Assigned(SeriesClass)) and (IndexOfObject(TObject(FunctionClass))=-1) then AddObject(ReplaceChar(Description {$IFNDEF CLR}^{$ENDIF},TeeLineSeparator,' '), TObject(FunctionClass)); EndUpdate; end; end; procedure TTeeFuncEditor.FormCreate(Sender: TObject); begin inherited; {$IFNDEF CLX} CBSources.Sorted:=True; {$ENDIF} FillTeeFunctions(CBSources); end; Function TTeeFuncEditor.FunctionClass:TTeeFunctionClass; begin With CBSources do if ItemIndex=-1 then result:=nil else result:=TTeeFunctionClass(Items.Objects[ItemIndex]); end; Procedure TTeeFuncEditor.FillSeries; // Fill selection combos... Procedure FillSources(AItems:TStrings; AddCurrent:Boolean); Procedure AddSource(ASeries: TChartSeries); var tmp : String; begin if TheSeries.ParentChart.IsValidDataSource(TheSeries,ASeries) then begin tmp:=SeriesTitleOrName(ASeries); CBSingle.Items.AddObject(tmp,ASeries); if AddCurrent or (TheSeries.DataSources.IndexOf(ASeries)=-1) then AItems.AddObject(tmp,ASeries); end; end; var t : Integer; begin if Assigned(TheSeries.Owner) then With TheSeries.Owner do for t:=0 to ComponentCount-1 do if Components[t] is TChartSeries then AddSource(TChartSeries(Components[t])); end; var t : Integer; tmp : TChartSeries; tmpSource : TObject; tmpList : String; tmpIndex : Integer; begin CBSingle.Items.Clear; With ISources do begin FromList.Items.Clear; FillSources(FromList.Items,False); With ToList do begin Items.BeginUpdate; Clear; With TheSeries do if Assigned(DataSource) then for t:=0 to DataSources.Count-1 do if TComponent(DataSources[t]) is TChartSeries then begin tmp:=TChartSeries(DataSources[t]); Items.AddObject(SeriesTitleOrName(tmp),tmp); with FromList.Items do Delete(IndexOfObject(tmp)); end; Items.EndUpdate; end; end; if PanSingle.Visible then begin // Set current selected single series tmpSource:=TheSeries.DataSource; if Assigned(tmpSource) and (tmpSource is TChartSeries) then begin with CBSingle do begin tmpIndex:=Items.IndexOfObject(tmpSource); if tmpIndex<>ItemIndex then begin ItemIndex:=tmpIndex; CBSingleChange(Self); end; end; tmpList:=TheSeries.MandatoryValueList.ValueSource; if tmpList='' then CBValues.ItemIndex:=0 else CBValues.ItemIndex:=CBValues.Items.IndexOf(tmpList); end else CBSingle.ItemIndex:=-1; end; end; type TFunctionAccess=class(TTeeFunction); {$IFNDEF CLR} TTeePanelAccess=class(TCustomAxisPanel); {$ENDIF} procedure TTeeFuncEditor.FormShow(Sender: TObject); begin inherited; PageControl1.ActivePage:=TabSource; TheSeries:=TChartSeries({$IFDEF CLR}TObject{$ENDIF}(Tag)); if Assigned(TheSeries) and Assigned(TheSeries.ParentChart) then {$IFNDEF CLR}TTeePanelAccess{$ENDIF}(TheSeries.ParentChart).Listeners.Add(Self); // Create multi-list form ISources:=TSelectListForm.Create(Self); With ISources do begin FromList.Height:=FromList.Height-5; ToList.Height:=ToList.Height-5; Height:=Height-8; Align:=alClient; OnChange:=CBSourcesChange; end; AddFormTo(ISources,TabSource,{$IFDEF CLR}TheSeries{$ELSE}Tag{$ENDIF}); if Assigned(TheSeries) then begin FillSeries; // Select current at list of functions With CBSources do if Assigned(TheSeries.FunctionType) then ItemIndex:=Items.IndexOfObject(TObject(TheSeries.FunctionType.ClassType)) else ItemIndex:=Items.IndexOf(TeeMsg_FunctionNone); CBSourcesChange(Self); BApply.Enabled:=(not Assigned(TheSeries.FunctionType)) and (TheSeries.DataSource=nil); end; ISources.EnableButtons; end; procedure TTeeFuncEditor.TryCreateNewFunction; var tmpClass : TTeeFunctionClass; begin { Create a new function... } tmpClass:=FunctionClass; if Assigned(tmpClass) then begin if (not Assigned(TheSeries.FunctionType)) or (TheSeries.FunctionType.ClassType<>tmpClass) then begin TheSeries.FunctionType:=nil; CreateNewTeeFunction(TheSeries,tmpClass); BApply.Enabled:=False; end; end else TheSeries.FunctionType:=nil; end; procedure TTeeFuncEditor.CBSourcesChange(Sender: TObject); Procedure CreateEditorForm(const EditorClass:String); var tmpF : TFormClass; begin FreeAndNil(IOptions); tmpF:=TFormClass(GetClass(EditorClass)); if Assigned(tmpF) then begin IOptions:=tmpF.Create(Self); TeeTranslateControl(IOptions); AddFormTo(IOptions,TabOptions,{$IFNDEF CLR}Integer{$ENDIF}(TheSeries.FunctionType)); end; end; var tmpEdit : String; tmp : TTeeFunction; tmpNoSource : Boolean; begin inherited; TabOptions.TabVisible:=FunctionClass<>nil; if TabOptions.TabVisible then begin TryCreateNewFunction; tmp:=FunctionClass.Create(nil); // temporary function try tmpEdit:=TFunctionAccess(tmp).GetEditorClass; tmpNoSource:=TFunctionAccess(tmp).NoSourceRequired; PanSingle.Visible:=(not tmpNoSource) and TFunctionAccess(tmp).SingleSource; if PanSingle.Visible then begin LValues.Visible:=not TFunctionAccess(tmp).HideSourceList; CBValues.Visible:=LValues.Visible; end; if tmpEdit='' then TabOptions.TabVisible:=False else CreateEditorForm(tmpEdit); if tmpNoSource then begin TabOptions.Visible:=True; PageControl1.ActivePage:=TabOptions; end; TabSource.TabVisible:=not tmpNoSource; // Hack due to a VCL bug in TPageControl. See OnTimer // Anybody knows a better solution? if ((TheSeries.DataSource<>nil) or tmpNoSource) and Assigned(IOptions) then Timer1.Enabled:=True; finally tmp.Free; end; end else begin TabSource.TabVisible:=True; PanSingle.Visible:=False; end; ISources.Visible:=not PanSingle.Visible; end; type TSeriesAccess=class(TChartSeries); procedure TTeeFuncEditor.BApplyClick(Sender: TObject); procedure DoApply; var t : Integer; // tmp : TChartSeries; begin { Set datasources... } if PanSingle.Visible then begin if CBSingle.ItemIndex=-1 then begin TheSeries.DataSource:=nil; TheSeries.MandatoryValueList.ValueSource:=''; end else begin TheSeries.DataSource:=TChartSeries(CBSingle.Items.Objects[CBSingle.ItemIndex]); if CBValues.ItemIndex=-1 then TheSeries.MandatoryValueList.ValueSource:='' else TheSeries.MandatoryValueList.ValueSource:=CBValues.Items[CBValues.ItemIndex]; end; end else begin if ISources.ToList.Items.Count=0 then TheSeries.DataSource:=nil else begin With ISources.ToList.Items do for t:=0 to Count-1 do TheSeries.CheckOtherSeries(TChartSeries(Objects[t])); With TheSeries.DataSources do begin // for t:=0 to Count-1 do // 6.02 // TSeriesAccess(Items[t]).RemoveLinkedSeries(TheSeries); Clear; With ISources.ToList.Items do for t:=0 to Count-1 do // tmp:=TChartSeries(Objects[t]); TheSeries.DataSources.Add(TChartSeries(Objects[t])); //TSeriesAccess(tmp).AddLinkedSeries(TheSeries); // 6.02 end; end; end; TryCreateNewFunction; end; var tmp : Boolean; begin inherited; if Assigned(IOptions) and Assigned(IOptions.OnCloseQuery) then begin tmp:=True; IOptions.OnCloseQuery(IOptions,tmp); end; TheSeries.BeginUpdate; DoApply; TheSeries.EndUpdate; TheSeries.CheckDataSource; BApply.Enabled:=False; end; procedure TTeeFuncEditor.CBSingleChange(Sender: TObject); var tmp : TChartSeries; t : Integer; begin BApply.Enabled:=True; with CBValues do begin Items.Clear; Enabled:=CBSingle.ItemIndex<>-1; BNone.Enabled:=Enabled; if Enabled then begin tmp:=TChartSeries(CBSingle.Items.Objects[CBSingle.ItemIndex]); for t:=1 to tmp.ValuesList.Count-1 do Items.Add(tmp.ValuesList[t].Name); CBValues.ItemIndex:=0; end; end; end; procedure TTeeFuncEditor.BNoneClick(Sender: TObject); begin CBSingle.ItemIndex:=-1; CBSingleChange(Self); end; procedure TTeeFuncEditor.CBValuesChange(Sender: TObject); begin BApply.Enabled:=True; end; procedure TTeeFuncEditor.TeeEvent(Event: TTeeEvent); begin if not (csDestroying in ComponentState) then if Event is TTeeSeriesEvent then With TTeeSeriesEvent(Event) do Case Event of seRemove : if Series<>TheSeries then FillSeries else BApply.Enabled:=False; seAdd, seSwap: if Series<>TheSeries then FillSeries else BApply.Enabled:=False; end; end; procedure TTeeFuncEditor.FormDestroy(Sender: TObject); begin if Assigned(TheSeries) and Assigned(TheSeries.ParentChart) then {$IFNDEF CLR}TTeePanelAccess{$ENDIF}(TheSeries.ParentChart).RemoveListener(Self); inherited; end; procedure TTeeFuncEditor.Timer1Timer(Sender: TObject); begin // Force pagecontrol to re-show again our tab with the correct controls on it. // This must be done using a timer to delay until parent form is totally // visible. Anybody knows a better solution? Timer1.Enabled:=False; {$IFNDEF CLX} PageControl1.ActivePage:=nil; PageControl1.ActivePage:=TabOptions; {$ENDIF} end; end.
unit SMCnst; interface {Russian strings} const strMessage = 'Печать...'; strSaveChanges = 'Вы хотите сохранить внесенные изменения на сервере?'; strErrSaveChanges = 'Данные не удалось сохранить! Проверьте соединение с сервером и допустимость введенных данных.'; strDeleteWarning = 'Вы действительно хотите удалить таблицу %s?'; strEmptyWarning = 'Вы действительно хотите удалить данные из таблицы %s?'; const PopUpCaption: array[0..24] of string[33] = ('Добавить запись', 'Вставить запись', 'Редактировать запись', 'Удалить запись', '-', 'Печать ...', 'Экспорт данных ...', 'Фильтр ...', 'Поиск ...', '-', 'Сохранить изменения', 'Отменить изменения', 'Обновить данные', '-', 'Пометка/Разотметка записей', 'Пометить запись', 'Пометить все записи', '-', 'Разотметить запись', 'Разотметить все записи', '-', 'Сохранить расположение колонок', 'Восстановить расположение колонок', '-', 'Настройка...'); const //for TSMSetDBGridDialog SgbTitle = ' Заголовок '; SgbData = ' Данные '; STitleCaption = 'Название:'; STitleAlignment = 'Выравнивание:'; STitleColor = 'Цвет фона:'; STitleFont = 'Шрифт:'; SWidth = 'Ширина:'; SWidthFix = 'символов'; SAlignLeft = 'слева'; SAlignRight = 'справа'; SAlignCenter = 'по центру'; const //for TSMDBFilterDialog strEqual = 'равно'; strNonEqual = 'не равно'; strNonMore = 'не более'; strNonLess = 'не менее'; strLessThan = 'меньше чем'; strLargeThan = 'больше чем'; strExist = 'пусто'; strNonExist = 'не пусто'; strIn = 'в списке'; strBetween = 'между'; strOR = 'ИЛИ'; strAND = 'И'; strField = 'Поле'; strCondition = 'Условие'; strValue = 'Значение'; strAddCondition = ' Определите дополнительное условие:'; strSelection = ' Выбор записей по следующим условиям:'; strAddToList = 'Добавить в список'; strEditInList = 'Редактировать'; strDeleteFromList = 'Удалить из списка'; strTemplate = 'Шаблоны фильтров'; strFLoadFrom = 'Загрузить из...'; strFSaveAs = 'Сохранить как..'; strFDescription = 'Описание'; strFFileName = 'Имя файла'; strFCreate = 'Создан: %s'; strFModify = 'Модифицирован: %s'; strFProtect = 'Защита от перезаписи'; strFProtectErr = 'Файл защищен от записи!'; const //for SMDBNavigator SFirstRecord = 'Первая запись'; SPriorRecord = 'Предыдущая запись'; SNextRecord = 'Следующая запись'; SLastRecord = 'Последняя запись'; SInsertRecord = 'Вставка записи'; SCopyRecord = 'Копирование записи'; SDeleteRecord = 'Удаление записи'; SEditRecord = 'Редактирование записи'; SFilterRecord = 'Выборка записей'; SFindRecord = 'Поиск записи'; SPrintRecord = 'Печать записей'; SExportRecord = 'Экспорт записей'; SPostEdit = 'Сохранение изменений'; SCancelEdit = 'Отмена изменений'; SRefreshRecord = 'Обновление данных'; SChoice = 'Выбор данных'; SClear = 'Очистка данных'; SDeleteRecordQuestion = 'Удалить запись?'; SDeleteMultipleRecordsQuestion = 'Удалить все выбранные записи?'; SRecordNotFound = 'Запись не найдена'; SFirstName = 'Начало'; SPriorName = 'Пред.'; SNextName = 'След.'; SLastName = 'Конец'; SInsertName = 'Вставка'; SCopyName = 'Копирование'; SDeleteName = 'Удаление'; SEditName = 'Редактирование'; SFilterName = 'Фильтр'; SFindName = 'Поиск'; SPrintName = 'Печать'; SExportName = 'Экспорт'; SPostName = 'Сохранение'; SCancelName = 'Отмена'; SRefreshName = 'Обновление'; SChoiceName = 'Выбор'; SClearName = 'Сброс'; SBtnOk = '&OK'; SBtnCancel = 'О&тмена'; SBtnLoad = 'Загрузить'; SBtnSave = 'Сохранить'; SBtnCopy = 'Копировать'; SBtnPaste = 'Вставить'; SBtnClear = 'Очистить'; SRecNo = '№'; SRecOf = ' из '; const //for EditTyped etValidNumber = 'корректным числом'; etValidInteger = 'корректным целым числом'; etValidDateTime = 'корректной датой и временем'; etValidDate = 'корректной датой'; etValidTime = 'корректным временем'; etValid = 'корректным'; etIsNot = 'не является'; etOutOfRange = 'Значение %s не принадлежит диапазону %s..%s'; SPrevYear = 'Предыдущий год'; SNextYear = 'Следующий год|'; SPrevMonth = 'Предыдущий месяц|'; SNextMonth = 'Следующий месяц|'; SApplyAll = 'Применить всем'; implementation end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} ///<summary> /// This unit contains several <c>TDBXReader</c> implementations for the TParams /// class as well as the TDataSet and TClientDataSet components. These TDBXReader /// implementations allow the contents of these classes and components to be /// used as parameters for a <c>TDBXCommand</c>. DataSnap server methods support /// <c>TDBXReader</c> parameters. ///</summary> unit Data.DBXDBReaders; interface uses Data.DB, System.Classes, Data.DBXCommon, Data.DBXPlatform, Data.DBXCommonTable, System.SysUtils, Data.SqlTimSt, Data.FmtBcd, System.Generics.Collections ; type /// <summary>Not used directly by applications.</summary> TDBXParamsRow = class(TDBXRow) private [Weak]FParams: TParams; public constructor Create(Params: TParams); function CreateCustomValue(const ValueType: TDBXValueType): TDBXValue; override; ///<summary>Returns a string from the row in the Value parameter or sets IsNull to true.</summary> procedure GetWideString(DbxValue: TDBXWideStringValue; var Value: string; var IsNull: LongBool); override; ///<summary>Returns a LongBool from the row in the Value parameter or sets IsNull to true.</summary> procedure GetBoolean(DbxValue: TDBXBooleanValue; var Value: LongBool; var IsNull: LongBool); override; ///<summary>Returns a Byte from the row in the Value parameter or sets IsNull to true.</summary> procedure GetUInt8(DbxValue: TDBXUInt8Value; var Value: Byte; var IsNull: LongBool); override; ///<summary>Returns a ShortInt from the row in the Value parameter or sets IsNull to true.</summary> procedure GetInt8(DbxValue: TDBXInt8Value; var Value: ShortInt; var IsNull: LongBool); override; ///<summary>Returns a Word from the row in the Value parameter or sets IsNull to true.</summary> procedure GetUInt16(DbxValue: TDBXUInt16Value; var Value: Word; var IsNull: LongBool); override; ///<summary>Returns a SmallInt from the row in the Value parameter or sets IsNull to true.</summary> procedure GetInt16(DbxValue: TDBXInt16Value; var Value: SmallInt; var IsNull: LongBool); override; ///<summary>Returns an Integer from the row in the Value parameter or sets IsNull to true.</summary> procedure GetInt32(DbxValue: TDBXInt32Value; var Value: TInt32; var IsNull: LongBool); override; ///<summary>Returns an Int64 from the row in the Value parameter or sets IsNull to true.</summary> procedure GetInt64(DbxValue: TDBXInt64Value; var Value: Int64; var IsNull: LongBool); override; ///<summary>Returns a Single from the row in the Value parameter or sets IsNull to true.</summary> procedure GetSingle(DbxValue: TDBXSingleValue; var Value: Single; var IsNull: LongBool); override; ///<summary>Returns a Double from the row in the Value parameter or sets IsNull to true.</summary> procedure GetDouble(DbxValue: TDBXDoubleValue; var Value: Double; var IsNull: LongBool); override; ///<summary>Returns a PAnsiChar from the row in the AnsiStringBuilder parameter or sets IsNull to true.</summary> {$IFNDEF NEXTGEN} procedure GetAnsiString(DbxValue: TDBXAnsiStringValue; var AnsiStringBuilder: TDBXAnsiStringBuilder; var IsNull: LongBool); override; {$ENDIF !NEXTGEN} ///<summary>Returns a TDBXDate from the row in the Value parameter or sets IsNull to true.</summary> procedure GetDate(DbxValue: TDBXDateValue; var Value: TDBXDate; var IsNull: LongBool); override; ///<summary>Returns an array of byte from the row in the Buffer parameter, and the number /// of bytes copied into the Buffer in the ReturnLength parameter or sets IsNull to true.</summary> procedure GetBytes(DbxValue: TDBXByteArrayValue; Offset: Int64; const Buffer: TArray<Byte>; BufferOffset: Int64; Length: Int64; var ReturnLength: Int64; var IsNull: LongBool); override; ///<summary>Returns the DataSize from the row in the ByteLength parameter or sets IsNull to true.</summary> procedure GetByteLength(DbxValue: TDBXByteArrayValue; var ByteLength: Int64; var IsNull: LongBool); override; ///<summary>Returns a TDBXTime from the row in the Value parameter or sets IsNull to true.</summary> procedure GetTime(DbxValue: TDBXTimeValue; var Value: TDBXTime; var IsNull: LongBool); override; ///<summary>Returns a TBcd from the row in the Value parameter or sets IsNull to true.</summary> procedure GetBcd(DbxValue: TDBXBcdValue; var Value: TBcd; var IsNull: LongBool); override; ///<summary>Returns a TSQLTimeStamp from the row in the Value parameter or sets IsNull to true.</summary> procedure GetTimeStamp(DbxValue: TDBXTimeStampValue; var Value: TSQLTimeStamp; var IsNull: LongBool); override; ///<summary>Returns a TSQLTimeStampOffset from the row in the Value parameter or sets IsNull to true.</summary> procedure GetTimeStampOffset(DbxValue: TDBXTimeStampOffsetValue; var Value: TSQLTimeStampOffset; var IsNull: LongBool); override; ///<summary>Returns a TStream from the row in the Value parameter or sets IsNull to true.</summary> procedure GetStream(DbxValue: TDBXStreamValue; var Stream: TStream; var IsNull: LongBool); overload; override; ///<summary>Sets the param value to null.</summary> procedure SetNull(DbxValue: TDBXValue); override; ///<summary>Sets the param value to the string Value.</summary> procedure SetWideString(DbxValue: TDBXWideStringValue; const Value: string); override; ///<summary>Sets the param value to the Boolean Value.</summary> procedure SetBoolean(DbxValue: TDBXBooleanValue; Value: Boolean); override; ///<summary>Sets the param value to the Byte Value.</summary> procedure SetUInt8(DbxValue: TDBXUInt8Value; Value: Byte); override; ///<summary>Sets the param value to the ShortInt Value.</summary> procedure SetInt8(DbxValue: TDBXInt8Value; Value: ShortInt); override; ///<summary>Sets the param value to the Word Value.</summary> procedure SetUInt16(DbxValue: TDBXUInt16Value; Value: Word); override; ///<summary>Sets the param value to the SmallInt Value.</summary> procedure SetInt16(DbxValue: TDBXInt16Value; Value: SmallInt); override; ///<summary>Sets the param value to the Integer Value.</summary> procedure SetInt32(DbxValue: TDBXInt32Value; Value: TInt32); override; ///<summary>Sets the param value to the Int64 Value.</summary> procedure SetInt64(DbxValue: TDBXInt64Value; Value: Int64); override; ///<summary>Sets the param value to the Single Value.</summary> procedure SetSingle(DbxValue: TDBXSingleValue; Value: Single); override; ///<summary>Sets the param value to the Double Value.</summary> procedure SetDouble(DbxValue: TDBXDoubleValue; Value: Double); override; {$IFNDEF NEXTGEN} ///<summary>Sets the param value to the AnsiString Value.</summary> procedure SetAnsiString(DbxValue: TDBXAnsiStringValue; const Value: AnsiString); override; ///<summary>Sets the param value to the AnsiString Value.</summary> procedure SetString(DbxValue: TDBXAnsiStringValue; const Value: AnsiString); override; {$ELSE} procedure SetString(DbxValue: TDBXAnsiStringValue; const Value: string); override; {$ENDIF !NEXTGEN} ///<summary>Sets the param value to the TDBXDate Value.</summary> procedure SetDate(DbxValue: TDBXDateValue; Value: TDBXDate); override; ///<summary>Sets the param value to the TDBXTime Value.</summary> procedure SetTime(DbxValue: TDBXTimeValue; Value: TDBXTime); override; ///<summary>Sets the param value to the TBcd Value.</summary> procedure SetBCD(DbxValue: TDBXBcdValue; var Value: TBcd); override; ///<summary>Sets the param value to the TSQLTimeStamp Value unless the DataType /// of the DbxValue is TDBXDataTypes.DateTimeType. In that case, the field value /// is set to a TDateTime after converting Value. ///</summary> procedure SetTimestamp(DbxValue: TDBXTimeStampValue; var Value: TSQLTimeStamp); override; ///<summary>Sets the param value to the TSQLTimeStampOffset Value unless the DataType /// of the DbxValue is TDBXDataTypes.DateTimeType. In that case, the param value /// is set to a TDateTime after converting Value. ///</summary> procedure SetTimestampOffset(DbxValue: TDBXTimeStampOffsetValue; var Value: TSQLTimeStampOffset); override; ///<summary>Sets the param value to the TDBXStreamReader Value.</summary> procedure SetStream(DbxValue: TDBXStreamValue; StreamReader: TDBXStreamReader); override; procedure ValueSet(Value: TDBXWritableValue); override; procedure SetDynamicBytes(DbxValue: TDBXValue; Offset: Int64; const Buffer: TArray<Byte>; BufferOffset: Int64; Length: Int64); override; end; /// <summary>TDBXMemoryTable implements a database-independent /// dataset.</summary> TDBXMemoryTable = class(TDBXTable) private FIndex: Integer; FOrderByColumn: Integer; FName: string; FValueTypes: TDBXValueTypeArray; FValueRows: TList<TDBXWritableValueArray>; function CreateWritableValueArray: TDBXWritableValueArray; procedure ClearValues(AValues: TDBXWritableValueArray); procedure ClearValueTypes(AValueTypes: TDBXValueTypeArray); protected function GetTableCount: Integer; override; procedure OrderByColumn(Column: Integer); virtual; public procedure Close; override; constructor Create; destructor Destroy; override; procedure Insert; override; procedure Post; override; procedure Clear; override; function InBounds: Boolean; override; function Next: Boolean; override; function First: Boolean; override; procedure SetColumns(const Columns: TDBXValueTypeArray); override; function GetColumns: TDBXValueTypeArray; override; procedure SetDBXTableName(const AName: string); override; function GetDBXTableName: string; override; procedure AcceptChanges; override; function CreateTableView(const OrderByColumnName: string): TDBXTable; override; ///<summary>Checks whether the string key Value is in the Ordinal column.</summary> ///<returns>True if the string key is found and False otherwise</returns> function FindStringKey(const Ordinal: Integer; const Value: string): Boolean; override; end; TDBXCache = class private FOwnsValues: Boolean; FValueTypes: TDBXValueTypeArray; FValueRows: TList<TDBXWritableValueArray>; FInsertedRows: TList<TDBXWritableValueArray>; FDeletedRows: TList<TDBXWritableValueArray>; FUpdatedRows: TList<TDBXWritableValueArray>; procedure ClearChangeLog; procedure ClearValues(AValues: TDBXWritableValueArray); function CreateWritableValueArray: TDBXWritableValueArray; procedure ClearValueTypes(AValueTypes: TDBXValueTypeArray); public procedure AcceptChanges; procedure AddRow(ARow: TDBXWritableValueArray); procedure Clear; constructor Create; overload; constructor Create(AOwnsValues: Boolean); overload; procedure DeleteRow(AIndex: Integer); destructor Destroy; override; function GetColumns: TDBXValueTypeArray; procedure Insert(AIndex: Integer); procedure SetColumns(Columns: TDBXValueTypeArray); property DeletedRows: TList<TDBXWritableValueArray> read FDeletedRows; property InsertedRows: TList<TDBXWritableValueArray> read FInsertedRows; property OwnsValues: Boolean read FOwnsValues; property UpdatedRows: TList<TDBXWritableValueArray> read FUpdatedRows; property ValueRows: TList<TDBXWritableValueArray> read FValueRows; property ValueTypes: TDBXValueTypeArray read FValueTypes; end; TDBXTableStorage = class(TDBXTable) private FIndex: Integer; FName: string; FCache: TDBXCache; FOriginalRow: TDBXTableRow; FDeletedTable: TDBXTable; FInsertedTable: TDBXTable; FUpdatedTable: TDBXTable; procedure ClearValues(AValues: TDBXWritableValueArray); function CloneRow(const ARow: TDBXWritableValueArray): TDBXWritableValueArray; procedure AddRow(const ATable: TDBXTable; const ARow: TDBXWritableValueArray; const AClone: Boolean); procedure UpdateCurrentRow; protected function GetDeletedRows: TDBXTable; override; function GetInsertedRows: TDBXTable; override; function GetUpdatedRows: TDBXTable; override; function GetOriginalRow: TDBXTableRow; override; function GetTableCount: Integer; override; procedure OrderByColumn(Column: Integer); virtual; public procedure Close; override; constructor Create; overload; constructor Create(const AOwnsValues: Boolean); overload; destructor Destroy; override; procedure Insert; overload; override; procedure Insert(const AIndex: Integer); reintroduce; overload; procedure DeleteRow; overload; override; procedure DeleteRow(const AIndex: Integer); reintroduce; overload; function GetRow(const AIndex: Integer): TDBXWritableValueArray; function Edit: Boolean; override; procedure Cancel; override; procedure Post; override; procedure Clear; override; function InBounds: Boolean; override; function Next: Boolean; override; function First: Boolean; override; procedure SetColumns(const Columns: TDBXValueTypeArray); override; function GetColumns: TDBXValueTypeArray; override; procedure SetDBXTableName(const AName: string); override; function GetDBXTableName: string; override; procedure AcceptChanges; override; procedure CopyFrom(const Source: TDBXTable); override; function CreateTableView(const OrderByColumnName: string): TDBXTable; override; ///<summary>Checks whether the string key Value is in the Ordinal column.</summary> ///<returns>True if the string key is found and False otherwise</returns> function FindStringKey(const Ordinal: Integer; const Value: string): Boolean; override; end; /// <summary>Not used directly by applications.</summary> TDBXDBTable = class(TDBXRowTable) private FCollectionName: string; FValueTypes: TDBXValueTypeArray; ///<summary> TFieldType to DBX type mapper</summary> class function ToDataType(FieldType: TFieldType): Integer; static; ///<summary> TFieldType to DBX subtype mapper</summary> class function ToDataSubType(FieldType: TFieldType): Integer; static; class function ToFieldType(ValueType: TDBXValueType): TFieldType; static; class function ToDBXParameterDirection(ParameterType: TParamType): Integer; static; class function ToParameterType(ParameterDirection: Integer): TParamType; static; protected procedure FreeValueTypes; property ValueTypes: TDBXValueTypeArray read FValueTypes write FValueTypes; property CollectionName: string read FCollectionName; procedure SetDBXTableName(const CollectionName: string); override; function GetDBXTableName: string; override; end; /// <summary>TDBXTable implementation for TParams object used by /// TDBXParamsReader.</summary> TDBXParamsTable = class(TDBXDBTable) private FParams: TParams; FAtEnd: Boolean; FInstanceOwner: Boolean; class procedure CopyValueTypes(const ValueTypes: TDBXValueTypeArray; const Params: TParams); static; class procedure CopyValueType(Ordinal: Integer; ValueType: TDBXValueType; Param: TParam); static; protected function GetColumns: TDBXValueTypeArray; override; procedure SetColumns(const Columns: TDBXValueTypeArray); override; function GetStorage: TObject; override; public constructor Create; overload; constructor Create(Params: TParams; InstanceOwner: Boolean = true); overload; destructor Destroy; override; function First: Boolean; override; function Next: Boolean; override; function InBounds: Boolean; override; procedure Close; override; function GetOrdinal(const ColumnName: string): Integer; override; end; /// <summary>TDBXReader implementation for TParams object.</summary> TDBXParamsReader = class(TDBXTableReader) public /// <summary> /// Creates a <c>TDBXReader</c> for a <c>TParams</c> instance. If /// <c>InstanceOwner</c> is true, the <c>TParams</c> instance will be /// freed when this <c>TDBXParamsReader</c> instance is freed. /// </summary> constructor Create(Params: TParams; InstanceOwner: Boolean = true); /// <summary> /// Copies the contents of the current <c>Reader</c> row into the <c>Params</c> /// instance. /// </summary> class procedure CopyReaderToParams(Reader: TDBXReader; Params: TParams); static; /// <summary> /// Copies the contents of the current <c>Reader</c> row into a new <c>TParams</c> /// instance. The new <c>TParams</c> instance will constructed with the /// <c>AOwner</c> instance as its owner. /// </summary> class function ToParams(AOwner: TPersistent; Reader: TDBXReader; AOwnsInstance: Boolean): TParams; static; destructor Destroy; override; end; /// <summary>Not used directly by applications.</summary> TDBXDataSetRow = class(TDBXRow) private [Weak]FTable: TDataset; function EnsureEditState: Boolean; public constructor Create(Table: TDataset); ///<summary>Returns a TDBXWideStringBuiler from the row in the WideStringBuilder /// parameter or sets IsNull to true.</summary> procedure GetWideString(DbxValue: TDBXWideStringValue; var WideStringBuilder: TDBXWideStringBuilder; var IsNull: LongBool); override; ///<summary>Returns a LongBool from the row in the Value parameter or sets IsNull to true.</summary> procedure GetBoolean(DbxValue: TDBXBooleanValue; var Value: LongBool; var IsNull: LongBool); override; ///<summary>Returns a Byte from the row in the Value parameter or sets IsNull to true.</summary> procedure GetUInt8(DbxValue: TDBXUInt8Value; var Value: Byte; var IsNull: LongBool); override; ///<summary>Returns a ShortInt from the row in the Value parameter or sets IsNull to true.</summary> procedure GetInt8(DbxValue: TDBXInt8Value; var Value: ShortInt; var IsNull: LongBool); override; ///<summary>Returns a Word from the row in the Value parameter or sets IsNull to true.</summary> procedure GetUInt16(DbxValue: TDBXUInt16Value; var Value: Word; var IsNull: LongBool); override; ///<summary>Returns a SmallInt from the row in the Value parameter or sets IsNull to true.</summary> procedure GetInt16(DbxValue: TDBXInt16Value; var Value: SmallInt; var IsNull: LongBool); override; ///<summary>Returns an Integer from the row in the Value parameter or sets IsNull to true.</summary> procedure GetInt32(DbxValue: TDBXInt32Value; var Value: TInt32; var IsNull: LongBool); override; ///<summary>Returns an Int64 from the row in the Value parameter or sets IsNull to true.</summary> procedure GetInt64(DbxValue: TDBXInt64Value; var Value: Int64; var IsNull: LongBool); override; ///<summary>Returns a Single from the row in the Value parameter or sets IsNull to true.</summary> procedure GetSingle(DbxValue: TDBXSingleValue; var Value: Single; var IsNull: LongBool); override; ///<summary>Returns a Double from the row in the Value parameter or sets IsNull to true.</summary> procedure GetDouble(DbxValue: TDBXDoubleValue; var Value: Double; var IsNull: LongBool); override; ///<summary>Returns a PAnsiChar from the row in the AnsiStringBuilder parameter /// or sets IsNull to true.</summary> procedure GetAnsiString(DbxValue: TDBXAnsiStringValue; var AnsiStringBuilder: TDBXAnsiStringBuilder; var IsNull: LongBool); override; ///<summary>Returns a TDBXDate from the row in the Value parameter or sets IsNull to true.</summary> procedure GetDate(DbxValue: TDBXDateValue; var Value: TDBXDate; var IsNull: LongBool); override; ///<summary>Returns a TDBXTime from the row in the Value parameter or sets IsNull to true.</summary> procedure GetTime(DbxValue: TDBXTimeValue; var Value: TDBXTime; var IsNull: LongBool); override; ///<summary>Returns a TSQLTimeStamp from the row in the Value parameter or sets IsNull to true.</summary> procedure GetTimeStamp(DbxValue: TDBXTimeStampValue; var Value: TSQLTimeStamp; var IsNull: LongBool); override; ///<summary>Returns a TSQLTimeStampOffset from the row in the Value parameter or sets IsNull to true.</summary> procedure GetTimeStampOffset(DbxValue: TDBXTimeStampOffsetValue; var Value: TSQLTimeStampOffset; var IsNull: LongBool); override; ///<summary>Returns a TBcd from the row in the Value parameter or sets IsNull to true.</summary> procedure GetBcd(DbxValue: TDBXBcdValue; var Value: TBcd; var IsNull: LongBool); override; ///<summary>Returns an array of byte from the row in the Buffer parameter, and the number /// of bytes copied into the Buffer in the ReturnLength parameter or sets IsNull to true. ///</summary> procedure GetBytes(DbxValue: TDBXByteArrayValue; Offset: Int64; const Buffer: TArray<Byte>; BufferOffset: Int64; Length: Int64; var ReturnLength: Int64; var IsNull: LongBool); override; ///<summary>Returns the DataSize or the BlobSize from the row in the ByteLength /// parameter or sets IsNull to true.</summary> procedure GetByteLength(DbxValue: TDBXByteArrayValue; var ByteLength: Int64; var IsNull: LongBool); override; ///<summary>Returns a TStream from the row in the Stream parameter or sets IsNull to true.</summary> procedure GetStream(DbxValue: TDBXStreamValue; var Stream: TStream; var IsNull: LongBool); overload; override; ///<summary>Sets the field value to null.</summary> procedure SetNull(DbxValue: TDBXValue); override; ///<summary>Sets the field value to the string Value.</summary> procedure SetWideString(DbxValue: TDBXWideStringValue; const Value: string); override; ///<summary>Sets the field value to the Boolean Value.</summary> procedure SetBoolean(DbxValue: TDBXBooleanValue; Value: Boolean); override; ///<summary>Sets the field value to the Byte Value.</summary> procedure SetUInt8(DbxValue: TDBXUInt8Value; Value: Byte); override; ///<summary>Sets the field value to the ShortInt Value.</summary> procedure SetInt8(DbxValue: TDBXInt8Value; Value: ShortInt); override; ///<summary>Sets the field value to the Word Value.</summary> procedure SetUInt16(DbxValue: TDBXUInt16Value; Value: Word); override; ///<summary>Sets the field value to the SmallInt Value.</summary> procedure SetInt16(DbxValue: TDBXInt16Value; Value: SmallInt); override; ///<summary>Sets the field value to the Integer Value.</summary> procedure SetInt32(DbxValue: TDBXInt32Value; Value: TInt32); override; ///<summary>Sets the field value to the Int64 Value.</summary> procedure SetInt64(DbxValue: TDBXInt64Value; Value: Int64); override; ///<summary>Sets the field value to the Single Value.</summary> procedure SetSingle(DbxValue: TDBXSingleValue; Value: Single); override; ///<summary>Sets the field value to the Double Value.</summary> procedure SetDouble(DbxValue: TDBXDoubleValue; Value: Double); override; {$IFNDEF NEXTGEN} ///<summary>Sets the field value to AnsiString Value.</summary> procedure SetAnsiString(DbxValue: TDBXAnsiStringValue; const Value: AnsiString); override; ///<summary>Sets the field value to the Value.</summary> procedure SetString(DbxValue: TDBXAnsiStringValue; const Value: AnsiString); override; {$ELSE} procedure SetString(DbxValue: TDBXAnsiStringValue; const Value: string); override; {$ENDIF !NEXTGEN} ///<summary>Sets the field value to a TDateTime after converting Value.</summary> procedure SetDate(DbxValue: TDBXDateValue; Value: TDBXDate); override; ///<summary>Sets the field value to a TDateTime after converting Value.</summary> procedure SetTime(DbxValue: TDBXTimeValue; Value: TDBXTime); override; ///<summary>Sets the field value to the TBcd Value.</summary> procedure SetBCD(DbxValue: TDBXBcdValue; var Value: TBcd); override; procedure SetStream(DbxValue: TDBXStreamValue; StreamReader: TDBXStreamReader); override; procedure SetDynamicBytes(DbxValue: TDBXValue; Offset: Int64; const Buffer: TArray<Byte>; BufferOffset: Int64; Length: Int64); override; ///<summary>Sets the field value to the TSQLTimeStamp Value unless the DataType /// of the DbxValue is TDBXDataTypes.DateTimeType. In that case, the field value /// is set to a TDateTime after converting Value. ///</summary> procedure SetTimestamp(DbxValue: TDBXTimeStampValue; var Value: TSQLTimeStamp); override; ///<summary>Sets the field value to the TSQLTimeStampOffset Value unless the DataType /// of the DbxValue is TDBXDataTypes.DateTimeType. In that case, the field value /// is set to a TDateTime after converting Value. ///</summary> procedure SetTimestampOffset(DbxValue: TDBXTimeStampOffsetValue; var Value: TSQLTimeStampOffset); override; procedure ValueSet(Value: TDBXWritableValue); override; end; /// <summary>TDBXTable implementation for TParams.</summary> TDBXDataSetTable = class(TDBXDBTable) private FOwnsTable: Boolean; FTable: TDataset; protected constructor Create(const CollectionName: string; Table: TDataset; OwnsTable: Boolean; ValuesNeedCreate: Boolean); overload; property Table: TDataset read FTable; procedure SkipOriginalRow; virtual; procedure SetDBXTableName(const CollectionName: string); override; function GetDBXTableName: string; override; function GetColumns: TDBXValueTypeArray; override; function GetStorage: TObject; override; function GetDataSize(FieldDef: TFieldDef; Field: TField): Integer; public constructor Create(Dataset: TDataset; InstanceOwner: Boolean = true); overload; destructor Destroy; override; function First: Boolean; override; function Next: Boolean; override; function InBounds: Boolean; override; procedure Insert; override; procedure Post; override; procedure DeleteRow; override; procedure Close; override; function GetOrdinal(const ColumnName: string): Integer; override; procedure FailIfRowIsNew; procedure CopyValueTypeProperties(FieldDef: TFieldDef; ValueType: TDBXValueType; Ordinal: Integer); end; /// <summary>TDBXReader implementation for TDataSet object.</summary> TDBXDataSetReader = class(TDBXTableReader) public /// <summary> /// Creates a <c>TDBXReader</c> for a <c>TDataSet</c> instance. If /// <c>InstanceOwner</c> is true, the <c>TDataSet</c> instance will be /// freed when this <c>TDBXDataSetReader</c> instance is freed. /// </summary> constructor Create(Params: TDataset; InstanceOwner: Boolean = true); overload; virtual; constructor Create(Params: TDBXDataSetTable); overload; end; implementation uses System.Variants, System.Generics.Defaults, System.JSON, Data.DBXJSON, Data.DBXCommonResStrs ; type TDBXMemoryValue = class(TDBXWritableValue) private FValue: TDBXWritableValue; FOriginalValue: TDBXWritableValue; FInitialized: Boolean; // FOwner: TDBXCache; public procedure SetOriginal; procedure ClearOriginal; procedure Cancel; procedure AcceptChanges; constructor Create(const AOriginalValue: TDBXWritableValue{; Owner: TDBXCache}); destructor Destroy; override; function GetValueSize: Int64; override; {$IFNDEF NEXTGEN} function GetAnsiString: AnsiString; override; {$ENDIF !NEXTGEN} function GetDate: TDBXDate; override; function GetBoolean: Boolean; override; function GetTime: TDBXTime; override; function GetWideString: string; override; function GetString: string; override; function GetUInt8: Byte; override; function GetInt8: ShortInt; override; function GetUInt16: Word; override; function GetInt16: SmallInt; override; function GetInt32: TInt32; override; function GetInt64: Int64; override; function GetSingle: Single; override; function GetDouble: Double; override; function GetBytes(Offset: Int64; const Buffer: TArray<Byte>; BufferOffset, Length: Int64): Int64; override; function GetTimeStamp: TSQLTimeStamp; override; function GetTimeStampOffset: TSQLTimeStampOffset; override; function GetBcd: TBcd; override; function GetDBXReader(AInstanceOwner: Boolean): TDBXReader; override; function GetDBXReader: TDBXReader; override; function GetDBXConnection: TDBXConnection; override; function GetStream(AInstanceOwner: Boolean): TStream; override; function GetStream: TStream; override; function GetJSONValue: TJSONValue; override; function GetJSONValue(AInstanceOwner: Boolean): TJSONValue; override; function GetCallbackValue: TDBXCallback; override; function GetObjectValue: TObject; override; function GetObjectValue(AInstanceOwner: Boolean): TObject; override; function GetWideString(defaultValue: string): string; override; function GetBoolean(defaultValue: Boolean): Boolean; override; function GetUInt8(defaultValue: Byte): Byte; override; function GetInt8(defaultValue: Shortint): Shortint; override; function GetUInt16(defaultValue: Word): Word; override; function GetInt16(defaultValue: Smallint): Smallint; override; function GetInt32(defaultValue: TInt32): TInt32; override; function GetInt64(defaultValue: Int64): Int64; override; function EqualsValue(Other: TDBXValue): Boolean; override; function Compare(Other: TDBXValue): Smallint; override; function IsNull: Boolean; override; procedure SetNull; override; procedure SetTimeStamp(const Value: TSQLTimeStamp); override; procedure SetTimeStampOffset(const Value: TSQLTimeStampOffset); override; procedure SetBcd(const Value: TBcd); override; {$IFNDEF NEXTGEN} procedure SetAnsiString(const Value: AnsiString); override; {$ENDIF !NEXTGEN} procedure SetBoolean(const Value: Boolean); override; procedure SetDate(const Value: TDBXDate); override; procedure SetTime(const Value: TDBXTime); override; procedure SetWideString(const Value: string); override; procedure SetString(const Value: string); override; procedure SetUInt8(const Value: Byte); override; procedure SetInt8(const Value: ShortInt); override; procedure SetUInt16(const Value: Word); override; procedure SetInt16(const Value: SmallInt); override; procedure SetInt32(const Value: TInt32); override; procedure SetInt64(const Value: Int64); override; procedure SetSingle(const Value: Single); override; procedure SetDouble(const Value: Double); override; procedure SetStaticBytes( Offset: Int64; const Buffer: array of Byte; BufferOffset: Int64; Length: Int64); override; procedure SetDynamicBytes( Offset: Int64; const Buffer: TArray<Byte>; BufferOffset: Int64; Length: Int64); override; procedure SetDBXReader(const Value: TDBXReader; const AInstanceOwner: Boolean); overload; override; procedure SetStream(const Stream: TStream; const AInstanceOwner: Boolean); override; procedure SetDBXConnection(const Value: TDBXConnection); override; procedure SetJSONValue(const Value: TJSONValue; const AInstanceOwner: Boolean); override; procedure SetObjectValue(const Value: TObject; const AInstanceOwner: Boolean); override; procedure SetCallbackValue(const Value: TDBXCallback); override; procedure SetValue(const Value: TDBXValue); override; end; TDBXWritableValueArrayComparer = class(TInterfacedObject, IComparer<TDBXWritableValueArray>) private FColumnIndex: Integer; public constructor Create(AColumnIndex: Integer); function Compare(const Left, Right: TDBXWritableValueArray): Integer; overload; class function CompareArrays(const Left, Right: TDBXWritableValueArray): Boolean; overload; property ColumnIndex: Integer read FColumnIndex; class function FindStringKey(const AValuesList: TList<TDBXWritableValueArray>; const Ordinal: Integer; const Value: string): Integer; end; { TDBXDataSetTable } constructor TDBXDataSetTable.Create(const CollectionName: string; Table: TDataSet; OwnsTable: Boolean; ValuesNeedCreate: Boolean); begin inherited Create(nil, TDBXDataSetRow.Create(Table)); FTable := Table; FCollectionName := CollectionName; FOwnsTable := OwnsTable; if ValuesNeedCreate then CreateValues; end; destructor TDBXDataSetTable.Destroy; begin if FOwnsTable then FreeAndNil(FTable); FreeValueTypes; inherited Destroy; end; function TDBXDataSetTable.First: Boolean; begin RowNavigated; // Some implementations don't support this. // if FTable.IsUniDirectional then Result := not FTable.IsEmpty else begin FTable.First; SkipOriginalRow; Result := FTable.RecordCount > 0; end; end; function TDBXDataSetTable.Next: Boolean; begin FailIfRowIsNew(); FTable.Next; SkipOriginalRow; RowNavigated; Result := not FTable.Eof; end; function TDBXDataSetTable.InBounds: Boolean; begin FailIfRowIsNew(); Result := not FTable.Eof and (FTable.RecordCount > 0); // if Result and FTable.Bof then // FTable.Next; end; procedure TDBXDataSetTable.Insert; begin FailIfRowIsNew(); FTable.Append; end; procedure TDBXDataSetTable.Post; begin if FTable.State <> dsInsert then raise TDBXError.Create(SInsertNotCalled); FTable.Post; end; procedure TDBXDataSetTable.DeleteRow; begin if FTable.State = dsInsert then FTable.Cancel else FTable.Delete; end; procedure TDBXDataSetTable.Close; begin Clear; end; function TDBXDataSetTable.GetOrdinal(const ColumnName: string): Integer; var FieldDef: TFieldDef; begin FieldDef := FTable.FieldDefs.Find(ColumnName); Result := FieldDef.FieldNo - 1; end; function TDBXDataSetTable.GetDataSize(FieldDef: TFieldDef; Field: TField): Integer; begin case FieldDef.DataType of ftVarBytes: Result := Field.DataSize - sizeof(Word); else if Field is TBlobField then Result := (Field as TBlobField).BlobSize else Result := Field.DataSize; end; end; function TDBXDataSetTable.GetDBXTableName: string; begin Result := FCollectionName; end; procedure TDBXDataSetTable.SetDBXTableName(const CollectionName: string); begin FCollectionName := CollectionName; end; procedure TDBXDataSetTable.SkipOriginalRow; begin end; function TDBXDataSetTable.GetColumns: TDBXValueTypeArray; var Ordinal: Integer; FieldDef: TFieldDef; ValueType: TDBXValueType; Field: TField; begin if FValueTypes = nil then begin SetLength(FValueTypes, FTable.FieldDefs.Count); for Ordinal := Low(FValueTypes) to High(FValueTypes) do begin FieldDef := FTable.FieldDefs[Ordinal]; Field := FTable.Fields[Ordinal]; ValueType := TDBXValueType.Create; ValueType.Name := FieldDef.Name; ValueType.DisplayName := FieldDef.DisplayName; ValueType.DataType := ToDataType(FieldDef.DataType); ValueType.SubType := ToDataSubType(FieldDef.DataType); ValueType.Size := GetDataSize(FieldDef, Field); ValueType.Precision := FieldDef.Precision; if ValueType.Precision = 0 then case ValueType.DataType of TDBXDataTypes.WideStringType, TDBXDataTypes.BlobType: ValueType.Precision := ValueType.Size; end; ValueType.Scale := FieldDef.Size; ValueType.Nullable := not FieldDef.Required; FValueTypes[Ordinal] := ValueType; end; end; Result := FValueTypes; end; function TDBXDataSetTable.GetStorage: TObject; begin Result := FTable; end; procedure TDBXDataSetTable.FailIfRowIsNew; begin if FTable.State = dsInsert then raise TDBXError.Create(SPostNotCalled); end; procedure TDBXDataSetTable.CopyValueTypeProperties(FieldDef: TFieldDef; ValueType: TDBXValueType; Ordinal: Integer); begin FieldDef.Name := ValueType.Name; FieldDef.DisplayName := ValueType.DisplayName; FieldDef.DataType := ToFieldType(ValueType); FieldDef.FieldNo := Ordinal; if (ValueType.DataType = TDBXDataTypes.WideStringType) or (ValueType.DataType = TDBXDataTypes.AnsiStringType) then begin if ValueType.Size <= 0 then FieldDef.Size := 128 // default size (make constant) else FieldDef.Size := ValueType.Size; end; // Don't set the size. It is error prone and not neccessary: // FieldDef.Size := Descriptor.DataSize; // Don't set the hidden attribute. Field access is forbidden to hidden fields !! // if Descriptor.Hidden then // FieldDef.Attributes := FieldDef.Attributes + [faHiddenCol]; end; constructor TDBXDataSetTable.Create(Dataset: TDataSet; InstanceOwner: Boolean); begin Create('', DataSet, InstanceOwner, true); end; { TDBXDataSetRow } constructor TDBXDataSetRow.Create(Table: TDataSet); begin inherited Create(nil); FTable := Table; end; procedure TDBXDataSetRow.GetBoolean(DbxValue: TDBXBooleanValue; var Value, IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := Field.AsBoolean; end; procedure TDBXDataSetRow.GetInt16(DbxValue: TDBXInt16Value; var Value: SmallInt; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := Field.Value; end; procedure TDBXDataSetRow.GetInt32(DbxValue: TDBXInt32Value; var Value: TInt32; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := Field.AsInteger; end; procedure TDBXDataSetRow.GetInt64(DbxValue: TDBXInt64Value; var Value: Int64; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := Field.Value; end; procedure TDBXDataSetRow.GetInt8(DbxValue: TDBXInt8Value; var Value: ShortInt; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := Field.Value; end; procedure TDBXDataSetRow.GetDouble(DbxValue: TDBXDoubleValue; var Value: Double; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := Field.Value; end; procedure TDBXDataSetRow.GetWideString(DbxValue: TDBXWideStringValue; var WideStringBuilder: TDBXWideStringBuilder; var IsNull: LongBool); var Field: TField; Value: string; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then begin Value := Field.AsWideString; TDBXPlatform.CopyWideStringToBuilder(Value, Value.Length+1, WideStringBuilder); end; end; procedure TDBXDataSetRow.GetAnsiString(DbxValue: TDBXAnsiStringValue; var AnsiStringBuilder: TDBXAnsiStringBuilder; var IsNull: LongBool); var Field: TField; {$IFNDEF NEXTGEN} Value: AnsiString; {$ELSE} Value: string; {$ENDIF} begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then begin {$IFNDEF NEXTGEN} Value := Field.AsAnsiString; {$ELSE} Value := Field.AsString; {$ENDIF} TDBXPlatform.CopyStringToBuilder(Value, Length(Value)+1, AnsiStringBuilder); end; end; procedure TDBXDataSetRow.GetDate(DbxValue: TDBXDateValue; var Value: TDBXDate; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := DateTimeToTimeStamp(Field.AsDateTime).Date; end; procedure TDBXDataSetRow.GetTime(DbxValue: TDBXTimeValue; var Value: TDBXTime; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := DateTimeToTimeStamp(Field.AsDateTime).Time; end; procedure TDBXDataSetRow.GetTimeStamp(DbxValue: TDBXTimeStampValue; var Value: TSQLTimeStamp; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := Field.AsSQLTimeStamp; end; procedure TDBXDataSetRow.GetTimeStampOffset(DbxValue: TDBXTimeStampOffsetValue; var Value: TSQLTimeStampOffset; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := Field.AsSQLTimeStampOffset; end; procedure TDBXDataSetRow.GetUInt16(DbxValue: TDBXUInt16Value; var Value: Word; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := Field.Value; end; procedure TDBXDataSetRow.GetUInt8(DbxValue: TDBXUInt8Value; var Value: Byte; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := Field.Value; end; procedure TDBXDataSetRow.GetBcd(DbxValue: TDBXBcdValue; var Value: TBcd; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := Field.AsBCD; end; procedure TDBXDataSetRow.GetBytes(DbxValue: TDBXByteArrayValue; Offset: Int64; const Buffer: TArray<Byte>; BufferOffset: Int64; Length: Int64; var ReturnLength: Int64; var IsNull: LongBool); var Field: TField; DataSize: Integer; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then begin if Field is TBlobField then DataSize := (Field as TBlobField).BlobSize else DataSize := Field.DataSize; if Length + BufferOffset > DataSize then ReturnLength := DataSize - BufferOffset else ReturnLength := Length; Move(Field.AsBytes[0], Buffer[BufferOffset], ReturnLength); end; end; procedure TDBXDataSetRow.GetByteLength(DbxValue: TDBXByteArrayValue; var ByteLength: Int64; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then if Field is TBlobField then ByteLength := (Field as TBlobField).BlobSize else ByteLength := Field.DataSize; end; procedure TDBXDataSetRow.GetSingle(DbxValue: TDBXSingleValue; var Value: Single; var IsNull: LongBool); var Field: TField; begin Field := FTable.Fields[DbxValue.ValueType.Ordinal]; IsNull := Field.IsNull; if not IsNull then Value := Field.Value; end; procedure TDBXDataSetRow.GetStream(DbxValue: TDBXStreamValue; var Stream: TStream; var IsNull: LongBool); var ByteLength: Int64; Bytes: TArray<Byte>; ReturnLength: Int64; begin GetByteLength(DbxValue, ByteLength, IsNull); if not IsNull then begin SetLength(Bytes, Integer(ByteLength)); GetBytes(DbxValue, 0, Bytes, 0, Integer(ByteLength), ReturnLength, IsNull); Stream := TBytesStream.Create(Bytes); end; end; procedure TDBXDataSetRow.SetBoolean(DbxValue: TDBXBooleanValue; Value: Boolean); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXDataSetRow.SetInt16(DbxValue: TDBXInt16Value; Value: SmallInt); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXDataSetRow.SetInt32(DbxValue: TDBXInt32Value; Value: TInt32); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXDataSetRow.SetInt64(DbxValue: TDBXInt64Value; Value: Int64); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXDataSetRow.SetInt8(DbxValue: TDBXInt8Value; Value: ShortInt); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXDataSetRow.SetDouble(DbxValue: TDBXDoubleValue; Value: Double); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXDataSetRow.SetNull(DbxValue: TDBXValue); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Null; end; procedure TDBXDataSetRow.SetSingle(DbxValue: TDBXSingleValue; Value: Single); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXDataSetRow.SetStream(DbxValue: TDBXStreamValue; StreamReader: TDBXStreamReader); var LData: TArray<Byte>; LRead: Integer; LTotalRead: Integer; const sMaxRead = 32000; begin EnsureEditState; if StreamReader.Size > 0 then begin SetLength(LData, StreamReader.Size); LTotalRead := StreamReader.Read(LData, 0, StreamReader.Size); if LTotalRead < StreamReader.Size then SetLength(LData, LTotalRead); end else begin LTotalRead := 0; while not StreamReader.Eos do begin SetLength(LData, sMaxRead+LTotalRead); LRead := StreamReader.Read(LData, LTotalRead, sMaxRead); if LRead < sMaxRead then SetLength(LData, LTotalRead + LRead); LTotalRead := LTotalRead + LRead; end; end; FTable.Fields[DbxValue.ValueType.Ordinal].AsBytes := LData; end; {$IFNDEF NEXTGEN} procedure TDBXDataSetRow.SetAnsiString(DbxValue: TDBXAnsiStringValue; const Value: AnsiString); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXDataSetRow.SetString(DbxValue: TDBXAnsiStringValue; const Value: AnsiString); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value; end; {$ELSE} procedure TDBXDataSetRow.SetString(DbxValue: TDBXAnsiStringValue; const Value: string); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value; end; {$ENDIF !NEXTGEN} procedure TDBXDataSetRow.SetWideString(DbxValue: TDBXWideStringValue; const Value: string); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXDataSetRow.SetDate(DbxValue: TDBXDateValue; Value: TDBXDate); var TimeStamp: TTimeStamp; begin TimeStamp.Date := Value; TimeStamp.Time := 0; EnsureEditState; FTable.Fields[DBXValue.ValueType.Ordinal].AsDateTime := TimeStampToDateTime(TimeStamp); end; procedure TDBXDataSetRow.SetTime(DbxValue: TDBXTimeValue; Value: TDBXTime); var TimeStamp: TTimeStamp; begin TimeStamp.Date := DateDelta; TimeStamp.Time := Value; EnsureEditState; FTable.Fields[DBXValue.ValueType.Ordinal].AsDateTime := TimeStampToDateTime(TimeStamp); end; procedure TDBXDataSetRow.SetTimestamp(DbxValue: TDBXTimeStampValue; var Value: TSQLTimeStamp); begin EnsureEditState; if DbxValue.ValueType.DataType = TDBXDataTypes.DateTimeType then FTable.Fields[DBXValue.ValueType.Ordinal].AsDateTime := SQLTimeStampToDateTime(Value) else FTable.Fields[DbxValue.ValueType.Ordinal].AsSQLTimeStamp := Value; end; procedure TDBXDataSetRow.SetTimestampOffset(DbxValue: TDBXTimeStampOffsetValue; var Value: TSQLTimeStampOffset); begin EnsureEditState; if DbxValue.ValueType.DataType = TDBXDataTypes.DateTimeType then FTable.Fields[DBXValue.ValueType.Ordinal].AsDateTime := SQLTimeStampOffsetToDateTime(Value) else FTable.Fields[DbxValue.ValueType.Ordinal].AsSQLTimeStampOffset := Value; end; procedure TDBXDataSetRow.SetUInt16(DbxValue: TDBXUInt16Value; Value: Word); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXDataSetRow.SetUInt8(DbxValue: TDBXUInt8Value; Value: Byte); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXDataSetRow.SetBCD(DbxValue: TDBXBcdValue; var Value: TBcd); begin EnsureEditState; FTable.Fields[DbxValue.ValueType.Ordinal].AsBCD := Value; end; procedure TDBXDataSetRow.SetDynamicBytes(DbxValue: TDBXValue; Offset: Int64; const Buffer: TArray<Byte>; BufferOffset, Length: Int64); var LData: TArray<Byte>; begin EnsureEditState; SetLength(LData, Length); TDBXPlatform.CopyByteArray(Buffer, BufferOffset, LData, 0, Length); if FTable.Fields[DbxValue.ValueType.Ordinal].DataType = ftString then FTable.Fields[DbxValue.ValueType.Ordinal].AsString := TMarshal.ReadStringAsAnsi(TPtrWrapper.Create(LData), Length) else FTable.Fields[DbxValue.ValueType.Ordinal].AsBytes := LData; end; procedure TDBXDataSetRow.ValueSet(Value: TDBXWritableValue); begin TDBXDriverHelp.SetPendingValue(Value); end; function TDBXDataSetRow.EnsureEditState: Boolean; begin Result := False; if not(FTable.State in dsEditModes) then begin FTable.Edit; Result := True; end; end; constructor TDBXParamsRow.Create(Params: TParams); begin inherited Create(nil); FParams := Params; end; function TDBXParamsRow.CreateCustomValue(const ValueType: TDBXValueType): TDBXValue; begin Result := nil; case ValueType.DataType of TDBXDataTypes.WideStringType: Result := TDBXStringValue.Create(ValueType); // TDBXDataTypes.AnsiStringType: // Result := TDBXAnsiCharsValue.Create(ValueType); TDBXDataTypes.BlobType: case ValueType.SubType of TDBXDataTypes.HMemoSubType, TDBXDataTypes.MemoSubType, TDBXDataTypes.WideMemoSubType: Result := TDBXStringValue.Create(ValueType); end; end; end; procedure TDBXParamsRow.GetBoolean(DbxValue: TDBXBooleanValue; var Value, IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then Value := Param.AsBoolean; end; procedure TDBXParamsRow.GetInt16(DbxValue: TDBXInt16Value; var Value: SmallInt; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then Value := Param.Value; end; procedure TDBXParamsRow.GetInt32(DbxValue: TDBXInt32Value; var Value: TInt32; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then Value := Param.AsInteger; end; procedure TDBXParamsRow.GetInt64(DbxValue: TDBXInt64Value; var Value: Int64; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then Value := Param.Value; end; procedure TDBXParamsRow.GetInt8(DbxValue: TDBXInt8Value; var Value: ShortInt; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then Value := Param.Value; end; procedure TDBXParamsRow.GetSingle(DbxValue: TDBXSingleValue; var Value: Single; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then Value := Param.Value; end; procedure TDBXParamsRow.GetStream(DbxValue: TDBXStreamValue; var Stream: TStream; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then begin Stream := Param.AsStream; // release ownership. Row implementations should not // maintain ownership of objects. // Param.SetStream(Stream, False); end; end; procedure TDBXParamsRow.GetDouble(DbxValue: TDBXDoubleValue; var Value: Double; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then Value := Param.Value; end; procedure TDBXParamsRow.GetWideString(DbxValue: TDBXWideStringValue; var Value: string; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then Value := Param.AsWideString else Value := ''; end; {$IFNDEF NEXTGEN} procedure TDBXParamsRow.GetAnsiString(DbxValue: TDBXAnsiStringValue; var AnsiStringBuilder: TDBXAnsiStringBuilder; var IsNull: LongBool); var Param: TParam; Value: AnsiString; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then begin Value := Param.AsAnsiString; TDBXPlatform.CopyStringToBuilder(Value, Length(Value)+1, AnsiStringBuilder); end; end; {$ENDIF !NEXTGEN} procedure TDBXParamsRow.GetDate(DbxValue: TDBXDateValue; var Value: TDBXDate; var IsNull: LongBool); var Param: TParam; LValue: Variant; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then begin LValue := Param.Value; case VarType(LValue) of varDate, varDouble: Value := DateTimeToTimeStamp(LValue).Date else Value := LValue; end; end; end; procedure TDBXParamsRow.GetTime(DbxValue: TDBXTimeValue; var Value: TDBXTime; var IsNull: LongBool); var Param: TParam; LValue: Variant; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then begin LValue := Param.Value; case VarType(LValue) of varDate, varDouble: Value := DateTimeToTimeStamp(LValue).Time else Value := LValue; end; end; end; procedure TDBXParamsRow.GetTimeStamp(DbxValue: TDBXTimeStampValue; var Value: TSQLTimeStamp; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then Value := Param.AsSQLTimeStamp; end; procedure TDBXParamsRow.GetTimeStampOffset(DbxValue: TDBXTimeStampOffsetValue; var Value: TSQLTimeStampOffset; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then Value := Param.AsSQLTimeStampOffset; end; procedure TDBXParamsRow.GetUInt16(DbxValue: TDBXUInt16Value; var Value: Word; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then Value := Param.Value; end; procedure TDBXParamsRow.GetUInt8(DbxValue: TDBXUInt8Value; var Value: Byte; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then Value := Param.Value; end; procedure TDBXParamsRow.GetBcd(DbxValue: TDBXBcdValue; var Value: TBcd; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then Value := Param.AsFMTBCD; end; procedure TDBXParamsRow.GetBytes(DbxValue: TDBXByteArrayValue; Offset: Int64; const Buffer: TArray<Byte>; BufferOffset: Int64; Length: Int64; var ReturnLength: Int64; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then begin if Length + BufferOffset > Param.GetDataSize then ReturnLength := Param.GetDataSize - BufferOffset else ReturnLength := Length; Move(Param.AsBytes[0], Buffer[BufferOffset], ReturnLength); end; end; procedure TDBXParamsRow.GetByteLength(DbxValue: TDBXByteArrayValue; var ByteLength: Int64; var IsNull: LongBool); var Param: TParam; begin Param := FParams[DbxValue.ValueType.Ordinal]; IsNull := Param.IsNull; if not IsNull then ByteLength := Param.GetDataSize; end; procedure TDBXParamsRow.SetBoolean(DbxValue: TDBXBooleanValue; Value: Boolean); begin FParams[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXParamsRow.SetInt16(DbxValue: TDBXInt16Value; Value: SmallInt); begin FParams[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXParamsRow.SetInt32(DbxValue: TDBXInt32Value; Value: TInt32); begin FParams[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXParamsRow.SetInt64(DbxValue: TDBXInt64Value; Value: Int64); begin FParams[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXParamsRow.SetInt8(DbxValue: TDBXInt8Value; Value: ShortInt); begin FParams[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXParamsRow.SetDouble(DbxValue: TDBXDoubleValue; Value: Double); begin FParams[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXParamsRow.SetDynamicBytes(DbxValue: TDBXValue; Offset: Int64; const Buffer: TArray<Byte>; BufferOffset, Length: Int64); var LData: TArray<Byte>; begin SetLength(LData, Length); TDBXPlatform.CopyByteArray(Buffer, BufferOffset, LData, 0, Length); if FParams[DbxValue.ValueType.Ordinal].DataType = ftString then FParams[DbxValue.ValueType.Ordinal].Value := TMarshal.ReadStringAsAnsi(TPtrWrapper.Create(LData), Length) else FParams[DbxValue.ValueType.Ordinal].AsBytes := LData; end; procedure TDBXParamsRow.SetNull(DbxValue: TDBXValue); begin FParams[DbxValue.ValueType.Ordinal].Value := Null; end; procedure TDBXParamsRow.SetSingle(DbxValue: TDBXSingleValue; Value: Single); begin FParams[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXParamsRow.SetStream(DbxValue: TDBXStreamValue; StreamReader: TDBXStreamReader); var MemoryStream: TMemoryStream; Buffer: TArray<Byte>; BytesRead: Integer; begin MemoryStream := TMemoryStream.Create; SetLength(Buffer, 512); BytesRead := 1; while BytesRead > 0 do begin BytesRead := StreamReader.Read(Buffer, 0, Length(Buffer)); if BytesRead > 0 then MemoryStream.Write(Buffer[0], BytesRead); end; MemoryStream.Seek(0, soBeginning); FParams[DBXValue.ValueType.Ordinal].SetStream(MemoryStream, True, MemoryStream.Size); end; procedure TDBXParamsRow.SetWideString(DbxValue: TDBXWideStringValue; const Value: string); begin FParams[DbxValue.ValueType.Ordinal].Value := Value; end; {$IFNDEF NEXTGEN} procedure TDBXParamsRow.SetAnsiString(DbxValue: TDBXAnsiStringValue; const Value: AnsiString); begin FParams[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXParamsRow.SetString(DbxValue: TDBXAnsiStringValue; const Value: AnsiString); begin FParams[DbxValue.ValueType.Ordinal].Value := Value; end; {$ELSE} procedure TDBXParamsRow.SetString(DbxValue: TDBXAnsiStringValue; const Value: string); begin FParams[DbxValue.ValueType.Ordinal].Value := Value; end; {$ENDIF !NEXTGEN} procedure TDBXParamsRow.SetDate(DbxValue: TDBXDateValue; Value: TDBXDate); var LTimeStamp: TTimeStamp; begin LTimeStamp.Date := Value; LTimeStamp.Time := 0; FParams[DbxValue.ValueType.Ordinal].Value := TimeStampToDateTime(LTimeStamp); end; procedure TDBXParamsRow.SetTime(DbxValue: TDBXTimeValue; Value: TDBXTime); var LTimeStamp: TTimeStamp; begin LTimeStamp.Date := DateDelta; LTimeStamp.Time := Value; FParams[DbxValue.ValueType.Ordinal].Value := TimeStampToDateTime(LTimeStamp); end; procedure TDBXParamsRow.SetTimestamp(DbxValue: TDBXTimeStampValue; var Value: TSQLTimeStamp); begin if DbxValue.ValueType.DataType = TDBXDataTypes.DateTimeType then FParams[DBXValue.ValueType.Ordinal].AsDateTime := SQLTimeStampToDateTime(Value) else FParams[DbxValue.ValueType.Ordinal].AsSQLTimeStamp := Value; end; procedure TDBXParamsRow.SetTimestampOffset(DbxValue: TDBXTimeStampOffsetValue; var Value: TSQLTimeStampOffset); begin if DbxValue.ValueType.DataType = TDBXDataTypes.DateTimeType then FParams[DBXValue.ValueType.Ordinal].AsDateTime := SQLTimeStampOffsetToDateTime(Value) else FParams[DbxValue.ValueType.Ordinal].AsSQLTimeStampOffset := Value; end; procedure TDBXParamsRow.SetUInt16(DbxValue: TDBXUInt16Value; Value: Word); begin FParams[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXParamsRow.SetUInt8(DbxValue: TDBXUInt8Value; Value: Byte); begin FParams[DbxValue.ValueType.Ordinal].Value := Value; end; procedure TDBXParamsRow.SetBCD(DbxValue: TDBXBcdValue; var Value: TBcd); begin FParams[DbxValue.ValueType.Ordinal].AsFMTBCD := Value; end; procedure TDBXParamsRow.ValueSet(Value: TDBXWritableValue); begin TDBXDriverHelp.SetPendingValue(Value); end; constructor TDBXParamsTable.Create; begin FParams := TParams.Create(nil); inherited Create(nil, TDBXParamsRow.Create(FParams)); end; constructor TDBXParamsTable.Create(Params: TParams; InstanceOwner: Boolean); begin inherited Create(nil, TDBXParamsRow.Create(Params)); FParams := Params; FInstanceOwner := InstanceOwner; CreateValues; end; destructor TDBXParamsTable.Destroy; begin if FInstanceOwner then FreeAndNil(FParams); FreeValueTypes; inherited Destroy; end; function TDBXParamsTable.First: Boolean; begin RowNavigated; FAtEnd := False; Result := true; end; function TDBXParamsTable.Next: Boolean; begin FAtEnd := True; Result := False; // if FAtEnd then // Result := false // else // begin // FAtEnd := true; // Result := true; // end; end; function TDBXParamsTable.InBounds: Boolean; begin Result := not FAtEnd; end; procedure TDBXParamsTable.Close; begin end; function TDBXParamsTable.GetOrdinal(const ColumnName: string): Integer; begin Result := FParams.ParamByName(ColumnName).Index; end; function TDBXParamsTable.GetColumns: TDBXValueTypeArray; var Ordinal: Integer; Param: TParam; ValueType: TDBXValueType; begin if FValueTypes = nil then begin SetLength(FValueTypes, FParams.Count); for Ordinal := Low(FValueTypes) to High(FValueTypes) do begin Param := FParams[Ordinal]; ValueType := TDBXValueType.Create(DBXContext); ValueType.Name := Param.Name; ValueType.DisplayName := Param.DisplayName; ValueType.DataType := ToDataType(Param.DataType); ValueType.SubType := ToDataSubType(Param.DataType); ValueType.Precision := Param.Precision; ValueType.Scale := Param.NumericScale; ValueType.Size := Param.GetDataSize; ValueType.ParameterDirection := ToDBXParameterDirection(Param.ParamType); FValueTypes[Ordinal] := ValueType; end; end; Result := FValueTypes; end; procedure TDBXParamsTable.SetColumns(const Columns: TDBXValueTypeArray); begin FreeValueTypes; FValueTypes := Columns; if FParams <> nil then CopyValueTypes(Columns, FParams); end; class procedure TDBXParamsTable.CopyValueTypes(const ValueTypes: TDBXValueTypeArray; const Params: TParams); var Ordinal: Integer; begin Params.Clear; for Ordinal := Low(ValueTypes) to High(ValueTypes) do begin if Ordinal >= Params.Count then CopyValueType(Ordinal, ValueTypes[Ordinal], Params[Ordinal]) else if not(Params[Ordinal].Name = ValueTypes[Ordinal].Name) then raise TDBXError.Create(SMustKeepOriginalColumnOrder); end; end; function TDBXParamsTable.GetStorage: TObject; begin Result := FParams; end; class procedure TDBXParamsTable.CopyValueType(Ordinal: Integer; ValueType: TDBXValueType; Param: TParam); begin Param.Name := ValueType.Name; Param.DisplayName := ValueType.DisplayName; Param.DataType := ToFieldType(ValueType); Param.ParamType := ToParameterType(ValueType.ParameterDirection); Param.Precision := ValueType.Precision; Param.NumericScale := ValueType.Scale; Param.Size := ValueType.Size; // if ValueType.DataType = TDBXDataTypes.WideStringType then // begin // if ValueType.Size <= 0 then // Param.Size := 128 // default size (make constant) // else // Param.Size := ValueType.Size; // end; end; procedure TDBXDBTable.FreeValueTypes; begin ClearValues; FValueTypes := nil; end; class function TDBXDBTable.ToDataSubType(FieldType: TFieldType): Integer; begin case FieldType of ftWideMemo: Result := TDBXDataTypes.WideMemoSubType; else Result := 0; end; end; class function TDBXDBTable.ToDataType(FieldType: TFieldType): Integer; begin case FieldType of ftBoolean: Result := TDBXDataTypes.BooleanType; ftByte: Result := TDBXDataTypes.UInt8Type; ftShortint: Result := TDBXDataTypes.Int8Type; ftSmallInt: Result := TDBXDataTypes.Int16Type; ftInteger, ftAutoInc: Result := TDBXDataTypes.Int32Type; ftLargeint: Result := TDBXDataTypes.Int64Type; ftSingle: Result := TDBXDataTypes.SingleType; ftFloat: Result := TDBXDataTypes.DoubleType; ftGuid, ftOraInterval: Result := TDBXDataTypes.AnsiStringType; ftString, ftFixedChar: Result := TDBXDataTypes.AnsiStringType; ftWideString, ftFixedWideChar: Result := TDBXDataTypes.WideStringType; ftMemo, ftWideMemo, ftBlob, ftGraphic, ftFmtMemo, ftParadoxOle, ftDBaseOle, ftTypedBinary, ftOraBlob, ftOraClob: Result := TDBXDataTypes.BlobType; ftFMTBcd: Result := TDBXDataTypes.BcdType; ftBcd: Result := TDBXDataTypes.CurrencyType; ftBytes: Result := TDBXDataTypes.BytesType; ftDate: Result := TDBXDataTypes.DateType; ftTime: Result := TDBXDataTypes.TimeType; ftTimeStamp, ftOraTimeStamp: Result := TDBXDataTypes.TimeStampType; ftTimeStampOffset: Result := TDBXDataTypes.TimeStampOffsetType; ftDateTime: Result := TDBXDataTypes.DateTimeType; ftStream: Result := TDBXDataTypes.BinaryBlobType; ftVarBytes: Result := TDBXDataTypes.VarBytesType; ftWord: Result := TDBXDataTypes.UInt16Type; ftCurrency: Result := TDBXDataTypes.DoubleType; // TDBXDataTypes.CurrencyType; ftCursor: Result := TDBXDataTypes.CursorType; ftADT: Result := TDBXDataTypes.AdtType; ftArray: Result := TDBXDataTypes.ArrayType; ftReference: Result := TDBXDataTypes.RefType; ftDataSet, ftParams: Result := TDBXDataTypes.TableType; ftVariant: Result := TDBXDataTypes.VariantType; ftConnection: Result := TDBXDataTypes.DBXConnectionType; { ftDataSet: Result := TDBXDataTypes.TableType; } else raise TDBXError.Create(SUnexpectedMetaDataType); end; end; class function TDBXDBTable.ToFieldType(ValueType: TDBXValueType): TFieldType; begin case ValueType.DataType of TDBXDataTypes.BooleanType: Result := ftBoolean; TDBXDataTypes.UInt8Type: Result := ftByte; TDBXDataTypes.Int8Type: Result := ftShortint; TDBXDataTypes.Int16Type: Result := ftSmallInt; TDBXDataTypes.Int32Type: Result := ftInteger; TDBXDataTypes.Int64Type: Result := ftLargeint; TDBXDataTypes.SingleType: Result := ftSingle; TDBXDataTypes.DoubleType: Result := ftFloat; TDBXDataTypes.WideStringType: // Switched back to this because metadata layer cannot create // Unicode identifiers without it. If there ar issues, we need // to find the root cause. TClientDataSet does support Unicode. // Result := ftWideString; // All strings are truncated to the empty string (bug!) // Result := ftWideMemo; // Cannot create an index for this column type (needed for keyword search) // Result := ftString; // Cannot hold unicode chars (bad) TDBXDataTypes.AnsiStringType: Result := ftString; TDBXDataTypes.DateType: Result := ftDate; TDBXDataTypes.TimeStampType: Result := ftTimeStamp; TDBXDataTypes.TimeStampOffsetType: Result := ftTimeStampOffset; TDBXDataTypes.BlobType: case ValueType.SubType of TDBXDataTypes.WideMemoSubType: Result := ftWideMemo; else Result := ftBlob; end; TDBXDataTypes.BcdType: Result := ftFMTBcd; TDBXDataTypes.CurrencyType: Result := ftCurrency; TDBXDataTypes.BytesType: Result := ftBytes; TDBXDataTypes.TimeType: Result := ftTime; TDBXDataTypes.BinaryBlobType: Result := ftStream; TDBXDataTypes.UInt16Type: Result := ftWord; TDBXDataTypes.CursorType: Result := ftCursor; TDBXDataTypes.AdtType: Result := ftADT; TDBXDataTypes.ArrayType: Result := ftArray; TDBXDataTypes.RefType: Result := ftReference; TDBXDataTypes.TableType: Result := ftDataSet; TDBXDataTypes.VariantType: Result := ftVariant; TDBXDataTypes.VarBytesType: Result := ftVarBytes; TDBXDataTypes.DBXConnectionType: Result := ftConnection; TDBXDataTypes.DateTimeType: Result := ftDateTime; else raise TDBXError.Create(SUnexpectedMetaDataType); end; end; function TDBXDBTable.GetDBXTableName: string; begin Result := FCollectionName; end; procedure TDBXDBTable.SetDBXTableName(const CollectionName: string); begin FCollectionName := CollectionName; end; class function TDBXDBTable.ToDBXParameterDirection(ParameterType: TParamType): Integer; begin case ParameterType of ptInput: Result := TDBXParameterDirections.InParameter; ptOutput: Result := TDBXParameterDirections.OutParameter; ptInputOutput: Result := TDBXParameterDirections.InOutParameter; ptResult: Result := TDBXParameterDirections.ReturnParameter; else Result := TDBXParameterDirections.Unknown; end; end; class function TDBXDBTable.ToParameterType(ParameterDirection: Integer): TParamType; begin case ParameterDirection of TDBXParameterDirections.InParameter: Result := ptInput; TDBXParameterDirections.OutParameter: Result := ptOutput; TDBXParameterDirections.InOutParameter: Result := ptInputOutput; TDBXParameterDirections.ReturnParameter: Result := ptResult; else Result := ptUnknown; end; end; constructor TDBXDataSetReader.Create(Params: TDBXDataSetTable); begin inherited Create(Params); end; constructor TDBXDataSetReader.Create(Params: TDataset; InstanceOwner: Boolean); begin inherited Create(TDBXDataSetTable.Create(Params.Name, Params, InstanceOwner, true)); end; { TDBXParamsReader } class procedure TDBXParamsReader.CopyReaderToParams(Reader: TDBXReader; Params: TParams); var Ordinal: Integer; Count: Integer; Param: TParam; DBXRow: TDBXParamsRow; begin Reader.Next; Params.Clear; Count := Reader.ColumnCount; for Ordinal := 0 to Count - 1 do begin Param := TParam.Create(Params); TDBXParamsTable.CopyValueType(Ordinal, Reader.ValueType[Ordinal], Param); end; DBXRow := TDBXParamsRow.Create(Params); try for Ordinal := 0 to Count - 1 do begin TDBXDriverHelp.CopyRowValue(Reader.Value[Ordinal], DBXRow); end; finally FreeAndNil(DBXRow); end; end; class function TDBXParamsReader.ToParams(AOwner: TPersistent; Reader: TDBXReader; AOwnsInstance: Boolean): TParams; begin Result := TParams.Create(AOwner); CopyReaderToParams(Reader, Result); if AOwnsInstance then Reader.Free; end; constructor TDBXParamsReader.Create(Params: TParams; InstanceOwner: Boolean); begin inherited Create(TDBXParamsTable.Create(Params, InstanceOwner)); end; destructor TDBXParamsReader.Destroy; begin inherited; end; { TDBXMemoryTable } procedure TDBXMemoryTable.AcceptChanges; begin // do nothing for memory tables end; procedure TDBXMemoryTable.Clear; begin //no op end; procedure TDBXMemoryTable.ClearValues(AValues: TDBXWritableValueArray); var I: Integer; begin for I := 0 to Length(AValues) - 1 do AValues[I].Free; end; procedure TDBXMemoryTable.ClearValueTypes(AValueTypes: TDBXValueTypeArray); var I: Integer; begin for I := 0 to Length(AValueTypes) - 1 do AValueTypes[I].Free; end; procedure TDBXMemoryTable.Close; var I: Integer; begin if Assigned(FValueRows) then begin // Free rows for I := FValueRows.Count - 1 downto 0 do ClearValues(FValueRows[I]); // Prevent ancestor from freeing current row SetValues(TDBXWritableValueArray(nil)); FreeAndNil(FValueRows); end; end; constructor TDBXMemoryTable.Create; begin FValueRows := TList<TDBXWritableValueArray>.Create; FIndex := 0; FOrderByColumn := -1; end; function TDBXMemoryTable.CreateTableView( const OrderByColumnName: string): TDBXTable; var Column: Integer; begin // get the column index Column := ColumnIndex(OrderByColumnName); if Column = -1 then raise TDBXError.Create(Format(SInvalidOrderByColumn, [OrderByColumnName])); Result := TDBXMemoryTable.Create; Result.Columns := CopyColumns; FIndex := -1; Result.CopyFrom(self); // sort the list based on the column value (Result as TDBXMemoryTable).OrderByColumn(Column); end; function TDBXMemoryTable.CreateWritableValueArray: TDBXWritableValueArray; var Value: TDBXWritableValue; Values: TDBXWritableValueArray; Ordinal: Integer; begin SetLength(Values, Length(Columns)); for Ordinal := 0 to Length(Values) - 1 do begin if Columns[Ordinal] <> nil then begin // Note that we must clone the column here because a TDBXValue owns the TDBXValueType. // Would be nice to add ownership control Value := TDBXWritableValue(TDBXValue.CreateValue(nil, Columns[Ordinal].Clone, nil, False)); Value.ValueType.Ordinal := Ordinal; Values[Ordinal] := Value; end; end; Result := Values; end; destructor TDBXMemoryTable.Destroy; begin Close; // Free column types ClearValueTypes(FValueTypes); inherited; end; function TDBXMemoryTable.FindStringKey(const Ordinal: Integer; const Value: string): Boolean; var refRow: TDBXWritableValueArray; Comparer: TDBXWritableValueArrayComparer; begin // false for an empty table if FValueRows.Count = 0 then exit(False); // sort if not sorted on the column, thinking is there is a repeat if Ordinal <> FOrderByColumn then OrderByColumn(Ordinal); // prepare the reference row, only Ordinal column is important SetLength(refRow, Ordinal + 1); refRow[Ordinal] := TDBXValue.CreateValue(FValueRows[0][Ordinal].ValueType.Clone); refRow[Ordinal].AsString := Value; // allocate the comparer and perform a binary search // if success, move index to the found column Comparer := TDBXWritableValueArrayComparer.Create(Ordinal); Result := FValueRows.BinarySearch(refRow, FIndex, Comparer); if Result then SetValues(FValueRows[FIndex]); // clean up Comparer.Free; refRow[Ordinal].Free; end; function TDBXMemoryTable.First: Boolean; begin FIndex := 0; Result := FIndex < FValueRows.Count; if Result then SetValues(FValueRows[FIndex]); end; function TDBXMemoryTable.GetColumns: TDBXValueTypeArray; begin Result := FValueTypes; end; function TDBXMemoryTable.GetDBXTableName: string; begin Result := FName; end; function TDBXMemoryTable.GetTableCount: Integer; begin Result := FValueRows.Count end; function TDBXMemoryTable.InBounds: Boolean; begin Result := (FIndex >= 0) and (FIndex < FValueRows.Count); end; procedure TDBXMemoryTable.Insert; var LRow: TDBXWritableValueArray; begin LRow := CreateWritableValueArray; SetValues(LRow, Length(LRow)); FValueRows.Add(LRow); FIndex := FValueRows.Count - 1; end; function TDBXMemoryTable.Next: Boolean; begin Inc(FIndex); Result := FIndex < FValueRows.Count; if Result then SetValues(FValueRows[FIndex]); end; procedure TDBXMemoryTable.OrderByColumn(Column: Integer); var Comparer: TDBXWritableValueArrayComparer; begin Comparer := TDBXWritableValueArrayComparer.Create(Column); try FValueRows.Sort(Comparer); FOrderByColumn := Column; finally Comparer.Free; end; end; procedure TDBXMemoryTable.Post; begin // Nothing to do because data is written to the actual row rather than a buffer row end; procedure TDBXMemoryTable.SetColumns(const Columns: TDBXValueTypeArray); begin FValueTypes := Columns; end; procedure TDBXMemoryTable.SetDBXTableName(const AName: string); begin FName := AName; end; { TDBXWritableValueArrayComparer } function TDBXWritableValueArrayComparer.Compare(const Left, Right: TDBXWritableValueArray): Integer; var LeftValue, RightValue: TDBXValue; begin LeftValue := Left[ColumnIndex]; RightValue := Right[ColumnIndex]; if LeftValue.IsNull or RightValue.IsNull then if LeftValue.IsNull then if RightValue.IsNull then Result := 0 else Result := -1 else Result := 1 else Result := LeftValue.Compare(RightValue); end; class function TDBXWritableValueArrayComparer.CompareArrays(const Left, Right: TDBXWritableValueArray): Boolean; var LeftValue, RightValue: TDBXValue; LColumnIndex: Integer; begin Result := False; if Length(Right) <> Length(Left) then Exit; for LColumnIndex := 0 to Length(Left) - 1 do begin LeftValue := Left[LColumnIndex]; RightValue := Right[LColumnIndex]; if LeftValue.IsNull or RightValue.IsNull then if LeftValue.IsNull then if RightValue.IsNull then Result := True else Result := False else Result := False else Result := LeftValue.Compare(RightValue) = 0; end; end; constructor TDBXWritableValueArrayComparer.Create(AColumnIndex: Integer); begin FColumnIndex := AColumnIndex; end; class function TDBXWritableValueArrayComparer.FindStringKey( const AValuesList: TList<TDBXWritableValueArray>; const Ordinal: Integer; const Value: string): Integer; var refRow: TDBXWritableValueArray; Comparer: TDBXWritableValueArrayComparer; begin Result := -1; if AValuesList.Count = 0 then Exit; // allocate the comparer and perform a binary search // if success, move index to the found column Comparer := TDBXWritableValueArrayComparer.Create(Ordinal); try // sort if not sorted on the column, thinking is there is a repeat AValuesList.Sort(Comparer); // prepare the reference row, only Ordinal column is important SetLength(refRow, Ordinal + 1); refRow[Ordinal] := TDBXValue.CreateValue(AValuesList[0][Ordinal].ValueType.Clone); refRow[Ordinal].AsString := Value; if not AValuesList.BinarySearch(refRow, Result, Comparer) then Result := -1; finally // clean up Comparer.Free; refRow[Ordinal].Free; end; end; { TDBXMemoryValue } procedure TDBXMemoryValue.ClearOriginal; begin FreeAndNil(FOriginalValue); end; function TDBXMemoryValue.Compare(Other: TDBXValue): Smallint; begin Result := FValue.Compare(Other) end; constructor TDBXMemoryValue.Create(const AOriginalValue: TDBXWritableValue{; Owner: TDBXCache}); begin inherited Create(AOriginalValue.ValueType.Clone); FValue := AOriginalValue; FInitialized := False; // FOwner := Owner; end; destructor TDBXMemoryValue.Destroy; begin FreeAndNil(FValue); FreeAndNil(FOriginalValue); inherited; end; function TDBXMemoryValue.EqualsValue(Other: TDBXValue): Boolean; begin Result := FValue.EqualsValue(Other) end; {$IFNDEF NEXTGEN} function TDBXMemoryValue.GetAnsiString: AnsiString; begin Result := AnsiString(FValue.AsString); end; {$ENDIF !NEXTGEN} function TDBXMemoryValue.GetBcd: TBcd; begin Result := FValue.AsBcd end; function TDBXMemoryValue.GetBoolean: Boolean; begin Result := FValue.AsBoolean; end; function TDBXMemoryValue.GetBoolean(defaultValue: Boolean): Boolean; begin Result := FValue.GetBoolean(defaultValue) end; function TDBXMemoryValue.GetBytes(Offset: Int64; const Buffer: TArray<Byte>; BufferOffset, Length: Int64): Int64; begin Result := FValue.GetBytes(Offset, Buffer, BufferOffset, Length) end; function TDBXMemoryValue.GetCallbackValue: TDBXCallback; begin Result := FValue.GetCallbackValue end; function TDBXMemoryValue.GetDate: TDBXDate; begin Result := FValue.AsDate; end; function TDBXMemoryValue.GetDBXConnection: TDBXConnection; begin Result := FValue.GetDBXConnection end; function TDBXMemoryValue.GetDBXReader: TDBXReader; begin Result := FValue.GetDBXReader end; function TDBXMemoryValue.GetDBXReader(AInstanceOwner: Boolean): TDBXReader; begin Result := FValue.GetDBXReader(AInstanceOwner) end; function TDBXMemoryValue.GetDouble: Double; begin Result := FValue.AsDouble end; function TDBXMemoryValue.GetInt16: SmallInt; begin Result := FValue.AsInt16 end; function TDBXMemoryValue.GetInt16(defaultValue: Smallint): Smallint; begin Result := FValue.GetInt16(defaultValue) end; function TDBXMemoryValue.GetInt32: TInt32; begin Result := FValue.AsInt32 end; function TDBXMemoryValue.GetInt32(defaultValue: TInt32): TInt32; begin Result := FValue.GetInt32(defaultValue) end; function TDBXMemoryValue.GetInt64(defaultValue: Int64): Int64; begin Result := FValue.GetInt64(defaultValue) end; function TDBXMemoryValue.GetInt64: Int64; begin Result := FValue.AsInt64 end; function TDBXMemoryValue.GetInt8: ShortInt; begin Result := FValue.AsInt8 end; function TDBXMemoryValue.GetInt8(defaultValue: Shortint): Shortint; begin Result := FValue.GetInt8(defaultValue) end; function TDBXMemoryValue.GetJSONValue: TJSONValue; begin Result := FValue.GetJSONValue end; function TDBXMemoryValue.GetJSONValue(AInstanceOwner: Boolean): TJSONValue; begin Result := FValue.GetJSONValue(AInstanceOwner) end; function TDBXMemoryValue.GetObjectValue(AInstanceOwner: Boolean): TObject; begin Result := FValue.GetObjectValue(AInstanceOwner) end; function TDBXMemoryValue.GetObjectValue: TObject; begin Result := FValue.GetObjectValue end; function TDBXMemoryValue.GetSingle: Single; begin Result := FValue.AsSingle end; function TDBXMemoryValue.GetStream(AInstanceOwner: Boolean): TStream; begin Result := FValue.GetStream(AInstanceOwner) end; function TDBXMemoryValue.GetStream: TStream; begin Result := FValue.GetStream end; function TDBXMemoryValue.GetString: string; begin Result := FValue.AsString end; function TDBXMemoryValue.GetTime: TDBXTime; begin Result := FValue.AsTime end; function TDBXMemoryValue.GetTimeStamp: TSQLTimeStamp; begin Result := FValue.AsTimeStamp end; function TDBXMemoryValue.GetTimeStampOffset: TSQLTimeStampOffset; begin Result := FValue.GetTimeStampOffset; end; function TDBXMemoryValue.GetUInt16: Word; begin Result := FValue.AsUInt16 end; function TDBXMemoryValue.GetUInt16(defaultValue: Word): Word; begin Result := FValue.GetUInt16(defaultValue) end; function TDBXMemoryValue.GetUInt8: Byte; begin Result := FValue.AsUInt8 end; function TDBXMemoryValue.GetUInt8(defaultValue: Byte): Byte; begin Result := FValue.GetUInt8(defaultValue) end; function TDBXMemoryValue.GetValueSize: Int64; begin Result := FValue.GetValueSize end; function TDBXMemoryValue.GetWideString(defaultValue: string): string; begin Result := FValue.GetWideString(defaultValue) end; function TDBXMemoryValue.GetWideString: string; begin Result := FValue.AsString end; function TDBXMemoryValue.IsNull: Boolean; begin Result := FValue.IsNull; end; procedure TDBXMemoryValue.AcceptChanges; begin FreeAndNil(FOriginalValue); if FValue <> nil then begin FOriginalValue := TDBXValue.CreateValue(nil, FValue.ValueType.Clone, nil, False); FOriginalValue.SetValue(FValue); end; end; procedure TDBXMemoryValue.Cancel; begin if FOriginalValue <> nil then begin FValue.SetValue(FOriginalValue); ClearOriginal; end; end; procedure TDBXMemoryValue.SetOriginal; begin if FInitialized then begin if FOriginalValue = nil then AcceptChanges; end else FInitialized := True; end; {$IFNDEF NEXTGEN} procedure TDBXMemoryValue.SetAnsiString(const Value: AnsiString); begin SetOriginal; FValue.AsString := string(Value); end; {$ENDIF !NEXTGEN} procedure TDBXMemoryValue.SetBcd(const Value: TBcd); begin SetOriginal; FValue.AsBcd := Value; end; procedure TDBXMemoryValue.SetBoolean(const Value: Boolean); begin SetOriginal; FValue.AsBoolean := Value; end; procedure TDBXMemoryValue.SetCallbackValue(const Value: TDBXCallback); begin SetOriginal; FValue.SetCallbackValue(Value); end; procedure TDBXMemoryValue.SetDate(const Value: TDBXDate); begin SetOriginal; FValue.AsDate := Value; end; procedure TDBXMemoryValue.SetDBXConnection(const Value: TDBXConnection); begin SetOriginal; FValue.SetDBXConnection(Value); end; procedure TDBXMemoryValue.SetDBXReader(const Value: TDBXReader; const AInstanceOwner: Boolean); begin SetOriginal; FValue.SetDBXReader(Value, AInstanceOwner); end; procedure TDBXMemoryValue.SetDouble(const Value: Double); begin SetOriginal; FValue.AsDouble := Value; end; procedure TDBXMemoryValue.SetDynamicBytes(Offset: Int64; const Buffer: TArray<Byte>; BufferOffset, Length: Int64); begin SetOriginal; FValue.SetDynamicBytes(Offset, Buffer, BufferOffset, Length); end; procedure TDBXMemoryValue.SetInt16(const Value: SmallInt); begin SetOriginal; FValue.AsInt16 := Value; end; procedure TDBXMemoryValue.SetInt32(const Value: TInt32); begin SetOriginal; FValue.AsInt32 := Value; end; procedure TDBXMemoryValue.SetInt64(const Value: Int64); begin SetOriginal; FValue.AsInt64 := Value; end; procedure TDBXMemoryValue.SetInt8(const Value: ShortInt); begin SetOriginal; FValue.AsInt8 := Value; end; procedure TDBXMemoryValue.SetJSONValue(const Value: TJSONValue; const AInstanceOwner: Boolean); begin SetOriginal; FValue.SetJSONValue(Value, AInstanceOwner); end; procedure TDBXMemoryValue.SetNull; begin SetOriginal; FValue.SetNull; end; procedure TDBXMemoryValue.SetObjectValue(const Value: TObject; const AInstanceOwner: Boolean); begin SetOriginal; FValue.SetObjectValue(Value, AInstanceOwner); end; procedure TDBXMemoryValue.SetSingle(const Value: Single); begin SetOriginal; FValue.AsSingle := Value; end; procedure TDBXMemoryValue.SetStaticBytes(Offset: Int64; const Buffer: array of Byte; BufferOffset, Length: Int64); begin SetOriginal; FValue.SetStaticBytes(Offset, Buffer, BufferOffset, Length); end; procedure TDBXMemoryValue.SetStream(const Stream: TStream; const AInstanceOwner: Boolean); begin SetOriginal; FValue.SetStream(Stream, AInstanceOwner); end; procedure TDBXMemoryValue.SetString(const Value: string); begin SetOriginal; FValue.AsString := Value; end; procedure TDBXMemoryValue.SetTime(const Value: TDBXTime); begin SetOriginal; FValue.AsTime := Value; end; procedure TDBXMemoryValue.SetTimeStamp(const Value: TSQLTimeStamp); begin SetOriginal; FValue.AsTimeStamp := Value; end; procedure TDBXMemoryValue.SetTimeStampOffset(const Value: TSQLTimeStampOffset); begin SetOriginal; FValue.SetTimeStampOffset(Value); end; procedure TDBXMemoryValue.SetUInt16(const Value: Word); begin SetOriginal; FValue.AsUInt16 := Value; end; procedure TDBXMemoryValue.SetUInt8(const Value: Byte); begin SetOriginal; FValue.AsUInt8 := Value; end; procedure TDBXMemoryValue.SetValue(const Value: TDBXValue); begin SetOriginal; if Value is TDBXMemoryValue then if TDBXMemoryValue(Value).FOriginalValue <> nil then begin if not Assigned(FOriginalValue) then FOriginalValue := TDBXValue.CreateValue(nil, TDBXMemoryValue(Value).ValueType.Clone, nil, False); FOriginalValue.SetValue(TDBXMemoryValue(Value).FOriginalValue); end; FValue.SetValue(Value); end; procedure TDBXMemoryValue.SetWideString(const Value: string); begin SetOriginal; FValue.AsString := Value; end; { TDBXTableStorage } procedure TDBXTableStorage.AcceptChanges; begin FCache.AcceptChanges; end; procedure TDBXTableStorage.AddRow(const ATable: TDBXTable; const ARow: TDBXWritableValueArray; const AClone: Boolean); var LValueArray: TDBXWritableValueArray; I: Integer; begin ATable.Insert; if AClone then LValueArray := CloneRow(ARow) else LValueArray := ARow; TDBXTableStorage(ATable).SetValues(LValueArray, Length(LValueArray)); I := TDBXTableStorage(ATable).FIndex; ClearValues(TDBXTableStorage(ATable).FCache.ValueRows.Items[I]); TDBXTableStorage(ATable).FCache.ValueRows.Items[I] := LValueArray; ATable.Post; end; procedure TDBXTableStorage.Cancel; begin inherited; end; procedure TDBXTableStorage.Clear; begin FCache.Clear; FIndex := 0; // Prevent ancestor from freeing current row SetValues(TDBXWritableValueArray(nil)); end; procedure TDBXTableStorage.ClearValues(AValues: TDBXWritableValueArray); var I: Integer; begin for I := 0 to Length(AValues) - 1 do AValues[I].Free; end; function TDBXTableStorage.CloneRow( const ARow: TDBXWritableValueArray): TDBXWritableValueArray; var I: Integer; begin SetLength(Result, Length(ARow)); for I := 0 to Length(Result) - 1 do begin if ARow[I] is TDBXMemoryValue then Result[I] := TDBXMemoryValue.Create(TDBXValue.CreateValue(ARow[I].ValueType.Clone)) else Result[I] := TDBXValue.CreateValue(ARow[I].ValueType.Clone); Result[I].SetValue(ARow[I]); end; end; procedure TDBXTableStorage.Close; begin //No-op end; procedure TDBXTableStorage.CopyFrom(const Source: TDBXTable); var Row: TDBXWritableValueArray; begin if Source.First then begin if Source.InBounds then repeat Row := CloneRow(Source.Values); FCache.AddRow(Row); SetValues(Row, Length(Source.Values)); // for Ordinal := 0 to ColumnCount - 1 do // Self.Value[Ordinal].SetValue(Source.Value[Ordinal]); until not Source.Next; end; end; constructor TDBXTableStorage.Create; begin Create(True); end; constructor TDBXTableStorage.Create(const AOwnsValues: Boolean); begin inherited Create(nil); FIndex := -1; FCache := TDBXCache.Create(AOwnsValues); FOriginalRow := nil; FInsertedTable := nil; FUpdatedTable := nil; FDeletedTable := nil; end; function TDBXTableStorage.CreateTableView( const OrderByColumnName: string): TDBXTable; var Column: Integer; begin // get the column index Column := ColumnIndex(OrderByColumnName); Result := TDBXTableStorage.Create; try Result.Columns := CopyColumns; //TDBXTableStorage(Result).SetColumns(Result.Columns); FIndex := -1; Result.CopyFrom(Self); // sort the list based on the column value if Column <> -1 then (Result as TDBXTableStorage).OrderByColumn(Column); except Result.Free; raise; end; end; procedure TDBXTableStorage.DeleteRow; begin DeleteRow(FIndex); end; procedure TDBXTableStorage.DeleteRow(const AIndex: Integer); begin FCache.DeleteRow(AIndex); UpdateCurrentRow; end; destructor TDBXTableStorage.Destroy; begin if FCache.OwnsValues then SetValues(nil, 0); FOriginalRow.Free; FInsertedTable.Free; FUpdatedTable.Free; FDeletedTable.Free; FCache.Free; inherited; end; function TDBXTableStorage.Edit: Boolean; begin Result := False; end; function TDBXTableStorage.FindStringKey(const Ordinal: Integer; const Value: string): Boolean; begin Result := False; FIndex := TDBXWritableValueArrayComparer.FindStringKey(FCache.ValueRows, Ordinal, Value); if FIndex <> -1 then begin Result := True; UpdateCurrentRow; end; end; function TDBXTableStorage.First: Boolean; begin FIndex := 0; Result := FIndex < FCache.ValueRows.Count; if Result then UpdateCurrentRow; end; function TDBXTableStorage.GetColumns: TDBXValueTypeArray; begin Result := FCache.GetColumns; end; function TDBXTableStorage.GetDBXTableName: string; begin Result := FName; end; function TDBXTableStorage.GetDeletedRows: TDBXTable; var I: Integer; begin FDeletedTable.Free; FDeletedTable := TDBXTableStorage.Create; Result := FDeletedTable; try Result.Columns := CopyColumns; TDBXTableStorage(Result).SetColumns(Result.Columns); for I := 0 to FCache.DeletedRows.Count - 1 do AddRow(Result, FCache.DeletedRows.Items[I], True); Result.AcceptChanges; except FDeletedTable := nil; Result.Free; raise; end; end; function TDBXTableStorage.GetInsertedRows: TDBXTable; var I: Integer; begin FInsertedTable.Free; FInsertedTable := TDBXTableStorage.Create; Result := FInsertedTable; try Result.Columns := CopyColumns; TDBXTableStorage(Result).SetColumns(Result.Columns); for I := 0 to FCache.InsertedRows.Count - 1 do AddRow(Result, FCache.InsertedRows.Items[I], True); Result.AcceptChanges; except FInsertedTable := nil; Result.Free; raise; end; end; function TDBXTableStorage.GetOriginalRow: TDBXTableRow; var LRow: TDBXWritableValueArray; I: Integer; begin FOriginalRow.Free; FOriginalRow := TDBXTableStorage.Create; Result := FOriginalRow; try Result.Columns := CopyColumns; if FCache.UpdatedRows.Count = 0 then AddRow(TDBXTable(Result), FCache.ValueRows[FIndex], True) else for LRow in FCache.UpdatedRows do begin if LRow = FCache.ValueRows[FIndex] then begin AddRow(TDBXTable(Result), LRow, True); //make sure the table here contains the original values! for I := 0 to Length(Result.Values) - 1 do if Result.Values[I] is TDBXMemoryValue then TDBXMemoryValue(Result.Values[I]).Cancel; end; end; except FOriginalRow := nil; Result.Free; raise; end; end; function TDBXTableStorage.GetRow(const AIndex: Integer): TDBXWritableValueArray; begin Result := FCache.ValueRows.Items[AIndex]; end; function TDBXTableStorage.GetTableCount: Integer; begin Result := FCache.ValueRows.Count; end; function TDBXTableStorage.GetUpdatedRows: TDBXTable; var I: Integer; begin FUpdatedTable.Free; FUpdatedTable := TDBXTableStorage.Create; Result := FUpdatedTable; try Result.Columns := CopyColumns; TDBXTableStorage(Result).SetColumns(Result.Columns); for I := 0 to FCache.UpdatedRows.Count - 1 do AddRow(Result, FCache.UpdatedRows.Items[I], True); except FUpdatedTable := nil; Result.Free; raise; end; end; function TDBXTableStorage.InBounds: Boolean; begin Result := (FIndex >= 0) and (FIndex < FCache.ValueRows.Count); end; procedure TDBXTableStorage.Insert(const AIndex: Integer); begin FIndex := AIndex; FCache.Insert(AIndex); UpdateCurrentRow; end; procedure TDBXTableStorage.Insert; begin Insert(FIndex + 1); end; function TDBXTableStorage.Next: Boolean; begin Inc(FIndex); Result := FIndex < FCache.ValueRows.Count; if Result then UpdateCurrentRow; end; procedure TDBXTableStorage.OrderByColumn(Column: Integer); var Comparer: TDBXWritableValueArrayComparer; begin Comparer := TDBXWritableValueArrayComparer.Create(Column); try FCache.ValueRows.Sort(Comparer); finally Comparer.Free; end; end; procedure TDBXTableStorage.Post; var LValue: TDBXWritableValue; I: Integer; begin for I := 0 to Length(Values) - 1 do begin LValue := Values[I]; if TDBXMemoryValue(LValue).FOriginalValue <> nil then if not TDBXMemoryValue(LValue).FOriginalValue.EqualsValue(LValue) then begin if not FCache.InsertedRows.Contains(Values) then if not FCache.UpdatedRows.Contains(Values) then FCache.UpdatedRows.Add(Values); break; end; end; end; procedure TDBXTableStorage.SetColumns(const Columns: TDBXValueTypeArray); begin FCache.SetColumns(Columns); end; procedure TDBXTableStorage.SetDBXTableName(const AName: string); begin FName := AName; end; procedure TDBXTableStorage.UpdateCurrentRow; begin if FIndex < FCache.ValueRows.Count then SetValues(FCache.ValueRows[FIndex], Length(FCache.ValueRows[FIndex])) end; { TDBXCache } constructor TDBXCache.Create; begin Create(True); end; procedure TDBXCache.AcceptChanges; var I, J: Integer; begin // Make sure all TDBXMemoryValue contains the correct "original value" // at this point before clearing the lists for I := 0 to FInsertedRows.Count - 1 do for J := 0 to Length(FInsertedRows.Items[I]) - 1 do if FInsertedRows.Items[I][J] is TDBXMemoryValue then TDBXMemoryValue(FInsertedRows.Items[I][J]).AcceptChanges; for I := 0 to FUpdatedRows.Count - 1 do for J := 0 to Length(FUpdatedRows.Items[I]) - 1 do if FUpdatedRows.Items[I][J] is TDBXMemoryValue then TDBXMemoryValue(FUpdatedRows.Items[I][J]).AcceptChanges; ClearChangeLog; end; procedure TDBXCache.AddRow(ARow: TDBXWritableValueArray); begin FValueRows.Add(ARow); end; procedure TDBXCache.Clear; var I: Integer; begin ClearChangeLog; if Assigned(FValueRows) then begin // Free rows if FOwnsValues then for I := FValueRows.Count - 1 downto 0 do begin ClearValues(FValueRows[I]); FValueRows.Delete(I); end; end; end; procedure TDBXCache.ClearChangeLog; var I: Integer; begin //cleanup after merge for I := 0 to FDeletedRows.Count - 1 do ClearValues(FDeletedRows[I]); FDeletedRows.Clear; FInsertedRows.Clear; FUpdatedRows.Clear; end; procedure TDBXCache.ClearValues(AValues: TDBXWritableValueArray); var I: Integer; begin for I := 0 to Length(AValues) - 1 do AValues[I].Free; end; constructor TDBXCache.Create(AOwnsValues: Boolean); begin inherited Create; FOwnsValues := AOwnsValues; FValueRows := TList<TDBXWritableValueArray>.Create; FInsertedRows := TList<TDBXWritableValueArray>.Create; FUpdatedRows := TList<TDBXWritableValueArray>.Create; FDeletedRows := TList<TDBXWritableValueArray>.Create; end; function TDBXCache.CreateWritableValueArray: TDBXWritableValueArray; var Value: TDBXWritableValue; Values: TDBXWritableValueArray; Ordinal: Integer; begin SetLength(Values, Length(FValueTypes)); for Ordinal := 0 to Length(Values) - 1 do begin if FValueTypes[Ordinal] <> nil then begin // Note that we must clone the column here because a TDBXValue owns the TDBXValueType. // Would be nice to add ownership control Value := TDBXMemoryValue.Create(TDBXValue.CreateValue(nil, FValueTypes[Ordinal].Clone, nil, False){, Self}); Value.ValueType.Ordinal := Ordinal; Values[Ordinal] := Value; end; end; Result := Values; end; procedure TDBXCache.DeleteRow(AIndex: Integer); var LRow: TDBXWritableValueArray; begin if (AIndex < FValueRows.Count) and (AIndex > -1) then begin LRow := FValueRows.Items[AIndex]; if FUpdatedRows.Contains(LRow) then FUpdatedRows.Remove(LRow); if FInsertedRows.Contains(LRow) then FInsertedRows.Remove(LRow) else FDeletedRows.Add(LRow); FValueRows.Delete(AIndex); if FOwnsValues then begin //only free if the row was not added to the list of // DeletedRows which will be freed at TearDown if not FDeletedRows.Contains(LRow) then ClearValues(LRow); end; end else raise Exception.Create('Invalid index'); end; procedure TDBXCache.ClearValueTypes(AValueTypes: TDBXValueTypeArray); var I: Integer; begin for I := 0 to Length(AValueTypes) - 1 do AValueTypes[I].Free; end; destructor TDBXCache.Destroy; begin Clear; ClearValueTypes(FValueTypes); FDeletedRows.Free; FInsertedRows.Free; FUpdatedRows.Free; FValueRows.Free; inherited; end; function TDBXCache.GetColumns: TDBXValueTypeArray; begin Result := FValueTypes; end; procedure TDBXCache.Insert(AIndex: Integer); var LRow: TDBXWritableValueArray; begin LRow := CreateWritableValueArray; FValueRows.Insert(AIndex, LRow); FInsertedRows.Add(LRow); end; procedure TDBXCache.SetColumns(Columns: TDBXValueTypeArray); begin FValueTypes := Columns; end; end.